echarts-en.simple.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774
  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: 'Box Select',
  21026. polygon: 'Lasso Select',
  21027. lineX: 'Horizontally Select',
  21028. lineY: 'Vertically Select',
  21029. keep: 'Keep Selections',
  21030. clear: 'Clear Selections'
  21031. }
  21032. },
  21033. dataView: {
  21034. title: 'Data View',
  21035. lang: ['Data View', 'Close', 'Refresh']
  21036. },
  21037. dataZoom: {
  21038. title: {
  21039. zoom: 'Zoom',
  21040. back: 'Zoom Reset'
  21041. }
  21042. },
  21043. magicType: {
  21044. title: {
  21045. line: 'Switch to Line Chart',
  21046. bar: 'Switch to Bar Chart',
  21047. stack: 'Stack',
  21048. tiled: 'Tile'
  21049. }
  21050. },
  21051. restore: {
  21052. title: 'Restore'
  21053. },
  21054. saveAsImage: {
  21055. title: 'Save as Image',
  21056. lang: ['Right Click to Save Image']
  21057. }
  21058. }
  21059. };
  21060. /*
  21061. * Licensed to the Apache Software Foundation (ASF) under one
  21062. * or more contributor license agreements. See the NOTICE file
  21063. * distributed with this work for additional information
  21064. * regarding copyright ownership. The ASF licenses this file
  21065. * to you under the Apache License, Version 2.0 (the
  21066. * "License"); you may not use this file except in compliance
  21067. * with the License. You may obtain a copy of the License at
  21068. *
  21069. * http://www.apache.org/licenses/LICENSE-2.0
  21070. *
  21071. * Unless required by applicable law or agreed to in writing,
  21072. * software distributed under the License is distributed on an
  21073. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21074. * KIND, either express or implied. See the License for the
  21075. * specific language governing permissions and limitations
  21076. * under the License.
  21077. */
  21078. var aria = function (dom, ecModel) {
  21079. var ariaModel = ecModel.getModel('aria');
  21080. if (!ariaModel.get('show')) {
  21081. return;
  21082. }
  21083. else if (ariaModel.get('description')) {
  21084. dom.setAttribute('aria-label', ariaModel.get('description'));
  21085. return;
  21086. }
  21087. var seriesCnt = 0;
  21088. ecModel.eachSeries(function (seriesModel, idx) {
  21089. ++seriesCnt;
  21090. }, this);
  21091. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  21092. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  21093. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  21094. var ariaLabel;
  21095. if (seriesCnt < 1) {
  21096. // No series, no aria label
  21097. return;
  21098. }
  21099. else {
  21100. var title = getTitle();
  21101. if (title) {
  21102. ariaLabel = replace(getConfig('general.withTitle'), {
  21103. title: title
  21104. });
  21105. }
  21106. else {
  21107. ariaLabel = getConfig('general.withoutTitle');
  21108. }
  21109. var seriesLabels = [];
  21110. var prefix = seriesCnt > 1
  21111. ? 'series.multiple.prefix'
  21112. : 'series.single.prefix';
  21113. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  21114. ecModel.eachSeries(function (seriesModel, idx) {
  21115. if (idx < displaySeriesCnt) {
  21116. var seriesLabel;
  21117. var seriesName = seriesModel.get('name');
  21118. var seriesTpl = 'series.'
  21119. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  21120. seriesLabel = getConfig(seriesName
  21121. ? seriesTpl + 'withName'
  21122. : seriesTpl + 'withoutName');
  21123. seriesLabel = replace(seriesLabel, {
  21124. seriesId: seriesModel.seriesIndex,
  21125. seriesName: seriesModel.get('name'),
  21126. seriesType: getSeriesTypeName(seriesModel.subType)
  21127. });
  21128. var data = seriesModel.getData();
  21129. window.data = data;
  21130. if (data.count() > maxDataCnt) {
  21131. // Show part of data
  21132. seriesLabel += replace(getConfig('data.partialData'), {
  21133. displayCnt: maxDataCnt
  21134. });
  21135. }
  21136. else {
  21137. seriesLabel += getConfig('data.allData');
  21138. }
  21139. var dataLabels = [];
  21140. for (var i = 0; i < data.count(); i++) {
  21141. if (i < maxDataCnt) {
  21142. var name = data.getName(i);
  21143. var value = retrieveRawValue(data, i);
  21144. dataLabels.push(
  21145. replace(
  21146. name
  21147. ? getConfig('data.withName')
  21148. : getConfig('data.withoutName'),
  21149. {
  21150. name: name,
  21151. value: value
  21152. }
  21153. )
  21154. );
  21155. }
  21156. }
  21157. seriesLabel += dataLabels
  21158. .join(getConfig('data.separator.middle'))
  21159. + getConfig('data.separator.end');
  21160. seriesLabels.push(seriesLabel);
  21161. }
  21162. });
  21163. ariaLabel += seriesLabels
  21164. .join(getConfig('series.multiple.separator.middle'))
  21165. + getConfig('series.multiple.separator.end');
  21166. dom.setAttribute('aria-label', ariaLabel);
  21167. }
  21168. function replace(str, keyValues) {
  21169. if (typeof str !== 'string') {
  21170. return str;
  21171. }
  21172. var result = str;
  21173. each$1(keyValues, function (value, key) {
  21174. result = result.replace(
  21175. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21176. value
  21177. );
  21178. });
  21179. return result;
  21180. }
  21181. function getConfig(path) {
  21182. var userConfig = ariaModel.get(path);
  21183. if (userConfig == null) {
  21184. var pathArr = path.split('.');
  21185. var result = lang.aria;
  21186. for (var i = 0; i < pathArr.length; ++i) {
  21187. result = result[pathArr[i]];
  21188. }
  21189. return result;
  21190. }
  21191. else {
  21192. return userConfig;
  21193. }
  21194. }
  21195. function getTitle() {
  21196. var title = ecModel.getModel('title').option;
  21197. if (title && title.length) {
  21198. title = title[0];
  21199. }
  21200. return title && title.text;
  21201. }
  21202. function getSeriesTypeName(type) {
  21203. return lang.series.typeNames[type] || '自定义图';
  21204. }
  21205. };
  21206. /*
  21207. * Licensed to the Apache Software Foundation (ASF) under one
  21208. * or more contributor license agreements. See the NOTICE file
  21209. * distributed with this work for additional information
  21210. * regarding copyright ownership. The ASF licenses this file
  21211. * to you under the Apache License, Version 2.0 (the
  21212. * "License"); you may not use this file except in compliance
  21213. * with the License. You may obtain a copy of the License at
  21214. *
  21215. * http://www.apache.org/licenses/LICENSE-2.0
  21216. *
  21217. * Unless required by applicable law or agreed to in writing,
  21218. * software distributed under the License is distributed on an
  21219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21220. * KIND, either express or implied. See the License for the
  21221. * specific language governing permissions and limitations
  21222. * under the License.
  21223. */
  21224. var PI$1 = Math.PI;
  21225. /**
  21226. * @param {module:echarts/ExtensionAPI} api
  21227. * @param {Object} [opts]
  21228. * @param {string} [opts.text]
  21229. * @param {string} [opts.color]
  21230. * @param {string} [opts.textColor]
  21231. * @return {module:zrender/Element}
  21232. */
  21233. var loadingDefault = function (api, opts) {
  21234. opts = opts || {};
  21235. defaults(opts, {
  21236. text: 'loading',
  21237. color: '#c23531',
  21238. textColor: '#000',
  21239. maskColor: 'rgba(255, 255, 255, 0.8)',
  21240. zlevel: 0
  21241. });
  21242. var mask = new Rect({
  21243. style: {
  21244. fill: opts.maskColor
  21245. },
  21246. zlevel: opts.zlevel,
  21247. z: 10000
  21248. });
  21249. var arc = new Arc({
  21250. shape: {
  21251. startAngle: -PI$1 / 2,
  21252. endAngle: -PI$1 / 2 + 0.1,
  21253. r: 10
  21254. },
  21255. style: {
  21256. stroke: opts.color,
  21257. lineCap: 'round',
  21258. lineWidth: 5
  21259. },
  21260. zlevel: opts.zlevel,
  21261. z: 10001
  21262. });
  21263. var labelRect = new Rect({
  21264. style: {
  21265. fill: 'none',
  21266. text: opts.text,
  21267. textPosition: 'right',
  21268. textDistance: 10,
  21269. textFill: opts.textColor
  21270. },
  21271. zlevel: opts.zlevel,
  21272. z: 10001
  21273. });
  21274. arc.animateShape(true)
  21275. .when(1000, {
  21276. endAngle: PI$1 * 3 / 2
  21277. })
  21278. .start('circularInOut');
  21279. arc.animateShape(true)
  21280. .when(1000, {
  21281. startAngle: PI$1 * 3 / 2
  21282. })
  21283. .delay(300)
  21284. .start('circularInOut');
  21285. var group = new Group();
  21286. group.add(arc);
  21287. group.add(labelRect);
  21288. group.add(mask);
  21289. // Inject resize
  21290. group.resize = function () {
  21291. var cx = api.getWidth() / 2;
  21292. var cy = api.getHeight() / 2;
  21293. arc.setShape({
  21294. cx: cx,
  21295. cy: cy
  21296. });
  21297. var r = arc.shape.r;
  21298. labelRect.setShape({
  21299. x: cx - r,
  21300. y: cy - r,
  21301. width: r * 2,
  21302. height: r * 2
  21303. });
  21304. mask.setShape({
  21305. x: 0,
  21306. y: 0,
  21307. width: api.getWidth(),
  21308. height: api.getHeight()
  21309. });
  21310. };
  21311. group.resize();
  21312. return group;
  21313. };
  21314. /*
  21315. * Licensed to the Apache Software Foundation (ASF) under one
  21316. * or more contributor license agreements. See the NOTICE file
  21317. * distributed with this work for additional information
  21318. * regarding copyright ownership. The ASF licenses this file
  21319. * to you under the Apache License, Version 2.0 (the
  21320. * "License"); you may not use this file except in compliance
  21321. * with the License. You may obtain a copy of the License at
  21322. *
  21323. * http://www.apache.org/licenses/LICENSE-2.0
  21324. *
  21325. * Unless required by applicable law or agreed to in writing,
  21326. * software distributed under the License is distributed on an
  21327. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21328. * KIND, either express or implied. See the License for the
  21329. * specific language governing permissions and limitations
  21330. * under the License.
  21331. */
  21332. /**
  21333. * @module echarts/stream/Scheduler
  21334. */
  21335. /**
  21336. * @constructor
  21337. */
  21338. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21339. this.ecInstance = ecInstance;
  21340. this.api = api;
  21341. this.unfinished;
  21342. // Fix current processors in case that in some rear cases that
  21343. // processors might be registered after echarts instance created.
  21344. // Register processors incrementally for a echarts instance is
  21345. // not supported by this stream architecture.
  21346. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21347. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21348. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21349. /**
  21350. * @private
  21351. * @type {
  21352. * [handlerUID: string]: {
  21353. * seriesTaskMap?: {
  21354. * [seriesUID: string]: Task
  21355. * },
  21356. * overallTask?: Task
  21357. * }
  21358. * }
  21359. */
  21360. this._stageTaskMap = createHashMap();
  21361. }
  21362. var proto = Scheduler.prototype;
  21363. /**
  21364. * @param {module:echarts/model/Global} ecModel
  21365. * @param {Object} payload
  21366. */
  21367. proto.restoreData = function (ecModel, payload) {
  21368. // TODO: Only restroe needed series and components, but not all components.
  21369. // Currently `restoreData` of all of the series and component will be called.
  21370. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21371. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21372. // and some components like coordinate system, axes, dataZoom, visualMap only
  21373. // need their target series refresh.
  21374. // (1) If we are implementing this feature some day, we should consider these cases:
  21375. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21376. // on the settings of `dataZoom`), it should be re-performed if the component
  21377. // is modified by `setOption`.
  21378. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21379. // it should be re-performed when the result array of `getTargetSeries` changed.
  21380. // We use `dependencies` to cover these issues.
  21381. // (3) How to update target series when coordinate system related components modified.
  21382. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21383. // and this case all of the tasks will be set as dirty.
  21384. ecModel.restoreData(payload);
  21385. // Theoretically an overall task not only depends on each of its target series, but also
  21386. // depends on all of the series.
  21387. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21388. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21389. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21390. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21391. // probably cause state chaos (consider `dataZoomProcessor`).
  21392. this._stageTaskMap.each(function (taskRecord) {
  21393. var overallTask = taskRecord.overallTask;
  21394. overallTask && overallTask.dirty();
  21395. });
  21396. };
  21397. // If seriesModel provided, incremental threshold is check by series data.
  21398. proto.getPerformArgs = function (task, isBlock) {
  21399. // For overall task
  21400. if (!task.__pipeline) {
  21401. return;
  21402. }
  21403. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21404. var pCtx = pipeline.context;
  21405. var incremental = !isBlock
  21406. && pipeline.progressiveEnabled
  21407. && (!pCtx || pCtx.progressiveRender)
  21408. && task.__idxInPipeline > pipeline.blockIndex;
  21409. var step = incremental ? pipeline.step : null;
  21410. var modDataCount = pCtx && pCtx.modDataCount;
  21411. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  21412. return {step: step, modBy: modBy, modDataCount: modDataCount};
  21413. };
  21414. proto.getPipeline = function (pipelineId) {
  21415. return this._pipelineMap.get(pipelineId);
  21416. };
  21417. /**
  21418. * Current, progressive rendering starts from visual and layout.
  21419. * Always detect render mode in the same stage, avoiding that incorrect
  21420. * detection caused by data filtering.
  21421. * Caution:
  21422. * `updateStreamModes` use `seriesModel.getData()`.
  21423. */
  21424. proto.updateStreamModes = function (seriesModel, view) {
  21425. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21426. var data = seriesModel.getData();
  21427. var dataLen = data.count();
  21428. // `progressiveRender` means that can render progressively in each
  21429. // animation frame. Note that some types of series do not provide
  21430. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21431. // use the term `incremental` but not `progressive` to describe the
  21432. // case that `chart.appendData`.
  21433. var progressiveRender = pipeline.progressiveEnabled
  21434. && view.incrementalPrepareRender
  21435. && dataLen >= pipeline.threshold;
  21436. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  21437. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21438. // see `test/candlestick-large3.html`
  21439. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21440. seriesModel.pipelineContext = pipeline.context = {
  21441. progressiveRender: progressiveRender,
  21442. modDataCount: modDataCount,
  21443. large: large
  21444. };
  21445. };
  21446. proto.restorePipelines = function (ecModel) {
  21447. var scheduler = this;
  21448. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21449. ecModel.eachSeries(function (seriesModel) {
  21450. var progressive = seriesModel.getProgressive();
  21451. var pipelineId = seriesModel.uid;
  21452. pipelineMap.set(pipelineId, {
  21453. id: pipelineId,
  21454. head: null,
  21455. tail: null,
  21456. threshold: seriesModel.getProgressiveThreshold(),
  21457. progressiveEnabled: progressive
  21458. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21459. blockIndex: -1,
  21460. step: Math.round(progressive || 700),
  21461. count: 0
  21462. });
  21463. pipe(scheduler, seriesModel, seriesModel.dataTask);
  21464. });
  21465. };
  21466. proto.prepareStageTasks = function () {
  21467. var stageTaskMap = this._stageTaskMap;
  21468. var ecModel = this.ecInstance.getModel();
  21469. var api = this.api;
  21470. each$1(this._allHandlers, function (handler) {
  21471. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  21472. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  21473. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  21474. }, this);
  21475. };
  21476. proto.prepareView = function (view, model, ecModel, api) {
  21477. var renderTask = view.renderTask;
  21478. var context = renderTask.context;
  21479. context.model = model;
  21480. context.ecModel = ecModel;
  21481. context.api = api;
  21482. renderTask.__block = !view.incrementalPrepareRender;
  21483. pipe(this, model, renderTask);
  21484. };
  21485. proto.performDataProcessorTasks = function (ecModel, payload) {
  21486. // If we do not use `block` here, it should be considered when to update modes.
  21487. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  21488. };
  21489. // opt
  21490. // opt.visualType: 'visual' or 'layout'
  21491. // opt.setDirty
  21492. proto.performVisualTasks = function (ecModel, payload, opt) {
  21493. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  21494. };
  21495. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  21496. opt = opt || {};
  21497. var unfinished;
  21498. each$1(stageHandlers, function (stageHandler, idx) {
  21499. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21500. return;
  21501. }
  21502. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21503. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21504. var overallTask = stageHandlerRecord.overallTask;
  21505. if (overallTask) {
  21506. var overallNeedDirty;
  21507. var agentStubMap = overallTask.agentStubMap;
  21508. agentStubMap.each(function (stub) {
  21509. if (needSetDirty(opt, stub)) {
  21510. stub.dirty();
  21511. overallNeedDirty = true;
  21512. }
  21513. });
  21514. overallNeedDirty && overallTask.dirty();
  21515. updatePayload(overallTask, payload);
  21516. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  21517. // Execute stubs firstly, which may set the overall task dirty,
  21518. // then execute the overall task. And stub will call seriesModel.setData,
  21519. // which ensures that in the overallTask seriesModel.getData() will not
  21520. // return incorrect data.
  21521. agentStubMap.each(function (stub) {
  21522. stub.perform(performArgs);
  21523. });
  21524. unfinished |= overallTask.perform(performArgs);
  21525. }
  21526. else if (seriesTaskMap) {
  21527. seriesTaskMap.each(function (task, pipelineId) {
  21528. if (needSetDirty(opt, task)) {
  21529. task.dirty();
  21530. }
  21531. var performArgs = scheduler.getPerformArgs(task, opt.block);
  21532. performArgs.skip = !stageHandler.performRawSeries
  21533. && ecModel.isSeriesFiltered(task.context.model);
  21534. updatePayload(task, payload);
  21535. unfinished |= task.perform(performArgs);
  21536. });
  21537. }
  21538. });
  21539. function needSetDirty(opt, task) {
  21540. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21541. }
  21542. scheduler.unfinished |= unfinished;
  21543. }
  21544. proto.performSeriesTasks = function (ecModel) {
  21545. var unfinished;
  21546. ecModel.eachSeries(function (seriesModel) {
  21547. // Progress to the end for dataInit and dataRestore.
  21548. unfinished |= seriesModel.dataTask.perform();
  21549. });
  21550. this.unfinished |= unfinished;
  21551. };
  21552. proto.plan = function () {
  21553. // Travel pipelines, check block.
  21554. this._pipelineMap.each(function (pipeline) {
  21555. var task = pipeline.tail;
  21556. do {
  21557. if (task.__block) {
  21558. pipeline.blockIndex = task.__idxInPipeline;
  21559. break;
  21560. }
  21561. task = task.getUpstream();
  21562. }
  21563. while (task);
  21564. });
  21565. };
  21566. var updatePayload = proto.updatePayload = function (task, payload) {
  21567. payload !== 'remain' && (task.context.payload = payload);
  21568. };
  21569. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21570. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  21571. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  21572. var seriesType = stageHandler.seriesType;
  21573. var getTargetSeries = stageHandler.getTargetSeries;
  21574. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21575. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21576. // it works but it may cause other irrelevant charts blocked.
  21577. if (stageHandler.createOnAllSeries) {
  21578. ecModel.eachRawSeries(create);
  21579. }
  21580. else if (seriesType) {
  21581. ecModel.eachRawSeriesByType(seriesType, create);
  21582. }
  21583. else if (getTargetSeries) {
  21584. getTargetSeries(ecModel, api).each(create);
  21585. }
  21586. function create(seriesModel) {
  21587. var pipelineId = seriesModel.uid;
  21588. // Init tasks for each seriesModel only once.
  21589. // Reuse original task instance.
  21590. var task = seriesTaskMap.get(pipelineId)
  21591. || seriesTaskMap.set(pipelineId, createTask({
  21592. plan: seriesTaskPlan,
  21593. reset: seriesTaskReset,
  21594. count: seriesTaskCount
  21595. }));
  21596. task.context = {
  21597. model: seriesModel,
  21598. ecModel: ecModel,
  21599. api: api,
  21600. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21601. plan: stageHandler.plan,
  21602. reset: stageHandler.reset,
  21603. scheduler: scheduler
  21604. };
  21605. pipe(scheduler, seriesModel, task);
  21606. }
  21607. // Clear unused series tasks.
  21608. var pipelineMap = scheduler._pipelineMap;
  21609. seriesTaskMap.each(function (task, pipelineId) {
  21610. if (!pipelineMap.get(pipelineId)) {
  21611. task.dispose();
  21612. seriesTaskMap.removeKey(pipelineId);
  21613. }
  21614. });
  21615. }
  21616. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21617. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  21618. // For overall task, the function only be called on reset stage.
  21619. || createTask({reset: overallTaskReset});
  21620. overallTask.context = {
  21621. ecModel: ecModel,
  21622. api: api,
  21623. overallReset: stageHandler.overallReset,
  21624. scheduler: scheduler
  21625. };
  21626. // Reuse orignal stubs.
  21627. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  21628. var seriesType = stageHandler.seriesType;
  21629. var getTargetSeries = stageHandler.getTargetSeries;
  21630. var overallProgress = true;
  21631. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  21632. // An overall task with seriesType detected or has `getTargetSeries`, we add
  21633. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21634. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21635. // we set the pipeline block.
  21636. if (seriesType) {
  21637. ecModel.eachRawSeriesByType(seriesType, createStub);
  21638. }
  21639. else if (getTargetSeries) {
  21640. getTargetSeries(ecModel, api).each(createStub);
  21641. }
  21642. // Otherwise, (usually it is legancy case), the overall task will only be
  21643. // executed when upstream dirty. Otherwise the progressive rendering of all
  21644. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  21645. // dirty info from upsteam.
  21646. else {
  21647. overallProgress = false;
  21648. each$1(ecModel.getSeries(), createStub);
  21649. }
  21650. function createStub(seriesModel) {
  21651. var pipelineId = seriesModel.uid;
  21652. var stub = agentStubMap.get(pipelineId);
  21653. if (!stub) {
  21654. stub = agentStubMap.set(pipelineId, createTask(
  21655. {reset: stubReset, onDirty: stubOnDirty}
  21656. ));
  21657. // When the result of `getTargetSeries` changed, the overallTask
  21658. // should be set as dirty and re-performed.
  21659. overallTask.dirty();
  21660. }
  21661. stub.context = {
  21662. model: seriesModel,
  21663. overallProgress: overallProgress,
  21664. modifyOutputEnd: modifyOutputEnd
  21665. };
  21666. stub.agent = overallTask;
  21667. stub.__block = overallProgress;
  21668. pipe(scheduler, seriesModel, stub);
  21669. }
  21670. // Clear unused stubs.
  21671. var pipelineMap = scheduler._pipelineMap;
  21672. agentStubMap.each(function (stub, pipelineId) {
  21673. if (!pipelineMap.get(pipelineId)) {
  21674. stub.dispose();
  21675. // When the result of `getTargetSeries` changed, the overallTask
  21676. // should be set as dirty and re-performed.
  21677. overallTask.dirty();
  21678. agentStubMap.removeKey(pipelineId);
  21679. }
  21680. });
  21681. }
  21682. function overallTaskReset(context) {
  21683. context.overallReset(
  21684. context.ecModel, context.api, context.payload
  21685. );
  21686. }
  21687. function stubReset(context, upstreamContext) {
  21688. return context.overallProgress && stubProgress;
  21689. }
  21690. function stubProgress() {
  21691. this.agent.dirty();
  21692. this.getDownstream().dirty();
  21693. }
  21694. function stubOnDirty() {
  21695. this.agent && this.agent.dirty();
  21696. }
  21697. function seriesTaskPlan(context) {
  21698. return context.plan && context.plan(
  21699. context.model, context.ecModel, context.api, context.payload
  21700. );
  21701. }
  21702. function seriesTaskReset(context) {
  21703. if (context.useClearVisual) {
  21704. context.data.clearAllVisual();
  21705. }
  21706. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  21707. context.model, context.ecModel, context.api, context.payload
  21708. ));
  21709. return resetDefines.length > 1
  21710. ? map(resetDefines, function (v, idx) {
  21711. return makeSeriesTaskProgress(idx);
  21712. })
  21713. : singleSeriesTaskProgress;
  21714. }
  21715. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  21716. function makeSeriesTaskProgress(resetDefineIdx) {
  21717. return function (params, context) {
  21718. var data = context.data;
  21719. var resetDefine = context.resetDefines[resetDefineIdx];
  21720. if (resetDefine && resetDefine.dataEach) {
  21721. for (var i = params.start; i < params.end; i++) {
  21722. resetDefine.dataEach(data, i);
  21723. }
  21724. }
  21725. else if (resetDefine && resetDefine.progress) {
  21726. resetDefine.progress(params, data);
  21727. }
  21728. };
  21729. }
  21730. function seriesTaskCount(context) {
  21731. return context.data.count();
  21732. }
  21733. function pipe(scheduler, seriesModel, task) {
  21734. var pipelineId = seriesModel.uid;
  21735. var pipeline = scheduler._pipelineMap.get(pipelineId);
  21736. !pipeline.head && (pipeline.head = task);
  21737. pipeline.tail && pipeline.tail.pipe(task);
  21738. pipeline.tail = task;
  21739. task.__idxInPipeline = pipeline.count++;
  21740. task.__pipeline = pipeline;
  21741. }
  21742. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  21743. if (isFunction$1(stageHandler)) {
  21744. stageHandler = {
  21745. overallReset: stageHandler,
  21746. seriesType: detectSeriseType(stageHandler)
  21747. };
  21748. }
  21749. stageHandler.uid = getUID('stageHandler');
  21750. visualType && (stageHandler.visualType = visualType);
  21751. return stageHandler;
  21752. };
  21753. /**
  21754. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  21755. * To ensure that they can work normally, they should work in block mode, that is,
  21756. * they should not be started util the previous tasks finished. So they cause the
  21757. * progressive rendering disabled. We try to detect the series type, to narrow down
  21758. * the block range to only the series type they concern, but not all series.
  21759. */
  21760. function detectSeriseType(legacyFunc) {
  21761. seriesType = null;
  21762. try {
  21763. // Assume there is no async when calling `eachSeriesByType`.
  21764. legacyFunc(ecModelMock, apiMock);
  21765. }
  21766. catch (e) {
  21767. }
  21768. return seriesType;
  21769. }
  21770. var ecModelMock = {};
  21771. var apiMock = {};
  21772. var seriesType;
  21773. mockMethods(ecModelMock, GlobalModel);
  21774. mockMethods(apiMock, ExtensionAPI);
  21775. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  21776. seriesType = type;
  21777. };
  21778. ecModelMock.eachComponent = function (cond) {
  21779. if (cond.mainType === 'series' && cond.subType) {
  21780. seriesType = cond.subType;
  21781. }
  21782. };
  21783. function mockMethods(target, Clz) {
  21784. /* eslint-disable */
  21785. for (var name in Clz.prototype) {
  21786. // Do not use hasOwnProperty
  21787. target[name] = noop;
  21788. }
  21789. /* eslint-enable */
  21790. }
  21791. /*
  21792. * Licensed to the Apache Software Foundation (ASF) under one
  21793. * or more contributor license agreements. See the NOTICE file
  21794. * distributed with this work for additional information
  21795. * regarding copyright ownership. The ASF licenses this file
  21796. * to you under the Apache License, Version 2.0 (the
  21797. * "License"); you may not use this file except in compliance
  21798. * with the License. You may obtain a copy of the License at
  21799. *
  21800. * http://www.apache.org/licenses/LICENSE-2.0
  21801. *
  21802. * Unless required by applicable law or agreed to in writing,
  21803. * software distributed under the License is distributed on an
  21804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21805. * KIND, either express or implied. See the License for the
  21806. * specific language governing permissions and limitations
  21807. * under the License.
  21808. */
  21809. var colorAll = [
  21810. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  21811. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  21812. ];
  21813. var lightTheme = {
  21814. color: colorAll,
  21815. colorLayer: [
  21816. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  21817. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  21818. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  21819. colorAll
  21820. ]
  21821. };
  21822. /*
  21823. * Licensed to the Apache Software Foundation (ASF) under one
  21824. * or more contributor license agreements. See the NOTICE file
  21825. * distributed with this work for additional information
  21826. * regarding copyright ownership. The ASF licenses this file
  21827. * to you under the Apache License, Version 2.0 (the
  21828. * "License"); you may not use this file except in compliance
  21829. * with the License. You may obtain a copy of the License at
  21830. *
  21831. * http://www.apache.org/licenses/LICENSE-2.0
  21832. *
  21833. * Unless required by applicable law or agreed to in writing,
  21834. * software distributed under the License is distributed on an
  21835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21836. * KIND, either express or implied. See the License for the
  21837. * specific language governing permissions and limitations
  21838. * under the License.
  21839. */
  21840. var contrastColor = '#eee';
  21841. var axisCommon = function () {
  21842. return {
  21843. axisLine: {
  21844. lineStyle: {
  21845. color: contrastColor
  21846. }
  21847. },
  21848. axisTick: {
  21849. lineStyle: {
  21850. color: contrastColor
  21851. }
  21852. },
  21853. axisLabel: {
  21854. textStyle: {
  21855. color: contrastColor
  21856. }
  21857. },
  21858. splitLine: {
  21859. lineStyle: {
  21860. type: 'dashed',
  21861. color: '#aaa'
  21862. }
  21863. },
  21864. splitArea: {
  21865. areaStyle: {
  21866. color: contrastColor
  21867. }
  21868. }
  21869. };
  21870. };
  21871. var colorPalette = [
  21872. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  21873. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  21874. ];
  21875. var theme = {
  21876. color: colorPalette,
  21877. backgroundColor: '#333',
  21878. tooltip: {
  21879. axisPointer: {
  21880. lineStyle: {
  21881. color: contrastColor
  21882. },
  21883. crossStyle: {
  21884. color: contrastColor
  21885. }
  21886. }
  21887. },
  21888. legend: {
  21889. textStyle: {
  21890. color: contrastColor
  21891. }
  21892. },
  21893. textStyle: {
  21894. color: contrastColor
  21895. },
  21896. title: {
  21897. textStyle: {
  21898. color: contrastColor
  21899. }
  21900. },
  21901. toolbox: {
  21902. iconStyle: {
  21903. normal: {
  21904. borderColor: contrastColor
  21905. }
  21906. }
  21907. },
  21908. dataZoom: {
  21909. textStyle: {
  21910. color: contrastColor
  21911. }
  21912. },
  21913. visualMap: {
  21914. textStyle: {
  21915. color: contrastColor
  21916. }
  21917. },
  21918. timeline: {
  21919. lineStyle: {
  21920. color: contrastColor
  21921. },
  21922. itemStyle: {
  21923. normal: {
  21924. color: colorPalette[1]
  21925. }
  21926. },
  21927. label: {
  21928. normal: {
  21929. textStyle: {
  21930. color: contrastColor
  21931. }
  21932. }
  21933. },
  21934. controlStyle: {
  21935. normal: {
  21936. color: contrastColor,
  21937. borderColor: contrastColor
  21938. }
  21939. }
  21940. },
  21941. timeAxis: axisCommon(),
  21942. logAxis: axisCommon(),
  21943. valueAxis: axisCommon(),
  21944. categoryAxis: axisCommon(),
  21945. line: {
  21946. symbol: 'circle'
  21947. },
  21948. graph: {
  21949. color: colorPalette
  21950. },
  21951. gauge: {
  21952. title: {
  21953. textStyle: {
  21954. color: contrastColor
  21955. }
  21956. }
  21957. },
  21958. candlestick: {
  21959. itemStyle: {
  21960. normal: {
  21961. color: '#FD1050',
  21962. color0: '#0CF49B',
  21963. borderColor: '#FD1050',
  21964. borderColor0: '#0CF49B'
  21965. }
  21966. }
  21967. }
  21968. };
  21969. theme.categoryAxis.splitLine.show = false;
  21970. /*
  21971. * Licensed to the Apache Software Foundation (ASF) under one
  21972. * or more contributor license agreements. See the NOTICE file
  21973. * distributed with this work for additional information
  21974. * regarding copyright ownership. The ASF licenses this file
  21975. * to you under the Apache License, Version 2.0 (the
  21976. * "License"); you may not use this file except in compliance
  21977. * with the License. You may obtain a copy of the License at
  21978. *
  21979. * http://www.apache.org/licenses/LICENSE-2.0
  21980. *
  21981. * Unless required by applicable law or agreed to in writing,
  21982. * software distributed under the License is distributed on an
  21983. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21984. * KIND, either express or implied. See the License for the
  21985. * specific language governing permissions and limitations
  21986. * under the License.
  21987. */
  21988. /**
  21989. * This module is imported by echarts directly.
  21990. *
  21991. * Notice:
  21992. * Always keep this file exists for backward compatibility.
  21993. * Because before 4.1.0, dataset is an optional component,
  21994. * some users may import this module manually.
  21995. */
  21996. ComponentModel.extend({
  21997. type: 'dataset',
  21998. /**
  21999. * @protected
  22000. */
  22001. defaultOption: {
  22002. // 'row', 'column'
  22003. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  22004. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  22005. sourceHeader: null,
  22006. dimensions: null,
  22007. source: null
  22008. },
  22009. optionUpdated: function () {
  22010. detectSourceFormat(this);
  22011. }
  22012. });
  22013. Component.extend({
  22014. type: 'dataset'
  22015. });
  22016. /**
  22017. * 椭圆形状
  22018. * @module zrender/graphic/shape/Ellipse
  22019. */
  22020. var Ellipse = Path.extend({
  22021. type: 'ellipse',
  22022. shape: {
  22023. cx: 0, cy: 0,
  22024. rx: 0, ry: 0
  22025. },
  22026. buildPath: function (ctx, shape) {
  22027. var k = 0.5522848;
  22028. var x = shape.cx;
  22029. var y = shape.cy;
  22030. var a = shape.rx;
  22031. var b = shape.ry;
  22032. var ox = a * k; // 水平控制点偏移量
  22033. var oy = b * k; // 垂直控制点偏移量
  22034. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  22035. ctx.moveTo(x - a, y);
  22036. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  22037. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  22038. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  22039. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  22040. ctx.closePath();
  22041. }
  22042. });
  22043. // import RadialGradient from '../graphic/RadialGradient';
  22044. // import Pattern from '../graphic/Pattern';
  22045. // import * as vector from '../core/vector';
  22046. // Most of the values can be separated by comma and/or white space.
  22047. var DILIMITER_REG = /[\s,]+/;
  22048. /**
  22049. * For big svg string, this method might be time consuming.
  22050. *
  22051. * @param {string} svg xml string
  22052. * @return {Object} xml root.
  22053. */
  22054. function parseXML(svg) {
  22055. if (isString(svg)) {
  22056. var parser = new DOMParser();
  22057. svg = parser.parseFromString(svg, 'text/xml');
  22058. }
  22059. // Document node. If using $.get, doc node may be input.
  22060. if (svg.nodeType === 9) {
  22061. svg = svg.firstChild;
  22062. }
  22063. // nodeName of <!DOCTYPE svg> is also 'svg'.
  22064. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  22065. svg = svg.nextSibling;
  22066. }
  22067. return svg;
  22068. }
  22069. function SVGParser() {
  22070. this._defs = {};
  22071. this._root = null;
  22072. this._isDefine = false;
  22073. this._isText = false;
  22074. }
  22075. SVGParser.prototype.parse = function (xml, opt) {
  22076. opt = opt || {};
  22077. var svg = parseXML(xml);
  22078. if (!svg) {
  22079. throw new Error('Illegal svg');
  22080. }
  22081. var root = new Group();
  22082. this._root = root;
  22083. // parse view port
  22084. var viewBox = svg.getAttribute('viewBox') || '';
  22085. // If width/height not specified, means "100%" of `opt.width/height`.
  22086. // TODO: Other percent value not supported yet.
  22087. var width = parseFloat(svg.getAttribute('width') || opt.width);
  22088. var height = parseFloat(svg.getAttribute('height') || opt.height);
  22089. // If width/height not specified, set as null for output.
  22090. isNaN(width) && (width = null);
  22091. isNaN(height) && (height = null);
  22092. // Apply inline style on svg element.
  22093. parseAttributes(svg, root, null, true);
  22094. var child = svg.firstChild;
  22095. while (child) {
  22096. this._parseNode(child, root);
  22097. child = child.nextSibling;
  22098. }
  22099. var viewBoxRect;
  22100. var viewBoxTransform;
  22101. if (viewBox) {
  22102. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  22103. // Some invalid case like viewBox: 'none'.
  22104. if (viewBoxArr.length >= 4) {
  22105. viewBoxRect = {
  22106. x: parseFloat(viewBoxArr[0] || 0),
  22107. y: parseFloat(viewBoxArr[1] || 0),
  22108. width: parseFloat(viewBoxArr[2]),
  22109. height: parseFloat(viewBoxArr[3])
  22110. };
  22111. }
  22112. }
  22113. if (viewBoxRect && width != null && height != null) {
  22114. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  22115. if (!opt.ignoreViewBox) {
  22116. // If set transform on the output group, it probably bring trouble when
  22117. // some users only intend to show the clipped content inside the viewBox,
  22118. // but not intend to transform the output group. So we keep the output
  22119. // group no transform. If the user intend to use the viewBox as a
  22120. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  22121. // manually according to the viewBox info in the output of this method.
  22122. var elRoot = root;
  22123. root = new Group();
  22124. root.add(elRoot);
  22125. elRoot.scale = viewBoxTransform.scale.slice();
  22126. elRoot.position = viewBoxTransform.position.slice();
  22127. }
  22128. }
  22129. // Some shapes might be overflow the viewport, which should be
  22130. // clipped despite whether the viewBox is used, as the SVG does.
  22131. if (!opt.ignoreRootClip && width != null && height != null) {
  22132. root.setClipPath(new Rect({
  22133. shape: {x: 0, y: 0, width: width, height: height}
  22134. }));
  22135. }
  22136. // Set width/height on group just for output the viewport size.
  22137. return {
  22138. root: root,
  22139. width: width,
  22140. height: height,
  22141. viewBoxRect: viewBoxRect,
  22142. viewBoxTransform: viewBoxTransform
  22143. };
  22144. };
  22145. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  22146. var nodeName = xmlNode.nodeName.toLowerCase();
  22147. // TODO
  22148. // support <style>...</style> in svg, where nodeName is 'style',
  22149. // CSS classes is defined globally wherever the style tags are declared.
  22150. if (nodeName === 'defs') {
  22151. // define flag
  22152. this._isDefine = true;
  22153. }
  22154. else if (nodeName === 'text') {
  22155. this._isText = true;
  22156. }
  22157. var el;
  22158. if (this._isDefine) {
  22159. var parser = defineParsers[nodeName];
  22160. if (parser) {
  22161. var def = parser.call(this, xmlNode);
  22162. var id = xmlNode.getAttribute('id');
  22163. if (id) {
  22164. this._defs[id] = def;
  22165. }
  22166. }
  22167. }
  22168. else {
  22169. var parser = nodeParsers[nodeName];
  22170. if (parser) {
  22171. el = parser.call(this, xmlNode, parentGroup);
  22172. parentGroup.add(el);
  22173. }
  22174. }
  22175. var child = xmlNode.firstChild;
  22176. while (child) {
  22177. if (child.nodeType === 1) {
  22178. this._parseNode(child, el);
  22179. }
  22180. // Is text
  22181. if (child.nodeType === 3 && this._isText) {
  22182. this._parseText(child, el);
  22183. }
  22184. child = child.nextSibling;
  22185. }
  22186. // Quit define
  22187. if (nodeName === 'defs') {
  22188. this._isDefine = false;
  22189. }
  22190. else if (nodeName === 'text') {
  22191. this._isText = false;
  22192. }
  22193. };
  22194. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  22195. if (xmlNode.nodeType === 1) {
  22196. var dx = xmlNode.getAttribute('dx') || 0;
  22197. var dy = xmlNode.getAttribute('dy') || 0;
  22198. this._textX += parseFloat(dx);
  22199. this._textY += parseFloat(dy);
  22200. }
  22201. var text = new Text({
  22202. style: {
  22203. text: xmlNode.textContent,
  22204. transformText: true
  22205. },
  22206. position: [this._textX || 0, this._textY || 0]
  22207. });
  22208. inheritStyle(parentGroup, text);
  22209. parseAttributes(xmlNode, text, this._defs);
  22210. var fontSize = text.style.fontSize;
  22211. if (fontSize && fontSize < 9) {
  22212. // PENDING
  22213. text.style.fontSize = 9;
  22214. text.scale = text.scale || [1, 1];
  22215. text.scale[0] *= fontSize / 9;
  22216. text.scale[1] *= fontSize / 9;
  22217. }
  22218. var rect = text.getBoundingRect();
  22219. this._textX += rect.width;
  22220. parentGroup.add(text);
  22221. return text;
  22222. };
  22223. var nodeParsers = {
  22224. 'g': function (xmlNode, parentGroup) {
  22225. var g = new Group();
  22226. inheritStyle(parentGroup, g);
  22227. parseAttributes(xmlNode, g, this._defs);
  22228. return g;
  22229. },
  22230. 'rect': function (xmlNode, parentGroup) {
  22231. var rect = new Rect();
  22232. inheritStyle(parentGroup, rect);
  22233. parseAttributes(xmlNode, rect, this._defs);
  22234. rect.setShape({
  22235. x: parseFloat(xmlNode.getAttribute('x') || 0),
  22236. y: parseFloat(xmlNode.getAttribute('y') || 0),
  22237. width: parseFloat(xmlNode.getAttribute('width') || 0),
  22238. height: parseFloat(xmlNode.getAttribute('height') || 0)
  22239. });
  22240. // console.log(xmlNode.getAttribute('transform'));
  22241. // console.log(rect.transform);
  22242. return rect;
  22243. },
  22244. 'circle': function (xmlNode, parentGroup) {
  22245. var circle = new Circle();
  22246. inheritStyle(parentGroup, circle);
  22247. parseAttributes(xmlNode, circle, this._defs);
  22248. circle.setShape({
  22249. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22250. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22251. r: parseFloat(xmlNode.getAttribute('r') || 0)
  22252. });
  22253. return circle;
  22254. },
  22255. 'line': function (xmlNode, parentGroup) {
  22256. var line = new Line();
  22257. inheritStyle(parentGroup, line);
  22258. parseAttributes(xmlNode, line, this._defs);
  22259. line.setShape({
  22260. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  22261. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  22262. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  22263. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  22264. });
  22265. return line;
  22266. },
  22267. 'ellipse': function (xmlNode, parentGroup) {
  22268. var ellipse = new Ellipse();
  22269. inheritStyle(parentGroup, ellipse);
  22270. parseAttributes(xmlNode, ellipse, this._defs);
  22271. ellipse.setShape({
  22272. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22273. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22274. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  22275. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  22276. });
  22277. return ellipse;
  22278. },
  22279. 'polygon': function (xmlNode, parentGroup) {
  22280. var points = xmlNode.getAttribute('points');
  22281. if (points) {
  22282. points = parsePoints(points);
  22283. }
  22284. var polygon = new Polygon({
  22285. shape: {
  22286. points: points || []
  22287. }
  22288. });
  22289. inheritStyle(parentGroup, polygon);
  22290. parseAttributes(xmlNode, polygon, this._defs);
  22291. return polygon;
  22292. },
  22293. 'polyline': function (xmlNode, parentGroup) {
  22294. var path = new Path();
  22295. inheritStyle(parentGroup, path);
  22296. parseAttributes(xmlNode, path, this._defs);
  22297. var points = xmlNode.getAttribute('points');
  22298. if (points) {
  22299. points = parsePoints(points);
  22300. }
  22301. var polyline = new Polyline({
  22302. shape: {
  22303. points: points || []
  22304. }
  22305. });
  22306. return polyline;
  22307. },
  22308. 'image': function (xmlNode, parentGroup) {
  22309. var img = new ZImage();
  22310. inheritStyle(parentGroup, img);
  22311. parseAttributes(xmlNode, img, this._defs);
  22312. img.setStyle({
  22313. image: xmlNode.getAttribute('xlink:href'),
  22314. x: xmlNode.getAttribute('x'),
  22315. y: xmlNode.getAttribute('y'),
  22316. width: xmlNode.getAttribute('width'),
  22317. height: xmlNode.getAttribute('height')
  22318. });
  22319. return img;
  22320. },
  22321. 'text': function (xmlNode, parentGroup) {
  22322. var x = xmlNode.getAttribute('x') || 0;
  22323. var y = xmlNode.getAttribute('y') || 0;
  22324. var dx = xmlNode.getAttribute('dx') || 0;
  22325. var dy = xmlNode.getAttribute('dy') || 0;
  22326. this._textX = parseFloat(x) + parseFloat(dx);
  22327. this._textY = parseFloat(y) + parseFloat(dy);
  22328. var g = new Group();
  22329. inheritStyle(parentGroup, g);
  22330. parseAttributes(xmlNode, g, this._defs);
  22331. return g;
  22332. },
  22333. 'tspan': function (xmlNode, parentGroup) {
  22334. var x = xmlNode.getAttribute('x');
  22335. var y = xmlNode.getAttribute('y');
  22336. if (x != null) {
  22337. // new offset x
  22338. this._textX = parseFloat(x);
  22339. }
  22340. if (y != null) {
  22341. // new offset y
  22342. this._textY = parseFloat(y);
  22343. }
  22344. var dx = xmlNode.getAttribute('dx') || 0;
  22345. var dy = xmlNode.getAttribute('dy') || 0;
  22346. var g = new Group();
  22347. inheritStyle(parentGroup, g);
  22348. parseAttributes(xmlNode, g, this._defs);
  22349. this._textX += dx;
  22350. this._textY += dy;
  22351. return g;
  22352. },
  22353. 'path': function (xmlNode, parentGroup) {
  22354. // TODO svg fill rule
  22355. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  22356. // path.style.globalCompositeOperation = 'xor';
  22357. var d = xmlNode.getAttribute('d') || '';
  22358. // Performance sensitive.
  22359. var path = createFromString(d);
  22360. inheritStyle(parentGroup, path);
  22361. parseAttributes(xmlNode, path, this._defs);
  22362. return path;
  22363. }
  22364. };
  22365. var defineParsers = {
  22366. 'lineargradient': function (xmlNode) {
  22367. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  22368. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  22369. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  22370. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  22371. var gradient = new LinearGradient(x1, y1, x2, y2);
  22372. _parseGradientColorStops(xmlNode, gradient);
  22373. return gradient;
  22374. },
  22375. 'radialgradient': function (xmlNode) {
  22376. }
  22377. };
  22378. function _parseGradientColorStops(xmlNode, gradient) {
  22379. var stop = xmlNode.firstChild;
  22380. while (stop) {
  22381. if (stop.nodeType === 1) {
  22382. var offset = stop.getAttribute('offset');
  22383. if (offset.indexOf('%') > 0) { // percentage
  22384. offset = parseInt(offset, 10) / 100;
  22385. }
  22386. else if (offset) { // number from 0 to 1
  22387. offset = parseFloat(offset);
  22388. }
  22389. else {
  22390. offset = 0;
  22391. }
  22392. var stopColor = stop.getAttribute('stop-color') || '#000000';
  22393. gradient.addColorStop(offset, stopColor);
  22394. }
  22395. stop = stop.nextSibling;
  22396. }
  22397. }
  22398. function inheritStyle(parent, child) {
  22399. if (parent && parent.__inheritedStyle) {
  22400. if (!child.__inheritedStyle) {
  22401. child.__inheritedStyle = {};
  22402. }
  22403. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  22404. }
  22405. }
  22406. function parsePoints(pointsString) {
  22407. var list = trim(pointsString).split(DILIMITER_REG);
  22408. var points = [];
  22409. for (var i = 0; i < list.length; i += 2) {
  22410. var x = parseFloat(list[i]);
  22411. var y = parseFloat(list[i + 1]);
  22412. points.push([x, y]);
  22413. }
  22414. return points;
  22415. }
  22416. var attributesMap = {
  22417. 'fill': 'fill',
  22418. 'stroke': 'stroke',
  22419. 'stroke-width': 'lineWidth',
  22420. 'opacity': 'opacity',
  22421. 'fill-opacity': 'fillOpacity',
  22422. 'stroke-opacity': 'strokeOpacity',
  22423. 'stroke-dasharray': 'lineDash',
  22424. 'stroke-dashoffset': 'lineDashOffset',
  22425. 'stroke-linecap': 'lineCap',
  22426. 'stroke-linejoin': 'lineJoin',
  22427. 'stroke-miterlimit': 'miterLimit',
  22428. 'font-family': 'fontFamily',
  22429. 'font-size': 'fontSize',
  22430. 'font-style': 'fontStyle',
  22431. 'font-weight': 'fontWeight',
  22432. 'text-align': 'textAlign',
  22433. 'alignment-baseline': 'textBaseline'
  22434. };
  22435. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  22436. var zrStyle = el.__inheritedStyle || {};
  22437. var isTextEl = el.type === 'text';
  22438. // TODO Shadow
  22439. if (xmlNode.nodeType === 1) {
  22440. parseTransformAttribute(xmlNode, el);
  22441. extend(zrStyle, parseStyleAttribute(xmlNode));
  22442. if (!onlyInlineStyle) {
  22443. for (var svgAttrName in attributesMap) {
  22444. if (attributesMap.hasOwnProperty(svgAttrName)) {
  22445. var attrValue = xmlNode.getAttribute(svgAttrName);
  22446. if (attrValue != null) {
  22447. zrStyle[attributesMap[svgAttrName]] = attrValue;
  22448. }
  22449. }
  22450. }
  22451. }
  22452. }
  22453. var elFillProp = isTextEl ? 'textFill' : 'fill';
  22454. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  22455. el.style = el.style || new Style();
  22456. var elStyle = el.style;
  22457. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  22458. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  22459. each$1([
  22460. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  22461. ], function (propName) {
  22462. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  22463. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  22464. });
  22465. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  22466. zrStyle.textBaseline = 'alphabetic';
  22467. }
  22468. if (zrStyle.textBaseline === 'alphabetic') {
  22469. zrStyle.textBaseline = 'bottom';
  22470. }
  22471. if (zrStyle.textAlign === 'start') {
  22472. zrStyle.textAlign = 'left';
  22473. }
  22474. if (zrStyle.textAlign === 'end') {
  22475. zrStyle.textAlign = 'right';
  22476. }
  22477. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  22478. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  22479. ], function (propName) {
  22480. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  22481. });
  22482. if (zrStyle.lineDash) {
  22483. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  22484. }
  22485. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  22486. // enable stroke
  22487. el[elStrokeProp] = true;
  22488. }
  22489. el.__inheritedStyle = zrStyle;
  22490. }
  22491. var urlRegex = /url\(\s*#(.*?)\)/;
  22492. function getPaint(str, defs) {
  22493. // if (str === 'none') {
  22494. // return;
  22495. // }
  22496. var urlMatch = defs && str && str.match(urlRegex);
  22497. if (urlMatch) {
  22498. var url = trim(urlMatch[1]);
  22499. var def = defs[url];
  22500. return def;
  22501. }
  22502. return str;
  22503. }
  22504. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  22505. function parseTransformAttribute(xmlNode, node) {
  22506. var transform = xmlNode.getAttribute('transform');
  22507. if (transform) {
  22508. transform = transform.replace(/,/g, ' ');
  22509. var m = null;
  22510. var transformOps = [];
  22511. transform.replace(transformRegex, function (str, type, value) {
  22512. transformOps.push(type, value);
  22513. });
  22514. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  22515. var value = transformOps[i];
  22516. var type = transformOps[i - 1];
  22517. m = m || create$1();
  22518. switch (type) {
  22519. case 'translate':
  22520. value = trim(value).split(DILIMITER_REG);
  22521. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  22522. break;
  22523. case 'scale':
  22524. value = trim(value).split(DILIMITER_REG);
  22525. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  22526. break;
  22527. case 'rotate':
  22528. value = trim(value).split(DILIMITER_REG);
  22529. rotate(m, m, parseFloat(value[0]));
  22530. break;
  22531. case 'skew':
  22532. value = trim(value).split(DILIMITER_REG);
  22533. console.warn('Skew transform is not supported yet');
  22534. break;
  22535. case 'matrix':
  22536. var value = trim(value).split(DILIMITER_REG);
  22537. m[0] = parseFloat(value[0]);
  22538. m[1] = parseFloat(value[1]);
  22539. m[2] = parseFloat(value[2]);
  22540. m[3] = parseFloat(value[3]);
  22541. m[4] = parseFloat(value[4]);
  22542. m[5] = parseFloat(value[5]);
  22543. break;
  22544. }
  22545. }
  22546. node.setLocalTransform(m);
  22547. }
  22548. }
  22549. // Value may contain space.
  22550. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  22551. function parseStyleAttribute(xmlNode) {
  22552. var style = xmlNode.getAttribute('style');
  22553. var result = {};
  22554. if (!style) {
  22555. return result;
  22556. }
  22557. var styleList = {};
  22558. styleRegex.lastIndex = 0;
  22559. var styleRegResult;
  22560. while ((styleRegResult = styleRegex.exec(style)) != null) {
  22561. styleList[styleRegResult[1]] = styleRegResult[2];
  22562. }
  22563. for (var svgAttrName in attributesMap) {
  22564. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  22565. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  22566. }
  22567. }
  22568. return result;
  22569. }
  22570. /**
  22571. * @param {Array.<number>} viewBoxRect
  22572. * @param {number} width
  22573. * @param {number} height
  22574. * @return {Object} {scale, position}
  22575. */
  22576. function makeViewBoxTransform(viewBoxRect, width, height) {
  22577. var scaleX = width / viewBoxRect.width;
  22578. var scaleY = height / viewBoxRect.height;
  22579. var scale = Math.min(scaleX, scaleY);
  22580. // preserveAspectRatio 'xMidYMid'
  22581. var viewBoxScale = [scale, scale];
  22582. var viewBoxPosition = [
  22583. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  22584. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  22585. ];
  22586. return {
  22587. scale: viewBoxScale,
  22588. position: viewBoxPosition
  22589. };
  22590. }
  22591. /**
  22592. * @param {string|XMLElement} xml
  22593. * @param {Object} [opt]
  22594. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  22595. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  22596. * @param {boolean} [opt.ignoreViewBox]
  22597. * @param {boolean} [opt.ignoreRootClip]
  22598. * @return {Object} result:
  22599. * {
  22600. * root: Group, The root of the the result tree of zrender shapes,
  22601. * width: number, the viewport width of the SVG,
  22602. * height: number, the viewport height of the SVG,
  22603. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  22604. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  22605. * }
  22606. */
  22607. /*
  22608. * Licensed to the Apache Software Foundation (ASF) under one
  22609. * or more contributor license agreements. See the NOTICE file
  22610. * distributed with this work for additional information
  22611. * regarding copyright ownership. The ASF licenses this file
  22612. * to you under the Apache License, Version 2.0 (the
  22613. * "License"); you may not use this file except in compliance
  22614. * with the License. You may obtain a copy of the License at
  22615. *
  22616. * http://www.apache.org/licenses/LICENSE-2.0
  22617. *
  22618. * Unless required by applicable law or agreed to in writing,
  22619. * software distributed under the License is distributed on an
  22620. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22621. * KIND, either express or implied. See the License for the
  22622. * specific language governing permissions and limitations
  22623. * under the License.
  22624. */
  22625. var storage = createHashMap();
  22626. // For minimize the code size of common echarts package,
  22627. // do not put too much logic in this module.
  22628. var mapDataStorage = {
  22629. // The format of record: see `echarts.registerMap`.
  22630. // Compatible with previous `echarts.registerMap`.
  22631. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  22632. var records;
  22633. if (isArray(rawGeoJson)) {
  22634. records = rawGeoJson;
  22635. }
  22636. else if (rawGeoJson.svg) {
  22637. records = [{
  22638. type: 'svg',
  22639. source: rawGeoJson.svg,
  22640. specialAreas: rawGeoJson.specialAreas
  22641. }];
  22642. }
  22643. else {
  22644. // Backward compatibility.
  22645. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  22646. rawSpecialAreas = rawGeoJson.specialAreas;
  22647. rawGeoJson = rawGeoJson.geoJson;
  22648. }
  22649. records = [{
  22650. type: 'geoJSON',
  22651. source: rawGeoJson,
  22652. specialAreas: rawSpecialAreas
  22653. }];
  22654. }
  22655. each$1(records, function (record) {
  22656. var type = record.type;
  22657. type === 'geoJson' && (type = record.type = 'geoJSON');
  22658. var parse = parsers[type];
  22659. if (__DEV__) {
  22660. assert$1(parse, 'Illegal map type: ' + type);
  22661. }
  22662. parse(record);
  22663. });
  22664. return storage.set(mapName, records);
  22665. },
  22666. retrieveMap: function (mapName) {
  22667. return storage.get(mapName);
  22668. }
  22669. };
  22670. var parsers = {
  22671. geoJSON: function (record) {
  22672. var source = record.source;
  22673. record.geoJSON = !isString(source)
  22674. ? source
  22675. : (typeof JSON !== 'undefined' && JSON.parse)
  22676. ? JSON.parse(source)
  22677. : (new Function('return (' + source + ');'))();
  22678. },
  22679. // Only perform parse to XML object here, which might be time
  22680. // consiming for large SVG.
  22681. // Although convert XML to zrender element is also time consiming,
  22682. // if we do it here, the clone of zrender elements has to be
  22683. // required. So we do it once for each geo instance, util real
  22684. // performance issues call for optimizing it.
  22685. svg: function (record) {
  22686. record.svgXML = parseXML(record.source);
  22687. }
  22688. };
  22689. /*
  22690. * Licensed to the Apache Software Foundation (ASF) under one
  22691. * or more contributor license agreements. See the NOTICE file
  22692. * distributed with this work for additional information
  22693. * regarding copyright ownership. The ASF licenses this file
  22694. * to you under the Apache License, Version 2.0 (the
  22695. * "License"); you may not use this file except in compliance
  22696. * with the License. You may obtain a copy of the License at
  22697. *
  22698. * http://www.apache.org/licenses/LICENSE-2.0
  22699. *
  22700. * Unless required by applicable law or agreed to in writing,
  22701. * software distributed under the License is distributed on an
  22702. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22703. * KIND, either express or implied. See the License for the
  22704. * specific language governing permissions and limitations
  22705. * under the License.
  22706. */
  22707. var assert = assert$1;
  22708. var each = each$1;
  22709. var isFunction = isFunction$1;
  22710. var isObject = isObject$1;
  22711. var parseClassType = ComponentModel.parseClassType;
  22712. var version = '4.2.1';
  22713. var dependencies = {
  22714. zrender: '4.0.6'
  22715. };
  22716. var TEST_FRAME_REMAIN_TIME = 1;
  22717. var PRIORITY_PROCESSOR_FILTER = 1000;
  22718. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  22719. var PRIORITY_VISUAL_LAYOUT = 1000;
  22720. var PRIORITY_VISUAL_GLOBAL = 2000;
  22721. var PRIORITY_VISUAL_CHART = 3000;
  22722. var PRIORITY_VISUAL_COMPONENT = 4000;
  22723. // FIXME
  22724. // necessary?
  22725. var PRIORITY_VISUAL_BRUSH = 5000;
  22726. var PRIORITY = {
  22727. PROCESSOR: {
  22728. FILTER: PRIORITY_PROCESSOR_FILTER,
  22729. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  22730. },
  22731. VISUAL: {
  22732. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  22733. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  22734. CHART: PRIORITY_VISUAL_CHART,
  22735. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  22736. BRUSH: PRIORITY_VISUAL_BRUSH
  22737. }
  22738. };
  22739. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  22740. // where they must not be invoked nestedly, except the only case: invoke
  22741. // dispatchAction with updateMethod "none" in main process.
  22742. // This flag is used to carry out this rule.
  22743. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  22744. var IN_MAIN_PROCESS = '__flagInMainProcess';
  22745. var OPTION_UPDATED = '__optionUpdated';
  22746. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  22747. function createRegisterEventWithLowercaseName(method) {
  22748. return function (eventName, handler, context) {
  22749. // Event name is all lowercase
  22750. eventName = eventName && eventName.toLowerCase();
  22751. Eventful.prototype[method].call(this, eventName, handler, context);
  22752. };
  22753. }
  22754. /**
  22755. * @module echarts~MessageCenter
  22756. */
  22757. function MessageCenter() {
  22758. Eventful.call(this);
  22759. }
  22760. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  22761. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  22762. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  22763. mixin(MessageCenter, Eventful);
  22764. /**
  22765. * @module echarts~ECharts
  22766. */
  22767. function ECharts(dom, theme$$1, opts) {
  22768. opts = opts || {};
  22769. // Get theme by name
  22770. if (typeof theme$$1 === 'string') {
  22771. theme$$1 = themeStorage[theme$$1];
  22772. }
  22773. /**
  22774. * @type {string}
  22775. */
  22776. this.id;
  22777. /**
  22778. * Group id
  22779. * @type {string}
  22780. */
  22781. this.group;
  22782. /**
  22783. * @type {HTMLElement}
  22784. * @private
  22785. */
  22786. this._dom = dom;
  22787. var defaultRenderer = 'canvas';
  22788. if (__DEV__) {
  22789. defaultRenderer = (
  22790. typeof window === 'undefined' ? global : window
  22791. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  22792. }
  22793. /**
  22794. * @type {module:zrender/ZRender}
  22795. * @private
  22796. */
  22797. var zr = this._zr = init$1(dom, {
  22798. renderer: opts.renderer || defaultRenderer,
  22799. devicePixelRatio: opts.devicePixelRatio,
  22800. width: opts.width,
  22801. height: opts.height
  22802. });
  22803. /**
  22804. * Expect 60 pfs.
  22805. * @type {Function}
  22806. * @private
  22807. */
  22808. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  22809. var theme$$1 = clone(theme$$1);
  22810. theme$$1 && backwardCompat(theme$$1, true);
  22811. /**
  22812. * @type {Object}
  22813. * @private
  22814. */
  22815. this._theme = theme$$1;
  22816. /**
  22817. * @type {Array.<module:echarts/view/Chart>}
  22818. * @private
  22819. */
  22820. this._chartsViews = [];
  22821. /**
  22822. * @type {Object.<string, module:echarts/view/Chart>}
  22823. * @private
  22824. */
  22825. this._chartsMap = {};
  22826. /**
  22827. * @type {Array.<module:echarts/view/Component>}
  22828. * @private
  22829. */
  22830. this._componentsViews = [];
  22831. /**
  22832. * @type {Object.<string, module:echarts/view/Component>}
  22833. * @private
  22834. */
  22835. this._componentsMap = {};
  22836. /**
  22837. * @type {module:echarts/CoordinateSystem}
  22838. * @private
  22839. */
  22840. this._coordSysMgr = new CoordinateSystemManager();
  22841. /**
  22842. * @type {module:echarts/ExtensionAPI}
  22843. * @private
  22844. */
  22845. var api = this._api = createExtensionAPI(this);
  22846. // Sort on demand
  22847. function prioritySortFunc(a, b) {
  22848. return a.__prio - b.__prio;
  22849. }
  22850. sort(visualFuncs, prioritySortFunc);
  22851. sort(dataProcessorFuncs, prioritySortFunc);
  22852. /**
  22853. * @type {module:echarts/stream/Scheduler}
  22854. */
  22855. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  22856. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  22857. /**
  22858. * @type {module:echarts~MessageCenter}
  22859. * @private
  22860. */
  22861. this._messageCenter = new MessageCenter();
  22862. // Init mouse events
  22863. this._initEvents();
  22864. // In case some people write `window.onresize = chart.resize`
  22865. this.resize = bind(this.resize, this);
  22866. // Can't dispatch action during rendering procedure
  22867. this._pendingActions = [];
  22868. zr.animation.on('frame', this._onframe, this);
  22869. bindRenderedEvent(zr, this);
  22870. // ECharts instance can be used as value.
  22871. setAsPrimitive(this);
  22872. }
  22873. var echartsProto = ECharts.prototype;
  22874. echartsProto._onframe = function () {
  22875. if (this._disposed) {
  22876. return;
  22877. }
  22878. var scheduler = this._scheduler;
  22879. // Lazy update
  22880. if (this[OPTION_UPDATED]) {
  22881. var silent = this[OPTION_UPDATED].silent;
  22882. this[IN_MAIN_PROCESS] = true;
  22883. prepare(this);
  22884. updateMethods.update.call(this);
  22885. this[IN_MAIN_PROCESS] = false;
  22886. this[OPTION_UPDATED] = false;
  22887. flushPendingActions.call(this, silent);
  22888. triggerUpdatedEvent.call(this, silent);
  22889. }
  22890. // Avoid do both lazy update and progress in one frame.
  22891. else if (scheduler.unfinished) {
  22892. // Stream progress.
  22893. var remainTime = TEST_FRAME_REMAIN_TIME;
  22894. var ecModel = this._model;
  22895. var api = this._api;
  22896. scheduler.unfinished = false;
  22897. do {
  22898. var startTime = +new Date();
  22899. scheduler.performSeriesTasks(ecModel);
  22900. // Currently dataProcessorFuncs do not check threshold.
  22901. scheduler.performDataProcessorTasks(ecModel);
  22902. updateStreamModes(this, ecModel);
  22903. // Do not update coordinate system here. Because that coord system update in
  22904. // each frame is not a good user experience. So we follow the rule that
  22905. // the extent of the coordinate system is determin in the first frame (the
  22906. // frame is executed immedietely after task reset.
  22907. // this._coordSysMgr.update(ecModel, api);
  22908. // console.log('--- ec frame visual ---', remainTime);
  22909. scheduler.performVisualTasks(ecModel);
  22910. renderSeries(this, this._model, api, 'remain');
  22911. remainTime -= (+new Date() - startTime);
  22912. }
  22913. while (remainTime > 0 && scheduler.unfinished);
  22914. // Call flush explicitly for trigger finished event.
  22915. if (!scheduler.unfinished) {
  22916. this._zr.flush();
  22917. }
  22918. // Else, zr flushing be ensue within the same frame,
  22919. // because zr flushing is after onframe event.
  22920. }
  22921. };
  22922. /**
  22923. * @return {HTMLElement}
  22924. */
  22925. echartsProto.getDom = function () {
  22926. return this._dom;
  22927. };
  22928. /**
  22929. * @return {module:zrender~ZRender}
  22930. */
  22931. echartsProto.getZr = function () {
  22932. return this._zr;
  22933. };
  22934. /**
  22935. * Usage:
  22936. * chart.setOption(option, notMerge, lazyUpdate);
  22937. * chart.setOption(option, {
  22938. * notMerge: ...,
  22939. * lazyUpdate: ...,
  22940. * silent: ...
  22941. * });
  22942. *
  22943. * @param {Object} option
  22944. * @param {Object|boolean} [opts] opts or notMerge.
  22945. * @param {boolean} [opts.notMerge=false]
  22946. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  22947. */
  22948. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  22949. if (__DEV__) {
  22950. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  22951. }
  22952. var silent;
  22953. if (isObject(notMerge)) {
  22954. lazyUpdate = notMerge.lazyUpdate;
  22955. silent = notMerge.silent;
  22956. notMerge = notMerge.notMerge;
  22957. }
  22958. this[IN_MAIN_PROCESS] = true;
  22959. if (!this._model || notMerge) {
  22960. var optionManager = new OptionManager(this._api);
  22961. var theme$$1 = this._theme;
  22962. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  22963. ecModel.scheduler = this._scheduler;
  22964. ecModel.init(null, null, theme$$1, optionManager);
  22965. }
  22966. this._model.setOption(option, optionPreprocessorFuncs);
  22967. if (lazyUpdate) {
  22968. this[OPTION_UPDATED] = {silent: silent};
  22969. this[IN_MAIN_PROCESS] = false;
  22970. }
  22971. else {
  22972. prepare(this);
  22973. updateMethods.update.call(this);
  22974. // Ensure zr refresh sychronously, and then pixel in canvas can be
  22975. // fetched after `setOption`.
  22976. this._zr.flush();
  22977. this[OPTION_UPDATED] = false;
  22978. this[IN_MAIN_PROCESS] = false;
  22979. flushPendingActions.call(this, silent);
  22980. triggerUpdatedEvent.call(this, silent);
  22981. }
  22982. };
  22983. /**
  22984. * @DEPRECATED
  22985. */
  22986. echartsProto.setTheme = function () {
  22987. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  22988. };
  22989. /**
  22990. * @return {module:echarts/model/Global}
  22991. */
  22992. echartsProto.getModel = function () {
  22993. return this._model;
  22994. };
  22995. /**
  22996. * @return {Object}
  22997. */
  22998. echartsProto.getOption = function () {
  22999. return this._model && this._model.getOption();
  23000. };
  23001. /**
  23002. * @return {number}
  23003. */
  23004. echartsProto.getWidth = function () {
  23005. return this._zr.getWidth();
  23006. };
  23007. /**
  23008. * @return {number}
  23009. */
  23010. echartsProto.getHeight = function () {
  23011. return this._zr.getHeight();
  23012. };
  23013. /**
  23014. * @return {number}
  23015. */
  23016. echartsProto.getDevicePixelRatio = function () {
  23017. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  23018. };
  23019. /**
  23020. * Get canvas which has all thing rendered
  23021. * @param {Object} opts
  23022. * @param {string} [opts.backgroundColor]
  23023. * @return {string}
  23024. */
  23025. echartsProto.getRenderedCanvas = function (opts) {
  23026. if (!env$1.canvasSupported) {
  23027. return;
  23028. }
  23029. opts = opts || {};
  23030. opts.pixelRatio = opts.pixelRatio || 1;
  23031. opts.backgroundColor = opts.backgroundColor
  23032. || this._model.get('backgroundColor');
  23033. var zr = this._zr;
  23034. // var list = zr.storage.getDisplayList();
  23035. // Stop animations
  23036. // Never works before in init animation, so remove it.
  23037. // zrUtil.each(list, function (el) {
  23038. // el.stopAnimation(true);
  23039. // });
  23040. return zr.painter.getRenderedCanvas(opts);
  23041. };
  23042. /**
  23043. * Get svg data url
  23044. * @return {string}
  23045. */
  23046. echartsProto.getSvgDataUrl = function () {
  23047. if (!env$1.svgSupported) {
  23048. return;
  23049. }
  23050. var zr = this._zr;
  23051. var list = zr.storage.getDisplayList();
  23052. // Stop animations
  23053. each$1(list, function (el) {
  23054. el.stopAnimation(true);
  23055. });
  23056. return zr.painter.pathToDataUrl();
  23057. };
  23058. /**
  23059. * @return {string}
  23060. * @param {Object} opts
  23061. * @param {string} [opts.type='png']
  23062. * @param {string} [opts.pixelRatio=1]
  23063. * @param {string} [opts.backgroundColor]
  23064. * @param {string} [opts.excludeComponents]
  23065. */
  23066. echartsProto.getDataURL = function (opts) {
  23067. opts = opts || {};
  23068. var excludeComponents = opts.excludeComponents;
  23069. var ecModel = this._model;
  23070. var excludesComponentViews = [];
  23071. var self = this;
  23072. each(excludeComponents, function (componentType) {
  23073. ecModel.eachComponent({
  23074. mainType: componentType
  23075. }, function (component) {
  23076. var view = self._componentsMap[component.__viewId];
  23077. if (!view.group.ignore) {
  23078. excludesComponentViews.push(view);
  23079. view.group.ignore = true;
  23080. }
  23081. });
  23082. });
  23083. var url = this._zr.painter.getType() === 'svg'
  23084. ? this.getSvgDataUrl()
  23085. : this.getRenderedCanvas(opts).toDataURL(
  23086. 'image/' + (opts && opts.type || 'png')
  23087. );
  23088. each(excludesComponentViews, function (view) {
  23089. view.group.ignore = false;
  23090. });
  23091. return url;
  23092. };
  23093. /**
  23094. * @return {string}
  23095. * @param {Object} opts
  23096. * @param {string} [opts.type='png']
  23097. * @param {string} [opts.pixelRatio=1]
  23098. * @param {string} [opts.backgroundColor]
  23099. */
  23100. echartsProto.getConnectedDataURL = function (opts) {
  23101. if (!env$1.canvasSupported) {
  23102. return;
  23103. }
  23104. var groupId = this.group;
  23105. var mathMin = Math.min;
  23106. var mathMax = Math.max;
  23107. var MAX_NUMBER = Infinity;
  23108. if (connectedGroups[groupId]) {
  23109. var left = MAX_NUMBER;
  23110. var top = MAX_NUMBER;
  23111. var right = -MAX_NUMBER;
  23112. var bottom = -MAX_NUMBER;
  23113. var canvasList = [];
  23114. var dpr = (opts && opts.pixelRatio) || 1;
  23115. each$1(instances, function (chart, id) {
  23116. if (chart.group === groupId) {
  23117. var canvas = chart.getRenderedCanvas(
  23118. clone(opts)
  23119. );
  23120. var boundingRect = chart.getDom().getBoundingClientRect();
  23121. left = mathMin(boundingRect.left, left);
  23122. top = mathMin(boundingRect.top, top);
  23123. right = mathMax(boundingRect.right, right);
  23124. bottom = mathMax(boundingRect.bottom, bottom);
  23125. canvasList.push({
  23126. dom: canvas,
  23127. left: boundingRect.left,
  23128. top: boundingRect.top
  23129. });
  23130. }
  23131. });
  23132. left *= dpr;
  23133. top *= dpr;
  23134. right *= dpr;
  23135. bottom *= dpr;
  23136. var width = right - left;
  23137. var height = bottom - top;
  23138. var targetCanvas = createCanvas();
  23139. targetCanvas.width = width;
  23140. targetCanvas.height = height;
  23141. var zr = init$1(targetCanvas);
  23142. each(canvasList, function (item) {
  23143. var img = new ZImage({
  23144. style: {
  23145. x: item.left * dpr - left,
  23146. y: item.top * dpr - top,
  23147. image: item.dom
  23148. }
  23149. });
  23150. zr.add(img);
  23151. });
  23152. zr.refreshImmediately();
  23153. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  23154. }
  23155. else {
  23156. return this.getDataURL(opts);
  23157. }
  23158. };
  23159. /**
  23160. * Convert from logical coordinate system to pixel coordinate system.
  23161. * See CoordinateSystem#convertToPixel.
  23162. * @param {string|Object} finder
  23163. * If string, e.g., 'geo', means {geoIndex: 0}.
  23164. * If Object, could contain some of these properties below:
  23165. * {
  23166. * seriesIndex / seriesId / seriesName,
  23167. * geoIndex / geoId, geoName,
  23168. * bmapIndex / bmapId / bmapName,
  23169. * xAxisIndex / xAxisId / xAxisName,
  23170. * yAxisIndex / yAxisId / yAxisName,
  23171. * gridIndex / gridId / gridName,
  23172. * ... (can be extended)
  23173. * }
  23174. * @param {Array|number} value
  23175. * @return {Array|number} result
  23176. */
  23177. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  23178. /**
  23179. * Convert from pixel coordinate system to logical coordinate system.
  23180. * See CoordinateSystem#convertFromPixel.
  23181. * @param {string|Object} finder
  23182. * If string, e.g., 'geo', means {geoIndex: 0}.
  23183. * If Object, could contain some of these properties below:
  23184. * {
  23185. * seriesIndex / seriesId / seriesName,
  23186. * geoIndex / geoId / geoName,
  23187. * bmapIndex / bmapId / bmapName,
  23188. * xAxisIndex / xAxisId / xAxisName,
  23189. * yAxisIndex / yAxisId / yAxisName
  23190. * gridIndex / gridId / gridName,
  23191. * ... (can be extended)
  23192. * }
  23193. * @param {Array|number} value
  23194. * @return {Array|number} result
  23195. */
  23196. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  23197. function doConvertPixel(methodName, finder, value) {
  23198. var ecModel = this._model;
  23199. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  23200. var result;
  23201. finder = parseFinder(ecModel, finder);
  23202. for (var i = 0; i < coordSysList.length; i++) {
  23203. var coordSys = coordSysList[i];
  23204. if (coordSys[methodName]
  23205. && (result = coordSys[methodName](ecModel, finder, value)) != null
  23206. ) {
  23207. return result;
  23208. }
  23209. }
  23210. if (__DEV__) {
  23211. console.warn(
  23212. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  23213. );
  23214. }
  23215. }
  23216. /**
  23217. * Is the specified coordinate systems or components contain the given pixel point.
  23218. * @param {string|Object} finder
  23219. * If string, e.g., 'geo', means {geoIndex: 0}.
  23220. * If Object, could contain some of these properties below:
  23221. * {
  23222. * seriesIndex / seriesId / seriesName,
  23223. * geoIndex / geoId / geoName,
  23224. * bmapIndex / bmapId / bmapName,
  23225. * xAxisIndex / xAxisId / xAxisName,
  23226. * yAxisIndex / yAxisId / yAxisName,
  23227. * gridIndex / gridId / gridName,
  23228. * ... (can be extended)
  23229. * }
  23230. * @param {Array|number} value
  23231. * @return {boolean} result
  23232. */
  23233. echartsProto.containPixel = function (finder, value) {
  23234. var ecModel = this._model;
  23235. var result;
  23236. finder = parseFinder(ecModel, finder);
  23237. each$1(finder, function (models, key) {
  23238. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  23239. var coordSys = model.coordinateSystem;
  23240. if (coordSys && coordSys.containPoint) {
  23241. result |= !!coordSys.containPoint(value);
  23242. }
  23243. else if (key === 'seriesModels') {
  23244. var view = this._chartsMap[model.__viewId];
  23245. if (view && view.containPoint) {
  23246. result |= view.containPoint(value, model);
  23247. }
  23248. else {
  23249. if (__DEV__) {
  23250. console.warn(key + ': ' + (view
  23251. ? 'The found component do not support containPoint.'
  23252. : 'No view mapping to the found component.'
  23253. ));
  23254. }
  23255. }
  23256. }
  23257. else {
  23258. if (__DEV__) {
  23259. console.warn(key + ': containPoint is not supported');
  23260. }
  23261. }
  23262. }, this);
  23263. }, this);
  23264. return !!result;
  23265. };
  23266. /**
  23267. * Get visual from series or data.
  23268. * @param {string|Object} finder
  23269. * If string, e.g., 'series', means {seriesIndex: 0}.
  23270. * If Object, could contain some of these properties below:
  23271. * {
  23272. * seriesIndex / seriesId / seriesName,
  23273. * dataIndex / dataIndexInside
  23274. * }
  23275. * If dataIndex is not specified, series visual will be fetched,
  23276. * but not data item visual.
  23277. * If all of seriesIndex, seriesId, seriesName are not specified,
  23278. * visual will be fetched from first series.
  23279. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  23280. */
  23281. echartsProto.getVisual = function (finder, visualType) {
  23282. var ecModel = this._model;
  23283. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  23284. var seriesModel = finder.seriesModel;
  23285. if (__DEV__) {
  23286. if (!seriesModel) {
  23287. console.warn('There is no specified seires model');
  23288. }
  23289. }
  23290. var data = seriesModel.getData();
  23291. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  23292. ? finder.dataIndexInside
  23293. : finder.hasOwnProperty('dataIndex')
  23294. ? data.indexOfRawIndex(finder.dataIndex)
  23295. : null;
  23296. return dataIndexInside != null
  23297. ? data.getItemVisual(dataIndexInside, visualType)
  23298. : data.getVisual(visualType);
  23299. };
  23300. /**
  23301. * Get view of corresponding component model
  23302. * @param {module:echarts/model/Component} componentModel
  23303. * @return {module:echarts/view/Component}
  23304. */
  23305. echartsProto.getViewOfComponentModel = function (componentModel) {
  23306. return this._componentsMap[componentModel.__viewId];
  23307. };
  23308. /**
  23309. * Get view of corresponding series model
  23310. * @param {module:echarts/model/Series} seriesModel
  23311. * @return {module:echarts/view/Chart}
  23312. */
  23313. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  23314. return this._chartsMap[seriesModel.__viewId];
  23315. };
  23316. var updateMethods = {
  23317. prepareAndUpdate: function (payload) {
  23318. prepare(this);
  23319. updateMethods.update.call(this, payload);
  23320. },
  23321. /**
  23322. * @param {Object} payload
  23323. * @private
  23324. */
  23325. update: function (payload) {
  23326. // console.profile && console.profile('update');
  23327. var ecModel = this._model;
  23328. var api = this._api;
  23329. var zr = this._zr;
  23330. var coordSysMgr = this._coordSysMgr;
  23331. var scheduler = this._scheduler;
  23332. // update before setOption
  23333. if (!ecModel) {
  23334. return;
  23335. }
  23336. scheduler.restoreData(ecModel, payload);
  23337. scheduler.performSeriesTasks(ecModel);
  23338. // TODO
  23339. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  23340. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  23341. // Create new coordinate system each update
  23342. // In LineView may save the old coordinate system and use it to get the orignal point
  23343. coordSysMgr.create(ecModel, api);
  23344. scheduler.performDataProcessorTasks(ecModel, payload);
  23345. // Current stream render is not supported in data process. So we can update
  23346. // stream modes after data processing, where the filtered data is used to
  23347. // deteming whether use progressive rendering.
  23348. updateStreamModes(this, ecModel);
  23349. // We update stream modes before coordinate system updated, then the modes info
  23350. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  23351. // the drawback is the full coord info can not be fetched. Fortunately this full
  23352. // coord is not requied in stream mode updater currently.
  23353. coordSysMgr.update(ecModel, api);
  23354. clearColorPalette(ecModel);
  23355. scheduler.performVisualTasks(ecModel, payload);
  23356. render(this, ecModel, api, payload);
  23357. // Set background
  23358. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  23359. // In IE8
  23360. if (!env$1.canvasSupported) {
  23361. var colorArr = parse(backgroundColor);
  23362. backgroundColor = stringify(colorArr, 'rgb');
  23363. if (colorArr[3] === 0) {
  23364. backgroundColor = 'transparent';
  23365. }
  23366. }
  23367. else {
  23368. zr.setBackgroundColor(backgroundColor);
  23369. }
  23370. performPostUpdateFuncs(ecModel, api);
  23371. // console.profile && console.profileEnd('update');
  23372. },
  23373. /**
  23374. * @param {Object} payload
  23375. * @private
  23376. */
  23377. updateTransform: function (payload) {
  23378. var ecModel = this._model;
  23379. var ecIns = this;
  23380. var api = this._api;
  23381. // update before setOption
  23382. if (!ecModel) {
  23383. return;
  23384. }
  23385. // ChartView.markUpdateMethod(payload, 'updateTransform');
  23386. var componentDirtyList = [];
  23387. ecModel.eachComponent(function (componentType, componentModel) {
  23388. var componentView = ecIns.getViewOfComponentModel(componentModel);
  23389. if (componentView && componentView.__alive) {
  23390. if (componentView.updateTransform) {
  23391. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  23392. result && result.update && componentDirtyList.push(componentView);
  23393. }
  23394. else {
  23395. componentDirtyList.push(componentView);
  23396. }
  23397. }
  23398. });
  23399. var seriesDirtyMap = createHashMap();
  23400. ecModel.eachSeries(function (seriesModel) {
  23401. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23402. if (chartView.updateTransform) {
  23403. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  23404. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  23405. }
  23406. else {
  23407. seriesDirtyMap.set(seriesModel.uid, 1);
  23408. }
  23409. });
  23410. clearColorPalette(ecModel);
  23411. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23412. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  23413. this._scheduler.performVisualTasks(
  23414. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  23415. );
  23416. // Currently, not call render of components. Geo render cost a lot.
  23417. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  23418. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  23419. performPostUpdateFuncs(ecModel, this._api);
  23420. },
  23421. /**
  23422. * @param {Object} payload
  23423. * @private
  23424. */
  23425. updateView: function (payload) {
  23426. var ecModel = this._model;
  23427. // update before setOption
  23428. if (!ecModel) {
  23429. return;
  23430. }
  23431. Chart.markUpdateMethod(payload, 'updateView');
  23432. clearColorPalette(ecModel);
  23433. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23434. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  23435. render(this, this._model, this._api, payload);
  23436. performPostUpdateFuncs(ecModel, this._api);
  23437. },
  23438. /**
  23439. * @param {Object} payload
  23440. * @private
  23441. */
  23442. updateVisual: function (payload) {
  23443. updateMethods.update.call(this, payload);
  23444. // var ecModel = this._model;
  23445. // // update before setOption
  23446. // if (!ecModel) {
  23447. // return;
  23448. // }
  23449. // ChartView.markUpdateMethod(payload, 'updateVisual');
  23450. // clearColorPalette(ecModel);
  23451. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23452. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  23453. // render(this, this._model, this._api, payload);
  23454. // performPostUpdateFuncs(ecModel, this._api);
  23455. },
  23456. /**
  23457. * @param {Object} payload
  23458. * @private
  23459. */
  23460. updateLayout: function (payload) {
  23461. updateMethods.update.call(this, payload);
  23462. // var ecModel = this._model;
  23463. // // update before setOption
  23464. // if (!ecModel) {
  23465. // return;
  23466. // }
  23467. // ChartView.markUpdateMethod(payload, 'updateLayout');
  23468. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23469. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  23470. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  23471. // render(this, this._model, this._api, payload);
  23472. // performPostUpdateFuncs(ecModel, this._api);
  23473. }
  23474. };
  23475. function prepare(ecIns) {
  23476. var ecModel = ecIns._model;
  23477. var scheduler = ecIns._scheduler;
  23478. scheduler.restorePipelines(ecModel);
  23479. scheduler.prepareStageTasks();
  23480. prepareView(ecIns, 'component', ecModel, scheduler);
  23481. prepareView(ecIns, 'chart', ecModel, scheduler);
  23482. scheduler.plan();
  23483. }
  23484. /**
  23485. * @private
  23486. */
  23487. function updateDirectly(ecIns, method, payload, mainType, subType) {
  23488. var ecModel = ecIns._model;
  23489. // broadcast
  23490. if (!mainType) {
  23491. // FIXME
  23492. // Chart will not be update directly here, except set dirty.
  23493. // But there is no such scenario now.
  23494. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  23495. return;
  23496. }
  23497. var query = {};
  23498. query[mainType + 'Id'] = payload[mainType + 'Id'];
  23499. query[mainType + 'Index'] = payload[mainType + 'Index'];
  23500. query[mainType + 'Name'] = payload[mainType + 'Name'];
  23501. var condition = {mainType: mainType, query: query};
  23502. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  23503. var excludeSeriesId = payload.excludeSeriesId;
  23504. if (excludeSeriesId != null) {
  23505. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  23506. }
  23507. // If dispatchAction before setOption, do nothing.
  23508. ecModel && ecModel.eachComponent(condition, function (model) {
  23509. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  23510. callView(ecIns[
  23511. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  23512. ][model.__viewId]);
  23513. }
  23514. }, ecIns);
  23515. function callView(view) {
  23516. view && view.__alive && view[method] && view[method](
  23517. view.__model, ecModel, ecIns._api, payload
  23518. );
  23519. }
  23520. }
  23521. /**
  23522. * Resize the chart
  23523. * @param {Object} opts
  23524. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  23525. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  23526. * @param {boolean} [opts.silent=false]
  23527. */
  23528. echartsProto.resize = function (opts) {
  23529. if (__DEV__) {
  23530. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  23531. }
  23532. this._zr.resize(opts);
  23533. var ecModel = this._model;
  23534. // Resize loading effect
  23535. this._loadingFX && this._loadingFX.resize();
  23536. if (!ecModel) {
  23537. return;
  23538. }
  23539. var optionChanged = ecModel.resetOption('media');
  23540. var silent = opts && opts.silent;
  23541. this[IN_MAIN_PROCESS] = true;
  23542. optionChanged && prepare(this);
  23543. updateMethods.update.call(this);
  23544. this[IN_MAIN_PROCESS] = false;
  23545. flushPendingActions.call(this, silent);
  23546. triggerUpdatedEvent.call(this, silent);
  23547. };
  23548. function updateStreamModes(ecIns, ecModel) {
  23549. var chartsMap = ecIns._chartsMap;
  23550. var scheduler = ecIns._scheduler;
  23551. ecModel.eachSeries(function (seriesModel) {
  23552. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  23553. });
  23554. }
  23555. /**
  23556. * Show loading effect
  23557. * @param {string} [name='default']
  23558. * @param {Object} [cfg]
  23559. */
  23560. echartsProto.showLoading = function (name, cfg) {
  23561. if (isObject(name)) {
  23562. cfg = name;
  23563. name = '';
  23564. }
  23565. name = name || 'default';
  23566. this.hideLoading();
  23567. if (!loadingEffects[name]) {
  23568. if (__DEV__) {
  23569. console.warn('Loading effects ' + name + ' not exists.');
  23570. }
  23571. return;
  23572. }
  23573. var el = loadingEffects[name](this._api, cfg);
  23574. var zr = this._zr;
  23575. this._loadingFX = el;
  23576. zr.add(el);
  23577. };
  23578. /**
  23579. * Hide loading effect
  23580. */
  23581. echartsProto.hideLoading = function () {
  23582. this._loadingFX && this._zr.remove(this._loadingFX);
  23583. this._loadingFX = null;
  23584. };
  23585. /**
  23586. * @param {Object} eventObj
  23587. * @return {Object}
  23588. */
  23589. echartsProto.makeActionFromEvent = function (eventObj) {
  23590. var payload = extend({}, eventObj);
  23591. payload.type = eventActionMap[eventObj.type];
  23592. return payload;
  23593. };
  23594. /**
  23595. * @pubilc
  23596. * @param {Object} payload
  23597. * @param {string} [payload.type] Action type
  23598. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  23599. * @param {boolean} [opt.silent=false] Whether trigger events.
  23600. * @param {boolean} [opt.flush=undefined]
  23601. * true: Flush immediately, and then pixel in canvas can be fetched
  23602. * immediately. Caution: it might affect performance.
  23603. * false: Not not flush.
  23604. * undefined: Auto decide whether perform flush.
  23605. */
  23606. echartsProto.dispatchAction = function (payload, opt) {
  23607. if (!isObject(opt)) {
  23608. opt = {silent: !!opt};
  23609. }
  23610. if (!actions[payload.type]) {
  23611. return;
  23612. }
  23613. // Avoid dispatch action before setOption. Especially in `connect`.
  23614. if (!this._model) {
  23615. return;
  23616. }
  23617. // May dispatchAction in rendering procedure
  23618. if (this[IN_MAIN_PROCESS]) {
  23619. this._pendingActions.push(payload);
  23620. return;
  23621. }
  23622. doDispatchAction.call(this, payload, opt.silent);
  23623. if (opt.flush) {
  23624. this._zr.flush(true);
  23625. }
  23626. else if (opt.flush !== false && env$1.browser.weChat) {
  23627. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  23628. // hang when sliding page (on touch event), which cause that zr does not
  23629. // refresh util user interaction finished, which is not expected.
  23630. // But `dispatchAction` may be called too frequently when pan on touch
  23631. // screen, which impacts performance if do not throttle them.
  23632. this._throttledZrFlush();
  23633. }
  23634. flushPendingActions.call(this, opt.silent);
  23635. triggerUpdatedEvent.call(this, opt.silent);
  23636. };
  23637. function doDispatchAction(payload, silent) {
  23638. var payloadType = payload.type;
  23639. var escapeConnect = payload.escapeConnect;
  23640. var actionWrap = actions[payloadType];
  23641. var actionInfo = actionWrap.actionInfo;
  23642. var cptType = (actionInfo.update || 'update').split(':');
  23643. var updateMethod = cptType.pop();
  23644. cptType = cptType[0] != null && parseClassType(cptType[0]);
  23645. this[IN_MAIN_PROCESS] = true;
  23646. var payloads = [payload];
  23647. var batched = false;
  23648. // Batch action
  23649. if (payload.batch) {
  23650. batched = true;
  23651. payloads = map(payload.batch, function (item) {
  23652. item = defaults(extend({}, item), payload);
  23653. item.batch = null;
  23654. return item;
  23655. });
  23656. }
  23657. var eventObjBatch = [];
  23658. var eventObj;
  23659. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  23660. each(payloads, function (batchItem) {
  23661. // Action can specify the event by return it.
  23662. eventObj = actionWrap.action(batchItem, this._model, this._api);
  23663. // Emit event outside
  23664. eventObj = eventObj || extend({}, batchItem);
  23665. // Convert type to eventType
  23666. eventObj.type = actionInfo.event || eventObj.type;
  23667. eventObjBatch.push(eventObj);
  23668. // light update does not perform data process, layout and visual.
  23669. if (isHighDown) {
  23670. // method, payload, mainType, subType
  23671. updateDirectly(this, updateMethod, batchItem, 'series');
  23672. }
  23673. else if (cptType) {
  23674. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  23675. }
  23676. }, this);
  23677. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  23678. // Still dirty
  23679. if (this[OPTION_UPDATED]) {
  23680. // FIXME Pass payload ?
  23681. prepare(this);
  23682. updateMethods.update.call(this, payload);
  23683. this[OPTION_UPDATED] = false;
  23684. }
  23685. else {
  23686. updateMethods[updateMethod].call(this, payload);
  23687. }
  23688. }
  23689. // Follow the rule of action batch
  23690. if (batched) {
  23691. eventObj = {
  23692. type: actionInfo.event || payloadType,
  23693. escapeConnect: escapeConnect,
  23694. batch: eventObjBatch
  23695. };
  23696. }
  23697. else {
  23698. eventObj = eventObjBatch[0];
  23699. }
  23700. this[IN_MAIN_PROCESS] = false;
  23701. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  23702. }
  23703. function flushPendingActions(silent) {
  23704. var pendingActions = this._pendingActions;
  23705. while (pendingActions.length) {
  23706. var payload = pendingActions.shift();
  23707. doDispatchAction.call(this, payload, silent);
  23708. }
  23709. }
  23710. function triggerUpdatedEvent(silent) {
  23711. !silent && this.trigger('updated');
  23712. }
  23713. /**
  23714. * Event `rendered` is triggered when zr
  23715. * rendered. It is useful for realtime
  23716. * snapshot (reflect animation).
  23717. *
  23718. * Event `finished` is triggered when:
  23719. * (1) zrender rendering finished.
  23720. * (2) initial animation finished.
  23721. * (3) progressive rendering finished.
  23722. * (4) no pending action.
  23723. * (5) no delayed setOption needs to be processed.
  23724. */
  23725. function bindRenderedEvent(zr, ecIns) {
  23726. zr.on('rendered', function () {
  23727. ecIns.trigger('rendered');
  23728. // The `finished` event should not be triggered repeatly,
  23729. // so it should only be triggered when rendering indeed happend
  23730. // in zrender. (Consider the case that dipatchAction is keep
  23731. // triggering when mouse move).
  23732. if (
  23733. // Although zr is dirty if initial animation is not finished
  23734. // and this checking is called on frame, we also check
  23735. // animation finished for robustness.
  23736. zr.animation.isFinished()
  23737. && !ecIns[OPTION_UPDATED]
  23738. && !ecIns._scheduler.unfinished
  23739. && !ecIns._pendingActions.length
  23740. ) {
  23741. ecIns.trigger('finished');
  23742. }
  23743. });
  23744. }
  23745. /**
  23746. * @param {Object} params
  23747. * @param {number} params.seriesIndex
  23748. * @param {Array|TypedArray} params.data
  23749. */
  23750. echartsProto.appendData = function (params) {
  23751. var seriesIndex = params.seriesIndex;
  23752. var ecModel = this.getModel();
  23753. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  23754. if (__DEV__) {
  23755. assert(params.data && seriesModel);
  23756. }
  23757. seriesModel.appendData(params);
  23758. // Note: `appendData` does not support that update extent of coordinate
  23759. // system, util some scenario require that. In the expected usage of
  23760. // `appendData`, the initial extent of coordinate system should better
  23761. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  23762. // the extent changed while `appendData`, the location of the painted
  23763. // graphic elements have to be changed, which make the usage of
  23764. // `appendData` meaningless.
  23765. this._scheduler.unfinished = true;
  23766. };
  23767. /**
  23768. * Register event
  23769. * @method
  23770. */
  23771. echartsProto.on = createRegisterEventWithLowercaseName('on');
  23772. echartsProto.off = createRegisterEventWithLowercaseName('off');
  23773. echartsProto.one = createRegisterEventWithLowercaseName('one');
  23774. /**
  23775. * Prepare view instances of charts and components
  23776. * @param {module:echarts/model/Global} ecModel
  23777. * @private
  23778. */
  23779. function prepareView(ecIns, type, ecModel, scheduler) {
  23780. var isComponent = type === 'component';
  23781. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  23782. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  23783. var zr = ecIns._zr;
  23784. var api = ecIns._api;
  23785. for (var i = 0; i < viewList.length; i++) {
  23786. viewList[i].__alive = false;
  23787. }
  23788. isComponent
  23789. ? ecModel.eachComponent(function (componentType, model) {
  23790. componentType !== 'series' && doPrepare(model);
  23791. })
  23792. : ecModel.eachSeries(doPrepare);
  23793. function doPrepare(model) {
  23794. // Consider: id same and type changed.
  23795. var viewId = '_ec_' + model.id + '_' + model.type;
  23796. var view = viewMap[viewId];
  23797. if (!view) {
  23798. var classType = parseClassType(model.type);
  23799. var Clazz = isComponent
  23800. ? Component.getClass(classType.main, classType.sub)
  23801. : Chart.getClass(classType.sub);
  23802. if (__DEV__) {
  23803. assert(Clazz, classType.sub + ' does not exist.');
  23804. }
  23805. view = new Clazz();
  23806. view.init(ecModel, api);
  23807. viewMap[viewId] = view;
  23808. viewList.push(view);
  23809. zr.add(view.group);
  23810. }
  23811. model.__viewId = view.__id = viewId;
  23812. view.__alive = true;
  23813. view.__model = model;
  23814. view.group.__ecComponentInfo = {
  23815. mainType: model.mainType,
  23816. index: model.componentIndex
  23817. };
  23818. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  23819. }
  23820. for (var i = 0; i < viewList.length;) {
  23821. var view = viewList[i];
  23822. if (!view.__alive) {
  23823. !isComponent && view.renderTask.dispose();
  23824. zr.remove(view.group);
  23825. view.dispose(ecModel, api);
  23826. viewList.splice(i, 1);
  23827. delete viewMap[view.__id];
  23828. view.__id = view.group.__ecComponentInfo = null;
  23829. }
  23830. else {
  23831. i++;
  23832. }
  23833. }
  23834. }
  23835. // /**
  23836. // * Encode visual infomation from data after data processing
  23837. // *
  23838. // * @param {module:echarts/model/Global} ecModel
  23839. // * @param {object} layout
  23840. // * @param {boolean} [layoutFilter] `true`: only layout,
  23841. // * `false`: only not layout,
  23842. // * `null`/`undefined`: all.
  23843. // * @param {string} taskBaseTag
  23844. // * @private
  23845. // */
  23846. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  23847. // each(visualFuncs, function (visual, index) {
  23848. // var isLayout = visual.isLayout;
  23849. // if (layoutFilter == null
  23850. // || (layoutFilter === false && !isLayout)
  23851. // || (layoutFilter === true && isLayout)
  23852. // ) {
  23853. // visual.func(ecModel, api, payload);
  23854. // }
  23855. // });
  23856. // }
  23857. function clearColorPalette(ecModel) {
  23858. ecModel.clearColorPalette();
  23859. ecModel.eachSeries(function (seriesModel) {
  23860. seriesModel.clearColorPalette();
  23861. });
  23862. }
  23863. function render(ecIns, ecModel, api, payload) {
  23864. renderComponents(ecIns, ecModel, api, payload);
  23865. each(ecIns._chartsViews, function (chart) {
  23866. chart.__alive = false;
  23867. });
  23868. renderSeries(ecIns, ecModel, api, payload);
  23869. // Remove groups of unrendered charts
  23870. each(ecIns._chartsViews, function (chart) {
  23871. if (!chart.__alive) {
  23872. chart.remove(ecModel, api);
  23873. }
  23874. });
  23875. }
  23876. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  23877. each(dirtyList || ecIns._componentsViews, function (componentView) {
  23878. var componentModel = componentView.__model;
  23879. componentView.render(componentModel, ecModel, api, payload);
  23880. updateZ(componentModel, componentView);
  23881. });
  23882. }
  23883. /**
  23884. * Render each chart and component
  23885. * @private
  23886. */
  23887. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  23888. // Render all charts
  23889. var scheduler = ecIns._scheduler;
  23890. var unfinished;
  23891. ecModel.eachSeries(function (seriesModel) {
  23892. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23893. chartView.__alive = true;
  23894. var renderTask = chartView.renderTask;
  23895. scheduler.updatePayload(renderTask, payload);
  23896. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  23897. renderTask.dirty();
  23898. }
  23899. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  23900. chartView.group.silent = !!seriesModel.get('silent');
  23901. updateZ(seriesModel, chartView);
  23902. updateBlend(seriesModel, chartView);
  23903. });
  23904. scheduler.unfinished |= unfinished;
  23905. // If use hover layer
  23906. updateHoverLayerStatus(ecIns._zr, ecModel);
  23907. // Add aria
  23908. aria(ecIns._zr.dom, ecModel);
  23909. }
  23910. function performPostUpdateFuncs(ecModel, api) {
  23911. each(postUpdateFuncs, function (func) {
  23912. func(ecModel, api);
  23913. });
  23914. }
  23915. var MOUSE_EVENT_NAMES = [
  23916. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  23917. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  23918. ];
  23919. /**
  23920. * @private
  23921. */
  23922. echartsProto._initEvents = function () {
  23923. each(MOUSE_EVENT_NAMES, function (eveName) {
  23924. var handler = function (e) {
  23925. var ecModel = this.getModel();
  23926. var el = e.target;
  23927. var params;
  23928. var isGlobalOut = eveName === 'globalout';
  23929. // no e.target when 'globalout'.
  23930. if (isGlobalOut) {
  23931. params = {};
  23932. }
  23933. else if (el && el.dataIndex != null) {
  23934. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  23935. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  23936. }
  23937. // If element has custom eventData of components
  23938. else if (el && el.eventData) {
  23939. params = extend({}, el.eventData);
  23940. }
  23941. // Contract: if params prepared in mouse event,
  23942. // these properties must be specified:
  23943. // {
  23944. // componentType: string (component main type)
  23945. // componentIndex: number
  23946. // }
  23947. // Otherwise event query can not work.
  23948. if (params) {
  23949. var componentType = params.componentType;
  23950. var componentIndex = params.componentIndex;
  23951. // Special handling for historic reason: when trigger by
  23952. // markLine/markPoint/markArea, the componentType is
  23953. // 'markLine'/'markPoint'/'markArea', but we should better
  23954. // enable them to be queried by seriesIndex, since their
  23955. // option is set in each series.
  23956. if (componentType === 'markLine'
  23957. || componentType === 'markPoint'
  23958. || componentType === 'markArea'
  23959. ) {
  23960. componentType = 'series';
  23961. componentIndex = params.seriesIndex;
  23962. }
  23963. var model = componentType && componentIndex != null
  23964. && ecModel.getComponent(componentType, componentIndex);
  23965. var view = model && this[
  23966. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  23967. ][model.__viewId];
  23968. if (__DEV__) {
  23969. // `event.componentType` and `event[componentTpype + 'Index']` must not
  23970. // be missed, otherwise there is no way to distinguish source component.
  23971. // See `dataFormat.getDataParams`.
  23972. if (!isGlobalOut && !(model && view)) {
  23973. console.warn('model or view can not be found by params');
  23974. }
  23975. }
  23976. params.event = e;
  23977. params.type = eveName;
  23978. this._ecEventProcessor.eventInfo = {
  23979. targetEl: el,
  23980. packedEvent: params,
  23981. model: model,
  23982. view: view
  23983. };
  23984. this.trigger(eveName, params);
  23985. }
  23986. };
  23987. // Consider that some component (like tooltip, brush, ...)
  23988. // register zr event handler, but user event handler might
  23989. // do anything, such as call `setOption` or `dispatchAction`,
  23990. // which probably update any of the content and probably
  23991. // cause problem if it is called previous other inner handlers.
  23992. handler.zrEventfulCallAtLast = true;
  23993. this._zr.on(eveName, handler, this);
  23994. }, this);
  23995. each(eventActionMap, function (actionType, eventType) {
  23996. this._messageCenter.on(eventType, function (event) {
  23997. this.trigger(eventType, event);
  23998. }, this);
  23999. }, this);
  24000. };
  24001. /**
  24002. * @return {boolean}
  24003. */
  24004. echartsProto.isDisposed = function () {
  24005. return this._disposed;
  24006. };
  24007. /**
  24008. * Clear
  24009. */
  24010. echartsProto.clear = function () {
  24011. this.setOption({ series: [] }, true);
  24012. };
  24013. /**
  24014. * Dispose instance
  24015. */
  24016. echartsProto.dispose = function () {
  24017. if (this._disposed) {
  24018. if (__DEV__) {
  24019. console.warn('Instance ' + this.id + ' has been disposed');
  24020. }
  24021. return;
  24022. }
  24023. this._disposed = true;
  24024. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24025. var api = this._api;
  24026. var ecModel = this._model;
  24027. each(this._componentsViews, function (component) {
  24028. component.dispose(ecModel, api);
  24029. });
  24030. each(this._chartsViews, function (chart) {
  24031. chart.dispose(ecModel, api);
  24032. });
  24033. // Dispose after all views disposed
  24034. this._zr.dispose();
  24035. delete instances[this.id];
  24036. };
  24037. mixin(ECharts, Eventful);
  24038. function updateHoverLayerStatus(zr, ecModel) {
  24039. var storage = zr.storage;
  24040. var elCount = 0;
  24041. storage.traverse(function (el) {
  24042. if (!el.isGroup) {
  24043. elCount++;
  24044. }
  24045. });
  24046. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  24047. storage.traverse(function (el) {
  24048. if (!el.isGroup) {
  24049. // Don't switch back.
  24050. el.useHoverLayer = true;
  24051. }
  24052. });
  24053. }
  24054. }
  24055. /**
  24056. * Update chart progressive and blend.
  24057. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24058. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24059. */
  24060. function updateBlend(seriesModel, chartView) {
  24061. var blendMode = seriesModel.get('blendMode') || null;
  24062. if (__DEV__) {
  24063. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  24064. console.warn('Only canvas support blendMode');
  24065. }
  24066. }
  24067. chartView.group.traverse(function (el) {
  24068. // FIXME marker and other components
  24069. if (!el.isGroup) {
  24070. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  24071. if (el.style.blend !== blendMode) {
  24072. el.setStyle('blend', blendMode);
  24073. }
  24074. }
  24075. if (el.eachPendingDisplayable) {
  24076. el.eachPendingDisplayable(function (displayable) {
  24077. displayable.setStyle('blend', blendMode);
  24078. });
  24079. }
  24080. });
  24081. }
  24082. /**
  24083. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24084. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24085. */
  24086. function updateZ(model, view) {
  24087. var z = model.get('z');
  24088. var zlevel = model.get('zlevel');
  24089. // Set z and zlevel
  24090. view.group.traverse(function (el) {
  24091. if (el.type !== 'group') {
  24092. z != null && (el.z = z);
  24093. zlevel != null && (el.zlevel = zlevel);
  24094. }
  24095. });
  24096. }
  24097. function createExtensionAPI(ecInstance) {
  24098. var coordSysMgr = ecInstance._coordSysMgr;
  24099. return extend(new ExtensionAPI(ecInstance), {
  24100. // Inject methods
  24101. getCoordinateSystems: bind(
  24102. coordSysMgr.getCoordinateSystems, coordSysMgr
  24103. ),
  24104. getComponentByElement: function (el) {
  24105. while (el) {
  24106. var modelInfo = el.__ecComponentInfo;
  24107. if (modelInfo != null) {
  24108. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  24109. }
  24110. el = el.parent;
  24111. }
  24112. }
  24113. });
  24114. }
  24115. /**
  24116. * @class
  24117. * Usage of query:
  24118. * `chart.on('click', query, handler);`
  24119. * The `query` can be:
  24120. * + The component type query string, only `mainType` or `mainType.subType`,
  24121. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  24122. * + The component query object, like:
  24123. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  24124. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  24125. * + The data query object, like:
  24126. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  24127. * + The other query object (cmponent customized query), like:
  24128. * `{element: 'some'}` (only available in custom series).
  24129. *
  24130. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  24131. * same as there is no such prop in the `query` object.
  24132. */
  24133. function EventProcessor() {
  24134. // These info required: targetEl, packedEvent, model, view
  24135. this.eventInfo;
  24136. }
  24137. EventProcessor.prototype = {
  24138. constructor: EventProcessor,
  24139. normalizeQuery: function (query) {
  24140. var cptQuery = {};
  24141. var dataQuery = {};
  24142. var otherQuery = {};
  24143. // `query` is `mainType` or `mainType.subType` of component.
  24144. if (isString(query)) {
  24145. var condCptType = parseClassType(query);
  24146. // `.main` and `.sub` may be ''.
  24147. cptQuery.mainType = condCptType.main || null;
  24148. cptQuery.subType = condCptType.sub || null;
  24149. }
  24150. // `query` is an object, convert to {mainType, index, name, id}.
  24151. else {
  24152. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  24153. // can not be used in `compomentModel.filterForExposedEvent`.
  24154. var suffixes = ['Index', 'Name', 'Id'];
  24155. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  24156. each$1(query, function (val, key) {
  24157. var reserved = false;
  24158. for (var i = 0; i < suffixes.length; i++) {
  24159. var propSuffix = suffixes[i];
  24160. var suffixPos = key.lastIndexOf(propSuffix);
  24161. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  24162. var mainType = key.slice(0, suffixPos);
  24163. // Consider `dataIndex`.
  24164. if (mainType !== 'data') {
  24165. cptQuery.mainType = mainType;
  24166. cptQuery[propSuffix.toLowerCase()] = val;
  24167. reserved = true;
  24168. }
  24169. }
  24170. }
  24171. if (dataKeys.hasOwnProperty(key)) {
  24172. dataQuery[key] = val;
  24173. reserved = true;
  24174. }
  24175. if (!reserved) {
  24176. otherQuery[key] = val;
  24177. }
  24178. });
  24179. }
  24180. return {
  24181. cptQuery: cptQuery,
  24182. dataQuery: dataQuery,
  24183. otherQuery: otherQuery
  24184. };
  24185. },
  24186. filter: function (eventType, query, args) {
  24187. // They should be assigned before each trigger call.
  24188. var eventInfo = this.eventInfo;
  24189. if (!eventInfo) {
  24190. return true;
  24191. }
  24192. var targetEl = eventInfo.targetEl;
  24193. var packedEvent = eventInfo.packedEvent;
  24194. var model = eventInfo.model;
  24195. var view = eventInfo.view;
  24196. // For event like 'globalout'.
  24197. if (!model || !view) {
  24198. return true;
  24199. }
  24200. var cptQuery = query.cptQuery;
  24201. var dataQuery = query.dataQuery;
  24202. return check(cptQuery, model, 'mainType')
  24203. && check(cptQuery, model, 'subType')
  24204. && check(cptQuery, model, 'index', 'componentIndex')
  24205. && check(cptQuery, model, 'name')
  24206. && check(cptQuery, model, 'id')
  24207. && check(dataQuery, packedEvent, 'name')
  24208. && check(dataQuery, packedEvent, 'dataIndex')
  24209. && check(dataQuery, packedEvent, 'dataType')
  24210. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  24211. eventType, query.otherQuery, targetEl, packedEvent
  24212. ));
  24213. function check(query, host, prop, propOnHost) {
  24214. return query[prop] == null || host[propOnHost || prop] === query[prop];
  24215. }
  24216. },
  24217. afterTrigger: function () {
  24218. // Make sure the eventInfo wont be used in next trigger.
  24219. this.eventInfo = null;
  24220. }
  24221. };
  24222. /**
  24223. * @type {Object} key: actionType.
  24224. * @inner
  24225. */
  24226. var actions = {};
  24227. /**
  24228. * Map eventType to actionType
  24229. * @type {Object}
  24230. */
  24231. var eventActionMap = {};
  24232. /**
  24233. * Data processor functions of each stage
  24234. * @type {Array.<Object.<string, Function>>}
  24235. * @inner
  24236. */
  24237. var dataProcessorFuncs = [];
  24238. /**
  24239. * @type {Array.<Function>}
  24240. * @inner
  24241. */
  24242. var optionPreprocessorFuncs = [];
  24243. /**
  24244. * @type {Array.<Function>}
  24245. * @inner
  24246. */
  24247. var postUpdateFuncs = [];
  24248. /**
  24249. * Visual encoding functions of each stage
  24250. * @type {Array.<Object.<string, Function>>}
  24251. */
  24252. var visualFuncs = [];
  24253. /**
  24254. * Theme storage
  24255. * @type {Object.<key, Object>}
  24256. */
  24257. var themeStorage = {};
  24258. /**
  24259. * Loading effects
  24260. */
  24261. var loadingEffects = {};
  24262. var instances = {};
  24263. var connectedGroups = {};
  24264. var idBase = new Date() - 0;
  24265. var groupIdBase = new Date() - 0;
  24266. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  24267. function enableConnect(chart) {
  24268. var STATUS_PENDING = 0;
  24269. var STATUS_UPDATING = 1;
  24270. var STATUS_UPDATED = 2;
  24271. var STATUS_KEY = '__connectUpdateStatus';
  24272. function updateConnectedChartsStatus(charts, status) {
  24273. for (var i = 0; i < charts.length; i++) {
  24274. var otherChart = charts[i];
  24275. otherChart[STATUS_KEY] = status;
  24276. }
  24277. }
  24278. each(eventActionMap, function (actionType, eventType) {
  24279. chart._messageCenter.on(eventType, function (event) {
  24280. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  24281. if (event && event.escapeConnect) {
  24282. return;
  24283. }
  24284. var action = chart.makeActionFromEvent(event);
  24285. var otherCharts = [];
  24286. each(instances, function (otherChart) {
  24287. if (otherChart !== chart && otherChart.group === chart.group) {
  24288. otherCharts.push(otherChart);
  24289. }
  24290. });
  24291. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  24292. each(otherCharts, function (otherChart) {
  24293. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  24294. otherChart.dispatchAction(action);
  24295. }
  24296. });
  24297. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  24298. }
  24299. });
  24300. });
  24301. }
  24302. /**
  24303. * @param {HTMLElement} dom
  24304. * @param {Object} [theme]
  24305. * @param {Object} opts
  24306. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  24307. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  24308. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  24309. * Can be 'auto' (the same as null/undefined)
  24310. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  24311. * Can be 'auto' (the same as null/undefined)
  24312. */
  24313. function init(dom, theme$$1, opts) {
  24314. if (__DEV__) {
  24315. // Check version
  24316. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  24317. throw new Error(
  24318. 'zrender/src ' + version$1
  24319. + ' is too old for ECharts ' + version
  24320. + '. Current version need ZRender '
  24321. + dependencies.zrender + '+'
  24322. );
  24323. }
  24324. if (!dom) {
  24325. throw new Error('Initialize failed: invalid dom.');
  24326. }
  24327. }
  24328. var existInstance = getInstanceByDom(dom);
  24329. if (existInstance) {
  24330. if (__DEV__) {
  24331. console.warn('There is a chart instance already initialized on the dom.');
  24332. }
  24333. return existInstance;
  24334. }
  24335. if (__DEV__) {
  24336. if (isDom(dom)
  24337. && dom.nodeName.toUpperCase() !== 'CANVAS'
  24338. && (
  24339. (!dom.clientWidth && (!opts || opts.width == null))
  24340. || (!dom.clientHeight && (!opts || opts.height == null))
  24341. )
  24342. ) {
  24343. console.warn('Can\'t get dom width or height');
  24344. }
  24345. }
  24346. var chart = new ECharts(dom, theme$$1, opts);
  24347. chart.id = 'ec_' + idBase++;
  24348. instances[chart.id] = chart;
  24349. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  24350. enableConnect(chart);
  24351. return chart;
  24352. }
  24353. /**
  24354. * @return {string|Array.<module:echarts~ECharts>} groupId
  24355. */
  24356. function connect(groupId) {
  24357. // Is array of charts
  24358. if (isArray(groupId)) {
  24359. var charts = groupId;
  24360. groupId = null;
  24361. // If any chart has group
  24362. each(charts, function (chart) {
  24363. if (chart.group != null) {
  24364. groupId = chart.group;
  24365. }
  24366. });
  24367. groupId = groupId || ('g_' + groupIdBase++);
  24368. each(charts, function (chart) {
  24369. chart.group = groupId;
  24370. });
  24371. }
  24372. connectedGroups[groupId] = true;
  24373. return groupId;
  24374. }
  24375. /**
  24376. * @DEPRECATED
  24377. * @return {string} groupId
  24378. */
  24379. function disConnect(groupId) {
  24380. connectedGroups[groupId] = false;
  24381. }
  24382. /**
  24383. * @return {string} groupId
  24384. */
  24385. var disconnect = disConnect;
  24386. /**
  24387. * Dispose a chart instance
  24388. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  24389. */
  24390. function dispose(chart) {
  24391. if (typeof chart === 'string') {
  24392. chart = instances[chart];
  24393. }
  24394. else if (!(chart instanceof ECharts)) {
  24395. // Try to treat as dom
  24396. chart = getInstanceByDom(chart);
  24397. }
  24398. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  24399. chart.dispose();
  24400. }
  24401. }
  24402. /**
  24403. * @param {HTMLElement} dom
  24404. * @return {echarts~ECharts}
  24405. */
  24406. function getInstanceByDom(dom) {
  24407. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  24408. }
  24409. /**
  24410. * @param {string} key
  24411. * @return {echarts~ECharts}
  24412. */
  24413. function getInstanceById(key) {
  24414. return instances[key];
  24415. }
  24416. /**
  24417. * Register theme
  24418. */
  24419. function registerTheme(name, theme$$1) {
  24420. themeStorage[name] = theme$$1;
  24421. }
  24422. /**
  24423. * Register option preprocessor
  24424. * @param {Function} preprocessorFunc
  24425. */
  24426. function registerPreprocessor(preprocessorFunc) {
  24427. optionPreprocessorFuncs.push(preprocessorFunc);
  24428. }
  24429. /**
  24430. * @param {number} [priority=1000]
  24431. * @param {Object|Function} processor
  24432. */
  24433. function registerProcessor(priority, processor) {
  24434. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  24435. }
  24436. /**
  24437. * Register postUpdater
  24438. * @param {Function} postUpdateFunc
  24439. */
  24440. function registerPostUpdate(postUpdateFunc) {
  24441. postUpdateFuncs.push(postUpdateFunc);
  24442. }
  24443. /**
  24444. * Usage:
  24445. * registerAction('someAction', 'someEvent', function () { ... });
  24446. * registerAction('someAction', function () { ... });
  24447. * registerAction(
  24448. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  24449. * function () { ... }
  24450. * );
  24451. *
  24452. * @param {(string|Object)} actionInfo
  24453. * @param {string} actionInfo.type
  24454. * @param {string} [actionInfo.event]
  24455. * @param {string} [actionInfo.update]
  24456. * @param {string} [eventName]
  24457. * @param {Function} action
  24458. */
  24459. function registerAction(actionInfo, eventName, action) {
  24460. if (typeof eventName === 'function') {
  24461. action = eventName;
  24462. eventName = '';
  24463. }
  24464. var actionType = isObject(actionInfo)
  24465. ? actionInfo.type
  24466. : ([actionInfo, actionInfo = {
  24467. event: eventName
  24468. }][0]);
  24469. // Event name is all lowercase
  24470. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  24471. eventName = actionInfo.event;
  24472. // Validate action type and event name.
  24473. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  24474. if (!actions[actionType]) {
  24475. actions[actionType] = {action: action, actionInfo: actionInfo};
  24476. }
  24477. eventActionMap[eventName] = actionType;
  24478. }
  24479. /**
  24480. * @param {string} type
  24481. * @param {*} CoordinateSystem
  24482. */
  24483. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  24484. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  24485. }
  24486. /**
  24487. * Get dimensions of specified coordinate system.
  24488. * @param {string} type
  24489. * @return {Array.<string|Object>}
  24490. */
  24491. function getCoordinateSystemDimensions(type) {
  24492. var coordSysCreator = CoordinateSystemManager.get(type);
  24493. if (coordSysCreator) {
  24494. return coordSysCreator.getDimensionsInfo
  24495. ? coordSysCreator.getDimensionsInfo()
  24496. : coordSysCreator.dimensions.slice();
  24497. }
  24498. }
  24499. /**
  24500. * Layout is a special stage of visual encoding
  24501. * Most visual encoding like color are common for different chart
  24502. * But each chart has it's own layout algorithm
  24503. *
  24504. * @param {number} [priority=1000]
  24505. * @param {Function} layoutTask
  24506. */
  24507. function registerLayout(priority, layoutTask) {
  24508. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  24509. }
  24510. /**
  24511. * @param {number} [priority=3000]
  24512. * @param {module:echarts/stream/Task} visualTask
  24513. */
  24514. function registerVisual(priority, visualTask) {
  24515. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  24516. }
  24517. /**
  24518. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  24519. */
  24520. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  24521. if (isFunction(priority) || isObject(priority)) {
  24522. fn = priority;
  24523. priority = defaultPriority;
  24524. }
  24525. if (__DEV__) {
  24526. if (isNaN(priority) || priority == null) {
  24527. throw new Error('Illegal priority');
  24528. }
  24529. // Check duplicate
  24530. each(targetList, function (wrap) {
  24531. assert(wrap.__raw !== fn);
  24532. });
  24533. }
  24534. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  24535. stageHandler.__prio = priority;
  24536. stageHandler.__raw = fn;
  24537. targetList.push(stageHandler);
  24538. return stageHandler;
  24539. }
  24540. /**
  24541. * @param {string} name
  24542. */
  24543. function registerLoading(name, loadingFx) {
  24544. loadingEffects[name] = loadingFx;
  24545. }
  24546. /**
  24547. * @param {Object} opts
  24548. * @param {string} [superClass]
  24549. */
  24550. function extendComponentModel(opts/*, superClass*/) {
  24551. // var Clazz = ComponentModel;
  24552. // if (superClass) {
  24553. // var classType = parseClassType(superClass);
  24554. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24555. // }
  24556. return ComponentModel.extend(opts);
  24557. }
  24558. /**
  24559. * @param {Object} opts
  24560. * @param {string} [superClass]
  24561. */
  24562. function extendComponentView(opts/*, superClass*/) {
  24563. // var Clazz = ComponentView;
  24564. // if (superClass) {
  24565. // var classType = parseClassType(superClass);
  24566. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  24567. // }
  24568. return Component.extend(opts);
  24569. }
  24570. /**
  24571. * @param {Object} opts
  24572. * @param {string} [superClass]
  24573. */
  24574. function extendSeriesModel(opts/*, superClass*/) {
  24575. // var Clazz = SeriesModel;
  24576. // if (superClass) {
  24577. // superClass = 'series.' + superClass.replace('series.', '');
  24578. // var classType = parseClassType(superClass);
  24579. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24580. // }
  24581. return SeriesModel.extend(opts);
  24582. }
  24583. /**
  24584. * @param {Object} opts
  24585. * @param {string} [superClass]
  24586. */
  24587. function extendChartView(opts/*, superClass*/) {
  24588. // var Clazz = ChartView;
  24589. // if (superClass) {
  24590. // superClass = superClass.replace('series.', '');
  24591. // var classType = parseClassType(superClass);
  24592. // Clazz = ChartView.getClass(classType.main, true);
  24593. // }
  24594. return Chart.extend(opts);
  24595. }
  24596. /**
  24597. * ZRender need a canvas context to do measureText.
  24598. * But in node environment canvas may be created by node-canvas.
  24599. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  24600. *
  24601. * Be careful of using it in the browser.
  24602. *
  24603. * @param {Function} creator
  24604. * @example
  24605. * var Canvas = require('canvas');
  24606. * var echarts = require('echarts');
  24607. * echarts.setCanvasCreator(function () {
  24608. * // Small size is enough.
  24609. * return new Canvas(32, 32);
  24610. * });
  24611. */
  24612. function setCanvasCreator(creator) {
  24613. $override('createCanvas', creator);
  24614. }
  24615. /**
  24616. * @param {string} mapName
  24617. * @param {Array.<Object>|Object|string} geoJson
  24618. * @param {Object} [specialAreas]
  24619. *
  24620. * @example GeoJSON
  24621. * $.get('USA.json', function (geoJson) {
  24622. * echarts.registerMap('USA', geoJson);
  24623. * // Or
  24624. * echarts.registerMap('USA', {
  24625. * geoJson: geoJson,
  24626. * specialAreas: {}
  24627. * })
  24628. * });
  24629. *
  24630. * $.get('airport.svg', function (svg) {
  24631. * echarts.registerMap('airport', {
  24632. * svg: svg
  24633. * }
  24634. * });
  24635. *
  24636. * echarts.registerMap('eu', [
  24637. * {svg: eu-topographic.svg},
  24638. * {geoJSON: eu.json}
  24639. * ])
  24640. */
  24641. function registerMap(mapName, geoJson, specialAreas) {
  24642. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  24643. }
  24644. /**
  24645. * @param {string} mapName
  24646. * @return {Object}
  24647. */
  24648. function getMap(mapName) {
  24649. // For backward compatibility, only return the first one.
  24650. var records = mapDataStorage.retrieveMap(mapName);
  24651. return records && records[0] && {
  24652. geoJson: records[0].geoJSON,
  24653. specialAreas: records[0].specialAreas
  24654. };
  24655. }
  24656. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  24657. registerPreprocessor(backwardCompat);
  24658. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  24659. registerLoading('default', loadingDefault);
  24660. // Default actions
  24661. registerAction({
  24662. type: 'highlight',
  24663. event: 'highlight',
  24664. update: 'highlight'
  24665. }, noop);
  24666. registerAction({
  24667. type: 'downplay',
  24668. event: 'downplay',
  24669. update: 'downplay'
  24670. }, noop);
  24671. // Default theme
  24672. registerTheme('light', lightTheme);
  24673. registerTheme('dark', theme);
  24674. // For backward compatibility, where the namespace `dataTool` will
  24675. // be mounted on `echarts` is the extension `dataTool` is imported.
  24676. var dataTool = {};
  24677. /*
  24678. * Licensed to the Apache Software Foundation (ASF) under one
  24679. * or more contributor license agreements. See the NOTICE file
  24680. * distributed with this work for additional information
  24681. * regarding copyright ownership. The ASF licenses this file
  24682. * to you under the Apache License, Version 2.0 (the
  24683. * "License"); you may not use this file except in compliance
  24684. * with the License. You may obtain a copy of the License at
  24685. *
  24686. * http://www.apache.org/licenses/LICENSE-2.0
  24687. *
  24688. * Unless required by applicable law or agreed to in writing,
  24689. * software distributed under the License is distributed on an
  24690. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24691. * KIND, either express or implied. See the License for the
  24692. * specific language governing permissions and limitations
  24693. * under the License.
  24694. */
  24695. function defaultKeyGetter(item) {
  24696. return item;
  24697. }
  24698. /**
  24699. * @param {Array} oldArr
  24700. * @param {Array} newArr
  24701. * @param {Function} oldKeyGetter
  24702. * @param {Function} newKeyGetter
  24703. * @param {Object} [context] Can be visited by this.context in callback.
  24704. */
  24705. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  24706. this._old = oldArr;
  24707. this._new = newArr;
  24708. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  24709. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  24710. this.context = context;
  24711. }
  24712. DataDiffer.prototype = {
  24713. constructor: DataDiffer,
  24714. /**
  24715. * Callback function when add a data
  24716. */
  24717. add: function (func) {
  24718. this._add = func;
  24719. return this;
  24720. },
  24721. /**
  24722. * Callback function when update a data
  24723. */
  24724. update: function (func) {
  24725. this._update = func;
  24726. return this;
  24727. },
  24728. /**
  24729. * Callback function when remove a data
  24730. */
  24731. remove: function (func) {
  24732. this._remove = func;
  24733. return this;
  24734. },
  24735. execute: function () {
  24736. var oldArr = this._old;
  24737. var newArr = this._new;
  24738. var oldDataIndexMap = {};
  24739. var newDataIndexMap = {};
  24740. var oldDataKeyArr = [];
  24741. var newDataKeyArr = [];
  24742. var i;
  24743. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  24744. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  24745. // Travel by inverted order to make sure order consistency
  24746. // when duplicate keys exists (consider newDataIndex.pop() below).
  24747. // For performance consideration, these code below do not look neat.
  24748. for (i = 0; i < oldArr.length; i++) {
  24749. var key = oldDataKeyArr[i];
  24750. var idx = newDataIndexMap[key];
  24751. // idx can never be empty array here. see 'set null' logic below.
  24752. if (idx != null) {
  24753. // Consider there is duplicate key (for example, use dataItem.name as key).
  24754. // We should make sure every item in newArr and oldArr can be visited.
  24755. var len = idx.length;
  24756. if (len) {
  24757. len === 1 && (newDataIndexMap[key] = null);
  24758. idx = idx.unshift();
  24759. }
  24760. else {
  24761. newDataIndexMap[key] = null;
  24762. }
  24763. this._update && this._update(idx, i);
  24764. }
  24765. else {
  24766. this._remove && this._remove(i);
  24767. }
  24768. }
  24769. for (var i = 0; i < newDataKeyArr.length; i++) {
  24770. var key = newDataKeyArr[i];
  24771. if (newDataIndexMap.hasOwnProperty(key)) {
  24772. var idx = newDataIndexMap[key];
  24773. if (idx == null) {
  24774. continue;
  24775. }
  24776. // idx can never be empty array here. see 'set null' logic above.
  24777. if (!idx.length) {
  24778. this._add && this._add(idx);
  24779. }
  24780. else {
  24781. for (var j = 0, len = idx.length; j < len; j++) {
  24782. this._add && this._add(idx[j]);
  24783. }
  24784. }
  24785. }
  24786. }
  24787. }
  24788. };
  24789. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  24790. for (var i = 0; i < arr.length; i++) {
  24791. // Add prefix to avoid conflict with Object.prototype.
  24792. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  24793. var existence = map[key];
  24794. if (existence == null) {
  24795. keyArr.push(key);
  24796. map[key] = i;
  24797. }
  24798. else {
  24799. if (!existence.length) {
  24800. map[key] = existence = [existence];
  24801. }
  24802. existence.push(i);
  24803. }
  24804. }
  24805. }
  24806. /*
  24807. * Licensed to the Apache Software Foundation (ASF) under one
  24808. * or more contributor license agreements. See the NOTICE file
  24809. * distributed with this work for additional information
  24810. * regarding copyright ownership. The ASF licenses this file
  24811. * to you under the Apache License, Version 2.0 (the
  24812. * "License"); you may not use this file except in compliance
  24813. * with the License. You may obtain a copy of the License at
  24814. *
  24815. * http://www.apache.org/licenses/LICENSE-2.0
  24816. *
  24817. * Unless required by applicable law or agreed to in writing,
  24818. * software distributed under the License is distributed on an
  24819. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24820. * KIND, either express or implied. See the License for the
  24821. * specific language governing permissions and limitations
  24822. * under the License.
  24823. */
  24824. var OTHER_DIMENSIONS = createHashMap([
  24825. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  24826. ]);
  24827. function summarizeDimensions(data) {
  24828. var summary = {};
  24829. var encode = summary.encode = {};
  24830. var notExtraCoordDimMap = createHashMap();
  24831. var defaultedLabel = [];
  24832. var defaultedTooltip = [];
  24833. each$1(data.dimensions, function (dimName) {
  24834. var dimItem = data.getDimensionInfo(dimName);
  24835. var coordDim = dimItem.coordDim;
  24836. if (coordDim) {
  24837. if (__DEV__) {
  24838. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  24839. }
  24840. var coordDimArr = encode[coordDim];
  24841. if (!encode.hasOwnProperty(coordDim)) {
  24842. coordDimArr = encode[coordDim] = [];
  24843. }
  24844. coordDimArr[dimItem.coordDimIndex] = dimName;
  24845. if (!dimItem.isExtraCoord) {
  24846. notExtraCoordDimMap.set(coordDim, 1);
  24847. // Use the last coord dim (and label friendly) as default label,
  24848. // because when dataset is used, it is hard to guess which dimension
  24849. // can be value dimension. If both show x, y on label is not look good,
  24850. // and conventionally y axis is focused more.
  24851. if (mayLabelDimType(dimItem.type)) {
  24852. defaultedLabel[0] = dimName;
  24853. }
  24854. }
  24855. if (dimItem.defaultTooltip) {
  24856. defaultedTooltip.push(dimName);
  24857. }
  24858. }
  24859. OTHER_DIMENSIONS.each(function (v, otherDim) {
  24860. var otherDimArr = encode[otherDim];
  24861. if (!encode.hasOwnProperty(otherDim)) {
  24862. otherDimArr = encode[otherDim] = [];
  24863. }
  24864. var dimIndex = dimItem.otherDims[otherDim];
  24865. if (dimIndex != null && dimIndex !== false) {
  24866. otherDimArr[dimIndex] = dimItem.name;
  24867. }
  24868. });
  24869. });
  24870. var dataDimsOnCoord = [];
  24871. var encodeFirstDimNotExtra = {};
  24872. notExtraCoordDimMap.each(function (v, coordDim) {
  24873. var dimArr = encode[coordDim];
  24874. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  24875. // But should fix the case that radar axes: simplify the logic
  24876. // of `completeDimension`, remove `extraPrefix`.
  24877. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  24878. // Not necessary to remove duplicate, because a data
  24879. // dim canot on more than one coordDim.
  24880. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  24881. });
  24882. summary.dataDimsOnCoord = dataDimsOnCoord;
  24883. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  24884. var encodeLabel = encode.label;
  24885. // FIXME `encode.label` is not recommanded, because formatter can not be set
  24886. // in this way. Use label.formatter instead. May be remove this approach someday.
  24887. if (encodeLabel && encodeLabel.length) {
  24888. defaultedLabel = encodeLabel.slice();
  24889. }
  24890. var encodeTooltip = encode.tooltip;
  24891. if (encodeTooltip && encodeTooltip.length) {
  24892. defaultedTooltip = encodeTooltip.slice();
  24893. }
  24894. else if (!defaultedTooltip.length) {
  24895. defaultedTooltip = defaultedLabel.slice();
  24896. }
  24897. encode.defaultedLabel = defaultedLabel;
  24898. encode.defaultedTooltip = defaultedTooltip;
  24899. return summary;
  24900. }
  24901. function getDimensionTypeByAxis(axisType) {
  24902. return axisType === 'category'
  24903. ? 'ordinal'
  24904. : axisType === 'time'
  24905. ? 'time'
  24906. : 'float';
  24907. }
  24908. function mayLabelDimType(dimType) {
  24909. // In most cases, ordinal and time do not suitable for label.
  24910. // Ordinal info can be displayed on axis. Time is too long.
  24911. return !(dimType === 'ordinal' || dimType === 'time');
  24912. }
  24913. // function findTheLastDimMayLabel(data) {
  24914. // // Get last value dim
  24915. // var dimensions = data.dimensions.slice();
  24916. // var valueType;
  24917. // var valueDim;
  24918. // while (dimensions.length && (
  24919. // valueDim = dimensions.pop(),
  24920. // valueType = data.getDimensionInfo(valueDim).type,
  24921. // valueType === 'ordinal' || valueType === 'time'
  24922. // )) {} // jshint ignore:line
  24923. // return valueDim;
  24924. // }
  24925. /*
  24926. * Licensed to the Apache Software Foundation (ASF) under one
  24927. * or more contributor license agreements. See the NOTICE file
  24928. * distributed with this work for additional information
  24929. * regarding copyright ownership. The ASF licenses this file
  24930. * to you under the Apache License, Version 2.0 (the
  24931. * "License"); you may not use this file except in compliance
  24932. * with the License. You may obtain a copy of the License at
  24933. *
  24934. * http://www.apache.org/licenses/LICENSE-2.0
  24935. *
  24936. * Unless required by applicable law or agreed to in writing,
  24937. * software distributed under the License is distributed on an
  24938. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24939. * KIND, either express or implied. See the License for the
  24940. * specific language governing permissions and limitations
  24941. * under the License.
  24942. */
  24943. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  24944. /**
  24945. * List for data storage
  24946. * @module echarts/data/List
  24947. */
  24948. var isObject$4 = isObject$1;
  24949. var UNDEFINED = 'undefined';
  24950. var INDEX_NOT_FOUND = -1;
  24951. // Use prefix to avoid index to be the same as otherIdList[idx],
  24952. // which will cause weird udpate animation.
  24953. var ID_PREFIX = 'e\0\0';
  24954. var dataCtors = {
  24955. 'float': typeof Float64Array === UNDEFINED
  24956. ? Array : Float64Array,
  24957. 'int': typeof Int32Array === UNDEFINED
  24958. ? Array : Int32Array,
  24959. // Ordinal data type can be string or int
  24960. 'ordinal': Array,
  24961. 'number': Array,
  24962. 'time': Array
  24963. };
  24964. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  24965. // different from the Ctor of typed array.
  24966. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  24967. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  24968. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  24969. function getIndicesCtor(list) {
  24970. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  24971. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  24972. }
  24973. function cloneChunk(originalChunk) {
  24974. var Ctor = originalChunk.constructor;
  24975. // Only shallow clone is enough when Array.
  24976. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  24977. }
  24978. var TRANSFERABLE_PROPERTIES = [
  24979. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  24980. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  24981. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  24982. ];
  24983. var CLONE_PROPERTIES = [
  24984. '_extent', '_approximateExtent', '_rawExtent'
  24985. ];
  24986. function transferProperties(target, source) {
  24987. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  24988. if (source.hasOwnProperty(propName)) {
  24989. target[propName] = source[propName];
  24990. }
  24991. });
  24992. target.__wrappedMethods = source.__wrappedMethods;
  24993. each$1(CLONE_PROPERTIES, function (propName) {
  24994. target[propName] = clone(source[propName]);
  24995. });
  24996. target._calculationInfo = extend(source._calculationInfo);
  24997. }
  24998. /**
  24999. * @constructor
  25000. * @alias module:echarts/data/List
  25001. *
  25002. * @param {Array.<string|Object>} dimensions
  25003. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  25004. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  25005. * Spetial fields: {
  25006. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  25007. * createInvertedIndices: <boolean>
  25008. * }
  25009. * @param {module:echarts/model/Model} hostModel
  25010. */
  25011. var List = function (dimensions, hostModel) {
  25012. dimensions = dimensions || ['x', 'y'];
  25013. var dimensionInfos = {};
  25014. var dimensionNames = [];
  25015. var invertedIndicesMap = {};
  25016. for (var i = 0; i < dimensions.length; i++) {
  25017. // Use the original dimensions[i], where other flag props may exists.
  25018. var dimensionInfo = dimensions[i];
  25019. if (isString(dimensionInfo)) {
  25020. dimensionInfo = {name: dimensionInfo};
  25021. }
  25022. var dimensionName = dimensionInfo.name;
  25023. dimensionInfo.type = dimensionInfo.type || 'float';
  25024. if (!dimensionInfo.coordDim) {
  25025. dimensionInfo.coordDim = dimensionName;
  25026. dimensionInfo.coordDimIndex = 0;
  25027. }
  25028. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  25029. dimensionNames.push(dimensionName);
  25030. dimensionInfos[dimensionName] = dimensionInfo;
  25031. dimensionInfo.index = i;
  25032. if (dimensionInfo.createInvertedIndices) {
  25033. invertedIndicesMap[dimensionName] = [];
  25034. }
  25035. }
  25036. /**
  25037. * @readOnly
  25038. * @type {Array.<string>}
  25039. */
  25040. this.dimensions = dimensionNames;
  25041. /**
  25042. * Infomation of each data dimension, like data type.
  25043. * @type {Object}
  25044. */
  25045. this._dimensionInfos = dimensionInfos;
  25046. /**
  25047. * @type {module:echarts/model/Model}
  25048. */
  25049. this.hostModel = hostModel;
  25050. /**
  25051. * @type {module:echarts/model/Model}
  25052. */
  25053. this.dataType;
  25054. /**
  25055. * Indices stores the indices of data subset after filtered.
  25056. * This data subset will be used in chart.
  25057. * @type {Array.<number>}
  25058. * @readOnly
  25059. */
  25060. this._indices = null;
  25061. this._count = 0;
  25062. this._rawCount = 0;
  25063. /**
  25064. * Data storage
  25065. * @type {Object.<key, Array.<TypedArray|Array>>}
  25066. * @private
  25067. */
  25068. this._storage = {};
  25069. /**
  25070. * @type {Array.<string>}
  25071. */
  25072. this._nameList = [];
  25073. /**
  25074. * @type {Array.<string>}
  25075. */
  25076. this._idList = [];
  25077. /**
  25078. * Models of data option is stored sparse for optimizing memory cost
  25079. * @type {Array.<module:echarts/model/Model>}
  25080. * @private
  25081. */
  25082. this._optionModels = [];
  25083. /**
  25084. * Global visual properties after visual coding
  25085. * @type {Object}
  25086. * @private
  25087. */
  25088. this._visual = {};
  25089. /**
  25090. * Globel layout properties.
  25091. * @type {Object}
  25092. * @private
  25093. */
  25094. this._layout = {};
  25095. /**
  25096. * Item visual properties after visual coding
  25097. * @type {Array.<Object>}
  25098. * @private
  25099. */
  25100. this._itemVisuals = [];
  25101. /**
  25102. * Key: visual type, Value: boolean
  25103. * @type {Object}
  25104. * @readOnly
  25105. */
  25106. this.hasItemVisual = {};
  25107. /**
  25108. * Item layout properties after layout
  25109. * @type {Array.<Object>}
  25110. * @private
  25111. */
  25112. this._itemLayouts = [];
  25113. /**
  25114. * Graphic elemnents
  25115. * @type {Array.<module:zrender/Element>}
  25116. * @private
  25117. */
  25118. this._graphicEls = [];
  25119. /**
  25120. * Max size of each chunk.
  25121. * @type {number}
  25122. * @private
  25123. */
  25124. this._chunkSize = 1e5;
  25125. /**
  25126. * @type {number}
  25127. * @private
  25128. */
  25129. this._chunkCount = 0;
  25130. /**
  25131. * @type {Array.<Array|Object>}
  25132. * @private
  25133. */
  25134. this._rawData;
  25135. /**
  25136. * Raw extent will not be cloned, but only transfered.
  25137. * It will not be calculated util needed.
  25138. * key: dim,
  25139. * value: {end: number, extent: Array.<number>}
  25140. * @type {Object}
  25141. * @private
  25142. */
  25143. this._rawExtent = {};
  25144. /**
  25145. * @type {Object}
  25146. * @private
  25147. */
  25148. this._extent = {};
  25149. /**
  25150. * key: dim
  25151. * value: extent
  25152. * @type {Object}
  25153. * @private
  25154. */
  25155. this._approximateExtent = {};
  25156. /**
  25157. * Cache summary info for fast visit. See "dimensionHelper".
  25158. * @type {Object}
  25159. * @private
  25160. */
  25161. this._dimensionsSummary = summarizeDimensions(this);
  25162. /**
  25163. * @type {Object.<Array|TypedArray>}
  25164. * @private
  25165. */
  25166. this._invertedIndicesMap = invertedIndicesMap;
  25167. /**
  25168. * @type {Object}
  25169. * @private
  25170. */
  25171. this._calculationInfo = {};
  25172. };
  25173. var listProto = List.prototype;
  25174. listProto.type = 'list';
  25175. /**
  25176. * If each data item has it's own option
  25177. * @type {boolean}
  25178. */
  25179. listProto.hasItemOption = true;
  25180. /**
  25181. * Get dimension name
  25182. * @param {string|number} dim
  25183. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25184. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25185. * @return {string} Concrete dim name.
  25186. */
  25187. listProto.getDimension = function (dim) {
  25188. if (!isNaN(dim)) {
  25189. dim = this.dimensions[dim] || dim;
  25190. }
  25191. return dim;
  25192. };
  25193. /**
  25194. * Get type and calculation info of particular dimension
  25195. * @param {string|number} dim
  25196. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25197. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25198. */
  25199. listProto.getDimensionInfo = function (dim) {
  25200. // Do not clone, because there may be categories in dimInfo.
  25201. return this._dimensionInfos[this.getDimension(dim)];
  25202. };
  25203. /**
  25204. * @return {Array.<string>} concrete dimension name list on coord.
  25205. */
  25206. listProto.getDimensionsOnCoord = function () {
  25207. return this._dimensionsSummary.dataDimsOnCoord.slice();
  25208. };
  25209. /**
  25210. * @param {string} coordDim
  25211. * @param {number} [idx] A coordDim may map to more than one data dim.
  25212. * If idx is `true`, return a array of all mapped dims.
  25213. * If idx is not specified, return the first dim not extra.
  25214. * @return {string|Array.<string>} concrete data dim.
  25215. * If idx is number, and not found, return null/undefined.
  25216. * If idx is `true`, and not found, return empty array (always return array).
  25217. */
  25218. listProto.mapDimension = function (coordDim, idx) {
  25219. var dimensionsSummary = this._dimensionsSummary;
  25220. if (idx == null) {
  25221. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  25222. }
  25223. var dims = dimensionsSummary.encode[coordDim];
  25224. return idx === true
  25225. // always return array if idx is `true`
  25226. ? (dims || []).slice()
  25227. : (dims && dims[idx]);
  25228. };
  25229. /**
  25230. * Initialize from data
  25231. * @param {Array.<Object|number|Array>} data source or data or data provider.
  25232. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  25233. * defualt label/tooltip.
  25234. * A name can be specified in encode.itemName,
  25235. * or dataItem.name (only for series option data),
  25236. * or provided in nameList from outside.
  25237. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  25238. */
  25239. listProto.initData = function (data, nameList, dimValueGetter) {
  25240. var notProvider = Source.isInstance(data) || isArrayLike(data);
  25241. if (notProvider) {
  25242. data = new DefaultDataProvider(data, this.dimensions.length);
  25243. }
  25244. if (__DEV__) {
  25245. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  25246. throw new Error('Inavlid data provider.');
  25247. }
  25248. }
  25249. this._rawData = data;
  25250. // Clear
  25251. this._storage = {};
  25252. this._indices = null;
  25253. this._nameList = nameList || [];
  25254. this._idList = [];
  25255. this._nameRepeatCount = {};
  25256. if (!dimValueGetter) {
  25257. this.hasItemOption = false;
  25258. }
  25259. /**
  25260. * @readOnly
  25261. */
  25262. this.defaultDimValueGetter = defaultDimValueGetters[
  25263. this._rawData.getSource().sourceFormat
  25264. ];
  25265. // Default dim value getter
  25266. this._dimValueGetter = dimValueGetter = dimValueGetter
  25267. || this.defaultDimValueGetter;
  25268. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  25269. // Reset raw extent.
  25270. this._rawExtent = {};
  25271. this._initDataFromProvider(0, data.count());
  25272. // If data has no item option.
  25273. if (data.pure) {
  25274. this.hasItemOption = false;
  25275. }
  25276. };
  25277. listProto.getProvider = function () {
  25278. return this._rawData;
  25279. };
  25280. /**
  25281. * Caution: Can be only called on raw data (before `this._indices` created).
  25282. */
  25283. listProto.appendData = function (data) {
  25284. if (__DEV__) {
  25285. assert$1(!this._indices, 'appendData can only be called on raw data.');
  25286. }
  25287. var rawData = this._rawData;
  25288. var start = this.count();
  25289. rawData.appendData(data);
  25290. var end = rawData.count();
  25291. if (!rawData.persistent) {
  25292. end += start;
  25293. }
  25294. this._initDataFromProvider(start, end);
  25295. };
  25296. /**
  25297. * Caution: Can be only called on raw data (before `this._indices` created).
  25298. * This method does not modify `rawData` (`dataProvider`), but only
  25299. * add values to storage.
  25300. *
  25301. * The final count will be increased by `Math.max(values.length, names.length)`.
  25302. *
  25303. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  25304. * [
  25305. * [12, 33, 44],
  25306. * [NaN, 43, 1],
  25307. * ['-', 'asdf', 0]
  25308. * ]
  25309. * Each item is exaclty cooresponding to a dimension.
  25310. * @param {Array.<string>} [names]
  25311. */
  25312. listProto.appendValues = function (values, names) {
  25313. var chunkSize = this._chunkSize;
  25314. var storage = this._storage;
  25315. var dimensions = this.dimensions;
  25316. var dimLen = dimensions.length;
  25317. var rawExtent = this._rawExtent;
  25318. var start = this.count();
  25319. var end = start + Math.max(values.length, names ? names.length : 0);
  25320. var originalChunkCount = this._chunkCount;
  25321. for (var i = 0; i < dimLen; i++) {
  25322. var dim = dimensions[i];
  25323. if (!rawExtent[dim]) {
  25324. rawExtent[dim] = getInitialExtent();
  25325. }
  25326. if (!storage[dim]) {
  25327. storage[dim] = [];
  25328. }
  25329. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  25330. this._chunkCount = storage[dim].length;
  25331. }
  25332. var emptyDataItem = new Array(dimLen);
  25333. for (var idx = start; idx < end; idx++) {
  25334. var sourceIdx = idx - start;
  25335. var chunkIndex = Math.floor(idx / chunkSize);
  25336. var chunkOffset = idx % chunkSize;
  25337. // Store the data by dimensions
  25338. for (var k = 0; k < dimLen; k++) {
  25339. var dim = dimensions[k];
  25340. var val = this._dimValueGetterArrayRows(
  25341. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  25342. );
  25343. storage[dim][chunkIndex][chunkOffset] = val;
  25344. var dimRawExtent = rawExtent[dim];
  25345. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  25346. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  25347. }
  25348. if (names) {
  25349. this._nameList[idx] = names[sourceIdx];
  25350. }
  25351. }
  25352. this._rawCount = this._count = end;
  25353. // Reset data extent
  25354. this._extent = {};
  25355. prepareInvertedIndex(this);
  25356. };
  25357. listProto._initDataFromProvider = function (start, end) {
  25358. // Optimize.
  25359. if (start >= end) {
  25360. return;
  25361. }
  25362. var chunkSize = this._chunkSize;
  25363. var rawData = this._rawData;
  25364. var storage = this._storage;
  25365. var dimensions = this.dimensions;
  25366. var dimLen = dimensions.length;
  25367. var dimensionInfoMap = this._dimensionInfos;
  25368. var nameList = this._nameList;
  25369. var idList = this._idList;
  25370. var rawExtent = this._rawExtent;
  25371. var nameRepeatCount = this._nameRepeatCount = {};
  25372. var nameDimIdx;
  25373. var originalChunkCount = this._chunkCount;
  25374. for (var i = 0; i < dimLen; i++) {
  25375. var dim = dimensions[i];
  25376. if (!rawExtent[dim]) {
  25377. rawExtent[dim] = getInitialExtent();
  25378. }
  25379. var dimInfo = dimensionInfoMap[dim];
  25380. if (dimInfo.otherDims.itemName === 0) {
  25381. nameDimIdx = this._nameDimIdx = i;
  25382. }
  25383. if (dimInfo.otherDims.itemId === 0) {
  25384. this._idDimIdx = i;
  25385. }
  25386. if (!storage[dim]) {
  25387. storage[dim] = [];
  25388. }
  25389. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  25390. this._chunkCount = storage[dim].length;
  25391. }
  25392. var dataItem = new Array(dimLen);
  25393. for (var idx = start; idx < end; idx++) {
  25394. // NOTICE: Try not to write things into dataItem
  25395. dataItem = rawData.getItem(idx, dataItem);
  25396. // Each data item is value
  25397. // [1, 2]
  25398. // 2
  25399. // Bar chart, line chart which uses category axis
  25400. // only gives the 'y' value. 'x' value is the indices of category
  25401. // Use a tempValue to normalize the value to be a (x, y) value
  25402. var chunkIndex = Math.floor(idx / chunkSize);
  25403. var chunkOffset = idx % chunkSize;
  25404. // Store the data by dimensions
  25405. for (var k = 0; k < dimLen; k++) {
  25406. var dim = dimensions[k];
  25407. var dimStorage = storage[dim][chunkIndex];
  25408. // PENDING NULL is empty or zero
  25409. var val = this._dimValueGetter(dataItem, dim, idx, k);
  25410. dimStorage[chunkOffset] = val;
  25411. var dimRawExtent = rawExtent[dim];
  25412. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  25413. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  25414. }
  25415. // ??? FIXME not check by pure but sourceFormat?
  25416. // TODO refactor these logic.
  25417. if (!rawData.pure) {
  25418. var name = nameList[idx];
  25419. if (dataItem && name == null) {
  25420. // If dataItem is {name: ...}, it has highest priority.
  25421. // That is appropriate for many common cases.
  25422. if (dataItem.name != null) {
  25423. // There is no other place to persistent dataItem.name,
  25424. // so save it to nameList.
  25425. nameList[idx] = name = dataItem.name;
  25426. }
  25427. else if (nameDimIdx != null) {
  25428. var nameDim = dimensions[nameDimIdx];
  25429. var nameDimChunk = storage[nameDim][chunkIndex];
  25430. if (nameDimChunk) {
  25431. name = nameDimChunk[chunkOffset];
  25432. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  25433. if (ordinalMeta && ordinalMeta.categories.length) {
  25434. name = ordinalMeta.categories[name];
  25435. }
  25436. }
  25437. }
  25438. }
  25439. // Try using the id in option
  25440. // id or name is used on dynamical data, mapping old and new items.
  25441. var id = dataItem == null ? null : dataItem.id;
  25442. if (id == null && name != null) {
  25443. // Use name as id and add counter to avoid same name
  25444. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  25445. id = name;
  25446. if (nameRepeatCount[name] > 0) {
  25447. id += '__ec__' + nameRepeatCount[name];
  25448. }
  25449. nameRepeatCount[name]++;
  25450. }
  25451. id != null && (idList[idx] = id);
  25452. }
  25453. }
  25454. if (!rawData.persistent && rawData.clean) {
  25455. // Clean unused data if data source is typed array.
  25456. rawData.clean();
  25457. }
  25458. this._rawCount = this._count = end;
  25459. // Reset data extent
  25460. this._extent = {};
  25461. prepareInvertedIndex(this);
  25462. };
  25463. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  25464. var DataCtor = dataCtors[dimInfo.type];
  25465. var lastChunkIndex = chunkCount - 1;
  25466. var dim = dimInfo.name;
  25467. var resizeChunkArray = storage[dim][lastChunkIndex];
  25468. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  25469. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  25470. // The cost of the copy is probably inconsiderable
  25471. // within the initial chunkSize.
  25472. for (var j = 0; j < resizeChunkArray.length; j++) {
  25473. newStore[j] = resizeChunkArray[j];
  25474. }
  25475. storage[dim][lastChunkIndex] = newStore;
  25476. }
  25477. // Create new chunks.
  25478. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  25479. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  25480. }
  25481. }
  25482. function prepareInvertedIndex(list) {
  25483. var invertedIndicesMap = list._invertedIndicesMap;
  25484. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  25485. var dimInfo = list._dimensionInfos[dim];
  25486. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  25487. var ordinalMeta = dimInfo.ordinalMeta;
  25488. if (ordinalMeta) {
  25489. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  25490. ordinalMeta.categories.length
  25491. );
  25492. // The default value of TypedArray is 0. To avoid miss
  25493. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  25494. for (var i = 0; i < invertedIndices.length; i++) {
  25495. invertedIndices[i] = INDEX_NOT_FOUND;
  25496. }
  25497. for (var i = 0; i < list._count; i++) {
  25498. // Only support the case that all values are distinct.
  25499. invertedIndices[list.get(dim, i)] = i;
  25500. }
  25501. }
  25502. });
  25503. }
  25504. function getRawValueFromStore(list, dimIndex, rawIndex) {
  25505. var val;
  25506. if (dimIndex != null) {
  25507. var chunkSize = list._chunkSize;
  25508. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25509. var chunkOffset = rawIndex % chunkSize;
  25510. var dim = list.dimensions[dimIndex];
  25511. var chunk = list._storage[dim][chunkIndex];
  25512. if (chunk) {
  25513. val = chunk[chunkOffset];
  25514. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  25515. if (ordinalMeta && ordinalMeta.categories.length) {
  25516. val = ordinalMeta.categories[val];
  25517. }
  25518. }
  25519. }
  25520. return val;
  25521. }
  25522. /**
  25523. * @return {number}
  25524. */
  25525. listProto.count = function () {
  25526. return this._count;
  25527. };
  25528. listProto.getIndices = function () {
  25529. var newIndices;
  25530. var indices = this._indices;
  25531. if (indices) {
  25532. var Ctor = indices.constructor;
  25533. var thisCount = this._count;
  25534. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  25535. if (Ctor === Array) {
  25536. newIndices = new Ctor(thisCount);
  25537. for (var i = 0; i < thisCount; i++) {
  25538. newIndices[i] = indices[i];
  25539. }
  25540. }
  25541. else {
  25542. newIndices = new Ctor(indices.buffer, 0, thisCount);
  25543. }
  25544. }
  25545. else {
  25546. var Ctor = getIndicesCtor(this);
  25547. var newIndices = new Ctor(this.count());
  25548. for (var i = 0; i < newIndices.length; i++) {
  25549. newIndices[i] = i;
  25550. }
  25551. }
  25552. return newIndices;
  25553. };
  25554. /**
  25555. * Get value. Return NaN if idx is out of range.
  25556. * @param {string} dim Dim must be concrete name.
  25557. * @param {number} idx
  25558. * @param {boolean} stack
  25559. * @return {number}
  25560. */
  25561. listProto.get = function (dim, idx /*, stack */) {
  25562. if (!(idx >= 0 && idx < this._count)) {
  25563. return NaN;
  25564. }
  25565. var storage = this._storage;
  25566. if (!storage[dim]) {
  25567. // TODO Warn ?
  25568. return NaN;
  25569. }
  25570. idx = this.getRawIndex(idx);
  25571. var chunkIndex = Math.floor(idx / this._chunkSize);
  25572. var chunkOffset = idx % this._chunkSize;
  25573. var chunkStore = storage[dim][chunkIndex];
  25574. var value = chunkStore[chunkOffset];
  25575. // FIXME ordinal data type is not stackable
  25576. // if (stack) {
  25577. // var dimensionInfo = this._dimensionInfos[dim];
  25578. // if (dimensionInfo && dimensionInfo.stackable) {
  25579. // var stackedOn = this.stackedOn;
  25580. // while (stackedOn) {
  25581. // // Get no stacked data of stacked on
  25582. // var stackedValue = stackedOn.get(dim, idx);
  25583. // // Considering positive stack, negative stack and empty data
  25584. // if ((value >= 0 && stackedValue > 0) // Positive stack
  25585. // || (value <= 0 && stackedValue < 0) // Negative stack
  25586. // ) {
  25587. // value += stackedValue;
  25588. // }
  25589. // stackedOn = stackedOn.stackedOn;
  25590. // }
  25591. // }
  25592. // }
  25593. return value;
  25594. };
  25595. /**
  25596. * @param {string} dim concrete dim
  25597. * @param {number} rawIndex
  25598. * @return {number|string}
  25599. */
  25600. listProto.getByRawIndex = function (dim, rawIdx) {
  25601. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  25602. return NaN;
  25603. }
  25604. var dimStore = this._storage[dim];
  25605. if (!dimStore) {
  25606. // TODO Warn ?
  25607. return NaN;
  25608. }
  25609. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25610. var chunkOffset = rawIdx % this._chunkSize;
  25611. var chunkStore = dimStore[chunkIndex];
  25612. return chunkStore[chunkOffset];
  25613. };
  25614. /**
  25615. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  25616. * Hack a much simpler _getFast
  25617. * @private
  25618. */
  25619. listProto._getFast = function (dim, rawIdx) {
  25620. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25621. var chunkOffset = rawIdx % this._chunkSize;
  25622. var chunkStore = this._storage[dim][chunkIndex];
  25623. return chunkStore[chunkOffset];
  25624. };
  25625. /**
  25626. * Get value for multi dimensions.
  25627. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  25628. * @param {number} idx
  25629. * @return {number}
  25630. */
  25631. listProto.getValues = function (dimensions, idx /*, stack */) {
  25632. var values = [];
  25633. if (!isArray(dimensions)) {
  25634. // stack = idx;
  25635. idx = dimensions;
  25636. dimensions = this.dimensions;
  25637. }
  25638. for (var i = 0, len = dimensions.length; i < len; i++) {
  25639. values.push(this.get(dimensions[i], idx /*, stack */));
  25640. }
  25641. return values;
  25642. };
  25643. /**
  25644. * If value is NaN. Inlcuding '-'
  25645. * Only check the coord dimensions.
  25646. * @param {string} dim
  25647. * @param {number} idx
  25648. * @return {number}
  25649. */
  25650. listProto.hasValue = function (idx) {
  25651. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  25652. var dimensionInfos = this._dimensionInfos;
  25653. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  25654. if (
  25655. // Ordinal type can be string or number
  25656. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  25657. // FIXME check ordinal when using index?
  25658. && isNaN(this.get(dataDimsOnCoord[i], idx))
  25659. ) {
  25660. return false;
  25661. }
  25662. }
  25663. return true;
  25664. };
  25665. /**
  25666. * Get extent of data in one dimension
  25667. * @param {string} dim
  25668. * @param {boolean} stack
  25669. */
  25670. listProto.getDataExtent = function (dim /*, stack */) {
  25671. // Make sure use concrete dim as cache name.
  25672. dim = this.getDimension(dim);
  25673. var dimData = this._storage[dim];
  25674. var initialExtent = getInitialExtent();
  25675. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  25676. if (!dimData) {
  25677. return initialExtent;
  25678. }
  25679. // Make more strict checkings to ensure hitting cache.
  25680. var currEnd = this.count();
  25681. // var cacheName = [dim, !!stack].join('_');
  25682. // var cacheName = dim;
  25683. // Consider the most cases when using data zoom, `getDataExtent`
  25684. // happened before filtering. We cache raw extent, which is not
  25685. // necessary to be cleared and recalculated when restore data.
  25686. var useRaw = !this._indices; // && !stack;
  25687. var dimExtent;
  25688. if (useRaw) {
  25689. return this._rawExtent[dim].slice();
  25690. }
  25691. dimExtent = this._extent[dim];
  25692. if (dimExtent) {
  25693. return dimExtent.slice();
  25694. }
  25695. dimExtent = initialExtent;
  25696. var min = dimExtent[0];
  25697. var max = dimExtent[1];
  25698. for (var i = 0; i < currEnd; i++) {
  25699. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  25700. var value = this._getFast(dim, this.getRawIndex(i));
  25701. value < min && (min = value);
  25702. value > max && (max = value);
  25703. }
  25704. dimExtent = [min, max];
  25705. this._extent[dim] = dimExtent;
  25706. return dimExtent;
  25707. };
  25708. /**
  25709. * Optimize for the scenario that data is filtered by a given extent.
  25710. * Consider that if data amount is more than hundreds of thousand,
  25711. * extent calculation will cost more than 10ms and the cache will
  25712. * be erased because of the filtering.
  25713. */
  25714. listProto.getApproximateExtent = function (dim /*, stack */) {
  25715. dim = this.getDimension(dim);
  25716. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  25717. };
  25718. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  25719. dim = this.getDimension(dim);
  25720. this._approximateExtent[dim] = extent.slice();
  25721. };
  25722. /**
  25723. * @param {string} key
  25724. * @return {*}
  25725. */
  25726. listProto.getCalculationInfo = function (key) {
  25727. return this._calculationInfo[key];
  25728. };
  25729. /**
  25730. * @param {string|Object} key or k-v object
  25731. * @param {*} [value]
  25732. */
  25733. listProto.setCalculationInfo = function (key, value) {
  25734. isObject$4(key)
  25735. ? extend(this._calculationInfo, key)
  25736. : (this._calculationInfo[key] = value);
  25737. };
  25738. /**
  25739. * Get sum of data in one dimension
  25740. * @param {string} dim
  25741. */
  25742. listProto.getSum = function (dim /*, stack */) {
  25743. var dimData = this._storage[dim];
  25744. var sum = 0;
  25745. if (dimData) {
  25746. for (var i = 0, len = this.count(); i < len; i++) {
  25747. var value = this.get(dim, i /*, stack */);
  25748. if (!isNaN(value)) {
  25749. sum += value;
  25750. }
  25751. }
  25752. }
  25753. return sum;
  25754. };
  25755. /**
  25756. * Get median of data in one dimension
  25757. * @param {string} dim
  25758. */
  25759. listProto.getMedian = function (dim /*, stack */) {
  25760. var dimDataArray = [];
  25761. // map all data of one dimension
  25762. this.each(dim, function (val, idx) {
  25763. if (!isNaN(val)) {
  25764. dimDataArray.push(val);
  25765. }
  25766. });
  25767. // TODO
  25768. // Use quick select?
  25769. // immutability & sort
  25770. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  25771. return a - b;
  25772. });
  25773. var len = this.count();
  25774. // calculate median
  25775. return len === 0
  25776. ? 0
  25777. : len % 2 === 1
  25778. ? sortedDimDataArray[(len - 1) / 2]
  25779. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  25780. };
  25781. // /**
  25782. // * Retreive the index with given value
  25783. // * @param {string} dim Concrete dimension.
  25784. // * @param {number} value
  25785. // * @return {number}
  25786. // */
  25787. // Currently incorrect: should return dataIndex but not rawIndex.
  25788. // Do not fix it until this method is to be used somewhere.
  25789. // FIXME Precision of float value
  25790. // listProto.indexOf = function (dim, value) {
  25791. // var storage = this._storage;
  25792. // var dimData = storage[dim];
  25793. // var chunkSize = this._chunkSize;
  25794. // if (dimData) {
  25795. // for (var i = 0, len = this.count(); i < len; i++) {
  25796. // var chunkIndex = Math.floor(i / chunkSize);
  25797. // var chunkOffset = i % chunkSize;
  25798. // if (dimData[chunkIndex][chunkOffset] === value) {
  25799. // return i;
  25800. // }
  25801. // }
  25802. // }
  25803. // return -1;
  25804. // };
  25805. /**
  25806. * Only support the dimension which inverted index created.
  25807. * Do not support other cases until required.
  25808. * @param {string} concrete dim
  25809. * @param {number|string} value
  25810. * @return {number} rawIndex
  25811. */
  25812. listProto.rawIndexOf = function (dim, value) {
  25813. var invertedIndices = dim && this._invertedIndicesMap[dim];
  25814. if (__DEV__) {
  25815. if (!invertedIndices) {
  25816. throw new Error('Do not supported yet');
  25817. }
  25818. }
  25819. var rawIndex = invertedIndices[value];
  25820. if (rawIndex == null || isNaN(rawIndex)) {
  25821. return INDEX_NOT_FOUND;
  25822. }
  25823. return rawIndex;
  25824. };
  25825. /**
  25826. * Retreive the index with given name
  25827. * @param {number} idx
  25828. * @param {number} name
  25829. * @return {number}
  25830. */
  25831. listProto.indexOfName = function (name) {
  25832. for (var i = 0, len = this.count(); i < len; i++) {
  25833. if (this.getName(i) === name) {
  25834. return i;
  25835. }
  25836. }
  25837. return -1;
  25838. };
  25839. /**
  25840. * Retreive the index with given raw data index
  25841. * @param {number} idx
  25842. * @param {number} name
  25843. * @return {number}
  25844. */
  25845. listProto.indexOfRawIndex = function (rawIndex) {
  25846. if (!this._indices) {
  25847. return rawIndex;
  25848. }
  25849. if (rawIndex >= this._rawCount || rawIndex < 0) {
  25850. return -1;
  25851. }
  25852. // Indices are ascending
  25853. var indices = this._indices;
  25854. // If rawIndex === dataIndex
  25855. var rawDataIndex = indices[rawIndex];
  25856. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  25857. return rawIndex;
  25858. }
  25859. var left = 0;
  25860. var right = this._count - 1;
  25861. while (left <= right) {
  25862. var mid = (left + right) / 2 | 0;
  25863. if (indices[mid] < rawIndex) {
  25864. left = mid + 1;
  25865. }
  25866. else if (indices[mid] > rawIndex) {
  25867. right = mid - 1;
  25868. }
  25869. else {
  25870. return mid;
  25871. }
  25872. }
  25873. return -1;
  25874. };
  25875. /**
  25876. * Retreive the index of nearest value
  25877. * @param {string} dim
  25878. * @param {number} value
  25879. * @param {number} [maxDistance=Infinity]
  25880. * @return {Array.<number>} Considere multiple points has the same value.
  25881. */
  25882. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  25883. var storage = this._storage;
  25884. var dimData = storage[dim];
  25885. var nearestIndices = [];
  25886. if (!dimData) {
  25887. return nearestIndices;
  25888. }
  25889. if (maxDistance == null) {
  25890. maxDistance = Infinity;
  25891. }
  25892. var minDist = Number.MAX_VALUE;
  25893. var minDiff = -1;
  25894. for (var i = 0, len = this.count(); i < len; i++) {
  25895. var diff = value - this.get(dim, i /*, stack */);
  25896. var dist = Math.abs(diff);
  25897. if (diff <= maxDistance && dist <= minDist) {
  25898. // For the case of two data are same on xAxis, which has sequence data.
  25899. // Show the nearest index
  25900. // https://github.com/ecomfe/echarts/issues/2869
  25901. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  25902. minDist = dist;
  25903. minDiff = diff;
  25904. nearestIndices.length = 0;
  25905. }
  25906. nearestIndices.push(i);
  25907. }
  25908. }
  25909. return nearestIndices;
  25910. };
  25911. /**
  25912. * Get raw data index
  25913. * @param {number} idx
  25914. * @return {number}
  25915. */
  25916. listProto.getRawIndex = getRawIndexWithoutIndices;
  25917. function getRawIndexWithoutIndices(idx) {
  25918. return idx;
  25919. }
  25920. function getRawIndexWithIndices(idx) {
  25921. if (idx < this._count && idx >= 0) {
  25922. return this._indices[idx];
  25923. }
  25924. return -1;
  25925. }
  25926. /**
  25927. * Get raw data item
  25928. * @param {number} idx
  25929. * @return {number}
  25930. */
  25931. listProto.getRawDataItem = function (idx) {
  25932. if (!this._rawData.persistent) {
  25933. var val = [];
  25934. for (var i = 0; i < this.dimensions.length; i++) {
  25935. var dim = this.dimensions[i];
  25936. val.push(this.get(dim, idx));
  25937. }
  25938. return val;
  25939. }
  25940. else {
  25941. return this._rawData.getItem(this.getRawIndex(idx));
  25942. }
  25943. };
  25944. /**
  25945. * @param {number} idx
  25946. * @param {boolean} [notDefaultIdx=false]
  25947. * @return {string}
  25948. */
  25949. listProto.getName = function (idx) {
  25950. var rawIndex = this.getRawIndex(idx);
  25951. return this._nameList[rawIndex]
  25952. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  25953. || '';
  25954. };
  25955. /**
  25956. * @param {number} idx
  25957. * @param {boolean} [notDefaultIdx=false]
  25958. * @return {string}
  25959. */
  25960. listProto.getId = function (idx) {
  25961. return getId(this, this.getRawIndex(idx));
  25962. };
  25963. function getId(list, rawIndex) {
  25964. var id = list._idList[rawIndex];
  25965. if (id == null) {
  25966. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  25967. }
  25968. if (id == null) {
  25969. // FIXME Check the usage in graph, should not use prefix.
  25970. id = ID_PREFIX + rawIndex;
  25971. }
  25972. return id;
  25973. }
  25974. function normalizeDimensions(dimensions) {
  25975. if (!isArray(dimensions)) {
  25976. dimensions = [dimensions];
  25977. }
  25978. return dimensions;
  25979. }
  25980. function validateDimensions(list, dims) {
  25981. for (var i = 0; i < dims.length; i++) {
  25982. // stroage may be empty when no data, so use
  25983. // dimensionInfos to check.
  25984. if (!list._dimensionInfos[dims[i]]) {
  25985. console.error('Unkown dimension ' + dims[i]);
  25986. }
  25987. }
  25988. }
  25989. /**
  25990. * Data iteration
  25991. * @param {string|Array.<string>}
  25992. * @param {Function} cb
  25993. * @param {*} [context=this]
  25994. *
  25995. * @example
  25996. * list.each('x', function (x, idx) {});
  25997. * list.each(['x', 'y'], function (x, y, idx) {});
  25998. * list.each(function (idx) {})
  25999. */
  26000. listProto.each = function (dims, cb, context, contextCompat) {
  26001. 'use strict';
  26002. if (!this._count) {
  26003. return;
  26004. }
  26005. if (typeof dims === 'function') {
  26006. contextCompat = context;
  26007. context = cb;
  26008. cb = dims;
  26009. dims = [];
  26010. }
  26011. // contextCompat just for compat echarts3
  26012. context = context || contextCompat || this;
  26013. dims = map(normalizeDimensions(dims), this.getDimension, this);
  26014. if (__DEV__) {
  26015. validateDimensions(this, dims);
  26016. }
  26017. var dimSize = dims.length;
  26018. for (var i = 0; i < this.count(); i++) {
  26019. // Simple optimization
  26020. switch (dimSize) {
  26021. case 0:
  26022. cb.call(context, i);
  26023. break;
  26024. case 1:
  26025. cb.call(context, this.get(dims[0], i), i);
  26026. break;
  26027. case 2:
  26028. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  26029. break;
  26030. default:
  26031. var k = 0;
  26032. var value = [];
  26033. for (; k < dimSize; k++) {
  26034. value[k] = this.get(dims[k], i);
  26035. }
  26036. // Index
  26037. value[k] = i;
  26038. cb.apply(context, value);
  26039. }
  26040. }
  26041. };
  26042. /**
  26043. * Data filter
  26044. * @param {string|Array.<string>}
  26045. * @param {Function} cb
  26046. * @param {*} [context=this]
  26047. */
  26048. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  26049. 'use strict';
  26050. if (!this._count) {
  26051. return;
  26052. }
  26053. if (typeof dimensions === 'function') {
  26054. contextCompat = context;
  26055. context = cb;
  26056. cb = dimensions;
  26057. dimensions = [];
  26058. }
  26059. // contextCompat just for compat echarts3
  26060. context = context || contextCompat || this;
  26061. dimensions = map(
  26062. normalizeDimensions(dimensions), this.getDimension, this
  26063. );
  26064. if (__DEV__) {
  26065. validateDimensions(this, dimensions);
  26066. }
  26067. var count = this.count();
  26068. var Ctor = getIndicesCtor(this);
  26069. var newIndices = new Ctor(count);
  26070. var value = [];
  26071. var dimSize = dimensions.length;
  26072. var offset = 0;
  26073. var dim0 = dimensions[0];
  26074. for (var i = 0; i < count; i++) {
  26075. var keep;
  26076. var rawIdx = this.getRawIndex(i);
  26077. // Simple optimization
  26078. if (dimSize === 0) {
  26079. keep = cb.call(context, i);
  26080. }
  26081. else if (dimSize === 1) {
  26082. var val = this._getFast(dim0, rawIdx);
  26083. keep = cb.call(context, val, i);
  26084. }
  26085. else {
  26086. for (var k = 0; k < dimSize; k++) {
  26087. value[k] = this._getFast(dim0, rawIdx);
  26088. }
  26089. value[k] = i;
  26090. keep = cb.apply(context, value);
  26091. }
  26092. if (keep) {
  26093. newIndices[offset++] = rawIdx;
  26094. }
  26095. }
  26096. // Set indices after filtered.
  26097. if (offset < count) {
  26098. this._indices = newIndices;
  26099. }
  26100. this._count = offset;
  26101. // Reset data extent
  26102. this._extent = {};
  26103. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26104. return this;
  26105. };
  26106. /**
  26107. * Select data in range. (For optimization of filter)
  26108. * (Manually inline code, support 5 million data filtering in data zoom.)
  26109. */
  26110. listProto.selectRange = function (range) {
  26111. 'use strict';
  26112. if (!this._count) {
  26113. return;
  26114. }
  26115. var dimensions = [];
  26116. for (var dim in range) {
  26117. if (range.hasOwnProperty(dim)) {
  26118. dimensions.push(dim);
  26119. }
  26120. }
  26121. if (__DEV__) {
  26122. validateDimensions(this, dimensions);
  26123. }
  26124. var dimSize = dimensions.length;
  26125. if (!dimSize) {
  26126. return;
  26127. }
  26128. var originalCount = this.count();
  26129. var Ctor = getIndicesCtor(this);
  26130. var newIndices = new Ctor(originalCount);
  26131. var offset = 0;
  26132. var dim0 = dimensions[0];
  26133. var min = range[dim0][0];
  26134. var max = range[dim0][1];
  26135. var quickFinished = false;
  26136. if (!this._indices) {
  26137. // Extreme optimization for common case. About 2x faster in chrome.
  26138. var idx = 0;
  26139. if (dimSize === 1) {
  26140. var dimStorage = this._storage[dimensions[0]];
  26141. for (var k = 0; k < this._chunkCount; k++) {
  26142. var chunkStorage = dimStorage[k];
  26143. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26144. for (var i = 0; i < len; i++) {
  26145. var val = chunkStorage[i];
  26146. // NaN will not be filtered. Consider the case, in line chart, empty
  26147. // value indicates the line should be broken. But for the case like
  26148. // scatter plot, a data item with empty value will not be rendered,
  26149. // but the axis extent may be effected if some other dim of the data
  26150. // item has value. Fortunately it is not a significant negative effect.
  26151. if (
  26152. (val >= min && val <= max) || isNaN(val)
  26153. ) {
  26154. newIndices[offset++] = idx;
  26155. }
  26156. idx++;
  26157. }
  26158. }
  26159. quickFinished = true;
  26160. }
  26161. else if (dimSize === 2) {
  26162. var dimStorage = this._storage[dim0];
  26163. var dimStorage2 = this._storage[dimensions[1]];
  26164. var min2 = range[dimensions[1]][0];
  26165. var max2 = range[dimensions[1]][1];
  26166. for (var k = 0; k < this._chunkCount; k++) {
  26167. var chunkStorage = dimStorage[k];
  26168. var chunkStorage2 = dimStorage2[k];
  26169. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26170. for (var i = 0; i < len; i++) {
  26171. var val = chunkStorage[i];
  26172. var val2 = chunkStorage2[i];
  26173. // Do not filter NaN, see comment above.
  26174. if ((
  26175. (val >= min && val <= max) || isNaN(val)
  26176. )
  26177. && (
  26178. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  26179. )
  26180. ) {
  26181. newIndices[offset++] = idx;
  26182. }
  26183. idx++;
  26184. }
  26185. }
  26186. quickFinished = true;
  26187. }
  26188. }
  26189. if (!quickFinished) {
  26190. if (dimSize === 1) {
  26191. for (var i = 0; i < originalCount; i++) {
  26192. var rawIndex = this.getRawIndex(i);
  26193. var val = this._getFast(dim0, rawIndex);
  26194. // Do not filter NaN, see comment above.
  26195. if (
  26196. (val >= min && val <= max) || isNaN(val)
  26197. ) {
  26198. newIndices[offset++] = rawIndex;
  26199. }
  26200. }
  26201. }
  26202. else {
  26203. for (var i = 0; i < originalCount; i++) {
  26204. var keep = true;
  26205. var rawIndex = this.getRawIndex(i);
  26206. for (var k = 0; k < dimSize; k++) {
  26207. var dimk = dimensions[k];
  26208. var val = this._getFast(dim, rawIndex);
  26209. // Do not filter NaN, see comment above.
  26210. if (val < range[dimk][0] || val > range[dimk][1]) {
  26211. keep = false;
  26212. }
  26213. }
  26214. if (keep) {
  26215. newIndices[offset++] = this.getRawIndex(i);
  26216. }
  26217. }
  26218. }
  26219. }
  26220. // Set indices after filtered.
  26221. if (offset < originalCount) {
  26222. this._indices = newIndices;
  26223. }
  26224. this._count = offset;
  26225. // Reset data extent
  26226. this._extent = {};
  26227. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26228. return this;
  26229. };
  26230. /**
  26231. * Data mapping to a plain array
  26232. * @param {string|Array.<string>} [dimensions]
  26233. * @param {Function} cb
  26234. * @param {*} [context=this]
  26235. * @return {Array}
  26236. */
  26237. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  26238. 'use strict';
  26239. if (typeof dimensions === 'function') {
  26240. contextCompat = context;
  26241. context = cb;
  26242. cb = dimensions;
  26243. dimensions = [];
  26244. }
  26245. // contextCompat just for compat echarts3
  26246. context = context || contextCompat || this;
  26247. var result = [];
  26248. this.each(dimensions, function () {
  26249. result.push(cb && cb.apply(this, arguments));
  26250. }, context);
  26251. return result;
  26252. };
  26253. // Data in excludeDimensions is copied, otherwise transfered.
  26254. function cloneListForMapAndSample(original, excludeDimensions) {
  26255. var allDimensions = original.dimensions;
  26256. var list = new List(
  26257. map(allDimensions, original.getDimensionInfo, original),
  26258. original.hostModel
  26259. );
  26260. // FIXME If needs stackedOn, value may already been stacked
  26261. transferProperties(list, original);
  26262. var storage = list._storage = {};
  26263. var originalStorage = original._storage;
  26264. // Init storage
  26265. for (var i = 0; i < allDimensions.length; i++) {
  26266. var dim = allDimensions[i];
  26267. if (originalStorage[dim]) {
  26268. // Notice that we do not reset invertedIndicesMap here, becuase
  26269. // there is no scenario of mapping or sampling ordinal dimension.
  26270. if (indexOf(excludeDimensions, dim) >= 0) {
  26271. storage[dim] = cloneDimStore(originalStorage[dim]);
  26272. list._rawExtent[dim] = getInitialExtent();
  26273. list._extent[dim] = null;
  26274. }
  26275. else {
  26276. // Direct reference for other dimensions
  26277. storage[dim] = originalStorage[dim];
  26278. }
  26279. }
  26280. }
  26281. return list;
  26282. }
  26283. function cloneDimStore(originalDimStore) {
  26284. var newDimStore = new Array(originalDimStore.length);
  26285. for (var j = 0; j < originalDimStore.length; j++) {
  26286. newDimStore[j] = cloneChunk(originalDimStore[j]);
  26287. }
  26288. return newDimStore;
  26289. }
  26290. function getInitialExtent() {
  26291. return [Infinity, -Infinity];
  26292. }
  26293. /**
  26294. * Data mapping to a new List with given dimensions
  26295. * @param {string|Array.<string>} dimensions
  26296. * @param {Function} cb
  26297. * @param {*} [context=this]
  26298. * @return {Array}
  26299. */
  26300. listProto.map = function (dimensions, cb, context, contextCompat) {
  26301. 'use strict';
  26302. // contextCompat just for compat echarts3
  26303. context = context || contextCompat || this;
  26304. dimensions = map(
  26305. normalizeDimensions(dimensions), this.getDimension, this
  26306. );
  26307. if (__DEV__) {
  26308. validateDimensions(this, dimensions);
  26309. }
  26310. var list = cloneListForMapAndSample(this, dimensions);
  26311. // Following properties are all immutable.
  26312. // So we can reference to the same value
  26313. list._indices = this._indices;
  26314. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26315. var storage = list._storage;
  26316. var tmpRetValue = [];
  26317. var chunkSize = this._chunkSize;
  26318. var dimSize = dimensions.length;
  26319. var dataCount = this.count();
  26320. var values = [];
  26321. var rawExtent = list._rawExtent;
  26322. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  26323. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  26324. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  26325. }
  26326. values[dimSize] = dataIndex;
  26327. var retValue = cb && cb.apply(context, values);
  26328. if (retValue != null) {
  26329. // a number or string (in oridinal dimension)?
  26330. if (typeof retValue !== 'object') {
  26331. tmpRetValue[0] = retValue;
  26332. retValue = tmpRetValue;
  26333. }
  26334. var rawIndex = this.getRawIndex(dataIndex);
  26335. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26336. var chunkOffset = rawIndex % chunkSize;
  26337. for (var i = 0; i < retValue.length; i++) {
  26338. var dim = dimensions[i];
  26339. var val = retValue[i];
  26340. var rawExtentOnDim = rawExtent[dim];
  26341. var dimStore = storage[dim];
  26342. if (dimStore) {
  26343. dimStore[chunkIndex][chunkOffset] = val;
  26344. }
  26345. if (val < rawExtentOnDim[0]) {
  26346. rawExtentOnDim[0] = val;
  26347. }
  26348. if (val > rawExtentOnDim[1]) {
  26349. rawExtentOnDim[1] = val;
  26350. }
  26351. }
  26352. }
  26353. }
  26354. return list;
  26355. };
  26356. /**
  26357. * Large data down sampling on given dimension
  26358. * @param {string} dimension
  26359. * @param {number} rate
  26360. * @param {Function} sampleValue
  26361. * @param {Function} sampleIndex Sample index for name and id
  26362. */
  26363. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  26364. var list = cloneListForMapAndSample(this, [dimension]);
  26365. var targetStorage = list._storage;
  26366. var frameValues = [];
  26367. var frameSize = Math.floor(1 / rate);
  26368. var dimStore = targetStorage[dimension];
  26369. var len = this.count();
  26370. var chunkSize = this._chunkSize;
  26371. var rawExtentOnDim = list._rawExtent[dimension];
  26372. var newIndices = new (getIndicesCtor(this))(len);
  26373. var offset = 0;
  26374. for (var i = 0; i < len; i += frameSize) {
  26375. // Last frame
  26376. if (frameSize > len - i) {
  26377. frameSize = len - i;
  26378. frameValues.length = frameSize;
  26379. }
  26380. for (var k = 0; k < frameSize; k++) {
  26381. var dataIdx = this.getRawIndex(i + k);
  26382. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  26383. var originalChunkOffset = dataIdx % chunkSize;
  26384. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  26385. }
  26386. var value = sampleValue(frameValues);
  26387. var sampleFrameIdx = this.getRawIndex(
  26388. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  26389. );
  26390. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  26391. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  26392. // Only write value on the filtered data
  26393. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  26394. if (value < rawExtentOnDim[0]) {
  26395. rawExtentOnDim[0] = value;
  26396. }
  26397. if (value > rawExtentOnDim[1]) {
  26398. rawExtentOnDim[1] = value;
  26399. }
  26400. newIndices[offset++] = sampleFrameIdx;
  26401. }
  26402. list._count = offset;
  26403. list._indices = newIndices;
  26404. list.getRawIndex = getRawIndexWithIndices;
  26405. return list;
  26406. };
  26407. /**
  26408. * Get model of one data item.
  26409. *
  26410. * @param {number} idx
  26411. */
  26412. // FIXME Model proxy ?
  26413. listProto.getItemModel = function (idx) {
  26414. var hostModel = this.hostModel;
  26415. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  26416. };
  26417. /**
  26418. * Create a data differ
  26419. * @param {module:echarts/data/List} otherList
  26420. * @return {module:echarts/data/DataDiffer}
  26421. */
  26422. listProto.diff = function (otherList) {
  26423. var thisList = this;
  26424. return new DataDiffer(
  26425. otherList ? otherList.getIndices() : [],
  26426. this.getIndices(),
  26427. function (idx) {
  26428. return getId(otherList, idx);
  26429. },
  26430. function (idx) {
  26431. return getId(thisList, idx);
  26432. }
  26433. );
  26434. };
  26435. /**
  26436. * Get visual property.
  26437. * @param {string} key
  26438. */
  26439. listProto.getVisual = function (key) {
  26440. var visual = this._visual;
  26441. return visual && visual[key];
  26442. };
  26443. /**
  26444. * Set visual property
  26445. * @param {string|Object} key
  26446. * @param {*} [value]
  26447. *
  26448. * @example
  26449. * setVisual('color', color);
  26450. * setVisual({
  26451. * 'color': color
  26452. * });
  26453. */
  26454. listProto.setVisual = function (key, val) {
  26455. if (isObject$4(key)) {
  26456. for (var name in key) {
  26457. if (key.hasOwnProperty(name)) {
  26458. this.setVisual(name, key[name]);
  26459. }
  26460. }
  26461. return;
  26462. }
  26463. this._visual = this._visual || {};
  26464. this._visual[key] = val;
  26465. };
  26466. /**
  26467. * Set layout property.
  26468. * @param {string|Object} key
  26469. * @param {*} [val]
  26470. */
  26471. listProto.setLayout = function (key, val) {
  26472. if (isObject$4(key)) {
  26473. for (var name in key) {
  26474. if (key.hasOwnProperty(name)) {
  26475. this.setLayout(name, key[name]);
  26476. }
  26477. }
  26478. return;
  26479. }
  26480. this._layout[key] = val;
  26481. };
  26482. /**
  26483. * Get layout property.
  26484. * @param {string} key.
  26485. * @return {*}
  26486. */
  26487. listProto.getLayout = function (key) {
  26488. return this._layout[key];
  26489. };
  26490. /**
  26491. * Get layout of single data item
  26492. * @param {number} idx
  26493. */
  26494. listProto.getItemLayout = function (idx) {
  26495. return this._itemLayouts[idx];
  26496. };
  26497. /**
  26498. * Set layout of single data item
  26499. * @param {number} idx
  26500. * @param {Object} layout
  26501. * @param {boolean=} [merge=false]
  26502. */
  26503. listProto.setItemLayout = function (idx, layout, merge$$1) {
  26504. this._itemLayouts[idx] = merge$$1
  26505. ? extend(this._itemLayouts[idx] || {}, layout)
  26506. : layout;
  26507. };
  26508. /**
  26509. * Clear all layout of single data item
  26510. */
  26511. listProto.clearItemLayouts = function () {
  26512. this._itemLayouts.length = 0;
  26513. };
  26514. /**
  26515. * Get visual property of single data item
  26516. * @param {number} idx
  26517. * @param {string} key
  26518. * @param {boolean} [ignoreParent=false]
  26519. */
  26520. listProto.getItemVisual = function (idx, key, ignoreParent) {
  26521. var itemVisual = this._itemVisuals[idx];
  26522. var val = itemVisual && itemVisual[key];
  26523. if (val == null && !ignoreParent) {
  26524. // Use global visual property
  26525. return this.getVisual(key);
  26526. }
  26527. return val;
  26528. };
  26529. /**
  26530. * Set visual property of single data item
  26531. *
  26532. * @param {number} idx
  26533. * @param {string|Object} key
  26534. * @param {*} [value]
  26535. *
  26536. * @example
  26537. * setItemVisual(0, 'color', color);
  26538. * setItemVisual(0, {
  26539. * 'color': color
  26540. * });
  26541. */
  26542. listProto.setItemVisual = function (idx, key, value) {
  26543. var itemVisual = this._itemVisuals[idx] || {};
  26544. var hasItemVisual = this.hasItemVisual;
  26545. this._itemVisuals[idx] = itemVisual;
  26546. if (isObject$4(key)) {
  26547. for (var name in key) {
  26548. if (key.hasOwnProperty(name)) {
  26549. itemVisual[name] = key[name];
  26550. hasItemVisual[name] = true;
  26551. }
  26552. }
  26553. return;
  26554. }
  26555. itemVisual[key] = value;
  26556. hasItemVisual[key] = true;
  26557. };
  26558. /**
  26559. * Clear itemVisuals and list visual.
  26560. */
  26561. listProto.clearAllVisual = function () {
  26562. this._visual = {};
  26563. this._itemVisuals = [];
  26564. this.hasItemVisual = {};
  26565. };
  26566. var setItemDataAndSeriesIndex = function (child) {
  26567. child.seriesIndex = this.seriesIndex;
  26568. child.dataIndex = this.dataIndex;
  26569. child.dataType = this.dataType;
  26570. };
  26571. /**
  26572. * Set graphic element relative to data. It can be set as null
  26573. * @param {number} idx
  26574. * @param {module:zrender/Element} [el]
  26575. */
  26576. listProto.setItemGraphicEl = function (idx, el) {
  26577. var hostModel = this.hostModel;
  26578. if (el) {
  26579. // Add data index and series index for indexing the data by element
  26580. // Useful in tooltip
  26581. el.dataIndex = idx;
  26582. el.dataType = this.dataType;
  26583. el.seriesIndex = hostModel && hostModel.seriesIndex;
  26584. if (el.type === 'group') {
  26585. el.traverse(setItemDataAndSeriesIndex, el);
  26586. }
  26587. }
  26588. this._graphicEls[idx] = el;
  26589. };
  26590. /**
  26591. * @param {number} idx
  26592. * @return {module:zrender/Element}
  26593. */
  26594. listProto.getItemGraphicEl = function (idx) {
  26595. return this._graphicEls[idx];
  26596. };
  26597. /**
  26598. * @param {Function} cb
  26599. * @param {*} context
  26600. */
  26601. listProto.eachItemGraphicEl = function (cb, context) {
  26602. each$1(this._graphicEls, function (el, idx) {
  26603. if (el) {
  26604. cb && cb.call(context, el, idx);
  26605. }
  26606. });
  26607. };
  26608. /**
  26609. * Shallow clone a new list except visual and layout properties, and graph elements.
  26610. * New list only change the indices.
  26611. */
  26612. listProto.cloneShallow = function (list) {
  26613. if (!list) {
  26614. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  26615. list = new List(dimensionInfoList, this.hostModel);
  26616. }
  26617. // FIXME
  26618. list._storage = this._storage;
  26619. transferProperties(list, this);
  26620. // Clone will not change the data extent and indices
  26621. if (this._indices) {
  26622. var Ctor = this._indices.constructor;
  26623. list._indices = new Ctor(this._indices);
  26624. }
  26625. else {
  26626. list._indices = null;
  26627. }
  26628. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26629. return list;
  26630. };
  26631. /**
  26632. * Wrap some method to add more feature
  26633. * @param {string} methodName
  26634. * @param {Function} injectFunction
  26635. */
  26636. listProto.wrapMethod = function (methodName, injectFunction) {
  26637. var originalMethod = this[methodName];
  26638. if (typeof originalMethod !== 'function') {
  26639. return;
  26640. }
  26641. this.__wrappedMethods = this.__wrappedMethods || [];
  26642. this.__wrappedMethods.push(methodName);
  26643. this[methodName] = function () {
  26644. var res = originalMethod.apply(this, arguments);
  26645. return injectFunction.apply(this, [res].concat(slice(arguments)));
  26646. };
  26647. };
  26648. // Methods that create a new list based on this list should be listed here.
  26649. // Notice that those method should `RETURN` the new list.
  26650. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  26651. // Methods that change indices of this list should be listed here.
  26652. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  26653. /*
  26654. * Licensed to the Apache Software Foundation (ASF) under one
  26655. * or more contributor license agreements. See the NOTICE file
  26656. * distributed with this work for additional information
  26657. * regarding copyright ownership. The ASF licenses this file
  26658. * to you under the Apache License, Version 2.0 (the
  26659. * "License"); you may not use this file except in compliance
  26660. * with the License. You may obtain a copy of the License at
  26661. *
  26662. * http://www.apache.org/licenses/LICENSE-2.0
  26663. *
  26664. * Unless required by applicable law or agreed to in writing,
  26665. * software distributed under the License is distributed on an
  26666. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26667. * KIND, either express or implied. See the License for the
  26668. * specific language governing permissions and limitations
  26669. * under the License.
  26670. */
  26671. /**
  26672. * @deprecated
  26673. * Use `echarts/data/helper/createDimensions` instead.
  26674. */
  26675. /**
  26676. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  26677. *
  26678. * Complete the dimensions array, by user defined `dimension` and `encode`,
  26679. * and guessing from the data structure.
  26680. * If no 'value' dimension specified, the first no-named dimension will be
  26681. * named as 'value'.
  26682. *
  26683. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  26684. * provides not only dim template, but also default order.
  26685. * properties: 'name', 'type', 'displayName'.
  26686. * `name` of each item provides default coord name.
  26687. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  26688. * provide dims count that the sysDim required.
  26689. * [{ordinalMeta}] can be specified.
  26690. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  26691. * @param {Object} [opt]
  26692. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  26693. * For example: ['asdf', {name, type}, ...].
  26694. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  26695. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  26696. * If not specified, extra dim names will be:
  26697. * 'value', 'value0', 'value1', ...
  26698. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  26699. * If `generateCoordCount` specified, the generated dim names will be:
  26700. * `generateCoord` + 0, `generateCoord` + 1, ...
  26701. * can be Infinity, indicate that use all of the remain columns.
  26702. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  26703. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  26704. * @return {Array.<Object>} [{
  26705. * name: string mandatory,
  26706. * displayName: string, the origin name in dimsDef, see source helper.
  26707. * If displayName given, the tooltip will displayed vertically.
  26708. * coordDim: string mandatory,
  26709. * coordDimIndex: number mandatory,
  26710. * type: string optional,
  26711. * otherDims: { never null/undefined
  26712. * tooltip: number optional,
  26713. * label: number optional,
  26714. * itemName: number optional,
  26715. * seriesName: number optional,
  26716. * },
  26717. * isExtraCoord: boolean true if coord is generated
  26718. * (not specified in encode and not series specified)
  26719. * other props ...
  26720. * }]
  26721. */
  26722. function completeDimensions(sysDims, source, opt) {
  26723. if (!Source.isInstance(source)) {
  26724. source = Source.seriesDataToSource(source);
  26725. }
  26726. opt = opt || {};
  26727. sysDims = (sysDims || []).slice();
  26728. var dimsDef = (opt.dimsDef || []).slice();
  26729. var encodeDef = createHashMap(opt.encodeDef);
  26730. var dataDimNameMap = createHashMap();
  26731. var coordDimNameMap = createHashMap();
  26732. // var valueCandidate;
  26733. var result = [];
  26734. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  26735. // Apply user defined dims (`name` and `type`) and init result.
  26736. for (var i = 0; i < dimCount; i++) {
  26737. var dimDefItem = dimsDef[i] = extend(
  26738. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  26739. );
  26740. var userDimName = dimDefItem.name;
  26741. var resultItem = result[i] = {otherDims: {}};
  26742. // Name will be applied later for avoiding duplication.
  26743. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  26744. // Only if `series.dimensions` is defined in option
  26745. // displayName, will be set, and dimension will be diplayed vertically in
  26746. // tooltip by default.
  26747. resultItem.name = resultItem.displayName = userDimName;
  26748. dataDimNameMap.set(userDimName, i);
  26749. }
  26750. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  26751. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  26752. }
  26753. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  26754. encodeDef.each(function (dataDims, coordDim) {
  26755. dataDims = normalizeToArray(dataDims).slice();
  26756. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  26757. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  26758. // this case.
  26759. if (dataDims.length === 1 && dataDims[0] < 0) {
  26760. encodeDef.set(coordDim, false);
  26761. return;
  26762. }
  26763. var validDataDims = encodeDef.set(coordDim, []);
  26764. each$1(dataDims, function (resultDimIdx, idx) {
  26765. // The input resultDimIdx can be dim name or index.
  26766. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  26767. if (resultDimIdx != null && resultDimIdx < dimCount) {
  26768. validDataDims[idx] = resultDimIdx;
  26769. applyDim(result[resultDimIdx], coordDim, idx);
  26770. }
  26771. });
  26772. });
  26773. // Apply templetes and default order from `sysDims`.
  26774. var availDimIdx = 0;
  26775. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  26776. var coordDim;
  26777. var sysDimItem;
  26778. var sysDimItemDimsDef;
  26779. var sysDimItemOtherDims;
  26780. if (isString(sysDimItem)) {
  26781. coordDim = sysDimItem;
  26782. sysDimItem = {};
  26783. }
  26784. else {
  26785. coordDim = sysDimItem.name;
  26786. var ordinalMeta = sysDimItem.ordinalMeta;
  26787. sysDimItem.ordinalMeta = null;
  26788. sysDimItem = clone(sysDimItem);
  26789. sysDimItem.ordinalMeta = ordinalMeta;
  26790. // `coordDimIndex` should not be set directly.
  26791. sysDimItemDimsDef = sysDimItem.dimsDef;
  26792. sysDimItemOtherDims = sysDimItem.otherDims;
  26793. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  26794. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  26795. }
  26796. var dataDims = encodeDef.get(coordDim);
  26797. // negative resultDimIdx means no need to mapping.
  26798. if (dataDims === false) {
  26799. return;
  26800. }
  26801. var dataDims = normalizeToArray(dataDims);
  26802. // dimensions provides default dim sequences.
  26803. if (!dataDims.length) {
  26804. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  26805. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  26806. availDimIdx++;
  26807. }
  26808. availDimIdx < result.length && dataDims.push(availDimIdx++);
  26809. }
  26810. }
  26811. // Apply templates.
  26812. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  26813. var resultItem = result[resultDimIdx];
  26814. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  26815. if (resultItem.name == null && sysDimItemDimsDef) {
  26816. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  26817. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  26818. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  26819. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  26820. }
  26821. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  26822. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  26823. });
  26824. });
  26825. function applyDim(resultItem, coordDim, coordDimIndex) {
  26826. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  26827. resultItem.otherDims[coordDim] = coordDimIndex;
  26828. }
  26829. else {
  26830. resultItem.coordDim = coordDim;
  26831. resultItem.coordDimIndex = coordDimIndex;
  26832. coordDimNameMap.set(coordDim, true);
  26833. }
  26834. }
  26835. // Make sure the first extra dim is 'value'.
  26836. var generateCoord = opt.generateCoord;
  26837. var generateCoordCount = opt.generateCoordCount;
  26838. var fromZero = generateCoordCount != null;
  26839. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  26840. var extra = generateCoord || 'value';
  26841. // Set dim `name` and other `coordDim` and other props.
  26842. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  26843. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  26844. var coordDim = resultItem.coordDim;
  26845. if (coordDim == null) {
  26846. resultItem.coordDim = genName(
  26847. extra, coordDimNameMap, fromZero
  26848. );
  26849. resultItem.coordDimIndex = 0;
  26850. if (!generateCoord || generateCoordCount <= 0) {
  26851. resultItem.isExtraCoord = true;
  26852. }
  26853. generateCoordCount--;
  26854. }
  26855. resultItem.name == null && (resultItem.name = genName(
  26856. resultItem.coordDim,
  26857. dataDimNameMap
  26858. ));
  26859. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  26860. resultItem.type = 'ordinal';
  26861. }
  26862. }
  26863. return result;
  26864. }
  26865. // ??? TODO
  26866. // Originally detect dimCount by data[0]. Should we
  26867. // optimize it to only by sysDims and dimensions and encode.
  26868. // So only necessary dims will be initialized.
  26869. // But
  26870. // (1) custom series should be considered. where other dims
  26871. // may be visited.
  26872. // (2) sometimes user need to calcualte bubble size or use visualMap
  26873. // on other dimensions besides coordSys needed.
  26874. // So, dims that is not used by system, should be shared in storage?
  26875. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  26876. // Note that the result dimCount should not small than columns count
  26877. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  26878. var dimCount = Math.max(
  26879. source.dimensionsDetectCount || 1,
  26880. sysDims.length,
  26881. dimsDef.length,
  26882. optDimCount || 0
  26883. );
  26884. each$1(sysDims, function (sysDimItem) {
  26885. var sysDimItemDimsDef = sysDimItem.dimsDef;
  26886. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  26887. });
  26888. return dimCount;
  26889. }
  26890. function genName(name, map$$1, fromZero) {
  26891. if (fromZero || map$$1.get(name) != null) {
  26892. var i = 0;
  26893. while (map$$1.get(name + i) != null) {
  26894. i++;
  26895. }
  26896. name += i;
  26897. }
  26898. map$$1.set(name, true);
  26899. return name;
  26900. }
  26901. /*
  26902. * Licensed to the Apache Software Foundation (ASF) under one
  26903. * or more contributor license agreements. See the NOTICE file
  26904. * distributed with this work for additional information
  26905. * regarding copyright ownership. The ASF licenses this file
  26906. * to you under the Apache License, Version 2.0 (the
  26907. * "License"); you may not use this file except in compliance
  26908. * with the License. You may obtain a copy of the License at
  26909. *
  26910. * http://www.apache.org/licenses/LICENSE-2.0
  26911. *
  26912. * Unless required by applicable law or agreed to in writing,
  26913. * software distributed under the License is distributed on an
  26914. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26915. * KIND, either express or implied. See the License for the
  26916. * specific language governing permissions and limitations
  26917. * under the License.
  26918. */
  26919. /**
  26920. * Substitute `completeDimensions`.
  26921. * `completeDimensions` is to be deprecated.
  26922. */
  26923. /**
  26924. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  26925. * @param {Object|Array} [opt]
  26926. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  26927. * @param {number} [opt.dimensionsCount]
  26928. * @param {string} [opt.generateCoord]
  26929. * @param {string} [opt.generateCoordCount]
  26930. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  26931. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  26932. * @return {Array.<Object>} dimensionsInfo
  26933. */
  26934. var createDimensions = function (source, opt) {
  26935. opt = opt || {};
  26936. return completeDimensions(opt.coordDimensions || [], source, {
  26937. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  26938. encodeDef: opt.encodeDefine || source.encodeDefine,
  26939. dimCount: opt.dimensionsCount,
  26940. generateCoord: opt.generateCoord,
  26941. generateCoordCount: opt.generateCoordCount
  26942. });
  26943. };
  26944. /*
  26945. * Licensed to the Apache Software Foundation (ASF) under one
  26946. * or more contributor license agreements. See the NOTICE file
  26947. * distributed with this work for additional information
  26948. * regarding copyright ownership. The ASF licenses this file
  26949. * to you under the Apache License, Version 2.0 (the
  26950. * "License"); you may not use this file except in compliance
  26951. * with the License. You may obtain a copy of the License at
  26952. *
  26953. * http://www.apache.org/licenses/LICENSE-2.0
  26954. *
  26955. * Unless required by applicable law or agreed to in writing,
  26956. * software distributed under the License is distributed on an
  26957. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26958. * KIND, either express or implied. See the License for the
  26959. * specific language governing permissions and limitations
  26960. * under the License.
  26961. */
  26962. /**
  26963. * Note that it is too complicated to support 3d stack by value
  26964. * (have to create two-dimension inverted index), so in 3d case
  26965. * we just support that stacked by index.
  26966. *
  26967. * @param {module:echarts/model/Series} seriesModel
  26968. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  26969. * The input dimensionInfoList will be modified.
  26970. * @param {Object} [opt]
  26971. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  26972. * @param {boolean} [opt.byIndex=false]
  26973. * @return {Object} calculationInfo
  26974. * {
  26975. * stackedDimension: string
  26976. * stackedByDimension: string
  26977. * isStackedByIndex: boolean
  26978. * stackedOverDimension: string
  26979. * stackResultDimension: string
  26980. * }
  26981. */
  26982. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  26983. opt = opt || {};
  26984. var byIndex = opt.byIndex;
  26985. var stackedCoordDimension = opt.stackedCoordDimension;
  26986. // Compatibal: when `stack` is set as '', do not stack.
  26987. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  26988. var stackedByDimInfo;
  26989. var stackedDimInfo;
  26990. var stackResultDimension;
  26991. var stackedOverDimension;
  26992. each$1(dimensionInfoList, function (dimensionInfo, index) {
  26993. if (isString(dimensionInfo)) {
  26994. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  26995. }
  26996. if (mayStack && !dimensionInfo.isExtraCoord) {
  26997. // Find the first ordinal dimension as the stackedByDimInfo.
  26998. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  26999. stackedByDimInfo = dimensionInfo;
  27000. }
  27001. // Find the first stackable dimension as the stackedDimInfo.
  27002. if (!stackedDimInfo
  27003. && dimensionInfo.type !== 'ordinal'
  27004. && dimensionInfo.type !== 'time'
  27005. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  27006. ) {
  27007. stackedDimInfo = dimensionInfo;
  27008. }
  27009. }
  27010. });
  27011. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  27012. // Compatible with previous design, value axis (time axis) only stack by index.
  27013. // It may make sense if the user provides elaborately constructed data.
  27014. byIndex = true;
  27015. }
  27016. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  27017. // That put stack logic in List is for using conveniently in echarts extensions, but it
  27018. // might not be a good way.
  27019. if (stackedDimInfo) {
  27020. // Use a weird name that not duplicated with other names.
  27021. stackResultDimension = '__\0ecstackresult';
  27022. stackedOverDimension = '__\0ecstackedover';
  27023. // Create inverted index to fast query index by value.
  27024. if (stackedByDimInfo) {
  27025. stackedByDimInfo.createInvertedIndices = true;
  27026. }
  27027. var stackedDimCoordDim = stackedDimInfo.coordDim;
  27028. var stackedDimType = stackedDimInfo.type;
  27029. var stackedDimCoordIndex = 0;
  27030. each$1(dimensionInfoList, function (dimensionInfo) {
  27031. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  27032. stackedDimCoordIndex++;
  27033. }
  27034. });
  27035. dimensionInfoList.push({
  27036. name: stackResultDimension,
  27037. coordDim: stackedDimCoordDim,
  27038. coordDimIndex: stackedDimCoordIndex,
  27039. type: stackedDimType,
  27040. isExtraCoord: true,
  27041. isCalculationCoord: true
  27042. });
  27043. stackedDimCoordIndex++;
  27044. dimensionInfoList.push({
  27045. name: stackedOverDimension,
  27046. // This dimension contains stack base (generally, 0), so do not set it as
  27047. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  27048. coordDim: stackedOverDimension,
  27049. coordDimIndex: stackedDimCoordIndex,
  27050. type: stackedDimType,
  27051. isExtraCoord: true,
  27052. isCalculationCoord: true
  27053. });
  27054. }
  27055. return {
  27056. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  27057. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  27058. isStackedByIndex: byIndex,
  27059. stackedOverDimension: stackedOverDimension,
  27060. stackResultDimension: stackResultDimension
  27061. };
  27062. }
  27063. /**
  27064. * @param {module:echarts/data/List} data
  27065. * @param {string} stackedDim
  27066. */
  27067. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  27068. // Each single series only maps to one pair of axis. So we do not need to
  27069. // check stackByDim, whatever stacked by a dimension or stacked by index.
  27070. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  27071. // && (
  27072. // stackedByDim != null
  27073. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  27074. // : data.getCalculationInfo('isStackedByIndex')
  27075. // );
  27076. }
  27077. /**
  27078. * @param {module:echarts/data/List} data
  27079. * @param {string} targetDim
  27080. * @param {string} [stackedByDim] If not input this parameter, check whether
  27081. * stacked by index.
  27082. * @return {string} dimension
  27083. */
  27084. function getStackedDimension(data, targetDim) {
  27085. return isDimensionStacked(data, targetDim)
  27086. ? data.getCalculationInfo('stackResultDimension')
  27087. : targetDim;
  27088. }
  27089. /*
  27090. * Licensed to the Apache Software Foundation (ASF) under one
  27091. * or more contributor license agreements. See the NOTICE file
  27092. * distributed with this work for additional information
  27093. * regarding copyright ownership. The ASF licenses this file
  27094. * to you under the Apache License, Version 2.0 (the
  27095. * "License"); you may not use this file except in compliance
  27096. * with the License. You may obtain a copy of the License at
  27097. *
  27098. * http://www.apache.org/licenses/LICENSE-2.0
  27099. *
  27100. * Unless required by applicable law or agreed to in writing,
  27101. * software distributed under the License is distributed on an
  27102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27103. * KIND, either express or implied. See the License for the
  27104. * specific language governing permissions and limitations
  27105. * under the License.
  27106. */
  27107. /**
  27108. * @param {module:echarts/data/Source|Array} source Or raw data.
  27109. * @param {module:echarts/model/Series} seriesModel
  27110. * @param {Object} [opt]
  27111. * @param {string} [opt.generateCoord]
  27112. */
  27113. function createListFromArray(source, seriesModel, opt) {
  27114. opt = opt || {};
  27115. if (!Source.isInstance(source)) {
  27116. source = Source.seriesDataToSource(source);
  27117. }
  27118. var coordSysName = seriesModel.get('coordinateSystem');
  27119. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  27120. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  27121. var coordSysDimDefs;
  27122. if (coordSysDefine) {
  27123. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  27124. var dimInfo = {name: dim};
  27125. var axisModel = coordSysDefine.axisMap.get(dim);
  27126. if (axisModel) {
  27127. var axisType = axisModel.get('type');
  27128. dimInfo.type = getDimensionTypeByAxis(axisType);
  27129. // dimInfo.stackable = isStackable(axisType);
  27130. }
  27131. return dimInfo;
  27132. });
  27133. }
  27134. if (!coordSysDimDefs) {
  27135. // Get dimensions from registered coordinate system
  27136. coordSysDimDefs = (registeredCoordSys && (
  27137. registeredCoordSys.getDimensionsInfo
  27138. ? registeredCoordSys.getDimensionsInfo()
  27139. : registeredCoordSys.dimensions.slice()
  27140. )) || ['x', 'y'];
  27141. }
  27142. var dimInfoList = createDimensions(source, {
  27143. coordDimensions: coordSysDimDefs,
  27144. generateCoord: opt.generateCoord
  27145. });
  27146. var firstCategoryDimIndex;
  27147. var hasNameEncode;
  27148. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  27149. var coordDim = dimInfo.coordDim;
  27150. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  27151. if (categoryAxisModel) {
  27152. if (firstCategoryDimIndex == null) {
  27153. firstCategoryDimIndex = dimIndex;
  27154. }
  27155. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  27156. }
  27157. if (dimInfo.otherDims.itemName != null) {
  27158. hasNameEncode = true;
  27159. }
  27160. });
  27161. if (!hasNameEncode && firstCategoryDimIndex != null) {
  27162. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  27163. }
  27164. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  27165. var list = new List(dimInfoList, seriesModel);
  27166. list.setCalculationInfo(stackCalculationInfo);
  27167. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  27168. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  27169. // Use dataIndex as ordinal value in categoryAxis
  27170. return dimIndex === firstCategoryDimIndex
  27171. ? dataIndex
  27172. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  27173. }
  27174. : null;
  27175. list.hasItemOption = false;
  27176. list.initData(source, null, dimValueGetter);
  27177. return list;
  27178. }
  27179. function isNeedCompleteOrdinalData(source) {
  27180. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  27181. var sampleItem = firstDataNotNull(source.data || []);
  27182. return sampleItem != null
  27183. && !isArray(getDataItemValue(sampleItem));
  27184. }
  27185. }
  27186. function firstDataNotNull(data) {
  27187. var i = 0;
  27188. while (i < data.length && data[i] == null) {
  27189. i++;
  27190. }
  27191. return data[i];
  27192. }
  27193. /*
  27194. * Licensed to the Apache Software Foundation (ASF) under one
  27195. * or more contributor license agreements. See the NOTICE file
  27196. * distributed with this work for additional information
  27197. * regarding copyright ownership. The ASF licenses this file
  27198. * to you under the Apache License, Version 2.0 (the
  27199. * "License"); you may not use this file except in compliance
  27200. * with the License. You may obtain a copy of the License at
  27201. *
  27202. * http://www.apache.org/licenses/LICENSE-2.0
  27203. *
  27204. * Unless required by applicable law or agreed to in writing,
  27205. * software distributed under the License is distributed on an
  27206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27207. * KIND, either express or implied. See the License for the
  27208. * specific language governing permissions and limitations
  27209. * under the License.
  27210. */
  27211. SeriesModel.extend({
  27212. type: 'series.line',
  27213. dependencies: ['grid', 'polar'],
  27214. getInitialData: function (option, ecModel) {
  27215. if (__DEV__) {
  27216. var coordSys = option.coordinateSystem;
  27217. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  27218. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  27219. }
  27220. }
  27221. return createListFromArray(this.getSource(), this);
  27222. },
  27223. defaultOption: {
  27224. zlevel: 0,
  27225. z: 2,
  27226. coordinateSystem: 'cartesian2d',
  27227. legendHoverLink: true,
  27228. hoverAnimation: true,
  27229. // stack: null
  27230. // xAxisIndex: 0,
  27231. // yAxisIndex: 0,
  27232. // polarIndex: 0,
  27233. // If clip the overflow value
  27234. clipOverflow: true,
  27235. // cursor: null,
  27236. label: {
  27237. position: 'top'
  27238. },
  27239. // itemStyle: {
  27240. // },
  27241. lineStyle: {
  27242. width: 2,
  27243. type: 'solid'
  27244. },
  27245. // areaStyle: {
  27246. // origin of areaStyle. Valid values:
  27247. // `'auto'/null/undefined`: from axisLine to data
  27248. // `'start'`: from min to data
  27249. // `'end'`: from data to max
  27250. // origin: 'auto'
  27251. // },
  27252. // false, 'start', 'end', 'middle'
  27253. step: false,
  27254. // Disabled if step is true
  27255. smooth: false,
  27256. smoothMonotone: null,
  27257. symbol: 'emptyCircle',
  27258. symbolSize: 4,
  27259. symbolRotate: null,
  27260. showSymbol: true,
  27261. // `false`: follow the label interval strategy.
  27262. // `true`: show all symbols.
  27263. // `'auto'`: If possible, show all symbols, otherwise
  27264. // follow the label interval strategy.
  27265. showAllSymbol: 'auto',
  27266. // Whether to connect break point.
  27267. connectNulls: false,
  27268. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  27269. sampling: 'none',
  27270. animationEasing: 'linear',
  27271. // Disable progressive
  27272. progressive: 0,
  27273. hoverLayerThreshold: Infinity
  27274. }
  27275. });
  27276. /*
  27277. * Licensed to the Apache Software Foundation (ASF) under one
  27278. * or more contributor license agreements. See the NOTICE file
  27279. * distributed with this work for additional information
  27280. * regarding copyright ownership. The ASF licenses this file
  27281. * to you under the Apache License, Version 2.0 (the
  27282. * "License"); you may not use this file except in compliance
  27283. * with the License. You may obtain a copy of the License at
  27284. *
  27285. * http://www.apache.org/licenses/LICENSE-2.0
  27286. *
  27287. * Unless required by applicable law or agreed to in writing,
  27288. * software distributed under the License is distributed on an
  27289. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27290. * KIND, either express or implied. See the License for the
  27291. * specific language governing permissions and limitations
  27292. * under the License.
  27293. */
  27294. // Symbol factory
  27295. /**
  27296. * Triangle shape
  27297. * @inner
  27298. */
  27299. var Triangle = extendShape({
  27300. type: 'triangle',
  27301. shape: {
  27302. cx: 0,
  27303. cy: 0,
  27304. width: 0,
  27305. height: 0
  27306. },
  27307. buildPath: function (path, shape) {
  27308. var cx = shape.cx;
  27309. var cy = shape.cy;
  27310. var width = shape.width / 2;
  27311. var height = shape.height / 2;
  27312. path.moveTo(cx, cy - height);
  27313. path.lineTo(cx + width, cy + height);
  27314. path.lineTo(cx - width, cy + height);
  27315. path.closePath();
  27316. }
  27317. });
  27318. /**
  27319. * Diamond shape
  27320. * @inner
  27321. */
  27322. var Diamond = extendShape({
  27323. type: 'diamond',
  27324. shape: {
  27325. cx: 0,
  27326. cy: 0,
  27327. width: 0,
  27328. height: 0
  27329. },
  27330. buildPath: function (path, shape) {
  27331. var cx = shape.cx;
  27332. var cy = shape.cy;
  27333. var width = shape.width / 2;
  27334. var height = shape.height / 2;
  27335. path.moveTo(cx, cy - height);
  27336. path.lineTo(cx + width, cy);
  27337. path.lineTo(cx, cy + height);
  27338. path.lineTo(cx - width, cy);
  27339. path.closePath();
  27340. }
  27341. });
  27342. /**
  27343. * Pin shape
  27344. * @inner
  27345. */
  27346. var Pin = extendShape({
  27347. type: 'pin',
  27348. shape: {
  27349. // x, y on the cusp
  27350. x: 0,
  27351. y: 0,
  27352. width: 0,
  27353. height: 0
  27354. },
  27355. buildPath: function (path, shape) {
  27356. var x = shape.x;
  27357. var y = shape.y;
  27358. var w = shape.width / 5 * 3;
  27359. // Height must be larger than width
  27360. var h = Math.max(w, shape.height);
  27361. var r = w / 2;
  27362. // Dist on y with tangent point and circle center
  27363. var dy = r * r / (h - r);
  27364. var cy = y - h + r + dy;
  27365. var angle = Math.asin(dy / r);
  27366. // Dist on x with tangent point and circle center
  27367. var dx = Math.cos(angle) * r;
  27368. var tanX = Math.sin(angle);
  27369. var tanY = Math.cos(angle);
  27370. var cpLen = r * 0.6;
  27371. var cpLen2 = r * 0.7;
  27372. path.moveTo(x - dx, cy + dy);
  27373. path.arc(
  27374. x, cy, r,
  27375. Math.PI - angle,
  27376. Math.PI * 2 + angle
  27377. );
  27378. path.bezierCurveTo(
  27379. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  27380. x, y - cpLen2,
  27381. x, y
  27382. );
  27383. path.bezierCurveTo(
  27384. x, y - cpLen2,
  27385. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  27386. x - dx, cy + dy
  27387. );
  27388. path.closePath();
  27389. }
  27390. });
  27391. /**
  27392. * Arrow shape
  27393. * @inner
  27394. */
  27395. var Arrow = extendShape({
  27396. type: 'arrow',
  27397. shape: {
  27398. x: 0,
  27399. y: 0,
  27400. width: 0,
  27401. height: 0
  27402. },
  27403. buildPath: function (ctx, shape) {
  27404. var height = shape.height;
  27405. var width = shape.width;
  27406. var x = shape.x;
  27407. var y = shape.y;
  27408. var dx = width / 3 * 2;
  27409. ctx.moveTo(x, y);
  27410. ctx.lineTo(x + dx, y + height);
  27411. ctx.lineTo(x, y + height / 4 * 3);
  27412. ctx.lineTo(x - dx, y + height);
  27413. ctx.lineTo(x, y);
  27414. ctx.closePath();
  27415. }
  27416. });
  27417. /**
  27418. * Map of path contructors
  27419. * @type {Object.<string, module:zrender/graphic/Path>}
  27420. */
  27421. var symbolCtors = {
  27422. line: Line,
  27423. rect: Rect,
  27424. roundRect: Rect,
  27425. square: Rect,
  27426. circle: Circle,
  27427. diamond: Diamond,
  27428. pin: Pin,
  27429. arrow: Arrow,
  27430. triangle: Triangle
  27431. };
  27432. var symbolShapeMakers = {
  27433. line: function (x, y, w, h, shape) {
  27434. // FIXME
  27435. shape.x1 = x;
  27436. shape.y1 = y + h / 2;
  27437. shape.x2 = x + w;
  27438. shape.y2 = y + h / 2;
  27439. },
  27440. rect: function (x, y, w, h, shape) {
  27441. shape.x = x;
  27442. shape.y = y;
  27443. shape.width = w;
  27444. shape.height = h;
  27445. },
  27446. roundRect: function (x, y, w, h, shape) {
  27447. shape.x = x;
  27448. shape.y = y;
  27449. shape.width = w;
  27450. shape.height = h;
  27451. shape.r = Math.min(w, h) / 4;
  27452. },
  27453. square: function (x, y, w, h, shape) {
  27454. var size = Math.min(w, h);
  27455. shape.x = x;
  27456. shape.y = y;
  27457. shape.width = size;
  27458. shape.height = size;
  27459. },
  27460. circle: function (x, y, w, h, shape) {
  27461. // Put circle in the center of square
  27462. shape.cx = x + w / 2;
  27463. shape.cy = y + h / 2;
  27464. shape.r = Math.min(w, h) / 2;
  27465. },
  27466. diamond: function (x, y, w, h, shape) {
  27467. shape.cx = x + w / 2;
  27468. shape.cy = y + h / 2;
  27469. shape.width = w;
  27470. shape.height = h;
  27471. },
  27472. pin: function (x, y, w, h, shape) {
  27473. shape.x = x + w / 2;
  27474. shape.y = y + h / 2;
  27475. shape.width = w;
  27476. shape.height = h;
  27477. },
  27478. arrow: function (x, y, w, h, shape) {
  27479. shape.x = x + w / 2;
  27480. shape.y = y + h / 2;
  27481. shape.width = w;
  27482. shape.height = h;
  27483. },
  27484. triangle: function (x, y, w, h, shape) {
  27485. shape.cx = x + w / 2;
  27486. shape.cy = y + h / 2;
  27487. shape.width = w;
  27488. shape.height = h;
  27489. }
  27490. };
  27491. var symbolBuildProxies = {};
  27492. each$1(symbolCtors, function (Ctor, name) {
  27493. symbolBuildProxies[name] = new Ctor();
  27494. });
  27495. var SymbolClz$2 = extendShape({
  27496. type: 'symbol',
  27497. shape: {
  27498. symbolType: '',
  27499. x: 0,
  27500. y: 0,
  27501. width: 0,
  27502. height: 0
  27503. },
  27504. beforeBrush: function () {
  27505. var style = this.style;
  27506. var shape = this.shape;
  27507. // FIXME
  27508. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  27509. style.textPosition = ['50%', '40%'];
  27510. style.textAlign = 'center';
  27511. style.textVerticalAlign = 'middle';
  27512. }
  27513. },
  27514. buildPath: function (ctx, shape, inBundle) {
  27515. var symbolType = shape.symbolType;
  27516. var proxySymbol = symbolBuildProxies[symbolType];
  27517. if (shape.symbolType !== 'none') {
  27518. if (!proxySymbol) {
  27519. // Default rect
  27520. symbolType = 'rect';
  27521. proxySymbol = symbolBuildProxies[symbolType];
  27522. }
  27523. symbolShapeMakers[symbolType](
  27524. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  27525. );
  27526. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  27527. }
  27528. }
  27529. });
  27530. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  27531. function symbolPathSetColor(color, innerColor) {
  27532. if (this.type !== 'image') {
  27533. var symbolStyle = this.style;
  27534. var symbolShape = this.shape;
  27535. if (symbolShape && symbolShape.symbolType === 'line') {
  27536. symbolStyle.stroke = color;
  27537. }
  27538. else if (this.__isEmptyBrush) {
  27539. symbolStyle.stroke = color;
  27540. symbolStyle.fill = innerColor || '#fff';
  27541. }
  27542. else {
  27543. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  27544. symbolStyle.fill && (symbolStyle.fill = color);
  27545. symbolStyle.stroke && (symbolStyle.stroke = color);
  27546. }
  27547. this.dirty(false);
  27548. }
  27549. }
  27550. /**
  27551. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  27552. * @param {string} symbolType
  27553. * @param {number} x
  27554. * @param {number} y
  27555. * @param {number} w
  27556. * @param {number} h
  27557. * @param {string} color
  27558. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  27559. * for path and image only.
  27560. */
  27561. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  27562. // TODO Support image object, DynamicImage.
  27563. var isEmpty = symbolType.indexOf('empty') === 0;
  27564. if (isEmpty) {
  27565. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  27566. }
  27567. var symbolPath;
  27568. if (symbolType.indexOf('image://') === 0) {
  27569. symbolPath = makeImage(
  27570. symbolType.slice(8),
  27571. new BoundingRect(x, y, w, h),
  27572. keepAspect ? 'center' : 'cover'
  27573. );
  27574. }
  27575. else if (symbolType.indexOf('path://') === 0) {
  27576. symbolPath = makePath(
  27577. symbolType.slice(7),
  27578. {},
  27579. new BoundingRect(x, y, w, h),
  27580. keepAspect ? 'center' : 'cover'
  27581. );
  27582. }
  27583. else {
  27584. symbolPath = new SymbolClz$2({
  27585. shape: {
  27586. symbolType: symbolType,
  27587. x: x,
  27588. y: y,
  27589. width: w,
  27590. height: h
  27591. }
  27592. });
  27593. }
  27594. symbolPath.__isEmptyBrush = isEmpty;
  27595. symbolPath.setColor = symbolPathSetColor;
  27596. symbolPath.setColor(color);
  27597. return symbolPath;
  27598. }
  27599. /*
  27600. * Licensed to the Apache Software Foundation (ASF) under one
  27601. * or more contributor license agreements. See the NOTICE file
  27602. * distributed with this work for additional information
  27603. * regarding copyright ownership. The ASF licenses this file
  27604. * to you under the Apache License, Version 2.0 (the
  27605. * "License"); you may not use this file except in compliance
  27606. * with the License. You may obtain a copy of the License at
  27607. *
  27608. * http://www.apache.org/licenses/LICENSE-2.0
  27609. *
  27610. * Unless required by applicable law or agreed to in writing,
  27611. * software distributed under the License is distributed on an
  27612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27613. * KIND, either express or implied. See the License for the
  27614. * specific language governing permissions and limitations
  27615. * under the License.
  27616. */
  27617. /**
  27618. * @param {module:echarts/data/List} data
  27619. * @param {number} dataIndex
  27620. * @return {string} label string. Not null/undefined
  27621. */
  27622. function getDefaultLabel(data, dataIndex) {
  27623. var labelDims = data.mapDimension('defaultedLabel', true);
  27624. var len = labelDims.length;
  27625. // Simple optimization (in lots of cases, label dims length is 1)
  27626. if (len === 1) {
  27627. return retrieveRawValue(data, dataIndex, labelDims[0]);
  27628. }
  27629. else if (len) {
  27630. var vals = [];
  27631. for (var i = 0; i < labelDims.length; i++) {
  27632. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  27633. vals.push(val);
  27634. }
  27635. return vals.join(' ');
  27636. }
  27637. }
  27638. /*
  27639. * Licensed to the Apache Software Foundation (ASF) under one
  27640. * or more contributor license agreements. See the NOTICE file
  27641. * distributed with this work for additional information
  27642. * regarding copyright ownership. The ASF licenses this file
  27643. * to you under the Apache License, Version 2.0 (the
  27644. * "License"); you may not use this file except in compliance
  27645. * with the License. You may obtain a copy of the License at
  27646. *
  27647. * http://www.apache.org/licenses/LICENSE-2.0
  27648. *
  27649. * Unless required by applicable law or agreed to in writing,
  27650. * software distributed under the License is distributed on an
  27651. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27652. * KIND, either express or implied. See the License for the
  27653. * specific language governing permissions and limitations
  27654. * under the License.
  27655. */
  27656. /**
  27657. * @module echarts/chart/helper/Symbol
  27658. */
  27659. /**
  27660. * @constructor
  27661. * @alias {module:echarts/chart/helper/Symbol}
  27662. * @param {module:echarts/data/List} data
  27663. * @param {number} idx
  27664. * @extends {module:zrender/graphic/Group}
  27665. */
  27666. function SymbolClz(data, idx, seriesScope) {
  27667. Group.call(this);
  27668. this.updateData(data, idx, seriesScope);
  27669. }
  27670. var symbolProto = SymbolClz.prototype;
  27671. /**
  27672. * @public
  27673. * @static
  27674. * @param {module:echarts/data/List} data
  27675. * @param {number} dataIndex
  27676. * @return {Array.<number>} [width, height]
  27677. */
  27678. var getSymbolSize = SymbolClz.getSymbolSize = function (data, idx) {
  27679. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  27680. return symbolSize instanceof Array
  27681. ? symbolSize.slice()
  27682. : [+symbolSize, +symbolSize];
  27683. };
  27684. function getScale(symbolSize) {
  27685. return [symbolSize[0] / 2, symbolSize[1] / 2];
  27686. }
  27687. function driftSymbol(dx, dy) {
  27688. this.parent.drift(dx, dy);
  27689. }
  27690. symbolProto._createSymbol = function (
  27691. symbolType,
  27692. data,
  27693. idx,
  27694. symbolSize,
  27695. keepAspect
  27696. ) {
  27697. // Remove paths created before
  27698. this.removeAll();
  27699. var color = data.getItemVisual(idx, 'color');
  27700. // var symbolPath = createSymbol(
  27701. // symbolType, -0.5, -0.5, 1, 1, color
  27702. // );
  27703. // If width/height are set too small (e.g., set to 1) on ios10
  27704. // and macOS Sierra, a circle stroke become a rect, no matter what
  27705. // the scale is set. So we set width/height as 2. See #4150.
  27706. var symbolPath = createSymbol(
  27707. symbolType, -1, -1, 2, 2, color, keepAspect
  27708. );
  27709. symbolPath.attr({
  27710. z2: 100,
  27711. culling: true,
  27712. scale: getScale(symbolSize)
  27713. });
  27714. // Rewrite drift method
  27715. symbolPath.drift = driftSymbol;
  27716. this._symbolType = symbolType;
  27717. this.add(symbolPath);
  27718. };
  27719. /**
  27720. * Stop animation
  27721. * @param {boolean} toLastFrame
  27722. */
  27723. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  27724. this.childAt(0).stopAnimation(toLastFrame);
  27725. };
  27726. /**
  27727. * FIXME:
  27728. * Caution: This method breaks the encapsulation of this module,
  27729. * but it indeed brings convenience. So do not use the method
  27730. * unless you detailedly know all the implements of `Symbol`,
  27731. * especially animation.
  27732. *
  27733. * Get symbol path element.
  27734. */
  27735. symbolProto.getSymbolPath = function () {
  27736. return this.childAt(0);
  27737. };
  27738. /**
  27739. * Get scale(aka, current symbol size).
  27740. * Including the change caused by animation
  27741. */
  27742. symbolProto.getScale = function () {
  27743. return this.childAt(0).scale;
  27744. };
  27745. /**
  27746. * Highlight symbol
  27747. */
  27748. symbolProto.highlight = function () {
  27749. this.childAt(0).trigger('emphasis');
  27750. };
  27751. /**
  27752. * Downplay symbol
  27753. */
  27754. symbolProto.downplay = function () {
  27755. this.childAt(0).trigger('normal');
  27756. };
  27757. /**
  27758. * @param {number} zlevel
  27759. * @param {number} z
  27760. */
  27761. symbolProto.setZ = function (zlevel, z) {
  27762. var symbolPath = this.childAt(0);
  27763. symbolPath.zlevel = zlevel;
  27764. symbolPath.z = z;
  27765. };
  27766. symbolProto.setDraggable = function (draggable) {
  27767. var symbolPath = this.childAt(0);
  27768. symbolPath.draggable = draggable;
  27769. symbolPath.cursor = draggable ? 'move' : 'pointer';
  27770. };
  27771. /**
  27772. * Update symbol properties
  27773. * @param {module:echarts/data/List} data
  27774. * @param {number} idx
  27775. * @param {Object} [seriesScope]
  27776. * @param {Object} [seriesScope.itemStyle]
  27777. * @param {Object} [seriesScope.hoverItemStyle]
  27778. * @param {Object} [seriesScope.symbolRotate]
  27779. * @param {Object} [seriesScope.symbolOffset]
  27780. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  27781. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  27782. * @param {boolean} [seriesScope.hoverAnimation]
  27783. * @param {Object} [seriesScope.cursorStyle]
  27784. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  27785. * @param {string} [seriesScope.symbolInnerColor]
  27786. * @param {Object} [seriesScope.fadeIn=false]
  27787. */
  27788. symbolProto.updateData = function (data, idx, seriesScope) {
  27789. this.silent = false;
  27790. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  27791. var seriesModel = data.hostModel;
  27792. var symbolSize = getSymbolSize(data, idx);
  27793. var isInit = symbolType !== this._symbolType;
  27794. if (isInit) {
  27795. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  27796. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  27797. }
  27798. else {
  27799. var symbolPath = this.childAt(0);
  27800. symbolPath.silent = false;
  27801. updateProps(symbolPath, {
  27802. scale: getScale(symbolSize)
  27803. }, seriesModel, idx);
  27804. }
  27805. this._updateCommon(data, idx, symbolSize, seriesScope);
  27806. if (isInit) {
  27807. var symbolPath = this.childAt(0);
  27808. var fadeIn = seriesScope && seriesScope.fadeIn;
  27809. var target = {scale: symbolPath.scale.slice()};
  27810. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  27811. symbolPath.scale = [0, 0];
  27812. fadeIn && (symbolPath.style.opacity = 0);
  27813. initProps(symbolPath, target, seriesModel, idx);
  27814. }
  27815. this._seriesModel = seriesModel;
  27816. };
  27817. // Update common properties
  27818. var normalStyleAccessPath = ['itemStyle'];
  27819. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  27820. var normalLabelAccessPath = ['label'];
  27821. var emphasisLabelAccessPath = ['emphasis', 'label'];
  27822. /**
  27823. * @param {module:echarts/data/List} data
  27824. * @param {number} idx
  27825. * @param {Array.<number>} symbolSize
  27826. * @param {Object} [seriesScope]
  27827. */
  27828. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  27829. var symbolPath = this.childAt(0);
  27830. var seriesModel = data.hostModel;
  27831. var color = data.getItemVisual(idx, 'color');
  27832. // Reset style
  27833. if (symbolPath.type !== 'image') {
  27834. symbolPath.useStyle({
  27835. strokeNoScale: true
  27836. });
  27837. }
  27838. var itemStyle = seriesScope && seriesScope.itemStyle;
  27839. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  27840. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  27841. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  27842. var labelModel = seriesScope && seriesScope.labelModel;
  27843. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  27844. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  27845. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  27846. if (!seriesScope || data.hasItemOption) {
  27847. var itemModel = (seriesScope && seriesScope.itemModel)
  27848. ? seriesScope.itemModel : data.getItemModel(idx);
  27849. // Color must be excluded.
  27850. // Because symbol provide setColor individually to set fill and stroke
  27851. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  27852. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  27853. symbolRotate = itemModel.getShallow('symbolRotate');
  27854. symbolOffset = itemModel.getShallow('symbolOffset');
  27855. labelModel = itemModel.getModel(normalLabelAccessPath);
  27856. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  27857. hoverAnimation = itemModel.getShallow('hoverAnimation');
  27858. cursorStyle = itemModel.getShallow('cursor');
  27859. }
  27860. else {
  27861. hoverItemStyle = extend({}, hoverItemStyle);
  27862. }
  27863. var elStyle = symbolPath.style;
  27864. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  27865. if (symbolOffset) {
  27866. symbolPath.attr('position', [
  27867. parsePercent$1(symbolOffset[0], symbolSize[0]),
  27868. parsePercent$1(symbolOffset[1], symbolSize[1])
  27869. ]);
  27870. }
  27871. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  27872. // PENDING setColor before setStyle!!!
  27873. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  27874. symbolPath.setStyle(itemStyle);
  27875. var opacity = data.getItemVisual(idx, 'opacity');
  27876. if (opacity != null) {
  27877. elStyle.opacity = opacity;
  27878. }
  27879. var liftZ = data.getItemVisual(idx, 'liftZ');
  27880. var z2Origin = symbolPath.__z2Origin;
  27881. if (liftZ != null) {
  27882. if (z2Origin == null) {
  27883. symbolPath.__z2Origin = symbolPath.z2;
  27884. symbolPath.z2 += liftZ;
  27885. }
  27886. }
  27887. else if (z2Origin != null) {
  27888. symbolPath.z2 = z2Origin;
  27889. symbolPath.__z2Origin = null;
  27890. }
  27891. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  27892. setLabelStyle(
  27893. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  27894. {
  27895. labelFetcher: seriesModel,
  27896. labelDataIndex: idx,
  27897. defaultText: getLabelDefaultText,
  27898. isRectText: true,
  27899. autoColor: color
  27900. }
  27901. );
  27902. // Do not execute util needed.
  27903. function getLabelDefaultText(idx, opt) {
  27904. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  27905. }
  27906. symbolPath.off('mouseover')
  27907. .off('mouseout')
  27908. .off('emphasis')
  27909. .off('normal');
  27910. symbolPath.hoverStyle = hoverItemStyle;
  27911. // FIXME
  27912. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  27913. setHoverStyle(symbolPath);
  27914. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  27915. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  27916. // Note: consider `off`, should use static function here.
  27917. symbolPath.on('mouseover', onMouseOver)
  27918. .on('mouseout', onMouseOut)
  27919. .on('emphasis', onEmphasis)
  27920. .on('normal', onNormal);
  27921. }
  27922. };
  27923. function onMouseOver() {
  27924. // see comment in `graphic.isInEmphasis`
  27925. !isInEmphasis(this) && onEmphasis.call(this);
  27926. }
  27927. function onMouseOut() {
  27928. // see comment in `graphic.isInEmphasis`
  27929. !isInEmphasis(this) && onNormal.call(this);
  27930. }
  27931. function onEmphasis() {
  27932. // Do not support this hover animation util some scenario required.
  27933. // Animation can only be supported in hover layer when using `el.incremetal`.
  27934. if (this.incremental || this.useHoverLayer) {
  27935. return;
  27936. }
  27937. var scale = this.__symbolOriginalScale;
  27938. var ratio = scale[1] / scale[0];
  27939. this.animateTo({
  27940. scale: [
  27941. Math.max(scale[0] * 1.1, scale[0] + 3),
  27942. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  27943. ]
  27944. }, 400, 'elasticOut');
  27945. }
  27946. function onNormal() {
  27947. if (this.incremental || this.useHoverLayer) {
  27948. return;
  27949. }
  27950. this.animateTo({
  27951. scale: this.__symbolOriginalScale
  27952. }, 400, 'elasticOut');
  27953. }
  27954. /**
  27955. * @param {Function} cb
  27956. * @param {Object} [opt]
  27957. * @param {Object} [opt.keepLabel=true]
  27958. */
  27959. symbolProto.fadeOut = function (cb, opt) {
  27960. var symbolPath = this.childAt(0);
  27961. // Avoid mistaken hover when fading out
  27962. this.silent = symbolPath.silent = true;
  27963. // Not show text when animating
  27964. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  27965. updateProps(
  27966. symbolPath,
  27967. {
  27968. style: {opacity: 0},
  27969. scale: [0, 0]
  27970. },
  27971. this._seriesModel,
  27972. this.dataIndex,
  27973. cb
  27974. );
  27975. };
  27976. inherits(SymbolClz, Group);
  27977. /*
  27978. * Licensed to the Apache Software Foundation (ASF) under one
  27979. * or more contributor license agreements. See the NOTICE file
  27980. * distributed with this work for additional information
  27981. * regarding copyright ownership. The ASF licenses this file
  27982. * to you under the Apache License, Version 2.0 (the
  27983. * "License"); you may not use this file except in compliance
  27984. * with the License. You may obtain a copy of the License at
  27985. *
  27986. * http://www.apache.org/licenses/LICENSE-2.0
  27987. *
  27988. * Unless required by applicable law or agreed to in writing,
  27989. * software distributed under the License is distributed on an
  27990. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27991. * KIND, either express or implied. See the License for the
  27992. * specific language governing permissions and limitations
  27993. * under the License.
  27994. */
  27995. /**
  27996. * @module echarts/chart/helper/SymbolDraw
  27997. */
  27998. /**
  27999. * @constructor
  28000. * @alias module:echarts/chart/helper/SymbolDraw
  28001. * @param {module:zrender/graphic/Group} [symbolCtor]
  28002. */
  28003. function SymbolDraw(symbolCtor) {
  28004. this.group = new Group();
  28005. this._symbolCtor = symbolCtor || SymbolClz;
  28006. }
  28007. var symbolDrawProto = SymbolDraw.prototype;
  28008. function symbolNeedsDraw(data, point, idx, opt) {
  28009. return point && !isNaN(point[0]) && !isNaN(point[1])
  28010. && !(opt.isIgnore && opt.isIgnore(idx))
  28011. // We do not set clipShape on group, because it will cut part of
  28012. // the symbol element shape. We use the same clip shape here as
  28013. // the line clip.
  28014. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  28015. && data.getItemVisual(idx, 'symbol') !== 'none';
  28016. }
  28017. /**
  28018. * Update symbols draw by new data
  28019. * @param {module:echarts/data/List} data
  28020. * @param {Object} [opt] Or isIgnore
  28021. * @param {Function} [opt.isIgnore]
  28022. * @param {Object} [opt.clipShape]
  28023. */
  28024. symbolDrawProto.updateData = function (data, opt) {
  28025. opt = normalizeUpdateOpt(opt);
  28026. var group = this.group;
  28027. var seriesModel = data.hostModel;
  28028. var oldData = this._data;
  28029. var SymbolCtor = this._symbolCtor;
  28030. var seriesScope = makeSeriesScope(data);
  28031. // There is no oldLineData only when first rendering or switching from
  28032. // stream mode to normal mode, where previous elements should be removed.
  28033. if (!oldData) {
  28034. group.removeAll();
  28035. }
  28036. data.diff(oldData)
  28037. .add(function (newIdx) {
  28038. var point = data.getItemLayout(newIdx);
  28039. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  28040. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  28041. symbolEl.attr('position', point);
  28042. data.setItemGraphicEl(newIdx, symbolEl);
  28043. group.add(symbolEl);
  28044. }
  28045. })
  28046. .update(function (newIdx, oldIdx) {
  28047. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  28048. var point = data.getItemLayout(newIdx);
  28049. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  28050. group.remove(symbolEl);
  28051. return;
  28052. }
  28053. if (!symbolEl) {
  28054. symbolEl = new SymbolCtor(data, newIdx);
  28055. symbolEl.attr('position', point);
  28056. }
  28057. else {
  28058. symbolEl.updateData(data, newIdx, seriesScope);
  28059. updateProps(symbolEl, {
  28060. position: point
  28061. }, seriesModel);
  28062. }
  28063. // Add back
  28064. group.add(symbolEl);
  28065. data.setItemGraphicEl(newIdx, symbolEl);
  28066. })
  28067. .remove(function (oldIdx) {
  28068. var el = oldData.getItemGraphicEl(oldIdx);
  28069. el && el.fadeOut(function () {
  28070. group.remove(el);
  28071. });
  28072. })
  28073. .execute();
  28074. this._data = data;
  28075. };
  28076. symbolDrawProto.isPersistent = function () {
  28077. return true;
  28078. };
  28079. symbolDrawProto.updateLayout = function () {
  28080. var data = this._data;
  28081. if (data) {
  28082. // Not use animation
  28083. data.eachItemGraphicEl(function (el, idx) {
  28084. var point = data.getItemLayout(idx);
  28085. el.attr('position', point);
  28086. });
  28087. }
  28088. };
  28089. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  28090. this._seriesScope = makeSeriesScope(data);
  28091. this._data = null;
  28092. this.group.removeAll();
  28093. };
  28094. /**
  28095. * Update symbols draw by new data
  28096. * @param {module:echarts/data/List} data
  28097. * @param {Object} [opt] Or isIgnore
  28098. * @param {Function} [opt.isIgnore]
  28099. * @param {Object} [opt.clipShape]
  28100. */
  28101. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  28102. opt = normalizeUpdateOpt(opt);
  28103. function updateIncrementalAndHover(el) {
  28104. if (!el.isGroup) {
  28105. el.incremental = el.useHoverLayer = true;
  28106. }
  28107. }
  28108. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  28109. var point = data.getItemLayout(idx);
  28110. if (symbolNeedsDraw(data, point, idx, opt)) {
  28111. var el = new this._symbolCtor(data, idx, this._seriesScope);
  28112. el.traverse(updateIncrementalAndHover);
  28113. el.attr('position', point);
  28114. this.group.add(el);
  28115. data.setItemGraphicEl(idx, el);
  28116. }
  28117. }
  28118. };
  28119. function normalizeUpdateOpt(opt) {
  28120. if (opt != null && !isObject$1(opt)) {
  28121. opt = {isIgnore: opt};
  28122. }
  28123. return opt || {};
  28124. }
  28125. symbolDrawProto.remove = function (enableAnimation) {
  28126. var group = this.group;
  28127. var data = this._data;
  28128. // Incremental model do not have this._data.
  28129. if (data && enableAnimation) {
  28130. data.eachItemGraphicEl(function (el) {
  28131. el.fadeOut(function () {
  28132. group.remove(el);
  28133. });
  28134. });
  28135. }
  28136. else {
  28137. group.removeAll();
  28138. }
  28139. };
  28140. function makeSeriesScope(data) {
  28141. var seriesModel = data.hostModel;
  28142. return {
  28143. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  28144. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  28145. symbolRotate: seriesModel.get('symbolRotate'),
  28146. symbolOffset: seriesModel.get('symbolOffset'),
  28147. hoverAnimation: seriesModel.get('hoverAnimation'),
  28148. labelModel: seriesModel.getModel('label'),
  28149. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  28150. cursorStyle: seriesModel.get('cursor')
  28151. };
  28152. }
  28153. /*
  28154. * Licensed to the Apache Software Foundation (ASF) under one
  28155. * or more contributor license agreements. See the NOTICE file
  28156. * distributed with this work for additional information
  28157. * regarding copyright ownership. The ASF licenses this file
  28158. * to you under the Apache License, Version 2.0 (the
  28159. * "License"); you may not use this file except in compliance
  28160. * with the License. You may obtain a copy of the License at
  28161. *
  28162. * http://www.apache.org/licenses/LICENSE-2.0
  28163. *
  28164. * Unless required by applicable law or agreed to in writing,
  28165. * software distributed under the License is distributed on an
  28166. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28167. * KIND, either express or implied. See the License for the
  28168. * specific language governing permissions and limitations
  28169. * under the License.
  28170. */
  28171. /**
  28172. * @param {Object} coordSys
  28173. * @param {module:echarts/data/List} data
  28174. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  28175. */
  28176. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  28177. var baseAxis = coordSys.getBaseAxis();
  28178. var valueAxis = coordSys.getOtherAxis(baseAxis);
  28179. var valueStart = getValueStart(valueAxis, valueOrigin);
  28180. var baseAxisDim = baseAxis.dim;
  28181. var valueAxisDim = valueAxis.dim;
  28182. var valueDim = data.mapDimension(valueAxisDim);
  28183. var baseDim = data.mapDimension(baseAxisDim);
  28184. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  28185. var dims = map(coordSys.dimensions, function (coordDim) {
  28186. return data.mapDimension(coordDim);
  28187. });
  28188. var stacked;
  28189. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  28190. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  28191. dims[0] = stackResultDim;
  28192. }
  28193. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  28194. dims[1] = stackResultDim;
  28195. }
  28196. return {
  28197. dataDimsForPoint: dims,
  28198. valueStart: valueStart,
  28199. valueAxisDim: valueAxisDim,
  28200. baseAxisDim: baseAxisDim,
  28201. stacked: !!stacked,
  28202. valueDim: valueDim,
  28203. baseDim: baseDim,
  28204. baseDataOffset: baseDataOffset,
  28205. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  28206. };
  28207. }
  28208. function getValueStart(valueAxis, valueOrigin) {
  28209. var valueStart = 0;
  28210. var extent = valueAxis.scale.getExtent();
  28211. if (valueOrigin === 'start') {
  28212. valueStart = extent[0];
  28213. }
  28214. else if (valueOrigin === 'end') {
  28215. valueStart = extent[1];
  28216. }
  28217. // auto
  28218. else {
  28219. // Both positive
  28220. if (extent[0] > 0) {
  28221. valueStart = extent[0];
  28222. }
  28223. // Both negative
  28224. else if (extent[1] < 0) {
  28225. valueStart = extent[1];
  28226. }
  28227. // If is one positive, and one negative, onZero shall be true
  28228. }
  28229. return valueStart;
  28230. }
  28231. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  28232. var value = NaN;
  28233. if (dataCoordInfo.stacked) {
  28234. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  28235. }
  28236. if (isNaN(value)) {
  28237. value = dataCoordInfo.valueStart;
  28238. }
  28239. var baseDataOffset = dataCoordInfo.baseDataOffset;
  28240. var stackedData = [];
  28241. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  28242. stackedData[1 - baseDataOffset] = value;
  28243. return coordSys.dataToPoint(stackedData);
  28244. }
  28245. /*
  28246. * Licensed to the Apache Software Foundation (ASF) under one
  28247. * or more contributor license agreements. See the NOTICE file
  28248. * distributed with this work for additional information
  28249. * regarding copyright ownership. The ASF licenses this file
  28250. * to you under the Apache License, Version 2.0 (the
  28251. * "License"); you may not use this file except in compliance
  28252. * with the License. You may obtain a copy of the License at
  28253. *
  28254. * http://www.apache.org/licenses/LICENSE-2.0
  28255. *
  28256. * Unless required by applicable law or agreed to in writing,
  28257. * software distributed under the License is distributed on an
  28258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28259. * KIND, either express or implied. See the License for the
  28260. * specific language governing permissions and limitations
  28261. * under the License.
  28262. */
  28263. // var arrayDiff = require('zrender/src/core/arrayDiff');
  28264. // 'zrender/src/core/arrayDiff' has been used before, but it did
  28265. // not do well in performance when roam with fixed dataZoom window.
  28266. // function convertToIntId(newIdList, oldIdList) {
  28267. // // Generate int id instead of string id.
  28268. // // Compare string maybe slow in score function of arrDiff
  28269. // // Assume id in idList are all unique
  28270. // var idIndicesMap = {};
  28271. // var idx = 0;
  28272. // for (var i = 0; i < newIdList.length; i++) {
  28273. // idIndicesMap[newIdList[i]] = idx;
  28274. // newIdList[i] = idx++;
  28275. // }
  28276. // for (var i = 0; i < oldIdList.length; i++) {
  28277. // var oldId = oldIdList[i];
  28278. // // Same with newIdList
  28279. // if (idIndicesMap[oldId]) {
  28280. // oldIdList[i] = idIndicesMap[oldId];
  28281. // }
  28282. // else {
  28283. // oldIdList[i] = idx++;
  28284. // }
  28285. // }
  28286. // }
  28287. function diffData(oldData, newData) {
  28288. var diffResult = [];
  28289. newData.diff(oldData)
  28290. .add(function (idx) {
  28291. diffResult.push({cmd: '+', idx: idx});
  28292. })
  28293. .update(function (newIdx, oldIdx) {
  28294. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  28295. })
  28296. .remove(function (idx) {
  28297. diffResult.push({cmd: '-', idx: idx});
  28298. })
  28299. .execute();
  28300. return diffResult;
  28301. }
  28302. var lineAnimationDiff = function (
  28303. oldData, newData,
  28304. oldStackedOnPoints, newStackedOnPoints,
  28305. oldCoordSys, newCoordSys,
  28306. oldValueOrigin, newValueOrigin
  28307. ) {
  28308. var diff = diffData(oldData, newData);
  28309. // var newIdList = newData.mapArray(newData.getId);
  28310. // var oldIdList = oldData.mapArray(oldData.getId);
  28311. // convertToIntId(newIdList, oldIdList);
  28312. // // FIXME One data ?
  28313. // diff = arrayDiff(oldIdList, newIdList);
  28314. var currPoints = [];
  28315. var nextPoints = [];
  28316. // Points for stacking base line
  28317. var currStackedPoints = [];
  28318. var nextStackedPoints = [];
  28319. var status = [];
  28320. var sortedIndices = [];
  28321. var rawIndices = [];
  28322. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  28323. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  28324. for (var i = 0; i < diff.length; i++) {
  28325. var diffItem = diff[i];
  28326. var pointAdded = true;
  28327. // FIXME, animation is not so perfect when dataZoom window moves fast
  28328. // Which is in case remvoing or add more than one data in the tail or head
  28329. switch (diffItem.cmd) {
  28330. case '=':
  28331. var currentPt = oldData.getItemLayout(diffItem.idx);
  28332. var nextPt = newData.getItemLayout(diffItem.idx1);
  28333. // If previous data is NaN, use next point directly
  28334. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  28335. currentPt = nextPt.slice();
  28336. }
  28337. currPoints.push(currentPt);
  28338. nextPoints.push(nextPt);
  28339. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  28340. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  28341. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  28342. break;
  28343. case '+':
  28344. var idx = diffItem.idx;
  28345. currPoints.push(
  28346. oldCoordSys.dataToPoint([
  28347. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  28348. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  28349. ])
  28350. );
  28351. nextPoints.push(newData.getItemLayout(idx).slice());
  28352. currStackedPoints.push(
  28353. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  28354. );
  28355. nextStackedPoints.push(newStackedOnPoints[idx]);
  28356. rawIndices.push(newData.getRawIndex(idx));
  28357. break;
  28358. case '-':
  28359. var idx = diffItem.idx;
  28360. var rawIndex = oldData.getRawIndex(idx);
  28361. // Data is replaced. In the case of dynamic data queue
  28362. // FIXME FIXME FIXME
  28363. if (rawIndex !== idx) {
  28364. currPoints.push(oldData.getItemLayout(idx));
  28365. nextPoints.push(newCoordSys.dataToPoint([
  28366. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  28367. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  28368. ]));
  28369. currStackedPoints.push(oldStackedOnPoints[idx]);
  28370. nextStackedPoints.push(
  28371. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  28372. );
  28373. rawIndices.push(rawIndex);
  28374. }
  28375. else {
  28376. pointAdded = false;
  28377. }
  28378. }
  28379. // Original indices
  28380. if (pointAdded) {
  28381. status.push(diffItem);
  28382. sortedIndices.push(sortedIndices.length);
  28383. }
  28384. }
  28385. // Diff result may be crossed if all items are changed
  28386. // Sort by data index
  28387. sortedIndices.sort(function (a, b) {
  28388. return rawIndices[a] - rawIndices[b];
  28389. });
  28390. var sortedCurrPoints = [];
  28391. var sortedNextPoints = [];
  28392. var sortedCurrStackedPoints = [];
  28393. var sortedNextStackedPoints = [];
  28394. var sortedStatus = [];
  28395. for (var i = 0; i < sortedIndices.length; i++) {
  28396. var idx = sortedIndices[i];
  28397. sortedCurrPoints[i] = currPoints[idx];
  28398. sortedNextPoints[i] = nextPoints[idx];
  28399. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  28400. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  28401. sortedStatus[i] = status[idx];
  28402. }
  28403. return {
  28404. current: sortedCurrPoints,
  28405. next: sortedNextPoints,
  28406. stackedOnCurrent: sortedCurrStackedPoints,
  28407. stackedOnNext: sortedNextStackedPoints,
  28408. status: sortedStatus
  28409. };
  28410. };
  28411. /*
  28412. * Licensed to the Apache Software Foundation (ASF) under one
  28413. * or more contributor license agreements. See the NOTICE file
  28414. * distributed with this work for additional information
  28415. * regarding copyright ownership. The ASF licenses this file
  28416. * to you under the Apache License, Version 2.0 (the
  28417. * "License"); you may not use this file except in compliance
  28418. * with the License. You may obtain a copy of the License at
  28419. *
  28420. * http://www.apache.org/licenses/LICENSE-2.0
  28421. *
  28422. * Unless required by applicable law or agreed to in writing,
  28423. * software distributed under the License is distributed on an
  28424. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28425. * KIND, either express or implied. See the License for the
  28426. * specific language governing permissions and limitations
  28427. * under the License.
  28428. */
  28429. // Poly path support NaN point
  28430. var vec2Min = min;
  28431. var vec2Max = max;
  28432. var scaleAndAdd$1 = scaleAndAdd;
  28433. var v2Copy = copy;
  28434. // Temporary variable
  28435. var v = [];
  28436. var cp0 = [];
  28437. var cp1 = [];
  28438. function isPointNull(p) {
  28439. return isNaN(p[0]) || isNaN(p[1]);
  28440. }
  28441. function drawSegment(
  28442. ctx, points, start, segLen, allLen,
  28443. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28444. ) {
  28445. // if (smoothMonotone == null) {
  28446. // if (isMono(points, 'x')) {
  28447. // return drawMono(ctx, points, start, segLen, allLen,
  28448. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  28449. // }
  28450. // else if (isMono(points, 'y')) {
  28451. // return drawMono(ctx, points, start, segLen, allLen,
  28452. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  28453. // }
  28454. // else {
  28455. // return drawNonMono.apply(this, arguments);
  28456. // }
  28457. // }
  28458. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  28459. // return drawMono.apply(this, arguments);
  28460. // }
  28461. // else {
  28462. // return drawNonMono.apply(this, arguments);
  28463. // }
  28464. if (smoothMonotone === 'none' || !smoothMonotone) {
  28465. return drawNonMono.apply(this, arguments);
  28466. }
  28467. else {
  28468. return drawMono.apply(this, arguments);
  28469. }
  28470. }
  28471. /**
  28472. * Check if points is in monotone.
  28473. *
  28474. * @param {number[][]} points Array of points which is in [x, y] form
  28475. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  28476. * dimension that is checking.
  28477. * If is 'none', `drawNonMono` should be
  28478. * called.
  28479. * If is undefined, either being monotone
  28480. * in 'x' or 'y' will call `drawMono`.
  28481. */
  28482. // function isMono(points, smoothMonotone) {
  28483. // if (points.length <= 1) {
  28484. // return true;
  28485. // }
  28486. // var dim = smoothMonotone === 'x' ? 0 : 1;
  28487. // var last = points[0][dim];
  28488. // var lastDiff = 0;
  28489. // for (var i = 1; i < points.length; ++i) {
  28490. // var diff = points[i][dim] - last;
  28491. // if (!isNaN(diff) && !isNaN(lastDiff)
  28492. // && diff !== 0 && lastDiff !== 0
  28493. // && ((diff >= 0) !== (lastDiff >= 0))
  28494. // ) {
  28495. // return false;
  28496. // }
  28497. // if (!isNaN(diff) && diff !== 0) {
  28498. // lastDiff = diff;
  28499. // last = points[i][dim];
  28500. // }
  28501. // }
  28502. // return true;
  28503. // }
  28504. /**
  28505. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  28506. * control points will be used. This should be used when points are monotone
  28507. * either in x or y dimension.
  28508. */
  28509. function drawMono(
  28510. ctx, points, start, segLen, allLen,
  28511. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28512. ) {
  28513. var prevIdx = 0;
  28514. var idx = start;
  28515. for (var k = 0; k < segLen; k++) {
  28516. var p = points[idx];
  28517. if (idx >= allLen || idx < 0) {
  28518. break;
  28519. }
  28520. if (isPointNull(p)) {
  28521. if (connectNulls) {
  28522. idx += dir;
  28523. continue;
  28524. }
  28525. break;
  28526. }
  28527. if (idx === start) {
  28528. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28529. }
  28530. else {
  28531. if (smooth > 0) {
  28532. var prevP = points[prevIdx];
  28533. var dim = smoothMonotone === 'y' ? 1 : 0;
  28534. // Length of control point to p, either in x or y, but not both
  28535. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  28536. v2Copy(cp0, prevP);
  28537. cp0[dim] = prevP[dim] + ctrlLen;
  28538. v2Copy(cp1, p);
  28539. cp1[dim] = p[dim] - ctrlLen;
  28540. ctx.bezierCurveTo(
  28541. cp0[0], cp0[1],
  28542. cp1[0], cp1[1],
  28543. p[0], p[1]
  28544. );
  28545. }
  28546. else {
  28547. ctx.lineTo(p[0], p[1]);
  28548. }
  28549. }
  28550. prevIdx = idx;
  28551. idx += dir;
  28552. }
  28553. return k;
  28554. }
  28555. /**
  28556. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  28557. * situations. This should be used when points are non-monotone neither in x or
  28558. * y dimension.
  28559. */
  28560. function drawNonMono(
  28561. ctx, points, start, segLen, allLen,
  28562. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28563. ) {
  28564. var prevIdx = 0;
  28565. var idx = start;
  28566. for (var k = 0; k < segLen; k++) {
  28567. var p = points[idx];
  28568. if (idx >= allLen || idx < 0) {
  28569. break;
  28570. }
  28571. if (isPointNull(p)) {
  28572. if (connectNulls) {
  28573. idx += dir;
  28574. continue;
  28575. }
  28576. break;
  28577. }
  28578. if (idx === start) {
  28579. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28580. v2Copy(cp0, p);
  28581. }
  28582. else {
  28583. if (smooth > 0) {
  28584. var nextIdx = idx + dir;
  28585. var nextP = points[nextIdx];
  28586. if (connectNulls) {
  28587. // Find next point not null
  28588. while (nextP && isPointNull(points[nextIdx])) {
  28589. nextIdx += dir;
  28590. nextP = points[nextIdx];
  28591. }
  28592. }
  28593. var ratioNextSeg = 0.5;
  28594. var prevP = points[prevIdx];
  28595. var nextP = points[nextIdx];
  28596. // Last point
  28597. if (!nextP || isPointNull(nextP)) {
  28598. v2Copy(cp1, p);
  28599. }
  28600. else {
  28601. // If next data is null in not connect case
  28602. if (isPointNull(nextP) && !connectNulls) {
  28603. nextP = p;
  28604. }
  28605. sub(v, nextP, prevP);
  28606. var lenPrevSeg;
  28607. var lenNextSeg;
  28608. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  28609. var dim = smoothMonotone === 'x' ? 0 : 1;
  28610. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  28611. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  28612. }
  28613. else {
  28614. lenPrevSeg = dist(p, prevP);
  28615. lenNextSeg = dist(p, nextP);
  28616. }
  28617. // Use ratio of seg length
  28618. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  28619. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  28620. }
  28621. // Smooth constraint
  28622. vec2Min(cp0, cp0, smoothMax);
  28623. vec2Max(cp0, cp0, smoothMin);
  28624. vec2Min(cp1, cp1, smoothMax);
  28625. vec2Max(cp1, cp1, smoothMin);
  28626. ctx.bezierCurveTo(
  28627. cp0[0], cp0[1],
  28628. cp1[0], cp1[1],
  28629. p[0], p[1]
  28630. );
  28631. // cp0 of next segment
  28632. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  28633. }
  28634. else {
  28635. ctx.lineTo(p[0], p[1]);
  28636. }
  28637. }
  28638. prevIdx = idx;
  28639. idx += dir;
  28640. }
  28641. return k;
  28642. }
  28643. function getBoundingBox(points, smoothConstraint) {
  28644. var ptMin = [Infinity, Infinity];
  28645. var ptMax = [-Infinity, -Infinity];
  28646. if (smoothConstraint) {
  28647. for (var i = 0; i < points.length; i++) {
  28648. var pt = points[i];
  28649. if (pt[0] < ptMin[0]) {
  28650. ptMin[0] = pt[0];
  28651. }
  28652. if (pt[1] < ptMin[1]) {
  28653. ptMin[1] = pt[1];
  28654. }
  28655. if (pt[0] > ptMax[0]) {
  28656. ptMax[0] = pt[0];
  28657. }
  28658. if (pt[1] > ptMax[1]) {
  28659. ptMax[1] = pt[1];
  28660. }
  28661. }
  28662. }
  28663. return {
  28664. min: smoothConstraint ? ptMin : ptMax,
  28665. max: smoothConstraint ? ptMax : ptMin
  28666. };
  28667. }
  28668. var Polyline$1 = Path.extend({
  28669. type: 'ec-polyline',
  28670. shape: {
  28671. points: [],
  28672. smooth: 0,
  28673. smoothConstraint: true,
  28674. smoothMonotone: null,
  28675. connectNulls: false
  28676. },
  28677. style: {
  28678. fill: null,
  28679. stroke: '#000'
  28680. },
  28681. brush: fixClipWithShadow(Path.prototype.brush),
  28682. buildPath: function (ctx, shape) {
  28683. var points = shape.points;
  28684. var i = 0;
  28685. var len$$1 = points.length;
  28686. var result = getBoundingBox(points, shape.smoothConstraint);
  28687. if (shape.connectNulls) {
  28688. // Must remove first and last null values avoid draw error in polygon
  28689. for (; len$$1 > 0; len$$1--) {
  28690. if (!isPointNull(points[len$$1 - 1])) {
  28691. break;
  28692. }
  28693. }
  28694. for (; i < len$$1; i++) {
  28695. if (!isPointNull(points[i])) {
  28696. break;
  28697. }
  28698. }
  28699. }
  28700. while (i < len$$1) {
  28701. i += drawSegment(
  28702. ctx, points, i, len$$1, len$$1,
  28703. 1, result.min, result.max, shape.smooth,
  28704. shape.smoothMonotone, shape.connectNulls
  28705. ) + 1;
  28706. }
  28707. }
  28708. });
  28709. var Polygon$1 = Path.extend({
  28710. type: 'ec-polygon',
  28711. shape: {
  28712. points: [],
  28713. // Offset between stacked base points and points
  28714. stackedOnPoints: [],
  28715. smooth: 0,
  28716. stackedOnSmooth: 0,
  28717. smoothConstraint: true,
  28718. smoothMonotone: null,
  28719. connectNulls: false
  28720. },
  28721. brush: fixClipWithShadow(Path.prototype.brush),
  28722. buildPath: function (ctx, shape) {
  28723. var points = shape.points;
  28724. var stackedOnPoints = shape.stackedOnPoints;
  28725. var i = 0;
  28726. var len$$1 = points.length;
  28727. var smoothMonotone = shape.smoothMonotone;
  28728. var bbox = getBoundingBox(points, shape.smoothConstraint);
  28729. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  28730. if (shape.connectNulls) {
  28731. // Must remove first and last null values avoid draw error in polygon
  28732. for (; len$$1 > 0; len$$1--) {
  28733. if (!isPointNull(points[len$$1 - 1])) {
  28734. break;
  28735. }
  28736. }
  28737. for (; i < len$$1; i++) {
  28738. if (!isPointNull(points[i])) {
  28739. break;
  28740. }
  28741. }
  28742. }
  28743. while (i < len$$1) {
  28744. var k = drawSegment(
  28745. ctx, points, i, len$$1, len$$1,
  28746. 1, bbox.min, bbox.max, shape.smooth,
  28747. smoothMonotone, shape.connectNulls
  28748. );
  28749. drawSegment(
  28750. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  28751. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  28752. smoothMonotone, shape.connectNulls
  28753. );
  28754. i += k + 1;
  28755. ctx.closePath();
  28756. }
  28757. }
  28758. });
  28759. /*
  28760. * Licensed to the Apache Software Foundation (ASF) under one
  28761. * or more contributor license agreements. See the NOTICE file
  28762. * distributed with this work for additional information
  28763. * regarding copyright ownership. The ASF licenses this file
  28764. * to you under the Apache License, Version 2.0 (the
  28765. * "License"); you may not use this file except in compliance
  28766. * with the License. You may obtain a copy of the License at
  28767. *
  28768. * http://www.apache.org/licenses/LICENSE-2.0
  28769. *
  28770. * Unless required by applicable law or agreed to in writing,
  28771. * software distributed under the License is distributed on an
  28772. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28773. * KIND, either express or implied. See the License for the
  28774. * specific language governing permissions and limitations
  28775. * under the License.
  28776. */
  28777. // FIXME step not support polar
  28778. function isPointsSame(points1, points2) {
  28779. if (points1.length !== points2.length) {
  28780. return;
  28781. }
  28782. for (var i = 0; i < points1.length; i++) {
  28783. var p1 = points1[i];
  28784. var p2 = points2[i];
  28785. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  28786. return;
  28787. }
  28788. }
  28789. return true;
  28790. }
  28791. function getSmooth(smooth) {
  28792. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  28793. }
  28794. function getAxisExtentWithGap(axis) {
  28795. var extent = axis.getGlobalExtent();
  28796. if (axis.onBand) {
  28797. // Remove extra 1px to avoid line miter in clipped edge
  28798. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  28799. var dir = extent[1] > extent[0] ? 1 : -1;
  28800. extent[0] += dir * halfBandWidth;
  28801. extent[1] -= dir * halfBandWidth;
  28802. }
  28803. return extent;
  28804. }
  28805. /**
  28806. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  28807. * @param {module:echarts/data/List} data
  28808. * @param {Object} dataCoordInfo
  28809. * @param {Array.<Array.<number>>} points
  28810. */
  28811. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  28812. if (!dataCoordInfo.valueDim) {
  28813. return [];
  28814. }
  28815. var points = [];
  28816. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28817. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  28818. }
  28819. return points;
  28820. }
  28821. function createGridClipShape(cartesian, hasAnimation, forSymbol, seriesModel) {
  28822. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  28823. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  28824. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  28825. var x = Math.min(xExtent[0], xExtent[1]);
  28826. var y = Math.min(yExtent[0], yExtent[1]);
  28827. var width = Math.max(xExtent[0], xExtent[1]) - x;
  28828. var height = Math.max(yExtent[0], yExtent[1]) - y;
  28829. // Avoid float number rounding error for symbol on the edge of axis extent.
  28830. // See #7913 and `test/dataZoom-clip.html`.
  28831. if (forSymbol) {
  28832. x -= 0.5;
  28833. width += 0.5;
  28834. y -= 0.5;
  28835. height += 0.5;
  28836. }
  28837. else {
  28838. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  28839. // Expand clip shape to avoid clipping when line value exceeds axis
  28840. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  28841. if (isHorizontal) {
  28842. y -= expandSize;
  28843. height += expandSize * 2;
  28844. }
  28845. else {
  28846. x -= expandSize;
  28847. width += expandSize * 2;
  28848. }
  28849. }
  28850. var clipPath = new Rect({
  28851. shape: {
  28852. x: x,
  28853. y: y,
  28854. width: width,
  28855. height: height
  28856. }
  28857. });
  28858. if (hasAnimation) {
  28859. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  28860. initProps(clipPath, {
  28861. shape: {
  28862. width: width,
  28863. height: height
  28864. }
  28865. }, seriesModel);
  28866. }
  28867. return clipPath;
  28868. }
  28869. function createPolarClipShape(polar, hasAnimation, forSymbol, seriesModel) {
  28870. var angleAxis = polar.getAngleAxis();
  28871. var radiusAxis = polar.getRadiusAxis();
  28872. var radiusExtent = radiusAxis.getExtent().slice();
  28873. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  28874. var angleExtent = angleAxis.getExtent();
  28875. var RADIAN = Math.PI / 180;
  28876. // Avoid float number rounding error for symbol on the edge of axis extent.
  28877. if (forSymbol) {
  28878. radiusExtent[0] -= 0.5;
  28879. radiusExtent[1] += 0.5;
  28880. }
  28881. var clipPath = new Sector({
  28882. shape: {
  28883. cx: round$2(polar.cx, 1),
  28884. cy: round$2(polar.cy, 1),
  28885. r0: round$2(radiusExtent[0], 1),
  28886. r: round$2(radiusExtent[1], 1),
  28887. startAngle: -angleExtent[0] * RADIAN,
  28888. endAngle: -angleExtent[1] * RADIAN,
  28889. clockwise: angleAxis.inverse
  28890. }
  28891. });
  28892. if (hasAnimation) {
  28893. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  28894. initProps(clipPath, {
  28895. shape: {
  28896. endAngle: -angleExtent[1] * RADIAN
  28897. }
  28898. }, seriesModel);
  28899. }
  28900. return clipPath;
  28901. }
  28902. function createClipShape(coordSys, hasAnimation, forSymbol, seriesModel) {
  28903. return coordSys.type === 'polar'
  28904. ? createPolarClipShape(coordSys, hasAnimation, forSymbol, seriesModel)
  28905. : createGridClipShape(coordSys, hasAnimation, forSymbol, seriesModel);
  28906. }
  28907. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  28908. var baseAxis = coordSys.getBaseAxis();
  28909. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  28910. var stepPoints = [];
  28911. for (var i = 0; i < points.length - 1; i++) {
  28912. var nextPt = points[i + 1];
  28913. var pt = points[i];
  28914. stepPoints.push(pt);
  28915. var stepPt = [];
  28916. switch (stepTurnAt) {
  28917. case 'end':
  28918. stepPt[baseIndex] = nextPt[baseIndex];
  28919. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28920. // default is start
  28921. stepPoints.push(stepPt);
  28922. break;
  28923. case 'middle':
  28924. // default is start
  28925. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  28926. var stepPt2 = [];
  28927. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  28928. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28929. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  28930. stepPoints.push(stepPt);
  28931. stepPoints.push(stepPt2);
  28932. break;
  28933. default:
  28934. stepPt[baseIndex] = pt[baseIndex];
  28935. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  28936. // default is start
  28937. stepPoints.push(stepPt);
  28938. }
  28939. }
  28940. // Last points
  28941. points[i] && stepPoints.push(points[i]);
  28942. return stepPoints;
  28943. }
  28944. function getVisualGradient(data, coordSys) {
  28945. var visualMetaList = data.getVisual('visualMeta');
  28946. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  28947. // When data.count() is 0, gradient range can not be calculated.
  28948. return;
  28949. }
  28950. if (coordSys.type !== 'cartesian2d') {
  28951. if (__DEV__) {
  28952. console.warn('Visual map on line style is only supported on cartesian2d.');
  28953. }
  28954. return;
  28955. }
  28956. var coordDim;
  28957. var visualMeta;
  28958. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  28959. var dimIndex = visualMetaList[i].dimension;
  28960. var dimName = data.dimensions[dimIndex];
  28961. var dimInfo = data.getDimensionInfo(dimName);
  28962. coordDim = dimInfo && dimInfo.coordDim;
  28963. // Can only be x or y
  28964. if (coordDim === 'x' || coordDim === 'y') {
  28965. visualMeta = visualMetaList[i];
  28966. break;
  28967. }
  28968. }
  28969. if (!visualMeta) {
  28970. if (__DEV__) {
  28971. console.warn('Visual map on line style only support x or y dimension.');
  28972. }
  28973. return;
  28974. }
  28975. // If the area to be rendered is bigger than area defined by LinearGradient,
  28976. // the canvas spec prescribes that the color of the first stop and the last
  28977. // stop should be used. But if two stops are added at offset 0, in effect
  28978. // browsers use the color of the second stop to render area outside
  28979. // LinearGradient. So we can only infinitesimally extend area defined in
  28980. // LinearGradient to render `outerColors`.
  28981. var axis = coordSys.getAxis(coordDim);
  28982. // dataToCoor mapping may not be linear, but must be monotonic.
  28983. var colorStops = map(visualMeta.stops, function (stop) {
  28984. return {
  28985. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  28986. color: stop.color
  28987. };
  28988. });
  28989. var stopLen = colorStops.length;
  28990. var outerColors = visualMeta.outerColors.slice();
  28991. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  28992. colorStops.reverse();
  28993. outerColors.reverse();
  28994. }
  28995. var tinyExtent = 10; // Arbitrary value: 10px
  28996. var minCoord = colorStops[0].coord - tinyExtent;
  28997. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  28998. var coordSpan = maxCoord - minCoord;
  28999. if (coordSpan < 1e-3) {
  29000. return 'transparent';
  29001. }
  29002. each$1(colorStops, function (stop) {
  29003. stop.offset = (stop.coord - minCoord) / coordSpan;
  29004. });
  29005. colorStops.push({
  29006. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  29007. color: outerColors[1] || 'transparent'
  29008. });
  29009. colorStops.unshift({ // notice colorStops.length have been changed.
  29010. offset: stopLen ? colorStops[0].offset : 0.5,
  29011. color: outerColors[0] || 'transparent'
  29012. });
  29013. // zrUtil.each(colorStops, function (colorStop) {
  29014. // // Make sure each offset has rounded px to avoid not sharp edge
  29015. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  29016. // });
  29017. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  29018. gradient[coordDim] = minCoord;
  29019. gradient[coordDim + '2'] = maxCoord;
  29020. return gradient;
  29021. }
  29022. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  29023. var showAllSymbol = seriesModel.get('showAllSymbol');
  29024. var isAuto = showAllSymbol === 'auto';
  29025. if (showAllSymbol && !isAuto) {
  29026. return;
  29027. }
  29028. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  29029. if (!categoryAxis) {
  29030. return;
  29031. }
  29032. // Note that category label interval strategy might bring some weird effect
  29033. // in some scenario: users may wonder why some of the symbols are not
  29034. // displayed. So we show all symbols as possible as we can.
  29035. if (isAuto
  29036. // Simplify the logic, do not determine label overlap here.
  29037. && canShowAllSymbolForCategory(categoryAxis, data)
  29038. ) {
  29039. return;
  29040. }
  29041. // Otherwise follow the label interval strategy on category axis.
  29042. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  29043. var labelMap = {};
  29044. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  29045. labelMap[labelItem.tickValue] = 1;
  29046. });
  29047. return function (dataIndex) {
  29048. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  29049. };
  29050. }
  29051. function canShowAllSymbolForCategory(categoryAxis, data) {
  29052. // In mose cases, line is monotonous on category axis, and the label size
  29053. // is close with each other. So we check the symbol size and some of the
  29054. // label size alone with the category axis to estimate whether all symbol
  29055. // can be shown without overlap.
  29056. var axisExtent = categoryAxis.getExtent();
  29057. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  29058. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  29059. // Sampling some points, max 5.
  29060. var dataLen = data.count();
  29061. var step = Math.max(1, Math.round(dataLen / 5));
  29062. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  29063. if (SymbolClz.getSymbolSize(
  29064. data, dataIndex
  29065. // Only for cartesian, where `isHorizontal` exists.
  29066. )[categoryAxis.isHorizontal() ? 1 : 0]
  29067. // Empirical number
  29068. * 1.5 > availSize
  29069. ) {
  29070. return false;
  29071. }
  29072. }
  29073. return true;
  29074. }
  29075. Chart.extend({
  29076. type: 'line',
  29077. init: function () {
  29078. var lineGroup = new Group();
  29079. var symbolDraw = new SymbolDraw();
  29080. this.group.add(symbolDraw.group);
  29081. this._symbolDraw = symbolDraw;
  29082. this._lineGroup = lineGroup;
  29083. },
  29084. render: function (seriesModel, ecModel, api) {
  29085. var coordSys = seriesModel.coordinateSystem;
  29086. var group = this.group;
  29087. var data = seriesModel.getData();
  29088. var lineStyleModel = seriesModel.getModel('lineStyle');
  29089. var areaStyleModel = seriesModel.getModel('areaStyle');
  29090. var points = data.mapArray(data.getItemLayout);
  29091. var isCoordSysPolar = coordSys.type === 'polar';
  29092. var prevCoordSys = this._coordSys;
  29093. var symbolDraw = this._symbolDraw;
  29094. var polyline = this._polyline;
  29095. var polygon = this._polygon;
  29096. var lineGroup = this._lineGroup;
  29097. var hasAnimation = seriesModel.get('animation');
  29098. var isAreaChart = !areaStyleModel.isEmpty();
  29099. var valueOrigin = areaStyleModel.get('origin');
  29100. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  29101. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  29102. var showSymbol = seriesModel.get('showSymbol');
  29103. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  29104. && getIsIgnoreFunc(seriesModel, data, coordSys);
  29105. // Remove temporary symbols
  29106. var oldData = this._data;
  29107. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  29108. if (el.__temp) {
  29109. group.remove(el);
  29110. oldData.setItemGraphicEl(idx, null);
  29111. }
  29112. });
  29113. // Remove previous created symbols if showSymbol changed to false
  29114. if (!showSymbol) {
  29115. symbolDraw.remove();
  29116. }
  29117. group.add(lineGroup);
  29118. // FIXME step not support polar
  29119. var step = !isCoordSysPolar && seriesModel.get('step');
  29120. // Initialization animation or coordinate system changed
  29121. if (
  29122. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  29123. ) {
  29124. showSymbol && symbolDraw.updateData(data, {
  29125. isIgnore: isIgnoreFunc,
  29126. clipShape: createClipShape(coordSys, false, true, seriesModel)
  29127. });
  29128. if (step) {
  29129. // TODO If stacked series is not step
  29130. points = turnPointsIntoStep(points, coordSys, step);
  29131. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  29132. }
  29133. polyline = this._newPolyline(points, coordSys, hasAnimation);
  29134. if (isAreaChart) {
  29135. polygon = this._newPolygon(
  29136. points, stackedOnPoints,
  29137. coordSys, hasAnimation
  29138. );
  29139. }
  29140. lineGroup.setClipPath(createClipShape(coordSys, true, false, seriesModel));
  29141. }
  29142. else {
  29143. if (isAreaChart && !polygon) {
  29144. // If areaStyle is added
  29145. polygon = this._newPolygon(
  29146. points, stackedOnPoints,
  29147. coordSys, hasAnimation
  29148. );
  29149. }
  29150. else if (polygon && !isAreaChart) {
  29151. // If areaStyle is removed
  29152. lineGroup.remove(polygon);
  29153. polygon = this._polygon = null;
  29154. }
  29155. // Update clipPath
  29156. lineGroup.setClipPath(createClipShape(coordSys, false, false, seriesModel));
  29157. // Always update, or it is wrong in the case turning on legend
  29158. // because points are not changed
  29159. showSymbol && symbolDraw.updateData(data, {
  29160. isIgnore: isIgnoreFunc,
  29161. clipShape: createClipShape(coordSys, false, true, seriesModel)
  29162. });
  29163. // Stop symbol animation and sync with line points
  29164. // FIXME performance?
  29165. data.eachItemGraphicEl(function (el) {
  29166. el.stopAnimation(true);
  29167. });
  29168. // In the case data zoom triggerred refreshing frequently
  29169. // Data may not change if line has a category axis. So it should animate nothing
  29170. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  29171. || !isPointsSame(this._points, points)
  29172. ) {
  29173. if (hasAnimation) {
  29174. this._updateAnimation(
  29175. data, stackedOnPoints, coordSys, api, step, valueOrigin
  29176. );
  29177. }
  29178. else {
  29179. // Not do it in update with animation
  29180. if (step) {
  29181. // TODO If stacked series is not step
  29182. points = turnPointsIntoStep(points, coordSys, step);
  29183. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  29184. }
  29185. polyline.setShape({
  29186. points: points
  29187. });
  29188. polygon && polygon.setShape({
  29189. points: points,
  29190. stackedOnPoints: stackedOnPoints
  29191. });
  29192. }
  29193. }
  29194. }
  29195. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  29196. polyline.useStyle(defaults(
  29197. // Use color in lineStyle first
  29198. lineStyleModel.getLineStyle(),
  29199. {
  29200. fill: 'none',
  29201. stroke: visualColor,
  29202. lineJoin: 'bevel'
  29203. }
  29204. ));
  29205. var smooth = seriesModel.get('smooth');
  29206. smooth = getSmooth(seriesModel.get('smooth'));
  29207. polyline.setShape({
  29208. smooth: smooth,
  29209. smoothMonotone: seriesModel.get('smoothMonotone'),
  29210. connectNulls: seriesModel.get('connectNulls')
  29211. });
  29212. if (polygon) {
  29213. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  29214. var stackedOnSmooth = 0;
  29215. polygon.useStyle(defaults(
  29216. areaStyleModel.getAreaStyle(),
  29217. {
  29218. fill: visualColor,
  29219. opacity: 0.7,
  29220. lineJoin: 'bevel'
  29221. }
  29222. ));
  29223. if (stackedOnSeries) {
  29224. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  29225. }
  29226. polygon.setShape({
  29227. smooth: smooth,
  29228. stackedOnSmooth: stackedOnSmooth,
  29229. smoothMonotone: seriesModel.get('smoothMonotone'),
  29230. connectNulls: seriesModel.get('connectNulls')
  29231. });
  29232. }
  29233. this._data = data;
  29234. // Save the coordinate system for transition animation when data changed
  29235. this._coordSys = coordSys;
  29236. this._stackedOnPoints = stackedOnPoints;
  29237. this._points = points;
  29238. this._step = step;
  29239. this._valueOrigin = valueOrigin;
  29240. },
  29241. dispose: function () {},
  29242. highlight: function (seriesModel, ecModel, api, payload) {
  29243. var data = seriesModel.getData();
  29244. var dataIndex = queryDataIndex(data, payload);
  29245. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  29246. var symbol = data.getItemGraphicEl(dataIndex);
  29247. if (!symbol) {
  29248. // Create a temporary symbol if it is not exists
  29249. var pt = data.getItemLayout(dataIndex);
  29250. if (!pt) {
  29251. // Null data
  29252. return;
  29253. }
  29254. symbol = new SymbolClz(data, dataIndex);
  29255. symbol.position = pt;
  29256. symbol.setZ(
  29257. seriesModel.get('zlevel'),
  29258. seriesModel.get('z')
  29259. );
  29260. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  29261. symbol.__temp = true;
  29262. data.setItemGraphicEl(dataIndex, symbol);
  29263. // Stop scale animation
  29264. symbol.stopSymbolAnimation(true);
  29265. this.group.add(symbol);
  29266. }
  29267. symbol.highlight();
  29268. }
  29269. else {
  29270. // Highlight whole series
  29271. Chart.prototype.highlight.call(
  29272. this, seriesModel, ecModel, api, payload
  29273. );
  29274. }
  29275. },
  29276. downplay: function (seriesModel, ecModel, api, payload) {
  29277. var data = seriesModel.getData();
  29278. var dataIndex = queryDataIndex(data, payload);
  29279. if (dataIndex != null && dataIndex >= 0) {
  29280. var symbol = data.getItemGraphicEl(dataIndex);
  29281. if (symbol) {
  29282. if (symbol.__temp) {
  29283. data.setItemGraphicEl(dataIndex, null);
  29284. this.group.remove(symbol);
  29285. }
  29286. else {
  29287. symbol.downplay();
  29288. }
  29289. }
  29290. }
  29291. else {
  29292. // FIXME
  29293. // can not downplay completely.
  29294. // Downplay whole series
  29295. Chart.prototype.downplay.call(
  29296. this, seriesModel, ecModel, api, payload
  29297. );
  29298. }
  29299. },
  29300. /**
  29301. * @param {module:zrender/container/Group} group
  29302. * @param {Array.<Array.<number>>} points
  29303. * @private
  29304. */
  29305. _newPolyline: function (points) {
  29306. var polyline = this._polyline;
  29307. // Remove previous created polyline
  29308. if (polyline) {
  29309. this._lineGroup.remove(polyline);
  29310. }
  29311. polyline = new Polyline$1({
  29312. shape: {
  29313. points: points
  29314. },
  29315. silent: true,
  29316. z2: 10
  29317. });
  29318. this._lineGroup.add(polyline);
  29319. this._polyline = polyline;
  29320. return polyline;
  29321. },
  29322. /**
  29323. * @param {module:zrender/container/Group} group
  29324. * @param {Array.<Array.<number>>} stackedOnPoints
  29325. * @param {Array.<Array.<number>>} points
  29326. * @private
  29327. */
  29328. _newPolygon: function (points, stackedOnPoints) {
  29329. var polygon = this._polygon;
  29330. // Remove previous created polygon
  29331. if (polygon) {
  29332. this._lineGroup.remove(polygon);
  29333. }
  29334. polygon = new Polygon$1({
  29335. shape: {
  29336. points: points,
  29337. stackedOnPoints: stackedOnPoints
  29338. },
  29339. silent: true
  29340. });
  29341. this._lineGroup.add(polygon);
  29342. this._polygon = polygon;
  29343. return polygon;
  29344. },
  29345. /**
  29346. * @private
  29347. */
  29348. // FIXME Two value axis
  29349. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  29350. var polyline = this._polyline;
  29351. var polygon = this._polygon;
  29352. var seriesModel = data.hostModel;
  29353. var diff = lineAnimationDiff(
  29354. this._data, data,
  29355. this._stackedOnPoints, stackedOnPoints,
  29356. this._coordSys, coordSys,
  29357. this._valueOrigin, valueOrigin
  29358. );
  29359. var current = diff.current;
  29360. var stackedOnCurrent = diff.stackedOnCurrent;
  29361. var next = diff.next;
  29362. var stackedOnNext = diff.stackedOnNext;
  29363. if (step) {
  29364. // TODO If stacked series is not step
  29365. current = turnPointsIntoStep(diff.current, coordSys, step);
  29366. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  29367. next = turnPointsIntoStep(diff.next, coordSys, step);
  29368. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  29369. }
  29370. // `diff.current` is subset of `current` (which should be ensured by
  29371. // turnPointsIntoStep), so points in `__points` can be updated when
  29372. // points in `current` are update during animation.
  29373. polyline.shape.__points = diff.current;
  29374. polyline.shape.points = current;
  29375. updateProps(polyline, {
  29376. shape: {
  29377. points: next
  29378. }
  29379. }, seriesModel);
  29380. if (polygon) {
  29381. polygon.setShape({
  29382. points: current,
  29383. stackedOnPoints: stackedOnCurrent
  29384. });
  29385. updateProps(polygon, {
  29386. shape: {
  29387. points: next,
  29388. stackedOnPoints: stackedOnNext
  29389. }
  29390. }, seriesModel);
  29391. }
  29392. var updatedDataInfo = [];
  29393. var diffStatus = diff.status;
  29394. for (var i = 0; i < diffStatus.length; i++) {
  29395. var cmd = diffStatus[i].cmd;
  29396. if (cmd === '=') {
  29397. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  29398. if (el) {
  29399. updatedDataInfo.push({
  29400. el: el,
  29401. ptIdx: i // Index of points
  29402. });
  29403. }
  29404. }
  29405. }
  29406. if (polyline.animators && polyline.animators.length) {
  29407. polyline.animators[0].during(function () {
  29408. for (var i = 0; i < updatedDataInfo.length; i++) {
  29409. var el = updatedDataInfo[i].el;
  29410. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  29411. }
  29412. });
  29413. }
  29414. },
  29415. remove: function (ecModel) {
  29416. var group = this.group;
  29417. var oldData = this._data;
  29418. this._lineGroup.removeAll();
  29419. this._symbolDraw.remove(true);
  29420. // Remove temporary created elements when highlighting
  29421. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  29422. if (el.__temp) {
  29423. group.remove(el);
  29424. oldData.setItemGraphicEl(idx, null);
  29425. }
  29426. });
  29427. this._polyline
  29428. = this._polygon
  29429. = this._coordSys
  29430. = this._points
  29431. = this._stackedOnPoints
  29432. = this._data = null;
  29433. }
  29434. });
  29435. /*
  29436. * Licensed to the Apache Software Foundation (ASF) under one
  29437. * or more contributor license agreements. See the NOTICE file
  29438. * distributed with this work for additional information
  29439. * regarding copyright ownership. The ASF licenses this file
  29440. * to you under the Apache License, Version 2.0 (the
  29441. * "License"); you may not use this file except in compliance
  29442. * with the License. You may obtain a copy of the License at
  29443. *
  29444. * http://www.apache.org/licenses/LICENSE-2.0
  29445. *
  29446. * Unless required by applicable law or agreed to in writing,
  29447. * software distributed under the License is distributed on an
  29448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29449. * KIND, either express or implied. See the License for the
  29450. * specific language governing permissions and limitations
  29451. * under the License.
  29452. */
  29453. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  29454. // Encoding visual for all series include which is filtered for legend drawing
  29455. return {
  29456. seriesType: seriesType,
  29457. // For legend.
  29458. performRawSeries: true,
  29459. reset: function (seriesModel, ecModel, api) {
  29460. var data = seriesModel.getData();
  29461. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  29462. var symbolSize = seriesModel.get('symbolSize');
  29463. var keepAspect = seriesModel.get('symbolKeepAspect');
  29464. data.setVisual({
  29465. legendSymbol: legendSymbol || symbolType,
  29466. symbol: symbolType,
  29467. symbolSize: symbolSize,
  29468. symbolKeepAspect: keepAspect
  29469. });
  29470. // Only visible series has each data be visual encoded
  29471. if (ecModel.isSeriesFiltered(seriesModel)) {
  29472. return;
  29473. }
  29474. var hasCallback = typeof symbolSize === 'function';
  29475. function dataEach(data, idx) {
  29476. if (typeof symbolSize === 'function') {
  29477. var rawValue = seriesModel.getRawValue(idx);
  29478. // FIXME
  29479. var params = seriesModel.getDataParams(idx);
  29480. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  29481. }
  29482. if (data.hasItemOption) {
  29483. var itemModel = data.getItemModel(idx);
  29484. var itemSymbolType = itemModel.getShallow('symbol', true);
  29485. var itemSymbolSize = itemModel.getShallow('symbolSize',
  29486. true);
  29487. var itemSymbolKeepAspect
  29488. = itemModel.getShallow('symbolKeepAspect', true);
  29489. // If has item symbol
  29490. if (itemSymbolType != null) {
  29491. data.setItemVisual(idx, 'symbol', itemSymbolType);
  29492. }
  29493. if (itemSymbolSize != null) {
  29494. // PENDING Transform symbolSize ?
  29495. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  29496. }
  29497. if (itemSymbolKeepAspect != null) {
  29498. data.setItemVisual(idx, 'symbolKeepAspect',
  29499. itemSymbolKeepAspect);
  29500. }
  29501. }
  29502. }
  29503. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  29504. }
  29505. };
  29506. };
  29507. /*
  29508. * Licensed to the Apache Software Foundation (ASF) under one
  29509. * or more contributor license agreements. See the NOTICE file
  29510. * distributed with this work for additional information
  29511. * regarding copyright ownership. The ASF licenses this file
  29512. * to you under the Apache License, Version 2.0 (the
  29513. * "License"); you may not use this file except in compliance
  29514. * with the License. You may obtain a copy of the License at
  29515. *
  29516. * http://www.apache.org/licenses/LICENSE-2.0
  29517. *
  29518. * Unless required by applicable law or agreed to in writing,
  29519. * software distributed under the License is distributed on an
  29520. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29521. * KIND, either express or implied. See the License for the
  29522. * specific language governing permissions and limitations
  29523. * under the License.
  29524. */
  29525. /* global Float32Array */
  29526. var layoutPoints = function (seriesType) {
  29527. return {
  29528. seriesType: seriesType,
  29529. plan: createRenderPlanner(),
  29530. reset: function (seriesModel) {
  29531. var data = seriesModel.getData();
  29532. var coordSys = seriesModel.coordinateSystem;
  29533. var pipelineContext = seriesModel.pipelineContext;
  29534. var isLargeRender = pipelineContext.large;
  29535. if (!coordSys) {
  29536. return;
  29537. }
  29538. var dims = map(coordSys.dimensions, function (dim) {
  29539. return data.mapDimension(dim);
  29540. }).slice(0, 2);
  29541. var dimLen = dims.length;
  29542. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  29543. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  29544. dims[0] = stackResultDim;
  29545. }
  29546. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  29547. dims[1] = stackResultDim;
  29548. }
  29549. function progress(params, data) {
  29550. var segCount = params.end - params.start;
  29551. var points = isLargeRender && new Float32Array(segCount * dimLen);
  29552. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  29553. var point;
  29554. if (dimLen === 1) {
  29555. var x = data.get(dims[0], i);
  29556. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  29557. }
  29558. else {
  29559. var x = tmpIn[0] = data.get(dims[0], i);
  29560. var y = tmpIn[1] = data.get(dims[1], i);
  29561. // Also {Array.<number>}, not undefined to avoid if...else... statement
  29562. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  29563. }
  29564. if (isLargeRender) {
  29565. points[offset++] = point ? point[0] : NaN;
  29566. points[offset++] = point ? point[1] : NaN;
  29567. }
  29568. else {
  29569. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  29570. }
  29571. }
  29572. isLargeRender && data.setLayout('symbolPoints', points);
  29573. }
  29574. return dimLen && {progress: progress};
  29575. }
  29576. };
  29577. };
  29578. /*
  29579. * Licensed to the Apache Software Foundation (ASF) under one
  29580. * or more contributor license agreements. See the NOTICE file
  29581. * distributed with this work for additional information
  29582. * regarding copyright ownership. The ASF licenses this file
  29583. * to you under the Apache License, Version 2.0 (the
  29584. * "License"); you may not use this file except in compliance
  29585. * with the License. You may obtain a copy of the License at
  29586. *
  29587. * http://www.apache.org/licenses/LICENSE-2.0
  29588. *
  29589. * Unless required by applicable law or agreed to in writing,
  29590. * software distributed under the License is distributed on an
  29591. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29592. * KIND, either express or implied. See the License for the
  29593. * specific language governing permissions and limitations
  29594. * under the License.
  29595. */
  29596. var samplers = {
  29597. average: function (frame) {
  29598. var sum = 0;
  29599. var count = 0;
  29600. for (var i = 0; i < frame.length; i++) {
  29601. if (!isNaN(frame[i])) {
  29602. sum += frame[i];
  29603. count++;
  29604. }
  29605. }
  29606. // Return NaN if count is 0
  29607. return count === 0 ? NaN : sum / count;
  29608. },
  29609. sum: function (frame) {
  29610. var sum = 0;
  29611. for (var i = 0; i < frame.length; i++) {
  29612. // Ignore NaN
  29613. sum += frame[i] || 0;
  29614. }
  29615. return sum;
  29616. },
  29617. max: function (frame) {
  29618. var max = -Infinity;
  29619. for (var i = 0; i < frame.length; i++) {
  29620. frame[i] > max && (max = frame[i]);
  29621. }
  29622. // NaN will cause illegal axis extent.
  29623. return isFinite(max) ? max : NaN;
  29624. },
  29625. min: function (frame) {
  29626. var min = Infinity;
  29627. for (var i = 0; i < frame.length; i++) {
  29628. frame[i] < min && (min = frame[i]);
  29629. }
  29630. // NaN will cause illegal axis extent.
  29631. return isFinite(min) ? min : NaN;
  29632. },
  29633. // TODO
  29634. // Median
  29635. nearest: function (frame) {
  29636. return frame[0];
  29637. }
  29638. };
  29639. var indexSampler = function (frame, value) {
  29640. return Math.round(frame.length / 2);
  29641. };
  29642. var dataSample = function (seriesType) {
  29643. return {
  29644. seriesType: seriesType,
  29645. modifyOutputEnd: true,
  29646. reset: function (seriesModel, ecModel, api) {
  29647. var data = seriesModel.getData();
  29648. var sampling = seriesModel.get('sampling');
  29649. var coordSys = seriesModel.coordinateSystem;
  29650. // Only cartesian2d support down sampling
  29651. if (coordSys.type === 'cartesian2d' && sampling) {
  29652. var baseAxis = coordSys.getBaseAxis();
  29653. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29654. var extent = baseAxis.getExtent();
  29655. // Coordinste system has been resized
  29656. var size = extent[1] - extent[0];
  29657. var rate = Math.round(data.count() / size);
  29658. if (rate > 1) {
  29659. var sampler;
  29660. if (typeof sampling === 'string') {
  29661. sampler = samplers[sampling];
  29662. }
  29663. else if (typeof sampling === 'function') {
  29664. sampler = sampling;
  29665. }
  29666. if (sampler) {
  29667. // Only support sample the first dim mapped from value axis.
  29668. seriesModel.setData(data.downSample(
  29669. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  29670. ));
  29671. }
  29672. }
  29673. }
  29674. }
  29675. };
  29676. };
  29677. /*
  29678. * Licensed to the Apache Software Foundation (ASF) under one
  29679. * or more contributor license agreements. See the NOTICE file
  29680. * distributed with this work for additional information
  29681. * regarding copyright ownership. The ASF licenses this file
  29682. * to you under the Apache License, Version 2.0 (the
  29683. * "License"); you may not use this file except in compliance
  29684. * with the License. You may obtain a copy of the License at
  29685. *
  29686. * http://www.apache.org/licenses/LICENSE-2.0
  29687. *
  29688. * Unless required by applicable law or agreed to in writing,
  29689. * software distributed under the License is distributed on an
  29690. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29691. * KIND, either express or implied. See the License for the
  29692. * specific language governing permissions and limitations
  29693. * under the License.
  29694. */
  29695. /**
  29696. * // Scale class management
  29697. * @module echarts/scale/Scale
  29698. */
  29699. /**
  29700. * @param {Object} [setting]
  29701. */
  29702. function Scale(setting) {
  29703. this._setting = setting || {};
  29704. /**
  29705. * Extent
  29706. * @type {Array.<number>}
  29707. * @protected
  29708. */
  29709. this._extent = [Infinity, -Infinity];
  29710. /**
  29711. * Step is calculated in adjustExtent
  29712. * @type {Array.<number>}
  29713. * @protected
  29714. */
  29715. this._interval = 0;
  29716. this.init && this.init.apply(this, arguments);
  29717. }
  29718. /**
  29719. * Parse input val to valid inner number.
  29720. * @param {*} val
  29721. * @return {number}
  29722. */
  29723. Scale.prototype.parse = function (val) {
  29724. // Notice: This would be a trap here, If the implementation
  29725. // of this method depends on extent, and this method is used
  29726. // before extent set (like in dataZoom), it would be wrong.
  29727. // Nevertheless, parse does not depend on extent generally.
  29728. return val;
  29729. };
  29730. Scale.prototype.getSetting = function (name) {
  29731. return this._setting[name];
  29732. };
  29733. Scale.prototype.contain = function (val) {
  29734. var extent = this._extent;
  29735. return val >= extent[0] && val <= extent[1];
  29736. };
  29737. /**
  29738. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  29739. * @param {number} val
  29740. * @return {number}
  29741. */
  29742. Scale.prototype.normalize = function (val) {
  29743. var extent = this._extent;
  29744. if (extent[1] === extent[0]) {
  29745. return 0.5;
  29746. }
  29747. return (val - extent[0]) / (extent[1] - extent[0]);
  29748. };
  29749. /**
  29750. * Scale normalized value
  29751. * @param {number} val
  29752. * @return {number}
  29753. */
  29754. Scale.prototype.scale = function (val) {
  29755. var extent = this._extent;
  29756. return val * (extent[1] - extent[0]) + extent[0];
  29757. };
  29758. /**
  29759. * Set extent from data
  29760. * @param {Array.<number>} other
  29761. */
  29762. Scale.prototype.unionExtent = function (other) {
  29763. var extent = this._extent;
  29764. other[0] < extent[0] && (extent[0] = other[0]);
  29765. other[1] > extent[1] && (extent[1] = other[1]);
  29766. // not setExtent because in log axis it may transformed to power
  29767. // this.setExtent(extent[0], extent[1]);
  29768. };
  29769. /**
  29770. * Set extent from data
  29771. * @param {module:echarts/data/List} data
  29772. * @param {string} dim
  29773. */
  29774. Scale.prototype.unionExtentFromData = function (data, dim) {
  29775. this.unionExtent(data.getApproximateExtent(dim));
  29776. };
  29777. /**
  29778. * Get extent
  29779. * @return {Array.<number>}
  29780. */
  29781. Scale.prototype.getExtent = function () {
  29782. return this._extent.slice();
  29783. };
  29784. /**
  29785. * Set extent
  29786. * @param {number} start
  29787. * @param {number} end
  29788. */
  29789. Scale.prototype.setExtent = function (start, end) {
  29790. var thisExtent = this._extent;
  29791. if (!isNaN(start)) {
  29792. thisExtent[0] = start;
  29793. }
  29794. if (!isNaN(end)) {
  29795. thisExtent[1] = end;
  29796. }
  29797. };
  29798. /**
  29799. * When axis extent depends on data and no data exists,
  29800. * axis ticks should not be drawn, which is named 'blank'.
  29801. */
  29802. Scale.prototype.isBlank = function () {
  29803. return this._isBlank;
  29804. },
  29805. /**
  29806. * When axis extent depends on data and no data exists,
  29807. * axis ticks should not be drawn, which is named 'blank'.
  29808. */
  29809. Scale.prototype.setBlank = function (isBlank) {
  29810. this._isBlank = isBlank;
  29811. };
  29812. /**
  29813. * @abstract
  29814. * @param {*} tick
  29815. * @return {string} label of the tick.
  29816. */
  29817. Scale.prototype.getLabel = null;
  29818. enableClassExtend(Scale);
  29819. enableClassManagement(Scale, {
  29820. registerWhenExtend: true
  29821. });
  29822. /*
  29823. * Licensed to the Apache Software Foundation (ASF) under one
  29824. * or more contributor license agreements. See the NOTICE file
  29825. * distributed with this work for additional information
  29826. * regarding copyright ownership. The ASF licenses this file
  29827. * to you under the Apache License, Version 2.0 (the
  29828. * "License"); you may not use this file except in compliance
  29829. * with the License. You may obtain a copy of the License at
  29830. *
  29831. * http://www.apache.org/licenses/LICENSE-2.0
  29832. *
  29833. * Unless required by applicable law or agreed to in writing,
  29834. * software distributed under the License is distributed on an
  29835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29836. * KIND, either express or implied. See the License for the
  29837. * specific language governing permissions and limitations
  29838. * under the License.
  29839. */
  29840. /**
  29841. * @constructor
  29842. * @param {Object} [opt]
  29843. * @param {Object} [opt.categories=[]]
  29844. * @param {Object} [opt.needCollect=false]
  29845. * @param {Object} [opt.deduplication=false]
  29846. */
  29847. function OrdinalMeta(opt) {
  29848. /**
  29849. * @readOnly
  29850. * @type {Array.<string>}
  29851. */
  29852. this.categories = opt.categories || [];
  29853. /**
  29854. * @private
  29855. * @type {boolean}
  29856. */
  29857. this._needCollect = opt.needCollect;
  29858. /**
  29859. * @private
  29860. * @type {boolean}
  29861. */
  29862. this._deduplication = opt.deduplication;
  29863. /**
  29864. * @private
  29865. * @type {boolean}
  29866. */
  29867. this._map;
  29868. }
  29869. /**
  29870. * @param {module:echarts/model/Model} axisModel
  29871. * @return {module:echarts/data/OrdinalMeta}
  29872. */
  29873. OrdinalMeta.createByAxisModel = function (axisModel) {
  29874. var option = axisModel.option;
  29875. var data = option.data;
  29876. var categories = data && map(data, getName);
  29877. return new OrdinalMeta({
  29878. categories: categories,
  29879. needCollect: !categories,
  29880. // deduplication is default in axis.
  29881. deduplication: option.dedplication !== false
  29882. });
  29883. };
  29884. var proto$1 = OrdinalMeta.prototype;
  29885. /**
  29886. * @param {string} category
  29887. * @return {number} ordinal
  29888. */
  29889. proto$1.getOrdinal = function (category) {
  29890. return getOrCreateMap(this).get(category);
  29891. };
  29892. /**
  29893. * @param {*} category
  29894. * @return {number} The ordinal. If not found, return NaN.
  29895. */
  29896. proto$1.parseAndCollect = function (category) {
  29897. var index;
  29898. var needCollect = this._needCollect;
  29899. // The value of category dim can be the index of the given category set.
  29900. // This feature is only supported when !needCollect, because we should
  29901. // consider a common case: a value is 2017, which is a number but is
  29902. // expected to be tread as a category. This case usually happen in dataset,
  29903. // where it happent to be no need of the index feature.
  29904. if (typeof category !== 'string' && !needCollect) {
  29905. return category;
  29906. }
  29907. // Optimize for the scenario:
  29908. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29909. // data has been ensured not duplicate and is large data.
  29910. // Notice, if a dataset dimension provide categroies, usually echarts
  29911. // should remove duplication except user tell echarts dont do that
  29912. // (set axis.deduplication = false), because echarts do not know whether
  29913. // the values in the category dimension has duplication (consider the
  29914. // parallel-aqi example)
  29915. if (needCollect && !this._deduplication) {
  29916. index = this.categories.length;
  29917. this.categories[index] = category;
  29918. return index;
  29919. }
  29920. var map$$1 = getOrCreateMap(this);
  29921. index = map$$1.get(category);
  29922. if (index == null) {
  29923. if (needCollect) {
  29924. index = this.categories.length;
  29925. this.categories[index] = category;
  29926. map$$1.set(category, index);
  29927. }
  29928. else {
  29929. index = NaN;
  29930. }
  29931. }
  29932. return index;
  29933. };
  29934. // Consider big data, do not create map until needed.
  29935. function getOrCreateMap(ordinalMeta) {
  29936. return ordinalMeta._map || (
  29937. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  29938. );
  29939. }
  29940. function getName(obj) {
  29941. if (isObject$1(obj) && obj.value != null) {
  29942. return obj.value;
  29943. }
  29944. else {
  29945. return obj + '';
  29946. }
  29947. }
  29948. /*
  29949. * Licensed to the Apache Software Foundation (ASF) under one
  29950. * or more contributor license agreements. See the NOTICE file
  29951. * distributed with this work for additional information
  29952. * regarding copyright ownership. The ASF licenses this file
  29953. * to you under the Apache License, Version 2.0 (the
  29954. * "License"); you may not use this file except in compliance
  29955. * with the License. You may obtain a copy of the License at
  29956. *
  29957. * http://www.apache.org/licenses/LICENSE-2.0
  29958. *
  29959. * Unless required by applicable law or agreed to in writing,
  29960. * software distributed under the License is distributed on an
  29961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29962. * KIND, either express or implied. See the License for the
  29963. * specific language governing permissions and limitations
  29964. * under the License.
  29965. */
  29966. /**
  29967. * Linear continuous scale
  29968. * @module echarts/coord/scale/Ordinal
  29969. *
  29970. * http://en.wikipedia.org/wiki/Level_of_measurement
  29971. */
  29972. // FIXME only one data
  29973. var scaleProto = Scale.prototype;
  29974. var OrdinalScale = Scale.extend({
  29975. type: 'ordinal',
  29976. /**
  29977. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  29978. */
  29979. init: function (ordinalMeta, extent) {
  29980. // Caution: Should not use instanceof, consider ec-extensions using
  29981. // import approach to get OrdinalMeta class.
  29982. if (!ordinalMeta || isArray(ordinalMeta)) {
  29983. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  29984. }
  29985. this._ordinalMeta = ordinalMeta;
  29986. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  29987. },
  29988. parse: function (val) {
  29989. return typeof val === 'string'
  29990. ? this._ordinalMeta.getOrdinal(val)
  29991. // val might be float.
  29992. : Math.round(val);
  29993. },
  29994. contain: function (rank) {
  29995. rank = this.parse(rank);
  29996. return scaleProto.contain.call(this, rank)
  29997. && this._ordinalMeta.categories[rank] != null;
  29998. },
  29999. /**
  30000. * Normalize given rank or name to linear [0, 1]
  30001. * @param {number|string} [val]
  30002. * @return {number}
  30003. */
  30004. normalize: function (val) {
  30005. return scaleProto.normalize.call(this, this.parse(val));
  30006. },
  30007. scale: function (val) {
  30008. return Math.round(scaleProto.scale.call(this, val));
  30009. },
  30010. /**
  30011. * @return {Array}
  30012. */
  30013. getTicks: function () {
  30014. var ticks = [];
  30015. var extent = this._extent;
  30016. var rank = extent[0];
  30017. while (rank <= extent[1]) {
  30018. ticks.push(rank);
  30019. rank++;
  30020. }
  30021. return ticks;
  30022. },
  30023. /**
  30024. * Get item on rank n
  30025. * @param {number} n
  30026. * @return {string}
  30027. */
  30028. getLabel: function (n) {
  30029. if (!this.isBlank()) {
  30030. // Note that if no data, ordinalMeta.categories is an empty array.
  30031. return this._ordinalMeta.categories[n];
  30032. }
  30033. },
  30034. /**
  30035. * @return {number}
  30036. */
  30037. count: function () {
  30038. return this._extent[1] - this._extent[0] + 1;
  30039. },
  30040. /**
  30041. * @override
  30042. */
  30043. unionExtentFromData: function (data, dim) {
  30044. this.unionExtent(data.getApproximateExtent(dim));
  30045. },
  30046. getOrdinalMeta: function () {
  30047. return this._ordinalMeta;
  30048. },
  30049. niceTicks: noop,
  30050. niceExtent: noop
  30051. });
  30052. /**
  30053. * @return {module:echarts/scale/Time}
  30054. */
  30055. OrdinalScale.create = function () {
  30056. return new OrdinalScale();
  30057. };
  30058. /*
  30059. * Licensed to the Apache Software Foundation (ASF) under one
  30060. * or more contributor license agreements. See the NOTICE file
  30061. * distributed with this work for additional information
  30062. * regarding copyright ownership. The ASF licenses this file
  30063. * to you under the Apache License, Version 2.0 (the
  30064. * "License"); you may not use this file except in compliance
  30065. * with the License. You may obtain a copy of the License at
  30066. *
  30067. * http://www.apache.org/licenses/LICENSE-2.0
  30068. *
  30069. * Unless required by applicable law or agreed to in writing,
  30070. * software distributed under the License is distributed on an
  30071. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30072. * KIND, either express or implied. See the License for the
  30073. * specific language governing permissions and limitations
  30074. * under the License.
  30075. */
  30076. /**
  30077. * For testable.
  30078. */
  30079. var roundNumber$1 = round$2;
  30080. /**
  30081. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  30082. * Should be extent[0] < extent[1].
  30083. * @param {number} splitNumber splitNumber should be >= 1.
  30084. * @param {number} [minInterval]
  30085. * @param {number} [maxInterval]
  30086. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  30087. */
  30088. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  30089. var result = {};
  30090. var span = extent[1] - extent[0];
  30091. var interval = result.interval = nice(span / splitNumber, true);
  30092. if (minInterval != null && interval < minInterval) {
  30093. interval = result.interval = minInterval;
  30094. }
  30095. if (maxInterval != null && interval > maxInterval) {
  30096. interval = result.interval = maxInterval;
  30097. }
  30098. // Tow more digital for tick.
  30099. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  30100. // Niced extent inside original extent
  30101. var niceTickExtent = result.niceTickExtent = [
  30102. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  30103. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  30104. ];
  30105. fixExtent(niceTickExtent, extent);
  30106. return result;
  30107. }
  30108. /**
  30109. * @param {number} interval
  30110. * @return {number} interval precision
  30111. */
  30112. function getIntervalPrecision(interval) {
  30113. // Tow more digital for tick.
  30114. return getPrecisionSafe(interval) + 2;
  30115. }
  30116. function clamp(niceTickExtent, idx, extent) {
  30117. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  30118. }
  30119. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  30120. function fixExtent(niceTickExtent, extent) {
  30121. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  30122. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  30123. clamp(niceTickExtent, 0, extent);
  30124. clamp(niceTickExtent, 1, extent);
  30125. if (niceTickExtent[0] > niceTickExtent[1]) {
  30126. niceTickExtent[0] = niceTickExtent[1];
  30127. }
  30128. }
  30129. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  30130. var ticks = [];
  30131. // If interval is 0, return [];
  30132. if (!interval) {
  30133. return ticks;
  30134. }
  30135. // Consider this case: using dataZoom toolbox, zoom and zoom.
  30136. var safeLimit = 10000;
  30137. if (extent[0] < niceTickExtent[0]) {
  30138. ticks.push(extent[0]);
  30139. }
  30140. var tick = niceTickExtent[0];
  30141. while (tick <= niceTickExtent[1]) {
  30142. ticks.push(tick);
  30143. // Avoid rounding error
  30144. tick = roundNumber$1(tick + interval, intervalPrecision);
  30145. if (tick === ticks[ticks.length - 1]) {
  30146. // Consider out of safe float point, e.g.,
  30147. // -3711126.9907707 + 2e-10 === -3711126.9907707
  30148. break;
  30149. }
  30150. if (ticks.length > safeLimit) {
  30151. return [];
  30152. }
  30153. }
  30154. // Consider this case: the last item of ticks is smaller
  30155. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  30156. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  30157. ticks.push(extent[1]);
  30158. }
  30159. return ticks;
  30160. }
  30161. /*
  30162. * Licensed to the Apache Software Foundation (ASF) under one
  30163. * or more contributor license agreements. See the NOTICE file
  30164. * distributed with this work for additional information
  30165. * regarding copyright ownership. The ASF licenses this file
  30166. * to you under the Apache License, Version 2.0 (the
  30167. * "License"); you may not use this file except in compliance
  30168. * with the License. You may obtain a copy of the License at
  30169. *
  30170. * http://www.apache.org/licenses/LICENSE-2.0
  30171. *
  30172. * Unless required by applicable law or agreed to in writing,
  30173. * software distributed under the License is distributed on an
  30174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30175. * KIND, either express or implied. See the License for the
  30176. * specific language governing permissions and limitations
  30177. * under the License.
  30178. */
  30179. /**
  30180. * Interval scale
  30181. * @module echarts/scale/Interval
  30182. */
  30183. var roundNumber = round$2;
  30184. /**
  30185. * @alias module:echarts/coord/scale/Interval
  30186. * @constructor
  30187. */
  30188. var IntervalScale = Scale.extend({
  30189. type: 'interval',
  30190. _interval: 0,
  30191. _intervalPrecision: 2,
  30192. setExtent: function (start, end) {
  30193. var thisExtent = this._extent;
  30194. //start,end may be a Number like '25',so...
  30195. if (!isNaN(start)) {
  30196. thisExtent[0] = parseFloat(start);
  30197. }
  30198. if (!isNaN(end)) {
  30199. thisExtent[1] = parseFloat(end);
  30200. }
  30201. },
  30202. unionExtent: function (other) {
  30203. var extent = this._extent;
  30204. other[0] < extent[0] && (extent[0] = other[0]);
  30205. other[1] > extent[1] && (extent[1] = other[1]);
  30206. // unionExtent may called by it's sub classes
  30207. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  30208. },
  30209. /**
  30210. * Get interval
  30211. */
  30212. getInterval: function () {
  30213. return this._interval;
  30214. },
  30215. /**
  30216. * Set interval
  30217. */
  30218. setInterval: function (interval) {
  30219. this._interval = interval;
  30220. // Dropped auto calculated niceExtent and use user setted extent
  30221. // We assume user wan't to set both interval, min, max to get a better result
  30222. this._niceExtent = this._extent.slice();
  30223. this._intervalPrecision = getIntervalPrecision(interval);
  30224. },
  30225. /**
  30226. * @return {Array.<number>}
  30227. */
  30228. getTicks: function () {
  30229. return intervalScaleGetTicks(
  30230. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  30231. );
  30232. },
  30233. /**
  30234. * @param {number} data
  30235. * @param {Object} [opt]
  30236. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  30237. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  30238. * @return {string}
  30239. */
  30240. getLabel: function (data, opt) {
  30241. if (data == null) {
  30242. return '';
  30243. }
  30244. var precision = opt && opt.precision;
  30245. if (precision == null) {
  30246. precision = getPrecisionSafe(data) || 0;
  30247. }
  30248. else if (precision === 'auto') {
  30249. // Should be more precise then tick.
  30250. precision = this._intervalPrecision;
  30251. }
  30252. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  30253. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  30254. data = roundNumber(data, precision, true);
  30255. return addCommas(data);
  30256. },
  30257. /**
  30258. * Update interval and extent of intervals for nice ticks
  30259. *
  30260. * @param {number} [splitNumber = 5] Desired number of ticks
  30261. * @param {number} [minInterval]
  30262. * @param {number} [maxInterval]
  30263. */
  30264. niceTicks: function (splitNumber, minInterval, maxInterval) {
  30265. splitNumber = splitNumber || 5;
  30266. var extent = this._extent;
  30267. var span = extent[1] - extent[0];
  30268. if (!isFinite(span)) {
  30269. return;
  30270. }
  30271. // User may set axis min 0 and data are all negative
  30272. // FIXME If it needs to reverse ?
  30273. if (span < 0) {
  30274. span = -span;
  30275. extent.reverse();
  30276. }
  30277. var result = intervalScaleNiceTicks(
  30278. extent, splitNumber, minInterval, maxInterval
  30279. );
  30280. this._intervalPrecision = result.intervalPrecision;
  30281. this._interval = result.interval;
  30282. this._niceExtent = result.niceTickExtent;
  30283. },
  30284. /**
  30285. * Nice extent.
  30286. * @param {Object} opt
  30287. * @param {number} [opt.splitNumber = 5] Given approx tick number
  30288. * @param {boolean} [opt.fixMin=false]
  30289. * @param {boolean} [opt.fixMax=false]
  30290. * @param {boolean} [opt.minInterval]
  30291. * @param {boolean} [opt.maxInterval]
  30292. */
  30293. niceExtent: function (opt) {
  30294. var extent = this._extent;
  30295. // If extent start and end are same, expand them
  30296. if (extent[0] === extent[1]) {
  30297. if (extent[0] !== 0) {
  30298. // Expand extent
  30299. var expandSize = extent[0];
  30300. // In the fowllowing case
  30301. // Axis has been fixed max 100
  30302. // Plus data are all 100 and axis extent are [100, 100].
  30303. // Extend to the both side will cause expanded max is larger than fixed max.
  30304. // So only expand to the smaller side.
  30305. if (!opt.fixMax) {
  30306. extent[1] += expandSize / 2;
  30307. extent[0] -= expandSize / 2;
  30308. }
  30309. else {
  30310. extent[0] -= expandSize / 2;
  30311. }
  30312. }
  30313. else {
  30314. extent[1] = 1;
  30315. }
  30316. }
  30317. var span = extent[1] - extent[0];
  30318. // If there are no data and extent are [Infinity, -Infinity]
  30319. if (!isFinite(span)) {
  30320. extent[0] = 0;
  30321. extent[1] = 1;
  30322. }
  30323. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30324. // var extent = this._extent;
  30325. var interval = this._interval;
  30326. if (!opt.fixMin) {
  30327. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  30328. }
  30329. if (!opt.fixMax) {
  30330. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  30331. }
  30332. }
  30333. });
  30334. /**
  30335. * @return {module:echarts/scale/Time}
  30336. */
  30337. IntervalScale.create = function () {
  30338. return new IntervalScale();
  30339. };
  30340. /*
  30341. * Licensed to the Apache Software Foundation (ASF) under one
  30342. * or more contributor license agreements. See the NOTICE file
  30343. * distributed with this work for additional information
  30344. * regarding copyright ownership. The ASF licenses this file
  30345. * to you under the Apache License, Version 2.0 (the
  30346. * "License"); you may not use this file except in compliance
  30347. * with the License. You may obtain a copy of the License at
  30348. *
  30349. * http://www.apache.org/licenses/LICENSE-2.0
  30350. *
  30351. * Unless required by applicable law or agreed to in writing,
  30352. * software distributed under the License is distributed on an
  30353. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30354. * KIND, either express or implied. See the License for the
  30355. * specific language governing permissions and limitations
  30356. * under the License.
  30357. */
  30358. /* global Float32Array */
  30359. var STACK_PREFIX = '__ec_stack_';
  30360. var LARGE_BAR_MIN_WIDTH = 0.5;
  30361. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  30362. function getSeriesStackId(seriesModel) {
  30363. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  30364. }
  30365. function getAxisKey(axis) {
  30366. return axis.dim + axis.index;
  30367. }
  30368. /**
  30369. * @param {Object} opt
  30370. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  30371. * @param {number} opt.count Positive interger.
  30372. * @param {number} [opt.barWidth]
  30373. * @param {number} [opt.barMaxWidth]
  30374. * @param {number} [opt.barGap]
  30375. * @param {number} [opt.barCategoryGap]
  30376. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  30377. */
  30378. function prepareLayoutBarSeries(seriesType, ecModel) {
  30379. var seriesModels = [];
  30380. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30381. // Check series coordinate, do layout for cartesian2d only
  30382. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  30383. seriesModels.push(seriesModel);
  30384. }
  30385. });
  30386. return seriesModels;
  30387. }
  30388. function makeColumnLayout(barSeries) {
  30389. var seriesInfoList = [];
  30390. each$1(barSeries, function (seriesModel) {
  30391. var data = seriesModel.getData();
  30392. var cartesian = seriesModel.coordinateSystem;
  30393. var baseAxis = cartesian.getBaseAxis();
  30394. var axisExtent = baseAxis.getExtent();
  30395. var bandWidth = baseAxis.type === 'category'
  30396. ? baseAxis.getBandWidth()
  30397. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  30398. var barWidth = parsePercent$1(
  30399. seriesModel.get('barWidth'), bandWidth
  30400. );
  30401. var barMaxWidth = parsePercent$1(
  30402. seriesModel.get('barMaxWidth'), bandWidth
  30403. );
  30404. var barGap = seriesModel.get('barGap');
  30405. var barCategoryGap = seriesModel.get('barCategoryGap');
  30406. seriesInfoList.push({
  30407. bandWidth: bandWidth,
  30408. barWidth: barWidth,
  30409. barMaxWidth: barMaxWidth,
  30410. barGap: barGap,
  30411. barCategoryGap: barCategoryGap,
  30412. axisKey: getAxisKey(baseAxis),
  30413. stackId: getSeriesStackId(seriesModel)
  30414. });
  30415. });
  30416. return doCalBarWidthAndOffset(seriesInfoList);
  30417. }
  30418. function doCalBarWidthAndOffset(seriesInfoList) {
  30419. // Columns info on each category axis. Key is cartesian name
  30420. var columnsMap = {};
  30421. each$1(seriesInfoList, function (seriesInfo, idx) {
  30422. var axisKey = seriesInfo.axisKey;
  30423. var bandWidth = seriesInfo.bandWidth;
  30424. var columnsOnAxis = columnsMap[axisKey] || {
  30425. bandWidth: bandWidth,
  30426. remainedWidth: bandWidth,
  30427. autoWidthCount: 0,
  30428. categoryGap: '20%',
  30429. gap: '30%',
  30430. stacks: {}
  30431. };
  30432. var stacks = columnsOnAxis.stacks;
  30433. columnsMap[axisKey] = columnsOnAxis;
  30434. var stackId = seriesInfo.stackId;
  30435. if (!stacks[stackId]) {
  30436. columnsOnAxis.autoWidthCount++;
  30437. }
  30438. stacks[stackId] = stacks[stackId] || {
  30439. width: 0,
  30440. maxWidth: 0
  30441. };
  30442. // Caution: In a single coordinate system, these barGrid attributes
  30443. // will be shared by series. Consider that they have default values,
  30444. // only the attributes set on the last series will work.
  30445. // Do not change this fact unless there will be a break change.
  30446. // TODO
  30447. var barWidth = seriesInfo.barWidth;
  30448. if (barWidth && !stacks[stackId].width) {
  30449. // See #6312, do not restrict width.
  30450. stacks[stackId].width = barWidth;
  30451. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30452. columnsOnAxis.remainedWidth -= barWidth;
  30453. }
  30454. var barMaxWidth = seriesInfo.barMaxWidth;
  30455. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30456. var barGap = seriesInfo.barGap;
  30457. (barGap != null) && (columnsOnAxis.gap = barGap);
  30458. var barCategoryGap = seriesInfo.barCategoryGap;
  30459. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  30460. });
  30461. var result = {};
  30462. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  30463. result[coordSysName] = {};
  30464. var stacks = columnsOnAxis.stacks;
  30465. var bandWidth = columnsOnAxis.bandWidth;
  30466. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  30467. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30468. var remainedWidth = columnsOnAxis.remainedWidth;
  30469. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30470. var autoWidth = (remainedWidth - categoryGap)
  30471. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30472. autoWidth = Math.max(autoWidth, 0);
  30473. // Find if any auto calculated bar exceeded maxBarWidth
  30474. each$1(stacks, function (column, stack) {
  30475. var maxWidth = column.maxWidth;
  30476. if (maxWidth && maxWidth < autoWidth) {
  30477. maxWidth = Math.min(maxWidth, remainedWidth);
  30478. if (column.width) {
  30479. maxWidth = Math.min(maxWidth, column.width);
  30480. }
  30481. remainedWidth -= maxWidth;
  30482. column.width = maxWidth;
  30483. autoWidthCount--;
  30484. }
  30485. });
  30486. // Recalculate width again
  30487. autoWidth = (remainedWidth - categoryGap)
  30488. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30489. autoWidth = Math.max(autoWidth, 0);
  30490. var widthSum = 0;
  30491. var lastColumn;
  30492. each$1(stacks, function (column, idx) {
  30493. if (!column.width) {
  30494. column.width = autoWidth;
  30495. }
  30496. lastColumn = column;
  30497. widthSum += column.width * (1 + barGapPercent);
  30498. });
  30499. if (lastColumn) {
  30500. widthSum -= lastColumn.width * barGapPercent;
  30501. }
  30502. var offset = -widthSum / 2;
  30503. each$1(stacks, function (column, stackId) {
  30504. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30505. offset: offset,
  30506. width: column.width
  30507. };
  30508. offset += column.width * (1 + barGapPercent);
  30509. });
  30510. });
  30511. return result;
  30512. }
  30513. /**
  30514. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  30515. * @param {module:echarts/coord/Axis} axis
  30516. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  30517. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  30518. */
  30519. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30520. if (barWidthAndOffset && axis) {
  30521. var result = barWidthAndOffset[getAxisKey(axis)];
  30522. if (result != null && seriesModel != null) {
  30523. result = result[getSeriesStackId(seriesModel)];
  30524. }
  30525. return result;
  30526. }
  30527. }
  30528. /**
  30529. * @param {string} seriesType
  30530. * @param {module:echarts/model/Global} ecModel
  30531. */
  30532. function layout(seriesType, ecModel) {
  30533. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30534. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30535. var lastStackCoords = {};
  30536. each$1(seriesModels, function (seriesModel) {
  30537. var data = seriesModel.getData();
  30538. var cartesian = seriesModel.coordinateSystem;
  30539. var baseAxis = cartesian.getBaseAxis();
  30540. var stackId = getSeriesStackId(seriesModel);
  30541. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30542. var columnOffset = columnLayoutInfo.offset;
  30543. var columnWidth = columnLayoutInfo.width;
  30544. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30545. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30546. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  30547. data.setLayout({
  30548. offset: columnOffset,
  30549. size: columnWidth
  30550. });
  30551. var valueDim = data.mapDimension(valueAxis.dim);
  30552. var baseDim = data.mapDimension(baseAxis.dim);
  30553. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  30554. var isValueAxisH = valueAxis.isHorizontal();
  30555. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  30556. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30557. var value = data.get(valueDim, idx);
  30558. var baseValue = data.get(baseDim, idx);
  30559. if (isNaN(value)) {
  30560. continue;
  30561. }
  30562. var sign = value >= 0 ? 'p' : 'n';
  30563. var baseCoord = valueAxisStart;
  30564. // Because of the barMinHeight, we can not use the value in
  30565. // stackResultDimension directly.
  30566. if (stacked) {
  30567. // Only ordinal axis can be stacked.
  30568. if (!lastStackCoords[stackId][baseValue]) {
  30569. lastStackCoords[stackId][baseValue] = {
  30570. p: valueAxisStart, // Positive stack
  30571. n: valueAxisStart // Negative stack
  30572. };
  30573. }
  30574. // Should also consider #4243
  30575. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30576. }
  30577. var x;
  30578. var y;
  30579. var width;
  30580. var height;
  30581. if (isValueAxisH) {
  30582. var coord = cartesian.dataToPoint([value, baseValue]);
  30583. x = baseCoord;
  30584. y = coord[1] + columnOffset;
  30585. width = coord[0] - valueAxisStart;
  30586. height = columnWidth;
  30587. if (Math.abs(width) < barMinHeight) {
  30588. width = (width < 0 ? -1 : 1) * barMinHeight;
  30589. }
  30590. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30591. }
  30592. else {
  30593. var coord = cartesian.dataToPoint([baseValue, value]);
  30594. x = coord[0] + columnOffset;
  30595. y = baseCoord;
  30596. width = columnWidth;
  30597. height = coord[1] - valueAxisStart;
  30598. if (Math.abs(height) < barMinHeight) {
  30599. // Include zero to has a positive bar
  30600. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30601. }
  30602. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30603. }
  30604. data.setItemLayout(idx, {
  30605. x: x,
  30606. y: y,
  30607. width: width,
  30608. height: height
  30609. });
  30610. }
  30611. }, this);
  30612. }
  30613. // TODO: Do not support stack in large mode yet.
  30614. var largeLayout = {
  30615. seriesType: 'bar',
  30616. plan: createRenderPlanner(),
  30617. reset: function (seriesModel) {
  30618. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30619. return;
  30620. }
  30621. var data = seriesModel.getData();
  30622. var cartesian = seriesModel.coordinateSystem;
  30623. var baseAxis = cartesian.getBaseAxis();
  30624. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30625. var valueDim = data.mapDimension(valueAxis.dim);
  30626. var baseDim = data.mapDimension(baseAxis.dim);
  30627. var valueAxisHorizontal = valueAxis.isHorizontal();
  30628. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30629. var barWidth = retrieveColumnLayout(
  30630. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  30631. ).width;
  30632. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  30633. barWidth = LARGE_BAR_MIN_WIDTH;
  30634. }
  30635. return {progress: progress};
  30636. function progress(params, data) {
  30637. var largePoints = new LargeArr(params.count * 2);
  30638. var dataIndex;
  30639. var coord = [];
  30640. var valuePair = [];
  30641. var offset = 0;
  30642. while ((dataIndex = params.next()) != null) {
  30643. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30644. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30645. coord = cartesian.dataToPoint(valuePair, null, coord);
  30646. largePoints[offset++] = coord[0];
  30647. largePoints[offset++] = coord[1];
  30648. }
  30649. data.setLayout({
  30650. largePoints: largePoints,
  30651. barWidth: barWidth,
  30652. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  30653. valueAxisHorizontal: valueAxisHorizontal
  30654. });
  30655. }
  30656. }
  30657. };
  30658. function isOnCartesian(seriesModel) {
  30659. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30660. }
  30661. function isInLargeMode(seriesModel) {
  30662. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30663. }
  30664. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30665. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30666. var extent = valueAxis.getGlobalExtent();
  30667. var min;
  30668. var max;
  30669. if (extent[0] > extent[1]) {
  30670. min = extent[1];
  30671. max = extent[0];
  30672. }
  30673. else {
  30674. min = extent[0];
  30675. max = extent[1];
  30676. }
  30677. var valueStart = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  30678. valueStart < min && (valueStart = min);
  30679. valueStart > max && (valueStart = max);
  30680. return valueStart;
  30681. }
  30682. /*
  30683. * Licensed to the Apache Software Foundation (ASF) under one
  30684. * or more contributor license agreements. See the NOTICE file
  30685. * distributed with this work for additional information
  30686. * regarding copyright ownership. The ASF licenses this file
  30687. * to you under the Apache License, Version 2.0 (the
  30688. * "License"); you may not use this file except in compliance
  30689. * with the License. You may obtain a copy of the License at
  30690. *
  30691. * http://www.apache.org/licenses/LICENSE-2.0
  30692. *
  30693. * Unless required by applicable law or agreed to in writing,
  30694. * software distributed under the License is distributed on an
  30695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30696. * KIND, either express or implied. See the License for the
  30697. * specific language governing permissions and limitations
  30698. * under the License.
  30699. */
  30700. /*
  30701. * A third-party license is embeded for some of the code in this file:
  30702. * The "scaleLevels" was originally copied from "d3.js" with some
  30703. * modifications made for this project.
  30704. * (See more details in the comment on the definition of "scaleLevels" below.)
  30705. * The use of the source code of this file is also subject to the terms
  30706. * and consitions of the license of "d3.js" (BSD-3Clause, see
  30707. * </licenses/LICENSE-d3>).
  30708. */
  30709. // [About UTC and local time zone]:
  30710. // In most cases, `number.parseDate` will treat input data string as local time
  30711. // (except time zone is specified in time string). And `format.formateTime` returns
  30712. // local time by default. option.useUTC is false by default. This design have
  30713. // concidered these common case:
  30714. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  30715. // in local time by default.
  30716. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  30717. // as its original time, without any time difference.
  30718. var intervalScaleProto = IntervalScale.prototype;
  30719. var mathCeil = Math.ceil;
  30720. var mathFloor = Math.floor;
  30721. var ONE_SECOND = 1000;
  30722. var ONE_MINUTE = ONE_SECOND * 60;
  30723. var ONE_HOUR = ONE_MINUTE * 60;
  30724. var ONE_DAY = ONE_HOUR * 24;
  30725. // FIXME 公用?
  30726. var bisect = function (a, x, lo, hi) {
  30727. while (lo < hi) {
  30728. var mid = lo + hi >>> 1;
  30729. if (a[mid][1] < x) {
  30730. lo = mid + 1;
  30731. }
  30732. else {
  30733. hi = mid;
  30734. }
  30735. }
  30736. return lo;
  30737. };
  30738. /**
  30739. * @alias module:echarts/coord/scale/Time
  30740. * @constructor
  30741. */
  30742. var TimeScale = IntervalScale.extend({
  30743. type: 'time',
  30744. /**
  30745. * @override
  30746. */
  30747. getLabel: function (val) {
  30748. var stepLvl = this._stepLvl;
  30749. var date = new Date(val);
  30750. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  30751. },
  30752. /**
  30753. * @override
  30754. */
  30755. niceExtent: function (opt) {
  30756. var extent = this._extent;
  30757. // If extent start and end are same, expand them
  30758. if (extent[0] === extent[1]) {
  30759. // Expand extent
  30760. extent[0] -= ONE_DAY;
  30761. extent[1] += ONE_DAY;
  30762. }
  30763. // If there are no data and extent are [Infinity, -Infinity]
  30764. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30765. var d = new Date();
  30766. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30767. extent[0] = extent[1] - ONE_DAY;
  30768. }
  30769. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30770. // var extent = this._extent;
  30771. var interval = this._interval;
  30772. if (!opt.fixMin) {
  30773. extent[0] = round$2(mathFloor(extent[0] / interval) * interval);
  30774. }
  30775. if (!opt.fixMax) {
  30776. extent[1] = round$2(mathCeil(extent[1] / interval) * interval);
  30777. }
  30778. },
  30779. /**
  30780. * @override
  30781. */
  30782. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  30783. approxTickNum = approxTickNum || 10;
  30784. var extent = this._extent;
  30785. var span = extent[1] - extent[0];
  30786. var approxInterval = span / approxTickNum;
  30787. if (minInterval != null && approxInterval < minInterval) {
  30788. approxInterval = minInterval;
  30789. }
  30790. if (maxInterval != null && approxInterval > maxInterval) {
  30791. approxInterval = maxInterval;
  30792. }
  30793. var scaleLevelsLen = scaleLevels.length;
  30794. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  30795. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  30796. var interval = level[1];
  30797. // Same with interval scale if span is much larger than 1 year
  30798. if (level[0] === 'year') {
  30799. var yearSpan = span / interval;
  30800. // From "Nice Numbers for Graph Labels" of Graphic Gems
  30801. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  30802. var yearStep = nice(yearSpan / approxTickNum, true);
  30803. interval *= yearStep;
  30804. }
  30805. var timezoneOffset = this.getSetting('useUTC')
  30806. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  30807. var niceExtent = [
  30808. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  30809. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  30810. ];
  30811. fixExtent(niceExtent, extent);
  30812. this._stepLvl = level;
  30813. // Interval will be used in getTicks
  30814. this._interval = interval;
  30815. this._niceExtent = niceExtent;
  30816. },
  30817. parse: function (val) {
  30818. // val might be float.
  30819. return +parseDate(val);
  30820. }
  30821. });
  30822. each$1(['contain', 'normalize'], function (methodName) {
  30823. TimeScale.prototype[methodName] = function (val) {
  30824. return intervalScaleProto[methodName].call(this, this.parse(val));
  30825. };
  30826. });
  30827. /**
  30828. * This implementation was originally copied from "d3.js"
  30829. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30830. * with some modifications made for this program.
  30831. * See the license statement at the head of this file.
  30832. */
  30833. var scaleLevels = [
  30834. // Format interval
  30835. ['hh:mm:ss', ONE_SECOND], // 1s
  30836. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  30837. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  30838. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  30839. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  30840. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  30841. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  30842. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  30843. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  30844. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  30845. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  30846. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  30847. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  30848. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  30849. ['MM-dd\nyyyy', ONE_DAY], // 1d
  30850. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  30851. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  30852. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  30853. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  30854. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  30855. ['week', ONE_DAY * 7], // 7d
  30856. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  30857. ['week', ONE_DAY * 14], // 2w
  30858. ['week', ONE_DAY * 21], // 3w
  30859. ['month', ONE_DAY * 31], // 1M
  30860. ['week', ONE_DAY * 42], // 6w
  30861. ['month', ONE_DAY * 62], // 2M
  30862. ['week', ONE_DAY * 70], // 10w
  30863. ['quarter', ONE_DAY * 95], // 3M
  30864. ['month', ONE_DAY * 31 * 4], // 4M
  30865. ['month', ONE_DAY * 31 * 5], // 5M
  30866. ['half-year', ONE_DAY * 380 / 2], // 6M
  30867. ['month', ONE_DAY * 31 * 8], // 8M
  30868. ['month', ONE_DAY * 31 * 10], // 10M
  30869. ['year', ONE_DAY * 380] // 1Y
  30870. ];
  30871. /**
  30872. * @param {module:echarts/model/Model}
  30873. * @return {module:echarts/scale/Time}
  30874. */
  30875. TimeScale.create = function (model) {
  30876. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  30877. };
  30878. /*
  30879. * Licensed to the Apache Software Foundation (ASF) under one
  30880. * or more contributor license agreements. See the NOTICE file
  30881. * distributed with this work for additional information
  30882. * regarding copyright ownership. The ASF licenses this file
  30883. * to you under the Apache License, Version 2.0 (the
  30884. * "License"); you may not use this file except in compliance
  30885. * with the License. You may obtain a copy of the License at
  30886. *
  30887. * http://www.apache.org/licenses/LICENSE-2.0
  30888. *
  30889. * Unless required by applicable law or agreed to in writing,
  30890. * software distributed under the License is distributed on an
  30891. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30892. * KIND, either express or implied. See the License for the
  30893. * specific language governing permissions and limitations
  30894. * under the License.
  30895. */
  30896. /**
  30897. * Log scale
  30898. * @module echarts/scale/Log
  30899. */
  30900. // Use some method of IntervalScale
  30901. var scaleProto$1 = Scale.prototype;
  30902. var intervalScaleProto$1 = IntervalScale.prototype;
  30903. var getPrecisionSafe$1 = getPrecisionSafe;
  30904. var roundingErrorFix = round$2;
  30905. var mathFloor$1 = Math.floor;
  30906. var mathCeil$1 = Math.ceil;
  30907. var mathPow$1 = Math.pow;
  30908. var mathLog = Math.log;
  30909. var LogScale = Scale.extend({
  30910. type: 'log',
  30911. base: 10,
  30912. $constructor: function () {
  30913. Scale.apply(this, arguments);
  30914. this._originalScale = new IntervalScale();
  30915. },
  30916. /**
  30917. * @return {Array.<number>}
  30918. */
  30919. getTicks: function () {
  30920. var originalScale = this._originalScale;
  30921. var extent = this._extent;
  30922. var originalExtent = originalScale.getExtent();
  30923. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  30924. var powVal = round$2(mathPow$1(this.base, val));
  30925. // Fix #4158
  30926. powVal = (val === extent[0] && originalScale.__fixMin)
  30927. ? fixRoundingError(powVal, originalExtent[0])
  30928. : powVal;
  30929. powVal = (val === extent[1] && originalScale.__fixMax)
  30930. ? fixRoundingError(powVal, originalExtent[1])
  30931. : powVal;
  30932. return powVal;
  30933. }, this);
  30934. },
  30935. /**
  30936. * @param {number} val
  30937. * @return {string}
  30938. */
  30939. getLabel: intervalScaleProto$1.getLabel,
  30940. /**
  30941. * @param {number} val
  30942. * @return {number}
  30943. */
  30944. scale: function (val) {
  30945. val = scaleProto$1.scale.call(this, val);
  30946. return mathPow$1(this.base, val);
  30947. },
  30948. /**
  30949. * @param {number} start
  30950. * @param {number} end
  30951. */
  30952. setExtent: function (start, end) {
  30953. var base = this.base;
  30954. start = mathLog(start) / mathLog(base);
  30955. end = mathLog(end) / mathLog(base);
  30956. intervalScaleProto$1.setExtent.call(this, start, end);
  30957. },
  30958. /**
  30959. * @return {number} end
  30960. */
  30961. getExtent: function () {
  30962. var base = this.base;
  30963. var extent = scaleProto$1.getExtent.call(this);
  30964. extent[0] = mathPow$1(base, extent[0]);
  30965. extent[1] = mathPow$1(base, extent[1]);
  30966. // Fix #4158
  30967. var originalScale = this._originalScale;
  30968. var originalExtent = originalScale.getExtent();
  30969. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30970. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30971. return extent;
  30972. },
  30973. /**
  30974. * @param {Array.<number>} extent
  30975. */
  30976. unionExtent: function (extent) {
  30977. this._originalScale.unionExtent(extent);
  30978. var base = this.base;
  30979. extent[0] = mathLog(extent[0]) / mathLog(base);
  30980. extent[1] = mathLog(extent[1]) / mathLog(base);
  30981. scaleProto$1.unionExtent.call(this, extent);
  30982. },
  30983. /**
  30984. * @override
  30985. */
  30986. unionExtentFromData: function (data, dim) {
  30987. // TODO
  30988. // filter value that <= 0
  30989. this.unionExtent(data.getApproximateExtent(dim));
  30990. },
  30991. /**
  30992. * Update interval and extent of intervals for nice ticks
  30993. * @param {number} [approxTickNum = 10] Given approx tick number
  30994. */
  30995. niceTicks: function (approxTickNum) {
  30996. approxTickNum = approxTickNum || 10;
  30997. var extent = this._extent;
  30998. var span = extent[1] - extent[0];
  30999. if (span === Infinity || span <= 0) {
  31000. return;
  31001. }
  31002. var interval = quantity(span);
  31003. var err = approxTickNum / span * interval;
  31004. // Filter ticks to get closer to the desired count.
  31005. if (err <= 0.5) {
  31006. interval *= 10;
  31007. }
  31008. // Interval should be integer
  31009. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  31010. interval *= 10;
  31011. }
  31012. var niceExtent = [
  31013. round$2(mathCeil$1(extent[0] / interval) * interval),
  31014. round$2(mathFloor$1(extent[1] / interval) * interval)
  31015. ];
  31016. this._interval = interval;
  31017. this._niceExtent = niceExtent;
  31018. },
  31019. /**
  31020. * Nice extent.
  31021. * @override
  31022. */
  31023. niceExtent: function (opt) {
  31024. intervalScaleProto$1.niceExtent.call(this, opt);
  31025. var originalScale = this._originalScale;
  31026. originalScale.__fixMin = opt.fixMin;
  31027. originalScale.__fixMax = opt.fixMax;
  31028. }
  31029. });
  31030. each$1(['contain', 'normalize'], function (methodName) {
  31031. LogScale.prototype[methodName] = function (val) {
  31032. val = mathLog(val) / mathLog(this.base);
  31033. return scaleProto$1[methodName].call(this, val);
  31034. };
  31035. });
  31036. LogScale.create = function () {
  31037. return new LogScale();
  31038. };
  31039. function fixRoundingError(val, originalVal) {
  31040. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  31041. }
  31042. /*
  31043. * Licensed to the Apache Software Foundation (ASF) under one
  31044. * or more contributor license agreements. See the NOTICE file
  31045. * distributed with this work for additional information
  31046. * regarding copyright ownership. The ASF licenses this file
  31047. * to you under the Apache License, Version 2.0 (the
  31048. * "License"); you may not use this file except in compliance
  31049. * with the License. You may obtain a copy of the License at
  31050. *
  31051. * http://www.apache.org/licenses/LICENSE-2.0
  31052. *
  31053. * Unless required by applicable law or agreed to in writing,
  31054. * software distributed under the License is distributed on an
  31055. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31056. * KIND, either express or implied. See the License for the
  31057. * specific language governing permissions and limitations
  31058. * under the License.
  31059. */
  31060. /**
  31061. * Get axis scale extent before niced.
  31062. * Item of returned array can only be number (including Infinity and NaN).
  31063. */
  31064. function getScaleExtent(scale, model) {
  31065. var scaleType = scale.type;
  31066. var min = model.getMin();
  31067. var max = model.getMax();
  31068. var fixMin = min != null;
  31069. var fixMax = max != null;
  31070. var originalExtent = scale.getExtent();
  31071. var axisDataLen;
  31072. var boundaryGap;
  31073. var span;
  31074. if (scaleType === 'ordinal') {
  31075. axisDataLen = model.getCategories().length;
  31076. }
  31077. else {
  31078. boundaryGap = model.get('boundaryGap');
  31079. if (!isArray(boundaryGap)) {
  31080. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  31081. }
  31082. if (typeof boundaryGap[0] === 'boolean') {
  31083. if (__DEV__) {
  31084. console.warn('Boolean type for boundaryGap is only '
  31085. + 'allowed for ordinal axis. Please use string in '
  31086. + 'percentage instead, e.g., "20%". Currently, '
  31087. + 'boundaryGap is set to be 0.');
  31088. }
  31089. boundaryGap = [0, 0];
  31090. }
  31091. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  31092. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  31093. span = (originalExtent[1] - originalExtent[0])
  31094. || Math.abs(originalExtent[0]);
  31095. }
  31096. // Notice: When min/max is not set (that is, when there are null/undefined,
  31097. // which is the most common case), these cases should be ensured:
  31098. // (1) For 'ordinal', show all axis.data.
  31099. // (2) For others:
  31100. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  31101. // disabled).
  31102. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  31103. // be the result that originalExtent enlarged by boundaryGap.
  31104. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  31105. // FIXME
  31106. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  31107. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  31108. // that the results processed by boundaryGap are positive/negative?
  31109. if (min == null) {
  31110. min = scaleType === 'ordinal'
  31111. ? (axisDataLen ? 0 : NaN)
  31112. : originalExtent[0] - boundaryGap[0] * span;
  31113. }
  31114. if (max == null) {
  31115. max = scaleType === 'ordinal'
  31116. ? (axisDataLen ? axisDataLen - 1 : NaN)
  31117. : originalExtent[1] + boundaryGap[1] * span;
  31118. }
  31119. if (min === 'dataMin') {
  31120. min = originalExtent[0];
  31121. }
  31122. else if (typeof min === 'function') {
  31123. min = min({
  31124. min: originalExtent[0],
  31125. max: originalExtent[1]
  31126. });
  31127. }
  31128. if (max === 'dataMax') {
  31129. max = originalExtent[1];
  31130. }
  31131. else if (typeof max === 'function') {
  31132. max = max({
  31133. min: originalExtent[0],
  31134. max: originalExtent[1]
  31135. });
  31136. }
  31137. (min == null || !isFinite(min)) && (min = NaN);
  31138. (max == null || !isFinite(max)) && (max = NaN);
  31139. scale.setBlank(
  31140. eqNaN(min)
  31141. || eqNaN(max)
  31142. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  31143. );
  31144. // Evaluate if axis needs cross zero
  31145. if (model.getNeedCrossZero()) {
  31146. // Axis is over zero and min is not set
  31147. if (min > 0 && max > 0 && !fixMin) {
  31148. min = 0;
  31149. }
  31150. // Axis is under zero and max is not set
  31151. if (min < 0 && max < 0 && !fixMax) {
  31152. max = 0;
  31153. }
  31154. }
  31155. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  31156. // is base axis
  31157. // FIXME
  31158. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31159. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31160. // Should not depend on series type `bar`?
  31161. // (3) Fix that might overlap when using dataZoom.
  31162. // (4) Consider other chart types using `barGrid`?
  31163. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31164. var ecModel = model.ecModel;
  31165. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  31166. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31167. var isBaseAxisAndHasBarSeries;
  31168. each$1(barSeriesModels, function (seriesModel) {
  31169. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  31170. });
  31171. if (isBaseAxisAndHasBarSeries) {
  31172. // Calculate placement of bars on axis
  31173. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  31174. // Adjust axis min and max to account for overflow
  31175. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31176. min = adjustedScale.min;
  31177. max = adjustedScale.max;
  31178. }
  31179. }
  31180. return [min, max];
  31181. }
  31182. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  31183. // Get Axis Length
  31184. var axisExtent = model.axis.getExtent();
  31185. var axisLength = axisExtent[1] - axisExtent[0];
  31186. // Get bars on current base axis and calculate min and max overflow
  31187. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31188. if (barsOnCurrentAxis === undefined) {
  31189. return {min: min, max: max};
  31190. }
  31191. var minOverflow = Infinity;
  31192. each$1(barsOnCurrentAxis, function (item) {
  31193. minOverflow = Math.min(item.offset, minOverflow);
  31194. });
  31195. var maxOverflow = -Infinity;
  31196. each$1(barsOnCurrentAxis, function (item) {
  31197. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31198. });
  31199. minOverflow = Math.abs(minOverflow);
  31200. maxOverflow = Math.abs(maxOverflow);
  31201. var totalOverFlow = minOverflow + maxOverflow;
  31202. // Calulate required buffer based on old range and overflow
  31203. var oldRange = max - min;
  31204. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  31205. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  31206. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31207. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31208. return {min: min, max: max};
  31209. }
  31210. function niceScaleExtent(scale, model) {
  31211. var extent = getScaleExtent(scale, model);
  31212. var fixMin = model.getMin() != null;
  31213. var fixMax = model.getMax() != null;
  31214. var splitNumber = model.get('splitNumber');
  31215. if (scale.type === 'log') {
  31216. scale.base = model.get('logBase');
  31217. }
  31218. var scaleType = scale.type;
  31219. scale.setExtent(extent[0], extent[1]);
  31220. scale.niceExtent({
  31221. splitNumber: splitNumber,
  31222. fixMin: fixMin,
  31223. fixMax: fixMax,
  31224. minInterval: (scaleType === 'interval' || scaleType === 'time')
  31225. ? model.get('minInterval') : null,
  31226. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  31227. ? model.get('maxInterval') : null
  31228. });
  31229. // If some one specified the min, max. And the default calculated interval
  31230. // is not good enough. He can specify the interval. It is often appeared
  31231. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  31232. // to be 60.
  31233. // FIXME
  31234. var interval = model.get('interval');
  31235. if (interval != null) {
  31236. scale.setInterval && scale.setInterval(interval);
  31237. }
  31238. }
  31239. /**
  31240. * @param {module:echarts/model/Model} model
  31241. * @param {string} [axisType] Default retrieve from model.type
  31242. * @return {module:echarts/scale/*}
  31243. */
  31244. function createScaleByModel(model, axisType) {
  31245. axisType = axisType || model.get('type');
  31246. if (axisType) {
  31247. switch (axisType) {
  31248. // Buildin scale
  31249. case 'category':
  31250. return new OrdinalScale(
  31251. model.getOrdinalMeta
  31252. ? model.getOrdinalMeta()
  31253. : model.getCategories(),
  31254. [Infinity, -Infinity]
  31255. );
  31256. case 'value':
  31257. return new IntervalScale();
  31258. // Extended scale, like time and log
  31259. default:
  31260. return (Scale.getClass(axisType) || IntervalScale).create(model);
  31261. }
  31262. }
  31263. }
  31264. /**
  31265. * Check if the axis corss 0
  31266. */
  31267. function ifAxisCrossZero(axis) {
  31268. var dataExtent = axis.scale.getExtent();
  31269. var min = dataExtent[0];
  31270. var max = dataExtent[1];
  31271. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  31272. }
  31273. /**
  31274. * @param {module:echarts/coord/Axis} axis
  31275. * @return {Function} Label formatter function.
  31276. * param: {number} tickValue,
  31277. * param: {number} idx, the index in all ticks.
  31278. * If category axis, this param is not requied.
  31279. * return: {string} label string.
  31280. */
  31281. function makeLabelFormatter(axis) {
  31282. var labelFormatter = axis.getLabelModel().get('formatter');
  31283. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31284. if (typeof labelFormatter === 'string') {
  31285. labelFormatter = (function (tpl) {
  31286. return function (val) {
  31287. // For category axis, get raw value; for numeric axis,
  31288. // get foramtted label like '1,333,444'.
  31289. val = axis.scale.getLabel(val);
  31290. return tpl.replace('{value}', val != null ? val : '');
  31291. };
  31292. })(labelFormatter);
  31293. // Consider empty array
  31294. return labelFormatter;
  31295. }
  31296. else if (typeof labelFormatter === 'function') {
  31297. return function (tickValue, idx) {
  31298. // The original intention of `idx` is "the index of the tick in all ticks".
  31299. // But the previous implementation of category axis do not consider the
  31300. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31301. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31302. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31303. // the definition here for back compatibility.
  31304. if (categoryTickStart != null) {
  31305. idx = tickValue - categoryTickStart;
  31306. }
  31307. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  31308. };
  31309. }
  31310. else {
  31311. return function (tick) {
  31312. return axis.scale.getLabel(tick);
  31313. };
  31314. }
  31315. }
  31316. function getAxisRawValue(axis, value) {
  31317. // In category axis with data zoom, tick is not the original
  31318. // index of axis.data. So tick should not be exposed to user
  31319. // in category axis.
  31320. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  31321. }
  31322. /**
  31323. * @param {module:echarts/coord/Axis} axis
  31324. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  31325. */
  31326. function estimateLabelUnionRect(axis) {
  31327. var axisModel = axis.model;
  31328. var scale = axis.scale;
  31329. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  31330. return;
  31331. }
  31332. var isCategory = axis.type === 'category';
  31333. var realNumberScaleTicks;
  31334. var tickCount;
  31335. var categoryScaleExtent = scale.getExtent();
  31336. // Optimize for large category data, avoid call `getTicks()`.
  31337. if (isCategory) {
  31338. tickCount = scale.count();
  31339. }
  31340. else {
  31341. realNumberScaleTicks = scale.getTicks();
  31342. tickCount = realNumberScaleTicks.length;
  31343. }
  31344. var axisLabelModel = axis.getLabelModel();
  31345. var labelFormatter = makeLabelFormatter(axis);
  31346. var rect;
  31347. var step = 1;
  31348. // Simple optimization for large amount of labels
  31349. if (tickCount > 40) {
  31350. step = Math.ceil(tickCount / 40);
  31351. }
  31352. for (var i = 0; i < tickCount; i += step) {
  31353. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  31354. var label = labelFormatter(tickValue);
  31355. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31356. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31357. rect ? rect.union(singleRect) : (rect = singleRect);
  31358. }
  31359. return rect;
  31360. }
  31361. function rotateTextRect(textRect, rotate) {
  31362. var rotateRadians = rotate * Math.PI / 180;
  31363. var boundingBox = textRect.plain();
  31364. var beforeWidth = boundingBox.width;
  31365. var beforeHeight = boundingBox.height;
  31366. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  31367. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  31368. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  31369. return rotatedRect;
  31370. }
  31371. /**
  31372. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  31373. * @return {number|String} Can be null|'auto'|number|function
  31374. */
  31375. function getOptionCategoryInterval(model) {
  31376. var interval = model.get('interval');
  31377. return interval == null ? 'auto' : interval;
  31378. }
  31379. /**
  31380. * Set `categoryInterval` as 0 implicitly indicates that
  31381. * show all labels reguardless of overlap.
  31382. * @param {Object} axis axisModel.axis
  31383. * @return {boolean}
  31384. */
  31385. function shouldShowAllLabels(axis) {
  31386. return axis.type === 'category'
  31387. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31388. }
  31389. /*
  31390. * Licensed to the Apache Software Foundation (ASF) under one
  31391. * or more contributor license agreements. See the NOTICE file
  31392. * distributed with this work for additional information
  31393. * regarding copyright ownership. The ASF licenses this file
  31394. * to you under the Apache License, Version 2.0 (the
  31395. * "License"); you may not use this file except in compliance
  31396. * with the License. You may obtain a copy of the License at
  31397. *
  31398. * http://www.apache.org/licenses/LICENSE-2.0
  31399. *
  31400. * Unless required by applicable law or agreed to in writing,
  31401. * software distributed under the License is distributed on an
  31402. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31403. * KIND, either express or implied. See the License for the
  31404. * specific language governing permissions and limitations
  31405. * under the License.
  31406. */
  31407. /**
  31408. * Cartesian coordinate system
  31409. * @module echarts/coord/Cartesian
  31410. *
  31411. */
  31412. function dimAxisMapper(dim) {
  31413. return this._axes[dim];
  31414. }
  31415. /**
  31416. * @alias module:echarts/coord/Cartesian
  31417. * @constructor
  31418. */
  31419. var Cartesian = function (name) {
  31420. this._axes = {};
  31421. this._dimList = [];
  31422. /**
  31423. * @type {string}
  31424. */
  31425. this.name = name || '';
  31426. };
  31427. Cartesian.prototype = {
  31428. constructor: Cartesian,
  31429. type: 'cartesian',
  31430. /**
  31431. * Get axis
  31432. * @param {number|string} dim
  31433. * @return {module:echarts/coord/Cartesian~Axis}
  31434. */
  31435. getAxis: function (dim) {
  31436. return this._axes[dim];
  31437. },
  31438. /**
  31439. * Get axes list
  31440. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  31441. */
  31442. getAxes: function () {
  31443. return map(this._dimList, dimAxisMapper, this);
  31444. },
  31445. /**
  31446. * Get axes list by given scale type
  31447. */
  31448. getAxesByScale: function (scaleType) {
  31449. scaleType = scaleType.toLowerCase();
  31450. return filter(
  31451. this.getAxes(),
  31452. function (axis) {
  31453. return axis.scale.type === scaleType;
  31454. }
  31455. );
  31456. },
  31457. /**
  31458. * Add axis
  31459. * @param {module:echarts/coord/Cartesian.Axis}
  31460. */
  31461. addAxis: function (axis) {
  31462. var dim = axis.dim;
  31463. this._axes[dim] = axis;
  31464. this._dimList.push(dim);
  31465. },
  31466. /**
  31467. * Convert data to coord in nd space
  31468. * @param {Array.<number>|Object.<string, number>} val
  31469. * @return {Array.<number>|Object.<string, number>}
  31470. */
  31471. dataToCoord: function (val) {
  31472. return this._dataCoordConvert(val, 'dataToCoord');
  31473. },
  31474. /**
  31475. * Convert coord in nd space to data
  31476. * @param {Array.<number>|Object.<string, number>} val
  31477. * @return {Array.<number>|Object.<string, number>}
  31478. */
  31479. coordToData: function (val) {
  31480. return this._dataCoordConvert(val, 'coordToData');
  31481. },
  31482. _dataCoordConvert: function (input, method) {
  31483. var dimList = this._dimList;
  31484. var output = input instanceof Array ? [] : {};
  31485. for (var i = 0; i < dimList.length; i++) {
  31486. var dim = dimList[i];
  31487. var axis = this._axes[dim];
  31488. output[dim] = axis[method](input[dim]);
  31489. }
  31490. return output;
  31491. }
  31492. };
  31493. /*
  31494. * Licensed to the Apache Software Foundation (ASF) under one
  31495. * or more contributor license agreements. See the NOTICE file
  31496. * distributed with this work for additional information
  31497. * regarding copyright ownership. The ASF licenses this file
  31498. * to you under the Apache License, Version 2.0 (the
  31499. * "License"); you may not use this file except in compliance
  31500. * with the License. You may obtain a copy of the License at
  31501. *
  31502. * http://www.apache.org/licenses/LICENSE-2.0
  31503. *
  31504. * Unless required by applicable law or agreed to in writing,
  31505. * software distributed under the License is distributed on an
  31506. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31507. * KIND, either express or implied. See the License for the
  31508. * specific language governing permissions and limitations
  31509. * under the License.
  31510. */
  31511. function Cartesian2D(name) {
  31512. Cartesian.call(this, name);
  31513. }
  31514. Cartesian2D.prototype = {
  31515. constructor: Cartesian2D,
  31516. type: 'cartesian2d',
  31517. /**
  31518. * @type {Array.<string>}
  31519. * @readOnly
  31520. */
  31521. dimensions: ['x', 'y'],
  31522. /**
  31523. * Base axis will be used on stacking.
  31524. *
  31525. * @return {module:echarts/coord/cartesian/Axis2D}
  31526. */
  31527. getBaseAxis: function () {
  31528. return this.getAxesByScale('ordinal')[0]
  31529. || this.getAxesByScale('time')[0]
  31530. || this.getAxis('x');
  31531. },
  31532. /**
  31533. * If contain point
  31534. * @param {Array.<number>} point
  31535. * @return {boolean}
  31536. */
  31537. containPoint: function (point) {
  31538. var axisX = this.getAxis('x');
  31539. var axisY = this.getAxis('y');
  31540. return axisX.contain(axisX.toLocalCoord(point[0]))
  31541. && axisY.contain(axisY.toLocalCoord(point[1]));
  31542. },
  31543. /**
  31544. * If contain data
  31545. * @param {Array.<number>} data
  31546. * @return {boolean}
  31547. */
  31548. containData: function (data) {
  31549. return this.getAxis('x').containData(data[0])
  31550. && this.getAxis('y').containData(data[1]);
  31551. },
  31552. /**
  31553. * @param {Array.<number>} data
  31554. * @param {Array.<number>} out
  31555. * @return {Array.<number>}
  31556. */
  31557. dataToPoint: function (data, reserved, out) {
  31558. var xAxis = this.getAxis('x');
  31559. var yAxis = this.getAxis('y');
  31560. out = out || [];
  31561. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  31562. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  31563. return out;
  31564. },
  31565. /**
  31566. * @param {Array.<number>} data
  31567. * @param {Array.<number>} out
  31568. * @return {Array.<number>}
  31569. */
  31570. clampData: function (data, out) {
  31571. var xScale = this.getAxis('x').scale;
  31572. var yScale = this.getAxis('y').scale;
  31573. var xAxisExtent = xScale.getExtent();
  31574. var yAxisExtent = yScale.getExtent();
  31575. var x = xScale.parse(data[0]);
  31576. var y = yScale.parse(data[1]);
  31577. out = out || [];
  31578. out[0] = Math.min(
  31579. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  31580. Math.max(xAxisExtent[0], xAxisExtent[1])
  31581. );
  31582. out[1] = Math.min(
  31583. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  31584. Math.max(yAxisExtent[0], yAxisExtent[1])
  31585. );
  31586. return out;
  31587. },
  31588. /**
  31589. * @param {Array.<number>} point
  31590. * @param {Array.<number>} out
  31591. * @return {Array.<number>}
  31592. */
  31593. pointToData: function (point, out) {
  31594. var xAxis = this.getAxis('x');
  31595. var yAxis = this.getAxis('y');
  31596. out = out || [];
  31597. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  31598. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  31599. return out;
  31600. },
  31601. /**
  31602. * Get other axis
  31603. * @param {module:echarts/coord/cartesian/Axis2D} axis
  31604. */
  31605. getOtherAxis: function (axis) {
  31606. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  31607. }
  31608. };
  31609. inherits(Cartesian2D, Cartesian);
  31610. /*
  31611. * Licensed to the Apache Software Foundation (ASF) under one
  31612. * or more contributor license agreements. See the NOTICE file
  31613. * distributed with this work for additional information
  31614. * regarding copyright ownership. The ASF licenses this file
  31615. * to you under the Apache License, Version 2.0 (the
  31616. * "License"); you may not use this file except in compliance
  31617. * with the License. You may obtain a copy of the License at
  31618. *
  31619. * http://www.apache.org/licenses/LICENSE-2.0
  31620. *
  31621. * Unless required by applicable law or agreed to in writing,
  31622. * software distributed under the License is distributed on an
  31623. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31624. * KIND, either express or implied. See the License for the
  31625. * specific language governing permissions and limitations
  31626. * under the License.
  31627. */
  31628. var inner$6 = makeInner();
  31629. /**
  31630. * @param {module:echats/coord/Axis} axis
  31631. * @return {Object} {
  31632. * labels: [{
  31633. * formattedLabel: string,
  31634. * rawLabel: string,
  31635. * tickValue: number
  31636. * }, ...],
  31637. * labelCategoryInterval: number
  31638. * }
  31639. */
  31640. function createAxisLabels(axis) {
  31641. // Only ordinal scale support tick interval
  31642. return axis.type === 'category'
  31643. ? makeCategoryLabels(axis)
  31644. : makeRealNumberLabels(axis);
  31645. }
  31646. /**
  31647. * @param {module:echats/coord/Axis} axis
  31648. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31649. * @return {Object} {
  31650. * ticks: Array.<number>
  31651. * tickCategoryInterval: number
  31652. * }
  31653. */
  31654. function createAxisTicks(axis, tickModel) {
  31655. // Only ordinal scale support tick interval
  31656. return axis.type === 'category'
  31657. ? makeCategoryTicks(axis, tickModel)
  31658. : {ticks: axis.scale.getTicks()};
  31659. }
  31660. function makeCategoryLabels(axis) {
  31661. var labelModel = axis.getLabelModel();
  31662. var result = makeCategoryLabelsActually(axis, labelModel);
  31663. return (!labelModel.get('show') || axis.scale.isBlank())
  31664. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  31665. : result;
  31666. }
  31667. function makeCategoryLabelsActually(axis, labelModel) {
  31668. var labelsCache = getListCache(axis, 'labels');
  31669. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31670. var result = listCacheGet(labelsCache, optionLabelInterval);
  31671. if (result) {
  31672. return result;
  31673. }
  31674. var labels;
  31675. var numericLabelInterval;
  31676. if (isFunction$1(optionLabelInterval)) {
  31677. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31678. }
  31679. else {
  31680. numericLabelInterval = optionLabelInterval === 'auto'
  31681. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31682. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31683. }
  31684. // Cache to avoid calling interval function repeatly.
  31685. return listCacheSet(labelsCache, optionLabelInterval, {
  31686. labels: labels, labelCategoryInterval: numericLabelInterval
  31687. });
  31688. }
  31689. function makeCategoryTicks(axis, tickModel) {
  31690. var ticksCache = getListCache(axis, 'ticks');
  31691. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31692. var result = listCacheGet(ticksCache, optionTickInterval);
  31693. if (result) {
  31694. return result;
  31695. }
  31696. var ticks;
  31697. var tickCategoryInterval;
  31698. // Optimize for the case that large category data and no label displayed,
  31699. // we should not return all ticks.
  31700. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31701. ticks = [];
  31702. }
  31703. if (isFunction$1(optionTickInterval)) {
  31704. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31705. }
  31706. // Always use label interval by default despite label show. Consider this
  31707. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31708. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31709. else if (optionTickInterval === 'auto') {
  31710. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31711. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31712. ticks = map(labelsResult.labels, function (labelItem) {
  31713. return labelItem.tickValue;
  31714. });
  31715. }
  31716. else {
  31717. tickCategoryInterval = optionTickInterval;
  31718. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31719. }
  31720. // Cache to avoid calling interval function repeatly.
  31721. return listCacheSet(ticksCache, optionTickInterval, {
  31722. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  31723. });
  31724. }
  31725. function makeRealNumberLabels(axis) {
  31726. var ticks = axis.scale.getTicks();
  31727. var labelFormatter = makeLabelFormatter(axis);
  31728. return {
  31729. labels: map(ticks, function (tickValue, idx) {
  31730. return {
  31731. formattedLabel: labelFormatter(tickValue, idx),
  31732. rawLabel: axis.scale.getLabel(tickValue),
  31733. tickValue: tickValue
  31734. };
  31735. })
  31736. };
  31737. }
  31738. // Large category data calculation is performence sensitive, and ticks and label
  31739. // probably be fetched by multiple times. So we cache the result.
  31740. // axis is created each time during a ec process, so we do not need to clear cache.
  31741. function getListCache(axis, prop) {
  31742. // Because key can be funciton, and cache size always be small, we use array cache.
  31743. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  31744. }
  31745. function listCacheGet(cache, key) {
  31746. for (var i = 0; i < cache.length; i++) {
  31747. if (cache[i].key === key) {
  31748. return cache[i].value;
  31749. }
  31750. }
  31751. }
  31752. function listCacheSet(cache, key, value) {
  31753. cache.push({key: key, value: value});
  31754. return value;
  31755. }
  31756. function makeAutoCategoryInterval(axis) {
  31757. var result = inner$6(axis).autoInterval;
  31758. return result != null
  31759. ? result
  31760. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  31761. }
  31762. /**
  31763. * Calculate interval for category axis ticks and labels.
  31764. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31765. * should be implemented in axis.
  31766. */
  31767. function calculateCategoryInterval(axis) {
  31768. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31769. var labelFormatter = makeLabelFormatter(axis);
  31770. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  31771. var ordinalScale = axis.scale;
  31772. var ordinalExtent = ordinalScale.getExtent();
  31773. // Providing this method is for optimization:
  31774. // avoid generating a long array by `getTicks`
  31775. // in large category data case.
  31776. var tickCount = ordinalScale.count();
  31777. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  31778. return 0;
  31779. }
  31780. var step = 1;
  31781. // Simple optimization. Empirical value: tick count should less than 40.
  31782. if (tickCount > 40) {
  31783. step = Math.max(1, Math.floor(tickCount / 40));
  31784. }
  31785. var tickValue = ordinalExtent[0];
  31786. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  31787. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  31788. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  31789. var maxW = 0;
  31790. var maxH = 0;
  31791. // Caution: Performance sensitive for large category data.
  31792. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  31793. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31794. var width = 0;
  31795. var height = 0;
  31796. // Not precise, do not consider align and vertical align
  31797. // and each distance from axis line yet.
  31798. var rect = getBoundingRect(
  31799. labelFormatter(tickValue), params.font, 'center', 'top'
  31800. );
  31801. // Magic number
  31802. width = rect.width * 1.3;
  31803. height = rect.height * 1.3;
  31804. // Min size, void long loop.
  31805. maxW = Math.max(maxW, width, 7);
  31806. maxH = Math.max(maxH, height, 7);
  31807. }
  31808. var dw = maxW / unitW;
  31809. var dh = maxH / unitH;
  31810. // 0/0 is NaN, 1/0 is Infinity.
  31811. isNaN(dw) && (dw = Infinity);
  31812. isNaN(dh) && (dh = Infinity);
  31813. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  31814. var cache = inner$6(axis.model);
  31815. var lastAutoInterval = cache.lastAutoInterval;
  31816. var lastTickCount = cache.lastTickCount;
  31817. // Use cache to keep interval stable while moving zoom window,
  31818. // otherwise the calculated interval might jitter when the zoom
  31819. // window size is close to the interval-changing size.
  31820. if (lastAutoInterval != null
  31821. && lastTickCount != null
  31822. && Math.abs(lastAutoInterval - interval) <= 1
  31823. && Math.abs(lastTickCount - tickCount) <= 1
  31824. // Always choose the bigger one, otherwise the critical
  31825. // point is not the same when zooming in or zooming out.
  31826. && lastAutoInterval > interval
  31827. ) {
  31828. interval = lastAutoInterval;
  31829. }
  31830. // Only update cache if cache not used, otherwise the
  31831. // changing of interval is too insensitive.
  31832. else {
  31833. cache.lastTickCount = tickCount;
  31834. cache.lastAutoInterval = interval;
  31835. }
  31836. return interval;
  31837. }
  31838. function fetchAutoCategoryIntervalCalculationParams(axis) {
  31839. var labelModel = axis.getLabelModel();
  31840. return {
  31841. axisRotate: axis.getRotate
  31842. ? axis.getRotate()
  31843. : (axis.isHorizontal && !axis.isHorizontal())
  31844. ? 90
  31845. : 0,
  31846. labelRotate: labelModel.get('rotate') || 0,
  31847. font: labelModel.getFont()
  31848. };
  31849. }
  31850. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  31851. var labelFormatter = makeLabelFormatter(axis);
  31852. var ordinalScale = axis.scale;
  31853. var ordinalExtent = ordinalScale.getExtent();
  31854. var labelModel = axis.getLabelModel();
  31855. var result = [];
  31856. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  31857. var step = Math.max((categoryInterval || 0) + 1, 1);
  31858. var startTick = ordinalExtent[0];
  31859. var tickCount = ordinalScale.count();
  31860. // Calculate start tick based on zero if possible to keep label consistent
  31861. // while zooming and moving while interval > 0. Otherwise the selection
  31862. // of displayable ticks and symbols probably keep changing.
  31863. // 3 is empirical value.
  31864. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  31865. startTick = Math.round(Math.ceil(startTick / step) * step);
  31866. }
  31867. // (1) Only add min max label here but leave overlap checking
  31868. // to render stage, which also ensure the returned list
  31869. // suitable for splitLine and splitArea rendering.
  31870. // (2) Scales except category always contain min max label so
  31871. // do not need to perform this process.
  31872. var showAllLabel = shouldShowAllLabels(axis);
  31873. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  31874. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  31875. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  31876. addItem(ordinalExtent[0]);
  31877. }
  31878. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  31879. var tickValue = startTick;
  31880. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31881. addItem(tickValue);
  31882. }
  31883. if (includeMaxLabel && tickValue !== ordinalExtent[1]) {
  31884. addItem(ordinalExtent[1]);
  31885. }
  31886. function addItem(tVal) {
  31887. result.push(onlyTick
  31888. ? tVal
  31889. : {
  31890. formattedLabel: labelFormatter(tVal),
  31891. rawLabel: ordinalScale.getLabel(tVal),
  31892. tickValue: tVal
  31893. }
  31894. );
  31895. }
  31896. return result;
  31897. }
  31898. // When interval is function, the result `false` means ignore the tick.
  31899. // It is time consuming for large category data.
  31900. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  31901. var ordinalScale = axis.scale;
  31902. var labelFormatter = makeLabelFormatter(axis);
  31903. var result = [];
  31904. each$1(ordinalScale.getTicks(), function (tickValue) {
  31905. var rawLabel = ordinalScale.getLabel(tickValue);
  31906. if (categoryInterval(tickValue, rawLabel)) {
  31907. result.push(onlyTick
  31908. ? tickValue
  31909. : {
  31910. formattedLabel: labelFormatter(tickValue),
  31911. rawLabel: rawLabel,
  31912. tickValue: tickValue
  31913. }
  31914. );
  31915. }
  31916. });
  31917. return result;
  31918. }
  31919. /*
  31920. * Licensed to the Apache Software Foundation (ASF) under one
  31921. * or more contributor license agreements. See the NOTICE file
  31922. * distributed with this work for additional information
  31923. * regarding copyright ownership. The ASF licenses this file
  31924. * to you under the Apache License, Version 2.0 (the
  31925. * "License"); you may not use this file except in compliance
  31926. * with the License. You may obtain a copy of the License at
  31927. *
  31928. * http://www.apache.org/licenses/LICENSE-2.0
  31929. *
  31930. * Unless required by applicable law or agreed to in writing,
  31931. * software distributed under the License is distributed on an
  31932. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31933. * KIND, either express or implied. See the License for the
  31934. * specific language governing permissions and limitations
  31935. * under the License.
  31936. */
  31937. var NORMALIZED_EXTENT = [0, 1];
  31938. /**
  31939. * Base class of Axis.
  31940. * @constructor
  31941. */
  31942. var Axis = function (dim, scale, extent) {
  31943. /**
  31944. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  31945. * @type {string}
  31946. */
  31947. this.dim = dim;
  31948. /**
  31949. * Axis scale
  31950. * @type {module:echarts/coord/scale/*}
  31951. */
  31952. this.scale = scale;
  31953. /**
  31954. * @type {Array.<number>}
  31955. * @private
  31956. */
  31957. this._extent = extent || [0, 0];
  31958. /**
  31959. * @type {boolean}
  31960. */
  31961. this.inverse = false;
  31962. /**
  31963. * Usually true when axis has a ordinal scale
  31964. * @type {boolean}
  31965. */
  31966. this.onBand = false;
  31967. };
  31968. Axis.prototype = {
  31969. constructor: Axis,
  31970. /**
  31971. * If axis extent contain given coord
  31972. * @param {number} coord
  31973. * @return {boolean}
  31974. */
  31975. contain: function (coord) {
  31976. var extent = this._extent;
  31977. var min = Math.min(extent[0], extent[1]);
  31978. var max = Math.max(extent[0], extent[1]);
  31979. return coord >= min && coord <= max;
  31980. },
  31981. /**
  31982. * If axis extent contain given data
  31983. * @param {number} data
  31984. * @return {boolean}
  31985. */
  31986. containData: function (data) {
  31987. return this.contain(this.dataToCoord(data));
  31988. },
  31989. /**
  31990. * Get coord extent.
  31991. * @return {Array.<number>}
  31992. */
  31993. getExtent: function () {
  31994. return this._extent.slice();
  31995. },
  31996. /**
  31997. * Get precision used for formatting
  31998. * @param {Array.<number>} [dataExtent]
  31999. * @return {number}
  32000. */
  32001. getPixelPrecision: function (dataExtent) {
  32002. return getPixelPrecision(
  32003. dataExtent || this.scale.getExtent(),
  32004. this._extent
  32005. );
  32006. },
  32007. /**
  32008. * Set coord extent
  32009. * @param {number} start
  32010. * @param {number} end
  32011. */
  32012. setExtent: function (start, end) {
  32013. var extent = this._extent;
  32014. extent[0] = start;
  32015. extent[1] = end;
  32016. },
  32017. /**
  32018. * Convert data to coord. Data is the rank if it has an ordinal scale
  32019. * @param {number} data
  32020. * @param {boolean} clamp
  32021. * @return {number}
  32022. */
  32023. dataToCoord: function (data, clamp) {
  32024. var extent = this._extent;
  32025. var scale = this.scale;
  32026. data = scale.normalize(data);
  32027. if (this.onBand && scale.type === 'ordinal') {
  32028. extent = extent.slice();
  32029. fixExtentWithBands(extent, scale.count());
  32030. }
  32031. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32032. },
  32033. /**
  32034. * Convert coord to data. Data is the rank if it has an ordinal scale
  32035. * @param {number} coord
  32036. * @param {boolean} clamp
  32037. * @return {number}
  32038. */
  32039. coordToData: function (coord, clamp) {
  32040. var extent = this._extent;
  32041. var scale = this.scale;
  32042. if (this.onBand && scale.type === 'ordinal') {
  32043. extent = extent.slice();
  32044. fixExtentWithBands(extent, scale.count());
  32045. }
  32046. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32047. return this.scale.scale(t);
  32048. },
  32049. /**
  32050. * Convert pixel point to data in axis
  32051. * @param {Array.<number>} point
  32052. * @param {boolean} clamp
  32053. * @return {number} data
  32054. */
  32055. pointToData: function (point, clamp) {
  32056. // Should be implemented in derived class if necessary.
  32057. },
  32058. /**
  32059. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32060. * `axis.getTicksCoords` considers `onBand`, which is used by
  32061. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32062. * @param {Object} [opt]
  32063. * @param {number} [opt.tickModel=axis.model.getModel('axisTick')]
  32064. * @param {boolean} [opt.clamp] If `true`, the first and the last
  32065. * tick must be at the axis end points. Otherwise, clip ticks
  32066. * that outside the axis extent.
  32067. * @return {Array.<Object>} [{
  32068. * coord: ...,
  32069. * tickValue: ...
  32070. * }, ...]
  32071. */
  32072. getTicksCoords: function (opt) {
  32073. opt = opt || {};
  32074. var tickModel = opt.tickModel || this.getTickModel();
  32075. var result = createAxisTicks(this, tickModel);
  32076. var ticks = result.ticks;
  32077. var ticksCoords = map(ticks, function (tickValue) {
  32078. return {
  32079. coord: this.dataToCoord(tickValue),
  32080. tickValue: tickValue
  32081. };
  32082. }, this);
  32083. var alignWithLabel = tickModel.get('alignWithLabel');
  32084. fixOnBandTicksCoords(
  32085. this, ticksCoords, result.tickCategoryInterval, alignWithLabel, opt.clamp
  32086. );
  32087. return ticksCoords;
  32088. },
  32089. /**
  32090. * @return {Array.<Object>} [{
  32091. * formattedLabel: string,
  32092. * rawLabel: axis.scale.getLabel(tickValue)
  32093. * tickValue: number
  32094. * }, ...]
  32095. */
  32096. getViewLabels: function () {
  32097. return createAxisLabels(this).labels;
  32098. },
  32099. /**
  32100. * @return {module:echarts/coord/model/Model}
  32101. */
  32102. getLabelModel: function () {
  32103. return this.model.getModel('axisLabel');
  32104. },
  32105. /**
  32106. * Notice here we only get the default tick model. For splitLine
  32107. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32108. * manually when calling `getTicksCoords`.
  32109. * In GL, this method may be overrided to:
  32110. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32111. * @return {module:echarts/coord/model/Model}
  32112. */
  32113. getTickModel: function () {
  32114. return this.model.getModel('axisTick');
  32115. },
  32116. /**
  32117. * Get width of band
  32118. * @return {number}
  32119. */
  32120. getBandWidth: function () {
  32121. var axisExtent = this._extent;
  32122. var dataExtent = this.scale.getExtent();
  32123. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32124. // Fix #2728, avoid NaN when only one data.
  32125. len === 0 && (len = 1);
  32126. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32127. return Math.abs(size) / len;
  32128. },
  32129. /**
  32130. * @abstract
  32131. * @return {boolean} Is horizontal
  32132. */
  32133. isHorizontal: null,
  32134. /**
  32135. * @abstract
  32136. * @return {number} Get axis rotate, by degree.
  32137. */
  32138. getRotate: null,
  32139. /**
  32140. * Only be called in category axis.
  32141. * Can be overrided, consider other axes like in 3D.
  32142. * @return {number} Auto interval for cateogry axis tick and label
  32143. */
  32144. calculateCategoryInterval: function () {
  32145. return calculateCategoryInterval(this);
  32146. }
  32147. };
  32148. function fixExtentWithBands(extent, nTick) {
  32149. var size = extent[1] - extent[0];
  32150. var len = nTick;
  32151. var margin = size / len / 2;
  32152. extent[0] += margin;
  32153. extent[1] -= margin;
  32154. }
  32155. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32156. // |---1---|---2---|---3---|---4---|.
  32157. // So the displayed ticks and splitLine/splitArea should between
  32158. // each data item, otherwise cause misleading (e.g., split tow bars
  32159. // of a single data item when there are two bar series).
  32160. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32161. // splitLine/spliteArea should layout appropriately corresponding
  32162. // to displayed labels. (So we should not use `getBandWidth` in this
  32163. // case).
  32164. function fixOnBandTicksCoords(axis, ticksCoords, tickCategoryInterval, alignWithLabel, clamp) {
  32165. var ticksLen = ticksCoords.length;
  32166. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32167. return;
  32168. }
  32169. var axisExtent = axis.getExtent();
  32170. var last;
  32171. if (ticksLen === 1) {
  32172. ticksCoords[0].coord = axisExtent[0];
  32173. last = ticksCoords[1] = {coord: axisExtent[0]};
  32174. }
  32175. else {
  32176. var shift = (ticksCoords[1].coord - ticksCoords[0].coord);
  32177. each$1(ticksCoords, function (ticksItem) {
  32178. ticksItem.coord -= shift / 2;
  32179. var tickCategoryInterval = tickCategoryInterval || 0;
  32180. // Avoid split a single data item when odd interval.
  32181. if (tickCategoryInterval % 2 > 0) {
  32182. ticksItem.coord -= shift / ((tickCategoryInterval + 1) * 2);
  32183. }
  32184. });
  32185. last = {coord: ticksCoords[ticksLen - 1].coord + shift};
  32186. ticksCoords.push(last);
  32187. }
  32188. var inverse = axisExtent[0] > axisExtent[1];
  32189. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32190. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  32191. }
  32192. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32193. ticksCoords.unshift({coord: axisExtent[0]});
  32194. }
  32195. if (littleThan(axisExtent[1], last.coord)) {
  32196. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  32197. }
  32198. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32199. ticksCoords.push({coord: axisExtent[1]});
  32200. }
  32201. function littleThan(a, b) {
  32202. return inverse ? a > b : a < b;
  32203. }
  32204. }
  32205. /*
  32206. * Licensed to the Apache Software Foundation (ASF) under one
  32207. * or more contributor license agreements. See the NOTICE file
  32208. * distributed with this work for additional information
  32209. * regarding copyright ownership. The ASF licenses this file
  32210. * to you under the Apache License, Version 2.0 (the
  32211. * "License"); you may not use this file except in compliance
  32212. * with the License. You may obtain a copy of the License at
  32213. *
  32214. * http://www.apache.org/licenses/LICENSE-2.0
  32215. *
  32216. * Unless required by applicable law or agreed to in writing,
  32217. * software distributed under the License is distributed on an
  32218. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32219. * KIND, either express or implied. See the License for the
  32220. * specific language governing permissions and limitations
  32221. * under the License.
  32222. */
  32223. /**
  32224. * Extend axis 2d
  32225. * @constructor module:echarts/coord/cartesian/Axis2D
  32226. * @extends {module:echarts/coord/cartesian/Axis}
  32227. * @param {string} dim
  32228. * @param {*} scale
  32229. * @param {Array.<number>} coordExtent
  32230. * @param {string} axisType
  32231. * @param {string} position
  32232. */
  32233. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  32234. Axis.call(this, dim, scale, coordExtent);
  32235. /**
  32236. * Axis type
  32237. * - 'category'
  32238. * - 'value'
  32239. * - 'time'
  32240. * - 'log'
  32241. * @type {string}
  32242. */
  32243. this.type = axisType || 'value';
  32244. /**
  32245. * Axis position
  32246. * - 'top'
  32247. * - 'bottom'
  32248. * - 'left'
  32249. * - 'right'
  32250. */
  32251. this.position = position || 'bottom';
  32252. };
  32253. Axis2D.prototype = {
  32254. constructor: Axis2D,
  32255. /**
  32256. * Index of axis, can be used as key
  32257. */
  32258. index: 0,
  32259. /**
  32260. * Implemented in <module:echarts/coord/cartesian/Grid>.
  32261. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  32262. * If not on zero of other axis, return null/undefined.
  32263. * If no axes, return an empty array.
  32264. */
  32265. getAxesOnZeroOf: null,
  32266. /**
  32267. * Axis model
  32268. * @param {module:echarts/coord/cartesian/AxisModel}
  32269. */
  32270. model: null,
  32271. isHorizontal: function () {
  32272. var position = this.position;
  32273. return position === 'top' || position === 'bottom';
  32274. },
  32275. /**
  32276. * Each item cooresponds to this.getExtent(), which
  32277. * means globalExtent[0] may greater than globalExtent[1],
  32278. * unless `asc` is input.
  32279. *
  32280. * @param {boolean} [asc]
  32281. * @return {Array.<number>}
  32282. */
  32283. getGlobalExtent: function (asc) {
  32284. var ret = this.getExtent();
  32285. ret[0] = this.toGlobalCoord(ret[0]);
  32286. ret[1] = this.toGlobalCoord(ret[1]);
  32287. asc && ret[0] > ret[1] && ret.reverse();
  32288. return ret;
  32289. },
  32290. getOtherAxis: function () {
  32291. this.grid.getOtherAxis();
  32292. },
  32293. /**
  32294. * @override
  32295. */
  32296. pointToData: function (point, clamp) {
  32297. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  32298. },
  32299. /**
  32300. * Transform global coord to local coord,
  32301. * i.e. var localCoord = axis.toLocalCoord(80);
  32302. * designate by module:echarts/coord/cartesian/Grid.
  32303. * @type {Function}
  32304. */
  32305. toLocalCoord: null,
  32306. /**
  32307. * Transform global coord to local coord,
  32308. * i.e. var globalCoord = axis.toLocalCoord(40);
  32309. * designate by module:echarts/coord/cartesian/Grid.
  32310. * @type {Function}
  32311. */
  32312. toGlobalCoord: null
  32313. };
  32314. inherits(Axis2D, Axis);
  32315. /*
  32316. * Licensed to the Apache Software Foundation (ASF) under one
  32317. * or more contributor license agreements. See the NOTICE file
  32318. * distributed with this work for additional information
  32319. * regarding copyright ownership. The ASF licenses this file
  32320. * to you under the Apache License, Version 2.0 (the
  32321. * "License"); you may not use this file except in compliance
  32322. * with the License. You may obtain a copy of the License at
  32323. *
  32324. * http://www.apache.org/licenses/LICENSE-2.0
  32325. *
  32326. * Unless required by applicable law or agreed to in writing,
  32327. * software distributed under the License is distributed on an
  32328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32329. * KIND, either express or implied. See the License for the
  32330. * specific language governing permissions and limitations
  32331. * under the License.
  32332. */
  32333. var defaultOption = {
  32334. show: true,
  32335. zlevel: 0,
  32336. z: 0,
  32337. // Inverse the axis.
  32338. inverse: false,
  32339. // Axis name displayed.
  32340. name: '',
  32341. // 'start' | 'middle' | 'end'
  32342. nameLocation: 'end',
  32343. // By degree. By defualt auto rotate by nameLocation.
  32344. nameRotate: null,
  32345. nameTruncate: {
  32346. maxWidth: null,
  32347. ellipsis: '...',
  32348. placeholder: '.'
  32349. },
  32350. // Use global text style by default.
  32351. nameTextStyle: {},
  32352. // The gap between axisName and axisLine.
  32353. nameGap: 15,
  32354. // Default `false` to support tooltip.
  32355. silent: false,
  32356. // Default `false` to avoid legacy user event listener fail.
  32357. triggerEvent: false,
  32358. tooltip: {
  32359. show: false
  32360. },
  32361. axisPointer: {},
  32362. axisLine: {
  32363. show: true,
  32364. onZero: true,
  32365. onZeroAxisIndex: null,
  32366. lineStyle: {
  32367. color: '#333',
  32368. width: 1,
  32369. type: 'solid'
  32370. },
  32371. // The arrow at both ends the the axis.
  32372. symbol: ['none', 'none'],
  32373. symbolSize: [10, 15]
  32374. },
  32375. axisTick: {
  32376. show: true,
  32377. // Whether axisTick is inside the grid or outside the grid.
  32378. inside: false,
  32379. // The length of axisTick.
  32380. length: 5,
  32381. lineStyle: {
  32382. width: 1
  32383. }
  32384. },
  32385. axisLabel: {
  32386. show: true,
  32387. // Whether axisLabel is inside the grid or outside the grid.
  32388. inside: false,
  32389. rotate: 0,
  32390. // true | false | null/undefined (auto)
  32391. showMinLabel: null,
  32392. // true | false | null/undefined (auto)
  32393. showMaxLabel: null,
  32394. margin: 8,
  32395. // formatter: null,
  32396. fontSize: 12
  32397. },
  32398. splitLine: {
  32399. show: true,
  32400. lineStyle: {
  32401. color: ['#ccc'],
  32402. width: 1,
  32403. type: 'solid'
  32404. }
  32405. },
  32406. splitArea: {
  32407. show: false,
  32408. areaStyle: {
  32409. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  32410. }
  32411. }
  32412. };
  32413. var axisDefault = {};
  32414. axisDefault.categoryAxis = merge({
  32415. // The gap at both ends of the axis. For categoryAxis, boolean.
  32416. boundaryGap: true,
  32417. // Set false to faster category collection.
  32418. // Only usefull in the case like: category is
  32419. // ['2012-01-01', '2012-01-02', ...], where the input
  32420. // data has been ensured not duplicate and is large data.
  32421. // null means "auto":
  32422. // if axis.data provided, do not deduplication,
  32423. // else do deduplication.
  32424. deduplication: null,
  32425. // splitArea: {
  32426. // show: false
  32427. // },
  32428. splitLine: {
  32429. show: false
  32430. },
  32431. axisTick: {
  32432. // If tick is align with label when boundaryGap is true
  32433. alignWithLabel: false,
  32434. interval: 'auto'
  32435. },
  32436. axisLabel: {
  32437. interval: 'auto'
  32438. }
  32439. }, defaultOption);
  32440. axisDefault.valueAxis = merge({
  32441. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  32442. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  32443. boundaryGap: [0, 0],
  32444. // TODO
  32445. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  32446. // Min value of the axis. can be:
  32447. // + a number
  32448. // + 'dataMin': use the min value in data.
  32449. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  32450. // min: null,
  32451. // Max value of the axis. can be:
  32452. // + a number
  32453. // + 'dataMax': use the max value in data.
  32454. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  32455. // max: null,
  32456. // Readonly prop, specifies start value of the range when using data zoom.
  32457. // rangeStart: null
  32458. // Readonly prop, specifies end value of the range when using data zoom.
  32459. // rangeEnd: null
  32460. // Optional value can be:
  32461. // + `false`: always include value 0.
  32462. // + `true`: the extent do not consider value 0.
  32463. // scale: false,
  32464. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  32465. splitNumber: 5
  32466. // Interval specifies the span of the ticks is mandatorily.
  32467. // interval: null
  32468. // Specify min interval when auto calculate tick interval.
  32469. // minInterval: null
  32470. // Specify max interval when auto calculate tick interval.
  32471. // maxInterval: null
  32472. }, defaultOption);
  32473. axisDefault.timeAxis = defaults({
  32474. scale: true,
  32475. min: 'dataMin',
  32476. max: 'dataMax'
  32477. }, axisDefault.valueAxis);
  32478. axisDefault.logAxis = defaults({
  32479. scale: true,
  32480. logBase: 10
  32481. }, axisDefault.valueAxis);
  32482. /*
  32483. * Licensed to the Apache Software Foundation (ASF) under one
  32484. * or more contributor license agreements. See the NOTICE file
  32485. * distributed with this work for additional information
  32486. * regarding copyright ownership. The ASF licenses this file
  32487. * to you under the Apache License, Version 2.0 (the
  32488. * "License"); you may not use this file except in compliance
  32489. * with the License. You may obtain a copy of the License at
  32490. *
  32491. * http://www.apache.org/licenses/LICENSE-2.0
  32492. *
  32493. * Unless required by applicable law or agreed to in writing,
  32494. * software distributed under the License is distributed on an
  32495. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32496. * KIND, either express or implied. See the License for the
  32497. * specific language governing permissions and limitations
  32498. * under the License.
  32499. */
  32500. // FIXME axisType is fixed ?
  32501. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  32502. /**
  32503. * Generate sub axis model class
  32504. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  32505. * @param {module:echarts/model/Component} BaseAxisModelClass
  32506. * @param {Function} axisTypeDefaulter
  32507. * @param {Object} [extraDefaultOption]
  32508. */
  32509. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  32510. each$1(AXIS_TYPES, function (axisType) {
  32511. BaseAxisModelClass.extend({
  32512. /**
  32513. * @readOnly
  32514. */
  32515. type: axisName + 'Axis.' + axisType,
  32516. mergeDefaultAndTheme: function (option, ecModel) {
  32517. var layoutMode = this.layoutMode;
  32518. var inputPositionParams = layoutMode
  32519. ? getLayoutParams(option) : {};
  32520. var themeModel = ecModel.getTheme();
  32521. merge(option, themeModel.get(axisType + 'Axis'));
  32522. merge(option, this.getDefaultOption());
  32523. option.type = axisTypeDefaulter(axisName, option);
  32524. if (layoutMode) {
  32525. mergeLayoutParam(option, inputPositionParams, layoutMode);
  32526. }
  32527. },
  32528. /**
  32529. * @override
  32530. */
  32531. optionUpdated: function () {
  32532. var thisOption = this.option;
  32533. if (thisOption.type === 'category') {
  32534. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  32535. }
  32536. },
  32537. /**
  32538. * Should not be called before all of 'getInitailData' finished.
  32539. * Because categories are collected during initializing data.
  32540. */
  32541. getCategories: function (rawData) {
  32542. var option = this.option;
  32543. // FIXME
  32544. // warning if called before all of 'getInitailData' finished.
  32545. if (option.type === 'category') {
  32546. if (rawData) {
  32547. return option.data;
  32548. }
  32549. return this.__ordinalMeta.categories;
  32550. }
  32551. },
  32552. getOrdinalMeta: function () {
  32553. return this.__ordinalMeta;
  32554. },
  32555. defaultOption: mergeAll(
  32556. [
  32557. {},
  32558. axisDefault[axisType + 'Axis'],
  32559. extraDefaultOption
  32560. ],
  32561. true
  32562. )
  32563. });
  32564. });
  32565. ComponentModel.registerSubTypeDefaulter(
  32566. axisName + 'Axis',
  32567. curry(axisTypeDefaulter, axisName)
  32568. );
  32569. };
  32570. /*
  32571. * Licensed to the Apache Software Foundation (ASF) under one
  32572. * or more contributor license agreements. See the NOTICE file
  32573. * distributed with this work for additional information
  32574. * regarding copyright ownership. The ASF licenses this file
  32575. * to you under the Apache License, Version 2.0 (the
  32576. * "License"); you may not use this file except in compliance
  32577. * with the License. You may obtain a copy of the License at
  32578. *
  32579. * http://www.apache.org/licenses/LICENSE-2.0
  32580. *
  32581. * Unless required by applicable law or agreed to in writing,
  32582. * software distributed under the License is distributed on an
  32583. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32584. * KIND, either express or implied. See the License for the
  32585. * specific language governing permissions and limitations
  32586. * under the License.
  32587. */
  32588. // import * as axisHelper from './axisHelper';
  32589. var axisModelCommonMixin = {
  32590. /**
  32591. * @param {boolean} origin
  32592. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  32593. */
  32594. getMin: function (origin) {
  32595. var option = this.option;
  32596. var min = (!origin && option.rangeStart != null)
  32597. ? option.rangeStart : option.min;
  32598. if (this.axis
  32599. && min != null
  32600. && min !== 'dataMin'
  32601. && typeof min !== 'function'
  32602. && !eqNaN(min)
  32603. ) {
  32604. min = this.axis.scale.parse(min);
  32605. }
  32606. return min;
  32607. },
  32608. /**
  32609. * @param {boolean} origin
  32610. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  32611. */
  32612. getMax: function (origin) {
  32613. var option = this.option;
  32614. var max = (!origin && option.rangeEnd != null)
  32615. ? option.rangeEnd : option.max;
  32616. if (this.axis
  32617. && max != null
  32618. && max !== 'dataMax'
  32619. && typeof max !== 'function'
  32620. && !eqNaN(max)
  32621. ) {
  32622. max = this.axis.scale.parse(max);
  32623. }
  32624. return max;
  32625. },
  32626. /**
  32627. * @return {boolean}
  32628. */
  32629. getNeedCrossZero: function () {
  32630. var option = this.option;
  32631. return (option.rangeStart != null || option.rangeEnd != null)
  32632. ? false : !option.scale;
  32633. },
  32634. /**
  32635. * Should be implemented by each axis model if necessary.
  32636. * @return {module:echarts/model/Component} coordinate system model
  32637. */
  32638. getCoordSysModel: noop,
  32639. /**
  32640. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  32641. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  32642. */
  32643. setRange: function (rangeStart, rangeEnd) {
  32644. this.option.rangeStart = rangeStart;
  32645. this.option.rangeEnd = rangeEnd;
  32646. },
  32647. /**
  32648. * Reset range
  32649. */
  32650. resetRange: function () {
  32651. // rangeStart and rangeEnd is readonly.
  32652. this.option.rangeStart = this.option.rangeEnd = null;
  32653. }
  32654. };
  32655. /*
  32656. * Licensed to the Apache Software Foundation (ASF) under one
  32657. * or more contributor license agreements. See the NOTICE file
  32658. * distributed with this work for additional information
  32659. * regarding copyright ownership. The ASF licenses this file
  32660. * to you under the Apache License, Version 2.0 (the
  32661. * "License"); you may not use this file except in compliance
  32662. * with the License. You may obtain a copy of the License at
  32663. *
  32664. * http://www.apache.org/licenses/LICENSE-2.0
  32665. *
  32666. * Unless required by applicable law or agreed to in writing,
  32667. * software distributed under the License is distributed on an
  32668. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32669. * KIND, either express or implied. See the License for the
  32670. * specific language governing permissions and limitations
  32671. * under the License.
  32672. */
  32673. var AxisModel = ComponentModel.extend({
  32674. type: 'cartesian2dAxis',
  32675. /**
  32676. * @type {module:echarts/coord/cartesian/Axis2D}
  32677. */
  32678. axis: null,
  32679. /**
  32680. * @override
  32681. */
  32682. init: function () {
  32683. AxisModel.superApply(this, 'init', arguments);
  32684. this.resetRange();
  32685. },
  32686. /**
  32687. * @override
  32688. */
  32689. mergeOption: function () {
  32690. AxisModel.superApply(this, 'mergeOption', arguments);
  32691. this.resetRange();
  32692. },
  32693. /**
  32694. * @override
  32695. */
  32696. restoreData: function () {
  32697. AxisModel.superApply(this, 'restoreData', arguments);
  32698. this.resetRange();
  32699. },
  32700. /**
  32701. * @override
  32702. * @return {module:echarts/model/Component}
  32703. */
  32704. getCoordSysModel: function () {
  32705. return this.ecModel.queryComponents({
  32706. mainType: 'grid',
  32707. index: this.option.gridIndex,
  32708. id: this.option.gridId
  32709. })[0];
  32710. }
  32711. });
  32712. function getAxisType(axisDim, option) {
  32713. // Default axis with data is category axis
  32714. return option.type || (option.data ? 'category' : 'value');
  32715. }
  32716. merge(AxisModel.prototype, axisModelCommonMixin);
  32717. var extraOption = {
  32718. // gridIndex: 0,
  32719. // gridId: '',
  32720. // Offset is for multiple axis on the same position
  32721. offset: 0
  32722. };
  32723. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  32724. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  32725. /*
  32726. * Licensed to the Apache Software Foundation (ASF) under one
  32727. * or more contributor license agreements. See the NOTICE file
  32728. * distributed with this work for additional information
  32729. * regarding copyright ownership. The ASF licenses this file
  32730. * to you under the Apache License, Version 2.0 (the
  32731. * "License"); you may not use this file except in compliance
  32732. * with the License. You may obtain a copy of the License at
  32733. *
  32734. * http://www.apache.org/licenses/LICENSE-2.0
  32735. *
  32736. * Unless required by applicable law or agreed to in writing,
  32737. * software distributed under the License is distributed on an
  32738. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32739. * KIND, either express or implied. See the License for the
  32740. * specific language governing permissions and limitations
  32741. * under the License.
  32742. */
  32743. // Grid 是在有直角坐标系的时候必须要存在的
  32744. // 所以这里也要被 Cartesian2D 依赖
  32745. ComponentModel.extend({
  32746. type: 'grid',
  32747. dependencies: ['xAxis', 'yAxis'],
  32748. layoutMode: 'box',
  32749. /**
  32750. * @type {module:echarts/coord/cartesian/Grid}
  32751. */
  32752. coordinateSystem: null,
  32753. defaultOption: {
  32754. show: false,
  32755. zlevel: 0,
  32756. z: 0,
  32757. left: '10%',
  32758. top: 60,
  32759. right: '10%',
  32760. bottom: 60,
  32761. // If grid size contain label
  32762. containLabel: false,
  32763. // width: {totalWidth} - left - right,
  32764. // height: {totalHeight} - top - bottom,
  32765. backgroundColor: 'rgba(0,0,0,0)',
  32766. borderWidth: 1,
  32767. borderColor: '#ccc'
  32768. }
  32769. });
  32770. /*
  32771. * Licensed to the Apache Software Foundation (ASF) under one
  32772. * or more contributor license agreements. See the NOTICE file
  32773. * distributed with this work for additional information
  32774. * regarding copyright ownership. The ASF licenses this file
  32775. * to you under the Apache License, Version 2.0 (the
  32776. * "License"); you may not use this file except in compliance
  32777. * with the License. You may obtain a copy of the License at
  32778. *
  32779. * http://www.apache.org/licenses/LICENSE-2.0
  32780. *
  32781. * Unless required by applicable law or agreed to in writing,
  32782. * software distributed under the License is distributed on an
  32783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32784. * KIND, either express or implied. See the License for the
  32785. * specific language governing permissions and limitations
  32786. * under the License.
  32787. */
  32788. /**
  32789. * Grid is a region which contains at most 4 cartesian systems
  32790. *
  32791. * TODO Default cartesian
  32792. */
  32793. // Depends on GridModel, AxisModel, which performs preprocess.
  32794. /**
  32795. * Check if the axis is used in the specified grid
  32796. * @inner
  32797. */
  32798. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  32799. return axisModel.getCoordSysModel() === gridModel;
  32800. }
  32801. function Grid(gridModel, ecModel, api) {
  32802. /**
  32803. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  32804. * @private
  32805. */
  32806. this._coordsMap = {};
  32807. /**
  32808. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  32809. * @private
  32810. */
  32811. this._coordsList = [];
  32812. /**
  32813. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  32814. * @private
  32815. */
  32816. this._axesMap = {};
  32817. /**
  32818. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  32819. * @private
  32820. */
  32821. this._axesList = [];
  32822. this._initCartesian(gridModel, ecModel, api);
  32823. this.model = gridModel;
  32824. }
  32825. var gridProto = Grid.prototype;
  32826. gridProto.type = 'grid';
  32827. gridProto.axisPointerEnabled = true;
  32828. gridProto.getRect = function () {
  32829. return this._rect;
  32830. };
  32831. gridProto.update = function (ecModel, api) {
  32832. var axesMap = this._axesMap;
  32833. this._updateScale(ecModel, this.model);
  32834. each$1(axesMap.x, function (xAxis) {
  32835. niceScaleExtent(xAxis.scale, xAxis.model);
  32836. });
  32837. each$1(axesMap.y, function (yAxis) {
  32838. niceScaleExtent(yAxis.scale, yAxis.model);
  32839. });
  32840. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  32841. var onZeroRecords = {};
  32842. each$1(axesMap.x, function (xAxis) {
  32843. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  32844. });
  32845. each$1(axesMap.y, function (yAxis) {
  32846. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  32847. });
  32848. // Resize again if containLabel is enabled
  32849. // FIXME It may cause getting wrong grid size in data processing stage
  32850. this.resize(this.model, api);
  32851. };
  32852. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  32853. axis.getAxesOnZeroOf = function () {
  32854. // TODO: onZero of multiple axes.
  32855. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  32856. };
  32857. // onZero can not be enabled in these two situations:
  32858. // 1. When any other axis is a category axis.
  32859. // 2. When no axis is cross 0 point.
  32860. var otherAxes = axesMap[otherAxisDim];
  32861. var otherAxisOnZeroOf;
  32862. var axisModel = axis.model;
  32863. var onZero = axisModel.get('axisLine.onZero');
  32864. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  32865. if (!onZero) {
  32866. return;
  32867. }
  32868. // If target axis is specified.
  32869. if (onZeroAxisIndex != null) {
  32870. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  32871. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  32872. }
  32873. }
  32874. else {
  32875. // Find the first available other axis.
  32876. for (var idx in otherAxes) {
  32877. if (otherAxes.hasOwnProperty(idx)
  32878. && canOnZeroToAxis(otherAxes[idx])
  32879. // Consider that two Y axes on one value axis,
  32880. // if both onZero, the two Y axes overlap.
  32881. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  32882. ) {
  32883. otherAxisOnZeroOf = otherAxes[idx];
  32884. break;
  32885. }
  32886. }
  32887. }
  32888. if (otherAxisOnZeroOf) {
  32889. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  32890. }
  32891. function getOnZeroRecordKey(axis) {
  32892. return axis.dim + '_' + axis.index;
  32893. }
  32894. }
  32895. function canOnZeroToAxis(axis) {
  32896. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  32897. }
  32898. /**
  32899. * Resize the grid
  32900. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  32901. * @param {module:echarts/ExtensionAPI} api
  32902. */
  32903. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  32904. var gridRect = getLayoutRect(
  32905. gridModel.getBoxLayoutParams(), {
  32906. width: api.getWidth(),
  32907. height: api.getHeight()
  32908. });
  32909. this._rect = gridRect;
  32910. var axesList = this._axesList;
  32911. adjustAxes();
  32912. // Minus label size
  32913. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  32914. each$1(axesList, function (axis) {
  32915. if (!axis.model.get('axisLabel.inside')) {
  32916. var labelUnionRect = estimateLabelUnionRect(axis);
  32917. if (labelUnionRect) {
  32918. var dim = axis.isHorizontal() ? 'height' : 'width';
  32919. var margin = axis.model.get('axisLabel.margin');
  32920. gridRect[dim] -= labelUnionRect[dim] + margin;
  32921. if (axis.position === 'top') {
  32922. gridRect.y += labelUnionRect.height + margin;
  32923. }
  32924. else if (axis.position === 'left') {
  32925. gridRect.x += labelUnionRect.width + margin;
  32926. }
  32927. }
  32928. }
  32929. });
  32930. adjustAxes();
  32931. }
  32932. function adjustAxes() {
  32933. each$1(axesList, function (axis) {
  32934. var isHorizontal = axis.isHorizontal();
  32935. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  32936. var idx = axis.inverse ? 1 : 0;
  32937. axis.setExtent(extent[idx], extent[1 - idx]);
  32938. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  32939. });
  32940. }
  32941. };
  32942. /**
  32943. * @param {string} axisType
  32944. * @param {number} [axisIndex]
  32945. */
  32946. gridProto.getAxis = function (axisType, axisIndex) {
  32947. var axesMapOnDim = this._axesMap[axisType];
  32948. if (axesMapOnDim != null) {
  32949. if (axisIndex == null) {
  32950. // Find first axis
  32951. for (var name in axesMapOnDim) {
  32952. if (axesMapOnDim.hasOwnProperty(name)) {
  32953. return axesMapOnDim[name];
  32954. }
  32955. }
  32956. }
  32957. return axesMapOnDim[axisIndex];
  32958. }
  32959. };
  32960. /**
  32961. * @return {Array.<module:echarts/coord/Axis>}
  32962. */
  32963. gridProto.getAxes = function () {
  32964. return this._axesList.slice();
  32965. };
  32966. /**
  32967. * Usage:
  32968. * grid.getCartesian(xAxisIndex, yAxisIndex);
  32969. * grid.getCartesian(xAxisIndex);
  32970. * grid.getCartesian(null, yAxisIndex);
  32971. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  32972. *
  32973. * @param {number|Object} [xAxisIndex]
  32974. * @param {number} [yAxisIndex]
  32975. */
  32976. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  32977. if (xAxisIndex != null && yAxisIndex != null) {
  32978. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  32979. return this._coordsMap[key];
  32980. }
  32981. if (isObject$1(xAxisIndex)) {
  32982. yAxisIndex = xAxisIndex.yAxisIndex;
  32983. xAxisIndex = xAxisIndex.xAxisIndex;
  32984. }
  32985. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  32986. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  32987. if (coordList[i].getAxis('x').index === xAxisIndex
  32988. || coordList[i].getAxis('y').index === yAxisIndex
  32989. ) {
  32990. return coordList[i];
  32991. }
  32992. }
  32993. };
  32994. gridProto.getCartesians = function () {
  32995. return this._coordsList.slice();
  32996. };
  32997. /**
  32998. * @implements
  32999. * see {module:echarts/CoodinateSystem}
  33000. */
  33001. gridProto.convertToPixel = function (ecModel, finder, value) {
  33002. var target = this._findConvertTarget(ecModel, finder);
  33003. return target.cartesian
  33004. ? target.cartesian.dataToPoint(value)
  33005. : target.axis
  33006. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  33007. : null;
  33008. };
  33009. /**
  33010. * @implements
  33011. * see {module:echarts/CoodinateSystem}
  33012. */
  33013. gridProto.convertFromPixel = function (ecModel, finder, value) {
  33014. var target = this._findConvertTarget(ecModel, finder);
  33015. return target.cartesian
  33016. ? target.cartesian.pointToData(value)
  33017. : target.axis
  33018. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  33019. : null;
  33020. };
  33021. /**
  33022. * @inner
  33023. */
  33024. gridProto._findConvertTarget = function (ecModel, finder) {
  33025. var seriesModel = finder.seriesModel;
  33026. var xAxisModel = finder.xAxisModel
  33027. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  33028. var yAxisModel = finder.yAxisModel
  33029. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  33030. var gridModel = finder.gridModel;
  33031. var coordsList = this._coordsList;
  33032. var cartesian;
  33033. var axis;
  33034. if (seriesModel) {
  33035. cartesian = seriesModel.coordinateSystem;
  33036. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  33037. }
  33038. else if (xAxisModel && yAxisModel) {
  33039. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  33040. }
  33041. else if (xAxisModel) {
  33042. axis = this.getAxis('x', xAxisModel.componentIndex);
  33043. }
  33044. else if (yAxisModel) {
  33045. axis = this.getAxis('y', yAxisModel.componentIndex);
  33046. }
  33047. // Lowest priority.
  33048. else if (gridModel) {
  33049. var grid = gridModel.coordinateSystem;
  33050. if (grid === this) {
  33051. cartesian = this._coordsList[0];
  33052. }
  33053. }
  33054. return {cartesian: cartesian, axis: axis};
  33055. };
  33056. /**
  33057. * @implements
  33058. * see {module:echarts/CoodinateSystem}
  33059. */
  33060. gridProto.containPoint = function (point) {
  33061. var coord = this._coordsList[0];
  33062. if (coord) {
  33063. return coord.containPoint(point);
  33064. }
  33065. };
  33066. /**
  33067. * Initialize cartesian coordinate systems
  33068. * @private
  33069. */
  33070. gridProto._initCartesian = function (gridModel, ecModel, api) {
  33071. var axisPositionUsed = {
  33072. left: false,
  33073. right: false,
  33074. top: false,
  33075. bottom: false
  33076. };
  33077. var axesMap = {
  33078. x: {},
  33079. y: {}
  33080. };
  33081. var axesCount = {
  33082. x: 0,
  33083. y: 0
  33084. };
  33085. /// Create axis
  33086. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  33087. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  33088. if (!axesCount.x || !axesCount.y) {
  33089. // Roll back when there no either x or y axis
  33090. this._axesMap = {};
  33091. this._axesList = [];
  33092. return;
  33093. }
  33094. this._axesMap = axesMap;
  33095. /// Create cartesian2d
  33096. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  33097. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  33098. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  33099. var cartesian = new Cartesian2D(key);
  33100. cartesian.grid = this;
  33101. cartesian.model = gridModel;
  33102. this._coordsMap[key] = cartesian;
  33103. this._coordsList.push(cartesian);
  33104. cartesian.addAxis(xAxis);
  33105. cartesian.addAxis(yAxis);
  33106. }, this);
  33107. }, this);
  33108. function createAxisCreator(axisType) {
  33109. return function (axisModel, idx) {
  33110. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  33111. return;
  33112. }
  33113. var axisPosition = axisModel.get('position');
  33114. if (axisType === 'x') {
  33115. // Fix position
  33116. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  33117. // Default bottom of X
  33118. axisPosition = 'bottom';
  33119. if (axisPositionUsed[axisPosition]) {
  33120. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  33121. }
  33122. }
  33123. }
  33124. else {
  33125. // Fix position
  33126. if (axisPosition !== 'left' && axisPosition !== 'right') {
  33127. // Default left of Y
  33128. axisPosition = 'left';
  33129. if (axisPositionUsed[axisPosition]) {
  33130. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  33131. }
  33132. }
  33133. }
  33134. axisPositionUsed[axisPosition] = true;
  33135. var axis = new Axis2D(
  33136. axisType, createScaleByModel(axisModel),
  33137. [0, 0],
  33138. axisModel.get('type'),
  33139. axisPosition
  33140. );
  33141. var isCategory = axis.type === 'category';
  33142. axis.onBand = isCategory && axisModel.get('boundaryGap');
  33143. axis.inverse = axisModel.get('inverse');
  33144. // Inject axis into axisModel
  33145. axisModel.axis = axis;
  33146. // Inject axisModel into axis
  33147. axis.model = axisModel;
  33148. // Inject grid info axis
  33149. axis.grid = this;
  33150. // Index of axis, can be used as key
  33151. axis.index = idx;
  33152. this._axesList.push(axis);
  33153. axesMap[axisType][idx] = axis;
  33154. axesCount[axisType]++;
  33155. };
  33156. }
  33157. };
  33158. /**
  33159. * Update cartesian properties from series
  33160. * @param {module:echarts/model/Option} option
  33161. * @private
  33162. */
  33163. gridProto._updateScale = function (ecModel, gridModel) {
  33164. // Reset scale
  33165. each$1(this._axesList, function (axis) {
  33166. axis.scale.setExtent(Infinity, -Infinity);
  33167. });
  33168. ecModel.eachSeries(function (seriesModel) {
  33169. if (isCartesian2D(seriesModel)) {
  33170. var axesModels = findAxesModels(seriesModel, ecModel);
  33171. var xAxisModel = axesModels[0];
  33172. var yAxisModel = axesModels[1];
  33173. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  33174. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  33175. ) {
  33176. return;
  33177. }
  33178. var cartesian = this.getCartesian(
  33179. xAxisModel.componentIndex, yAxisModel.componentIndex
  33180. );
  33181. var data = seriesModel.getData();
  33182. var xAxis = cartesian.getAxis('x');
  33183. var yAxis = cartesian.getAxis('y');
  33184. if (data.type === 'list') {
  33185. unionExtent(data, xAxis, seriesModel);
  33186. unionExtent(data, yAxis, seriesModel);
  33187. }
  33188. }
  33189. }, this);
  33190. function unionExtent(data, axis, seriesModel) {
  33191. each$1(data.mapDimension(axis.dim, true), function (dim) {
  33192. axis.scale.unionExtentFromData(
  33193. // For example, the extent of the orginal dimension
  33194. // is [0.1, 0.5], the extent of the `stackResultDimension`
  33195. // is [7, 9], the final extent should not include [0.1, 0.5].
  33196. data, getStackedDimension(data, dim)
  33197. );
  33198. });
  33199. }
  33200. };
  33201. /**
  33202. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  33203. * @return {Object} {baseAxes: [], otherAxes: []}
  33204. */
  33205. gridProto.getTooltipAxes = function (dim) {
  33206. var baseAxes = [];
  33207. var otherAxes = [];
  33208. each$1(this.getCartesians(), function (cartesian) {
  33209. var baseAxis = (dim != null && dim !== 'auto')
  33210. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  33211. var otherAxis = cartesian.getOtherAxis(baseAxis);
  33212. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  33213. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  33214. });
  33215. return {baseAxes: baseAxes, otherAxes: otherAxes};
  33216. };
  33217. /**
  33218. * @inner
  33219. */
  33220. function updateAxisTransform(axis, coordBase) {
  33221. var axisExtent = axis.getExtent();
  33222. var axisExtentSum = axisExtent[0] + axisExtent[1];
  33223. // Fast transform
  33224. axis.toGlobalCoord = axis.dim === 'x'
  33225. ? function (coord) {
  33226. return coord + coordBase;
  33227. }
  33228. : function (coord) {
  33229. return axisExtentSum - coord + coordBase;
  33230. };
  33231. axis.toLocalCoord = axis.dim === 'x'
  33232. ? function (coord) {
  33233. return coord - coordBase;
  33234. }
  33235. : function (coord) {
  33236. return axisExtentSum - coord + coordBase;
  33237. };
  33238. }
  33239. var axesTypes = ['xAxis', 'yAxis'];
  33240. /**
  33241. * @inner
  33242. */
  33243. function findAxesModels(seriesModel, ecModel) {
  33244. return map(axesTypes, function (axisType) {
  33245. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  33246. if (__DEV__) {
  33247. if (!axisModel) {
  33248. throw new Error(axisType + ' "' + retrieve(
  33249. seriesModel.get(axisType + 'Index'),
  33250. seriesModel.get(axisType + 'Id'),
  33251. 0
  33252. ) + '" not found');
  33253. }
  33254. }
  33255. return axisModel;
  33256. });
  33257. }
  33258. /**
  33259. * @inner
  33260. */
  33261. function isCartesian2D(seriesModel) {
  33262. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  33263. }
  33264. Grid.create = function (ecModel, api) {
  33265. var grids = [];
  33266. ecModel.eachComponent('grid', function (gridModel, idx) {
  33267. var grid = new Grid(gridModel, ecModel, api);
  33268. grid.name = 'grid_' + idx;
  33269. // dataSampling requires axis extent, so resize
  33270. // should be performed in create stage.
  33271. grid.resize(gridModel, api, true);
  33272. gridModel.coordinateSystem = grid;
  33273. grids.push(grid);
  33274. });
  33275. // Inject the coordinateSystems into seriesModel
  33276. ecModel.eachSeries(function (seriesModel) {
  33277. if (!isCartesian2D(seriesModel)) {
  33278. return;
  33279. }
  33280. var axesModels = findAxesModels(seriesModel, ecModel);
  33281. var xAxisModel = axesModels[0];
  33282. var yAxisModel = axesModels[1];
  33283. var gridModel = xAxisModel.getCoordSysModel();
  33284. if (__DEV__) {
  33285. if (!gridModel) {
  33286. throw new Error(
  33287. 'Grid "' + retrieve(
  33288. xAxisModel.get('gridIndex'),
  33289. xAxisModel.get('gridId'),
  33290. 0
  33291. ) + '" not found'
  33292. );
  33293. }
  33294. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  33295. throw new Error('xAxis and yAxis must use the same grid');
  33296. }
  33297. }
  33298. var grid = gridModel.coordinateSystem;
  33299. seriesModel.coordinateSystem = grid.getCartesian(
  33300. xAxisModel.componentIndex, yAxisModel.componentIndex
  33301. );
  33302. });
  33303. return grids;
  33304. };
  33305. // For deciding which dimensions to use when creating list data
  33306. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  33307. CoordinateSystemManager.register('cartesian2d', Grid);
  33308. /*
  33309. * Licensed to the Apache Software Foundation (ASF) under one
  33310. * or more contributor license agreements. See the NOTICE file
  33311. * distributed with this work for additional information
  33312. * regarding copyright ownership. The ASF licenses this file
  33313. * to you under the Apache License, Version 2.0 (the
  33314. * "License"); you may not use this file except in compliance
  33315. * with the License. You may obtain a copy of the License at
  33316. *
  33317. * http://www.apache.org/licenses/LICENSE-2.0
  33318. *
  33319. * Unless required by applicable law or agreed to in writing,
  33320. * software distributed under the License is distributed on an
  33321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33322. * KIND, either express or implied. See the License for the
  33323. * specific language governing permissions and limitations
  33324. * under the License.
  33325. */
  33326. var PI$2 = Math.PI;
  33327. function makeAxisEventDataBase(axisModel) {
  33328. var eventData = {
  33329. componentType: axisModel.mainType,
  33330. componentIndex: axisModel.componentIndex
  33331. };
  33332. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  33333. return eventData;
  33334. }
  33335. /**
  33336. * A final axis is translated and rotated from a "standard axis".
  33337. * So opt.position and opt.rotation is required.
  33338. *
  33339. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  33340. * for example: (0, 0) ------------> (0, 50)
  33341. *
  33342. * nameDirection or tickDirection or labelDirection is 1 means tick
  33343. * or label is below the standard axis, whereas is -1 means above
  33344. * the standard axis. labelOffset means offset between label and axis,
  33345. * which is useful when 'onZero', where axisLabel is in the grid and
  33346. * label in outside grid.
  33347. *
  33348. * Tips: like always,
  33349. * positive rotation represents anticlockwise, and negative rotation
  33350. * represents clockwise.
  33351. * The direction of position coordinate is the same as the direction
  33352. * of screen coordinate.
  33353. *
  33354. * Do not need to consider axis 'inverse', which is auto processed by
  33355. * axis extent.
  33356. *
  33357. * @param {module:zrender/container/Group} group
  33358. * @param {Object} axisModel
  33359. * @param {Object} opt Standard axis parameters.
  33360. * @param {Array.<number>} opt.position [x, y]
  33361. * @param {number} opt.rotation by radian
  33362. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  33363. * @param {number} [opt.tickDirection=1] 1 or -1
  33364. * @param {number} [opt.labelDirection=1] 1 or -1
  33365. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  33366. * @param {string} [opt.axisLabelShow] default get from axisModel.
  33367. * @param {string} [opt.axisName] default get from axisModel.
  33368. * @param {number} [opt.axisNameAvailableWidth]
  33369. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  33370. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  33371. * @param {number} [opt.nameTruncateMaxWidth]
  33372. */
  33373. var AxisBuilder = function (axisModel, opt) {
  33374. /**
  33375. * @readOnly
  33376. */
  33377. this.opt = opt;
  33378. /**
  33379. * @readOnly
  33380. */
  33381. this.axisModel = axisModel;
  33382. // Default value
  33383. defaults(
  33384. opt,
  33385. {
  33386. labelOffset: 0,
  33387. nameDirection: 1,
  33388. tickDirection: 1,
  33389. labelDirection: 1,
  33390. silent: true
  33391. }
  33392. );
  33393. /**
  33394. * @readOnly
  33395. */
  33396. this.group = new Group();
  33397. // FIXME Not use a seperate text group?
  33398. var dumbGroup = new Group({
  33399. position: opt.position.slice(),
  33400. rotation: opt.rotation
  33401. });
  33402. // this.group.add(dumbGroup);
  33403. // this._dumbGroup = dumbGroup;
  33404. dumbGroup.updateTransform();
  33405. this._transform = dumbGroup.transform;
  33406. this._dumbGroup = dumbGroup;
  33407. };
  33408. AxisBuilder.prototype = {
  33409. constructor: AxisBuilder,
  33410. hasBuilder: function (name) {
  33411. return !!builders[name];
  33412. },
  33413. add: function (name) {
  33414. builders[name].call(this);
  33415. },
  33416. getGroup: function () {
  33417. return this.group;
  33418. }
  33419. };
  33420. var builders = {
  33421. /**
  33422. * @private
  33423. */
  33424. axisLine: function () {
  33425. var opt = this.opt;
  33426. var axisModel = this.axisModel;
  33427. if (!axisModel.get('axisLine.show')) {
  33428. return;
  33429. }
  33430. var extent = this.axisModel.axis.getExtent();
  33431. var matrix = this._transform;
  33432. var pt1 = [extent[0], 0];
  33433. var pt2 = [extent[1], 0];
  33434. if (matrix) {
  33435. applyTransform(pt1, pt1, matrix);
  33436. applyTransform(pt2, pt2, matrix);
  33437. }
  33438. var lineStyle = extend(
  33439. {
  33440. lineCap: 'round'
  33441. },
  33442. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  33443. );
  33444. this.group.add(new Line(subPixelOptimizeLine({
  33445. // Id for animation
  33446. anid: 'line',
  33447. shape: {
  33448. x1: pt1[0],
  33449. y1: pt1[1],
  33450. x2: pt2[0],
  33451. y2: pt2[1]
  33452. },
  33453. style: lineStyle,
  33454. strokeContainThreshold: opt.strokeContainThreshold || 5,
  33455. silent: true,
  33456. z2: 1
  33457. })));
  33458. var arrows = axisModel.get('axisLine.symbol');
  33459. var arrowSize = axisModel.get('axisLine.symbolSize');
  33460. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  33461. if (typeof arrowOffset === 'number') {
  33462. arrowOffset = [arrowOffset, arrowOffset];
  33463. }
  33464. if (arrows != null) {
  33465. if (typeof arrows === 'string') {
  33466. // Use the same arrow for start and end point
  33467. arrows = [arrows, arrows];
  33468. }
  33469. if (typeof arrowSize === 'string'
  33470. || typeof arrowSize === 'number'
  33471. ) {
  33472. // Use the same size for width and height
  33473. arrowSize = [arrowSize, arrowSize];
  33474. }
  33475. var symbolWidth = arrowSize[0];
  33476. var symbolHeight = arrowSize[1];
  33477. each$1([{
  33478. rotate: opt.rotation + Math.PI / 2,
  33479. offset: arrowOffset[0],
  33480. r: 0
  33481. }, {
  33482. rotate: opt.rotation - Math.PI / 2,
  33483. offset: arrowOffset[1],
  33484. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  33485. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  33486. }], function (point, index) {
  33487. if (arrows[index] !== 'none' && arrows[index] != null) {
  33488. var symbol = createSymbol(
  33489. arrows[index],
  33490. -symbolWidth / 2,
  33491. -symbolHeight / 2,
  33492. symbolWidth,
  33493. symbolHeight,
  33494. lineStyle.stroke,
  33495. true
  33496. );
  33497. // Calculate arrow position with offset
  33498. var r = point.r + point.offset;
  33499. var pos = [
  33500. pt1[0] + r * Math.cos(opt.rotation),
  33501. pt1[1] - r * Math.sin(opt.rotation)
  33502. ];
  33503. symbol.attr({
  33504. rotation: point.rotate,
  33505. position: pos,
  33506. silent: true,
  33507. z2: 11
  33508. });
  33509. this.group.add(symbol);
  33510. }
  33511. }, this);
  33512. }
  33513. },
  33514. /**
  33515. * @private
  33516. */
  33517. axisTickLabel: function () {
  33518. var axisModel = this.axisModel;
  33519. var opt = this.opt;
  33520. var tickEls = buildAxisTick(this, axisModel, opt);
  33521. var labelEls = buildAxisLabel(this, axisModel, opt);
  33522. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  33523. },
  33524. /**
  33525. * @private
  33526. */
  33527. axisName: function () {
  33528. var opt = this.opt;
  33529. var axisModel = this.axisModel;
  33530. var name = retrieve(opt.axisName, axisModel.get('name'));
  33531. if (!name) {
  33532. return;
  33533. }
  33534. var nameLocation = axisModel.get('nameLocation');
  33535. var nameDirection = opt.nameDirection;
  33536. var textStyleModel = axisModel.getModel('nameTextStyle');
  33537. var gap = axisModel.get('nameGap') || 0;
  33538. var extent = this.axisModel.axis.getExtent();
  33539. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  33540. var pos = [
  33541. nameLocation === 'start'
  33542. ? extent[0] - gapSignal * gap
  33543. : nameLocation === 'end'
  33544. ? extent[1] + gapSignal * gap
  33545. : (extent[0] + extent[1]) / 2, // 'middle'
  33546. // Reuse labelOffset.
  33547. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  33548. ];
  33549. var labelLayout;
  33550. var nameRotation = axisModel.get('nameRotate');
  33551. if (nameRotation != null) {
  33552. nameRotation = nameRotation * PI$2 / 180; // To radian.
  33553. }
  33554. var axisNameAvailableWidth;
  33555. if (isNameLocationCenter(nameLocation)) {
  33556. labelLayout = innerTextLayout(
  33557. opt.rotation,
  33558. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  33559. nameDirection
  33560. );
  33561. }
  33562. else {
  33563. labelLayout = endTextLayout(
  33564. opt, nameLocation, nameRotation || 0, extent
  33565. );
  33566. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  33567. if (axisNameAvailableWidth != null) {
  33568. axisNameAvailableWidth = Math.abs(
  33569. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  33570. );
  33571. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  33572. }
  33573. }
  33574. var textFont = textStyleModel.getFont();
  33575. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  33576. var ellipsis = truncateOpt.ellipsis;
  33577. var maxWidth = retrieve(
  33578. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  33579. );
  33580. // FIXME
  33581. // truncate rich text? (consider performance)
  33582. var truncatedText = (ellipsis != null && maxWidth != null)
  33583. ? truncateText$1(
  33584. name, maxWidth, textFont, ellipsis,
  33585. {minChar: 2, placeholder: truncateOpt.placeholder}
  33586. )
  33587. : name;
  33588. var tooltipOpt = axisModel.get('tooltip', true);
  33589. var mainType = axisModel.mainType;
  33590. var formatterParams = {
  33591. componentType: mainType,
  33592. name: name,
  33593. $vars: ['name']
  33594. };
  33595. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  33596. var textEl = new Text({
  33597. // Id for animation
  33598. anid: 'name',
  33599. __fullText: name,
  33600. __truncatedText: truncatedText,
  33601. position: pos,
  33602. rotation: labelLayout.rotation,
  33603. silent: isSilent(axisModel),
  33604. z2: 1,
  33605. tooltip: (tooltipOpt && tooltipOpt.show)
  33606. ? extend({
  33607. content: name,
  33608. formatter: function () {
  33609. return name;
  33610. },
  33611. formatterParams: formatterParams
  33612. }, tooltipOpt)
  33613. : null
  33614. });
  33615. setTextStyle(textEl.style, textStyleModel, {
  33616. text: truncatedText,
  33617. textFont: textFont,
  33618. textFill: textStyleModel.getTextColor()
  33619. || axisModel.get('axisLine.lineStyle.color'),
  33620. textAlign: labelLayout.textAlign,
  33621. textVerticalAlign: labelLayout.textVerticalAlign
  33622. });
  33623. if (axisModel.get('triggerEvent')) {
  33624. textEl.eventData = makeAxisEventDataBase(axisModel);
  33625. textEl.eventData.targetType = 'axisName';
  33626. textEl.eventData.name = name;
  33627. }
  33628. // FIXME
  33629. this._dumbGroup.add(textEl);
  33630. textEl.updateTransform();
  33631. this.group.add(textEl);
  33632. textEl.decomposeTransform();
  33633. }
  33634. };
  33635. /**
  33636. * @public
  33637. * @static
  33638. * @param {Object} opt
  33639. * @param {number} axisRotation in radian
  33640. * @param {number} textRotation in radian
  33641. * @param {number} direction
  33642. * @return {Object} {
  33643. * rotation, // according to axis
  33644. * textAlign,
  33645. * textVerticalAlign
  33646. * }
  33647. */
  33648. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  33649. var rotationDiff = remRadian(textRotation - axisRotation);
  33650. var textAlign;
  33651. var textVerticalAlign;
  33652. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  33653. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  33654. textAlign = 'center';
  33655. }
  33656. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  33657. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  33658. textAlign = 'center';
  33659. }
  33660. else {
  33661. textVerticalAlign = 'middle';
  33662. if (rotationDiff > 0 && rotationDiff < PI$2) {
  33663. textAlign = direction > 0 ? 'right' : 'left';
  33664. }
  33665. else {
  33666. textAlign = direction > 0 ? 'left' : 'right';
  33667. }
  33668. }
  33669. return {
  33670. rotation: rotationDiff,
  33671. textAlign: textAlign,
  33672. textVerticalAlign: textVerticalAlign
  33673. };
  33674. };
  33675. function endTextLayout(opt, textPosition, textRotate, extent) {
  33676. var rotationDiff = remRadian(textRotate - opt.rotation);
  33677. var textAlign;
  33678. var textVerticalAlign;
  33679. var inverse = extent[0] > extent[1];
  33680. var onLeft = (textPosition === 'start' && !inverse)
  33681. || (textPosition !== 'start' && inverse);
  33682. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  33683. textVerticalAlign = onLeft ? 'bottom' : 'top';
  33684. textAlign = 'center';
  33685. }
  33686. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  33687. textVerticalAlign = onLeft ? 'top' : 'bottom';
  33688. textAlign = 'center';
  33689. }
  33690. else {
  33691. textVerticalAlign = 'middle';
  33692. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  33693. textAlign = onLeft ? 'left' : 'right';
  33694. }
  33695. else {
  33696. textAlign = onLeft ? 'right' : 'left';
  33697. }
  33698. }
  33699. return {
  33700. rotation: rotationDiff,
  33701. textAlign: textAlign,
  33702. textVerticalAlign: textVerticalAlign
  33703. };
  33704. }
  33705. function isSilent(axisModel) {
  33706. var tooltipOpt = axisModel.get('tooltip');
  33707. return axisModel.get('silent')
  33708. // Consider mouse cursor, add these restrictions.
  33709. || !(
  33710. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  33711. );
  33712. }
  33713. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  33714. if (shouldShowAllLabels(axisModel.axis)) {
  33715. return;
  33716. }
  33717. // If min or max are user set, we need to check
  33718. // If the tick on min(max) are overlap on their neighbour tick
  33719. // If they are overlapped, we need to hide the min(max) tick label
  33720. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  33721. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  33722. // FIXME
  33723. // Have not consider onBand yet, where tick els is more than label els.
  33724. labelEls = labelEls || [];
  33725. tickEls = tickEls || [];
  33726. var firstLabel = labelEls[0];
  33727. var nextLabel = labelEls[1];
  33728. var lastLabel = labelEls[labelEls.length - 1];
  33729. var prevLabel = labelEls[labelEls.length - 2];
  33730. var firstTick = tickEls[0];
  33731. var nextTick = tickEls[1];
  33732. var lastTick = tickEls[tickEls.length - 1];
  33733. var prevTick = tickEls[tickEls.length - 2];
  33734. if (showMinLabel === false) {
  33735. ignoreEl(firstLabel);
  33736. ignoreEl(firstTick);
  33737. }
  33738. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  33739. if (showMinLabel) {
  33740. ignoreEl(nextLabel);
  33741. ignoreEl(nextTick);
  33742. }
  33743. else {
  33744. ignoreEl(firstLabel);
  33745. ignoreEl(firstTick);
  33746. }
  33747. }
  33748. if (showMaxLabel === false) {
  33749. ignoreEl(lastLabel);
  33750. ignoreEl(lastTick);
  33751. }
  33752. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  33753. if (showMaxLabel) {
  33754. ignoreEl(prevLabel);
  33755. ignoreEl(prevTick);
  33756. }
  33757. else {
  33758. ignoreEl(lastLabel);
  33759. ignoreEl(lastTick);
  33760. }
  33761. }
  33762. }
  33763. function ignoreEl(el) {
  33764. el && (el.ignore = true);
  33765. }
  33766. function isTwoLabelOverlapped(current, next, labelLayout) {
  33767. // current and next has the same rotation.
  33768. var firstRect = current && current.getBoundingRect().clone();
  33769. var nextRect = next && next.getBoundingRect().clone();
  33770. if (!firstRect || !nextRect) {
  33771. return;
  33772. }
  33773. // When checking intersect of two rotated labels, we use mRotationBack
  33774. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  33775. var mRotationBack = identity([]);
  33776. rotate(mRotationBack, mRotationBack, -current.rotation);
  33777. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  33778. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  33779. return firstRect.intersect(nextRect);
  33780. }
  33781. function isNameLocationCenter(nameLocation) {
  33782. return nameLocation === 'middle' || nameLocation === 'center';
  33783. }
  33784. function buildAxisTick(axisBuilder, axisModel, opt) {
  33785. var axis = axisModel.axis;
  33786. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  33787. return;
  33788. }
  33789. var tickModel = axisModel.getModel('axisTick');
  33790. var lineStyleModel = tickModel.getModel('lineStyle');
  33791. var tickLen = tickModel.get('length');
  33792. var ticksCoords = axis.getTicksCoords();
  33793. var pt1 = [];
  33794. var pt2 = [];
  33795. var matrix = axisBuilder._transform;
  33796. var tickEls = [];
  33797. for (var i = 0; i < ticksCoords.length; i++) {
  33798. var tickCoord = ticksCoords[i].coord;
  33799. pt1[0] = tickCoord;
  33800. pt1[1] = 0;
  33801. pt2[0] = tickCoord;
  33802. pt2[1] = opt.tickDirection * tickLen;
  33803. if (matrix) {
  33804. applyTransform(pt1, pt1, matrix);
  33805. applyTransform(pt2, pt2, matrix);
  33806. }
  33807. // Tick line, Not use group transform to have better line draw
  33808. var tickEl = new Line(subPixelOptimizeLine({
  33809. // Id for animation
  33810. anid: 'tick_' + ticksCoords[i].tickValue,
  33811. shape: {
  33812. x1: pt1[0],
  33813. y1: pt1[1],
  33814. x2: pt2[0],
  33815. y2: pt2[1]
  33816. },
  33817. style: defaults(
  33818. lineStyleModel.getLineStyle(),
  33819. {
  33820. stroke: axisModel.get('axisLine.lineStyle.color')
  33821. }
  33822. ),
  33823. z2: 2,
  33824. silent: true
  33825. }));
  33826. axisBuilder.group.add(tickEl);
  33827. tickEls.push(tickEl);
  33828. }
  33829. return tickEls;
  33830. }
  33831. function buildAxisLabel(axisBuilder, axisModel, opt) {
  33832. var axis = axisModel.axis;
  33833. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  33834. if (!show || axis.scale.isBlank()) {
  33835. return;
  33836. }
  33837. var labelModel = axisModel.getModel('axisLabel');
  33838. var labelMargin = labelModel.get('margin');
  33839. var labels = axis.getViewLabels();
  33840. // Special label rotate.
  33841. var labelRotation = (
  33842. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  33843. ) * PI$2 / 180;
  33844. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  33845. var rawCategoryData = axisModel.getCategories(true);
  33846. var labelEls = [];
  33847. var silent = isSilent(axisModel);
  33848. var triggerEvent = axisModel.get('triggerEvent');
  33849. each$1(labels, function (labelItem, index) {
  33850. var tickValue = labelItem.tickValue;
  33851. var formattedLabel = labelItem.formattedLabel;
  33852. var rawLabel = labelItem.rawLabel;
  33853. var itemLabelModel = labelModel;
  33854. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  33855. itemLabelModel = new Model(
  33856. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  33857. );
  33858. }
  33859. var textColor = itemLabelModel.getTextColor()
  33860. || axisModel.get('axisLine.lineStyle.color');
  33861. var tickCoord = axis.dataToCoord(tickValue);
  33862. var pos = [
  33863. tickCoord,
  33864. opt.labelOffset + opt.labelDirection * labelMargin
  33865. ];
  33866. var textEl = new Text({
  33867. // Id for animation
  33868. anid: 'label_' + tickValue,
  33869. position: pos,
  33870. rotation: labelLayout.rotation,
  33871. silent: silent,
  33872. z2: 10
  33873. });
  33874. setTextStyle(textEl.style, itemLabelModel, {
  33875. text: formattedLabel,
  33876. textAlign: itemLabelModel.getShallow('align', true)
  33877. || labelLayout.textAlign,
  33878. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  33879. || itemLabelModel.getShallow('baseline', true)
  33880. || labelLayout.textVerticalAlign,
  33881. textFill: typeof textColor === 'function'
  33882. ? textColor(
  33883. // (1) In category axis with data zoom, tick is not the original
  33884. // index of axis.data. So tick should not be exposed to user
  33885. // in category axis.
  33886. // (2) Compatible with previous version, which always use formatted label as
  33887. // input. But in interval scale the formatted label is like '223,445', which
  33888. // maked user repalce ','. So we modify it to return original val but remain
  33889. // it as 'string' to avoid error in replacing.
  33890. axis.type === 'category'
  33891. ? rawLabel
  33892. : axis.type === 'value'
  33893. ? tickValue + ''
  33894. : tickValue,
  33895. index
  33896. )
  33897. : textColor
  33898. });
  33899. // Pack data for mouse event
  33900. if (triggerEvent) {
  33901. textEl.eventData = makeAxisEventDataBase(axisModel);
  33902. textEl.eventData.targetType = 'axisLabel';
  33903. textEl.eventData.value = rawLabel;
  33904. }
  33905. // FIXME
  33906. axisBuilder._dumbGroup.add(textEl);
  33907. textEl.updateTransform();
  33908. labelEls.push(textEl);
  33909. axisBuilder.group.add(textEl);
  33910. textEl.decomposeTransform();
  33911. });
  33912. return labelEls;
  33913. }
  33914. /*
  33915. * Licensed to the Apache Software Foundation (ASF) under one
  33916. * or more contributor license agreements. See the NOTICE file
  33917. * distributed with this work for additional information
  33918. * regarding copyright ownership. The ASF licenses this file
  33919. * to you under the Apache License, Version 2.0 (the
  33920. * "License"); you may not use this file except in compliance
  33921. * with the License. You may obtain a copy of the License at
  33922. *
  33923. * http://www.apache.org/licenses/LICENSE-2.0
  33924. *
  33925. * Unless required by applicable law or agreed to in writing,
  33926. * software distributed under the License is distributed on an
  33927. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33928. * KIND, either express or implied. See the License for the
  33929. * specific language governing permissions and limitations
  33930. * under the License.
  33931. */
  33932. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  33933. // allAxesInfo should be updated when setOption performed.
  33934. function fixValue(axisModel) {
  33935. var axisInfo = getAxisInfo(axisModel);
  33936. if (!axisInfo) {
  33937. return;
  33938. }
  33939. var axisPointerModel = axisInfo.axisPointerModel;
  33940. var scale = axisInfo.axis.scale;
  33941. var option = axisPointerModel.option;
  33942. var status = axisPointerModel.get('status');
  33943. var value = axisPointerModel.get('value');
  33944. // Parse init value for category and time axis.
  33945. if (value != null) {
  33946. value = scale.parse(value);
  33947. }
  33948. var useHandle = isHandleTrigger(axisPointerModel);
  33949. // If `handle` used, `axisPointer` will always be displayed, so value
  33950. // and status should be initialized.
  33951. if (status == null) {
  33952. option.status = useHandle ? 'show' : 'hide';
  33953. }
  33954. var extent = scale.getExtent().slice();
  33955. extent[0] > extent[1] && extent.reverse();
  33956. if (// Pick a value on axis when initializing.
  33957. value == null
  33958. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  33959. // where we should re-pick a value to keep `handle` displaying normally.
  33960. || value > extent[1]
  33961. ) {
  33962. // Make handle displayed on the end of the axis when init, which looks better.
  33963. value = extent[1];
  33964. }
  33965. if (value < extent[0]) {
  33966. value = extent[0];
  33967. }
  33968. option.value = value;
  33969. if (useHandle) {
  33970. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  33971. }
  33972. }
  33973. function getAxisInfo(axisModel) {
  33974. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  33975. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  33976. }
  33977. function getAxisPointerModel(axisModel) {
  33978. var axisInfo = getAxisInfo(axisModel);
  33979. return axisInfo && axisInfo.axisPointerModel;
  33980. }
  33981. function isHandleTrigger(axisPointerModel) {
  33982. return !!axisPointerModel.get('handle.show');
  33983. }
  33984. /**
  33985. * @param {module:echarts/model/Model} model
  33986. * @return {string} unique key
  33987. */
  33988. function makeKey(model) {
  33989. return model.type + '||' + model.id;
  33990. }
  33991. /*
  33992. * Licensed to the Apache Software Foundation (ASF) under one
  33993. * or more contributor license agreements. See the NOTICE file
  33994. * distributed with this work for additional information
  33995. * regarding copyright ownership. The ASF licenses this file
  33996. * to you under the Apache License, Version 2.0 (the
  33997. * "License"); you may not use this file except in compliance
  33998. * with the License. You may obtain a copy of the License at
  33999. *
  34000. * http://www.apache.org/licenses/LICENSE-2.0
  34001. *
  34002. * Unless required by applicable law or agreed to in writing,
  34003. * software distributed under the License is distributed on an
  34004. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34005. * KIND, either express or implied. See the License for the
  34006. * specific language governing permissions and limitations
  34007. * under the License.
  34008. */
  34009. /**
  34010. * Base class of AxisView.
  34011. */
  34012. var AxisView = extendComponentView({
  34013. type: 'axis',
  34014. /**
  34015. * @private
  34016. */
  34017. _axisPointer: null,
  34018. /**
  34019. * @protected
  34020. * @type {string}
  34021. */
  34022. axisPointerClass: null,
  34023. /**
  34024. * @override
  34025. */
  34026. render: function (axisModel, ecModel, api, payload) {
  34027. // FIXME
  34028. // This process should proformed after coordinate systems updated
  34029. // (axis scale updated), and should be performed each time update.
  34030. // So put it here temporarily, although it is not appropriate to
  34031. // put a model-writing procedure in `view`.
  34032. this.axisPointerClass && fixValue(axisModel);
  34033. AxisView.superApply(this, 'render', arguments);
  34034. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  34035. },
  34036. /**
  34037. * Action handler.
  34038. * @public
  34039. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  34040. * @param {module:echarts/model/Global} ecModel
  34041. * @param {module:echarts/ExtensionAPI} api
  34042. * @param {Object} payload
  34043. */
  34044. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  34045. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  34046. },
  34047. /**
  34048. * @override
  34049. */
  34050. remove: function (ecModel, api) {
  34051. var axisPointer = this._axisPointer;
  34052. axisPointer && axisPointer.remove(api);
  34053. AxisView.superApply(this, 'remove', arguments);
  34054. },
  34055. /**
  34056. * @override
  34057. */
  34058. dispose: function (ecModel, api) {
  34059. disposeAxisPointer(this, api);
  34060. AxisView.superApply(this, 'dispose', arguments);
  34061. }
  34062. });
  34063. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  34064. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  34065. if (!Clazz) {
  34066. return;
  34067. }
  34068. var axisPointerModel = getAxisPointerModel(axisModel);
  34069. axisPointerModel
  34070. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  34071. .render(axisModel, axisPointerModel, api, forceRender)
  34072. : disposeAxisPointer(axisView, api);
  34073. }
  34074. function disposeAxisPointer(axisView, ecModel, api) {
  34075. var axisPointer = axisView._axisPointer;
  34076. axisPointer && axisPointer.dispose(ecModel, api);
  34077. axisView._axisPointer = null;
  34078. }
  34079. var axisPointerClazz = [];
  34080. AxisView.registerAxisPointerClass = function (type, clazz) {
  34081. if (__DEV__) {
  34082. if (axisPointerClazz[type]) {
  34083. throw new Error('axisPointer ' + type + ' exists');
  34084. }
  34085. }
  34086. axisPointerClazz[type] = clazz;
  34087. };
  34088. AxisView.getAxisPointerClass = function (type) {
  34089. return type && axisPointerClazz[type];
  34090. };
  34091. /*
  34092. * Licensed to the Apache Software Foundation (ASF) under one
  34093. * or more contributor license agreements. See the NOTICE file
  34094. * distributed with this work for additional information
  34095. * regarding copyright ownership. The ASF licenses this file
  34096. * to you under the Apache License, Version 2.0 (the
  34097. * "License"); you may not use this file except in compliance
  34098. * with the License. You may obtain a copy of the License at
  34099. *
  34100. * http://www.apache.org/licenses/LICENSE-2.0
  34101. *
  34102. * Unless required by applicable law or agreed to in writing,
  34103. * software distributed under the License is distributed on an
  34104. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34105. * KIND, either express or implied. See the License for the
  34106. * specific language governing permissions and limitations
  34107. * under the License.
  34108. */
  34109. /**
  34110. * Can only be called after coordinate system creation stage.
  34111. * (Can be called before coordinate system update stage).
  34112. *
  34113. * @param {Object} opt {labelInside}
  34114. * @return {Object} {
  34115. * position, rotation, labelDirection, labelOffset,
  34116. * tickDirection, labelRotate, z2
  34117. * }
  34118. */
  34119. function layout$1(gridModel, axisModel, opt) {
  34120. opt = opt || {};
  34121. var grid = gridModel.coordinateSystem;
  34122. var axis = axisModel.axis;
  34123. var layout = {};
  34124. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  34125. var rawAxisPosition = axis.position;
  34126. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  34127. var axisDim = axis.dim;
  34128. var rect = grid.getRect();
  34129. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  34130. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  34131. var axisOffset = axisModel.get('offset') || 0;
  34132. var posBound = axisDim === 'x'
  34133. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  34134. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  34135. if (otherAxisOnZeroOf) {
  34136. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  34137. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  34138. }
  34139. // Axis position
  34140. layout.position = [
  34141. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  34142. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  34143. ];
  34144. // Axis rotation
  34145. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  34146. // Tick and label direction, x y is axisDim
  34147. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  34148. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  34149. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  34150. if (axisModel.get('axisTick.inside')) {
  34151. layout.tickDirection = -layout.tickDirection;
  34152. }
  34153. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  34154. layout.labelDirection = -layout.labelDirection;
  34155. }
  34156. // Special label rotation
  34157. var labelRotate = axisModel.get('axisLabel.rotate');
  34158. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  34159. // Over splitLine and splitArea
  34160. layout.z2 = 1;
  34161. return layout;
  34162. }
  34163. /*
  34164. * Licensed to the Apache Software Foundation (ASF) under one
  34165. * or more contributor license agreements. See the NOTICE file
  34166. * distributed with this work for additional information
  34167. * regarding copyright ownership. The ASF licenses this file
  34168. * to you under the Apache License, Version 2.0 (the
  34169. * "License"); you may not use this file except in compliance
  34170. * with the License. You may obtain a copy of the License at
  34171. *
  34172. * http://www.apache.org/licenses/LICENSE-2.0
  34173. *
  34174. * Unless required by applicable law or agreed to in writing,
  34175. * software distributed under the License is distributed on an
  34176. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34177. * KIND, either express or implied. See the License for the
  34178. * specific language governing permissions and limitations
  34179. * under the License.
  34180. */
  34181. var axisBuilderAttrs = [
  34182. 'axisLine', 'axisTickLabel', 'axisName'
  34183. ];
  34184. var selfBuilderAttrs = [
  34185. 'splitArea', 'splitLine'
  34186. ];
  34187. // function getAlignWithLabel(model, axisModel) {
  34188. // var alignWithLabel = model.get('alignWithLabel');
  34189. // if (alignWithLabel === 'auto') {
  34190. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  34191. // }
  34192. // return alignWithLabel;
  34193. // }
  34194. var CartesianAxisView = AxisView.extend({
  34195. type: 'cartesianAxis',
  34196. axisPointerClass: 'CartesianAxisPointer',
  34197. /**
  34198. * @override
  34199. */
  34200. render: function (axisModel, ecModel, api, payload) {
  34201. this.group.removeAll();
  34202. var oldAxisGroup = this._axisGroup;
  34203. this._axisGroup = new Group();
  34204. this.group.add(this._axisGroup);
  34205. if (!axisModel.get('show')) {
  34206. return;
  34207. }
  34208. var gridModel = axisModel.getCoordSysModel();
  34209. var layout = layout$1(gridModel, axisModel);
  34210. var axisBuilder = new AxisBuilder(axisModel, layout);
  34211. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  34212. this._axisGroup.add(axisBuilder.getGroup());
  34213. each$1(selfBuilderAttrs, function (name) {
  34214. if (axisModel.get(name + '.show')) {
  34215. this['_' + name](axisModel, gridModel);
  34216. }
  34217. }, this);
  34218. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  34219. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  34220. },
  34221. remove: function () {
  34222. this._splitAreaColors = null;
  34223. },
  34224. /**
  34225. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  34226. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  34227. * @private
  34228. */
  34229. _splitLine: function (axisModel, gridModel) {
  34230. var axis = axisModel.axis;
  34231. if (axis.scale.isBlank()) {
  34232. return;
  34233. }
  34234. var splitLineModel = axisModel.getModel('splitLine');
  34235. var lineStyleModel = splitLineModel.getModel('lineStyle');
  34236. var lineColors = lineStyleModel.get('color');
  34237. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  34238. var gridRect = gridModel.coordinateSystem.getRect();
  34239. var isHorizontal = axis.isHorizontal();
  34240. var lineCount = 0;
  34241. var ticksCoords = axis.getTicksCoords({
  34242. tickModel: splitLineModel
  34243. });
  34244. var p1 = [];
  34245. var p2 = [];
  34246. // Simple optimization
  34247. // Batching the lines if color are the same
  34248. var lineStyle = lineStyleModel.getLineStyle();
  34249. for (var i = 0; i < ticksCoords.length; i++) {
  34250. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  34251. if (isHorizontal) {
  34252. p1[0] = tickCoord;
  34253. p1[1] = gridRect.y;
  34254. p2[0] = tickCoord;
  34255. p2[1] = gridRect.y + gridRect.height;
  34256. }
  34257. else {
  34258. p1[0] = gridRect.x;
  34259. p1[1] = tickCoord;
  34260. p2[0] = gridRect.x + gridRect.width;
  34261. p2[1] = tickCoord;
  34262. }
  34263. var colorIndex = (lineCount++) % lineColors.length;
  34264. var tickValue = ticksCoords[i].tickValue;
  34265. this._axisGroup.add(new Line(subPixelOptimizeLine({
  34266. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  34267. shape: {
  34268. x1: p1[0],
  34269. y1: p1[1],
  34270. x2: p2[0],
  34271. y2: p2[1]
  34272. },
  34273. style: defaults({
  34274. stroke: lineColors[colorIndex]
  34275. }, lineStyle),
  34276. silent: true
  34277. })));
  34278. }
  34279. },
  34280. /**
  34281. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  34282. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  34283. * @private
  34284. */
  34285. _splitArea: function (axisModel, gridModel) {
  34286. var axis = axisModel.axis;
  34287. if (axis.scale.isBlank()) {
  34288. return;
  34289. }
  34290. var splitAreaModel = axisModel.getModel('splitArea');
  34291. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  34292. var areaColors = areaStyleModel.get('color');
  34293. var gridRect = gridModel.coordinateSystem.getRect();
  34294. var ticksCoords = axis.getTicksCoords({
  34295. tickModel: splitAreaModel,
  34296. clamp: true
  34297. });
  34298. if (!ticksCoords.length) {
  34299. return;
  34300. }
  34301. // For Making appropriate splitArea animation, the color and anid
  34302. // should be corresponding to previous one if possible.
  34303. var areaColorsLen = areaColors.length;
  34304. var lastSplitAreaColors = this._splitAreaColors;
  34305. var newSplitAreaColors = createHashMap();
  34306. var colorIndex = 0;
  34307. if (lastSplitAreaColors) {
  34308. for (var i = 0; i < ticksCoords.length; i++) {
  34309. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  34310. if (cIndex != null) {
  34311. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  34312. break;
  34313. }
  34314. }
  34315. }
  34316. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  34317. var areaStyle = areaStyleModel.getAreaStyle();
  34318. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  34319. for (var i = 1; i < ticksCoords.length; i++) {
  34320. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  34321. var x;
  34322. var y;
  34323. var width;
  34324. var height;
  34325. if (axis.isHorizontal()) {
  34326. x = prev;
  34327. y = gridRect.y;
  34328. width = tickCoord - x;
  34329. height = gridRect.height;
  34330. prev = x + width;
  34331. }
  34332. else {
  34333. x = gridRect.x;
  34334. y = prev;
  34335. width = gridRect.width;
  34336. height = tickCoord - y;
  34337. prev = y + height;
  34338. }
  34339. var tickValue = ticksCoords[i - 1].tickValue;
  34340. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  34341. this._axisGroup.add(new Rect({
  34342. anid: tickValue != null ? 'area_' + tickValue : null,
  34343. shape: {
  34344. x: x,
  34345. y: y,
  34346. width: width,
  34347. height: height
  34348. },
  34349. style: defaults({
  34350. fill: areaColors[colorIndex]
  34351. }, areaStyle),
  34352. silent: true
  34353. }));
  34354. colorIndex = (colorIndex + 1) % areaColorsLen;
  34355. }
  34356. this._splitAreaColors = newSplitAreaColors;
  34357. }
  34358. });
  34359. CartesianAxisView.extend({
  34360. type: 'xAxis'
  34361. });
  34362. CartesianAxisView.extend({
  34363. type: 'yAxis'
  34364. });
  34365. /*
  34366. * Licensed to the Apache Software Foundation (ASF) under one
  34367. * or more contributor license agreements. See the NOTICE file
  34368. * distributed with this work for additional information
  34369. * regarding copyright ownership. The ASF licenses this file
  34370. * to you under the Apache License, Version 2.0 (the
  34371. * "License"); you may not use this file except in compliance
  34372. * with the License. You may obtain a copy of the License at
  34373. *
  34374. * http://www.apache.org/licenses/LICENSE-2.0
  34375. *
  34376. * Unless required by applicable law or agreed to in writing,
  34377. * software distributed under the License is distributed on an
  34378. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34379. * KIND, either express or implied. See the License for the
  34380. * specific language governing permissions and limitations
  34381. * under the License.
  34382. */
  34383. /*
  34384. * Licensed to the Apache Software Foundation (ASF) under one
  34385. * or more contributor license agreements. See the NOTICE file
  34386. * distributed with this work for additional information
  34387. * regarding copyright ownership. The ASF licenses this file
  34388. * to you under the Apache License, Version 2.0 (the
  34389. * "License"); you may not use this file except in compliance
  34390. * with the License. You may obtain a copy of the License at
  34391. *
  34392. * http://www.apache.org/licenses/LICENSE-2.0
  34393. *
  34394. * Unless required by applicable law or agreed to in writing,
  34395. * software distributed under the License is distributed on an
  34396. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34397. * KIND, either express or implied. See the License for the
  34398. * specific language governing permissions and limitations
  34399. * under the License.
  34400. */
  34401. // Grid view
  34402. extendComponentView({
  34403. type: 'grid',
  34404. render: function (gridModel, ecModel) {
  34405. this.group.removeAll();
  34406. if (gridModel.get('show')) {
  34407. this.group.add(new Rect({
  34408. shape: gridModel.coordinateSystem.getRect(),
  34409. style: defaults({
  34410. fill: gridModel.get('backgroundColor')
  34411. }, gridModel.getItemStyle()),
  34412. silent: true,
  34413. z2: -1
  34414. }));
  34415. }
  34416. }
  34417. });
  34418. registerPreprocessor(function (option) {
  34419. // Only create grid when need
  34420. if (option.xAxis && option.yAxis && !option.grid) {
  34421. option.grid = {};
  34422. }
  34423. });
  34424. /*
  34425. * Licensed to the Apache Software Foundation (ASF) under one
  34426. * or more contributor license agreements. See the NOTICE file
  34427. * distributed with this work for additional information
  34428. * regarding copyright ownership. The ASF licenses this file
  34429. * to you under the Apache License, Version 2.0 (the
  34430. * "License"); you may not use this file except in compliance
  34431. * with the License. You may obtain a copy of the License at
  34432. *
  34433. * http://www.apache.org/licenses/LICENSE-2.0
  34434. *
  34435. * Unless required by applicable law or agreed to in writing,
  34436. * software distributed under the License is distributed on an
  34437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34438. * KIND, either express or implied. See the License for the
  34439. * specific language governing permissions and limitations
  34440. * under the License.
  34441. */
  34442. // In case developer forget to include grid component
  34443. registerVisual(visualSymbol('line', 'circle', 'line'));
  34444. registerLayout(layoutPoints('line'));
  34445. // Down sample after filter
  34446. registerProcessor(
  34447. PRIORITY.PROCESSOR.STATISTIC,
  34448. dataSample('line')
  34449. );
  34450. /*
  34451. * Licensed to the Apache Software Foundation (ASF) under one
  34452. * or more contributor license agreements. See the NOTICE file
  34453. * distributed with this work for additional information
  34454. * regarding copyright ownership. The ASF licenses this file
  34455. * to you under the Apache License, Version 2.0 (the
  34456. * "License"); you may not use this file except in compliance
  34457. * with the License. You may obtain a copy of the License at
  34458. *
  34459. * http://www.apache.org/licenses/LICENSE-2.0
  34460. *
  34461. * Unless required by applicable law or agreed to in writing,
  34462. * software distributed under the License is distributed on an
  34463. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34464. * KIND, either express or implied. See the License for the
  34465. * specific language governing permissions and limitations
  34466. * under the License.
  34467. */
  34468. var BaseBarSeries = SeriesModel.extend({
  34469. type: 'series.__base_bar__',
  34470. getInitialData: function (option, ecModel) {
  34471. return createListFromArray(this.getSource(), this);
  34472. },
  34473. getMarkerPosition: function (value) {
  34474. var coordSys = this.coordinateSystem;
  34475. if (coordSys) {
  34476. // PENDING if clamp ?
  34477. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  34478. var data = this.getData();
  34479. var offset = data.getLayout('offset');
  34480. var size = data.getLayout('size');
  34481. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  34482. pt[offsetIndex] += offset + size / 2;
  34483. return pt;
  34484. }
  34485. return [NaN, NaN];
  34486. },
  34487. defaultOption: {
  34488. zlevel: 0, // 一级层叠
  34489. z: 2, // 二级层叠
  34490. coordinateSystem: 'cartesian2d',
  34491. legendHoverLink: true,
  34492. // stack: null
  34493. // Cartesian coordinate system
  34494. // xAxisIndex: 0,
  34495. // yAxisIndex: 0,
  34496. // 最小高度改为0
  34497. barMinHeight: 0,
  34498. // 最小角度为0,仅对极坐标系下的柱状图有效
  34499. barMinAngle: 0,
  34500. // cursor: null,
  34501. large: false,
  34502. largeThreshold: 400,
  34503. progressive: 3e3,
  34504. progressiveChunkMode: 'mod',
  34505. // barMaxWidth: null,
  34506. // 默认自适应
  34507. // barWidth: null,
  34508. // 柱间距离,默认为柱形宽度的30%,可设固定值
  34509. // barGap: '30%',
  34510. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  34511. // barCategoryGap: '20%',
  34512. // label: {
  34513. // show: false
  34514. // },
  34515. itemStyle: {},
  34516. emphasis: {}
  34517. }
  34518. });
  34519. /*
  34520. * Licensed to the Apache Software Foundation (ASF) under one
  34521. * or more contributor license agreements. See the NOTICE file
  34522. * distributed with this work for additional information
  34523. * regarding copyright ownership. The ASF licenses this file
  34524. * to you under the Apache License, Version 2.0 (the
  34525. * "License"); you may not use this file except in compliance
  34526. * with the License. You may obtain a copy of the License at
  34527. *
  34528. * http://www.apache.org/licenses/LICENSE-2.0
  34529. *
  34530. * Unless required by applicable law or agreed to in writing,
  34531. * software distributed under the License is distributed on an
  34532. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34533. * KIND, either express or implied. See the License for the
  34534. * specific language governing permissions and limitations
  34535. * under the License.
  34536. */
  34537. BaseBarSeries.extend({
  34538. type: 'series.bar',
  34539. dependencies: ['grid', 'polar'],
  34540. brushSelector: 'rect',
  34541. /**
  34542. * @override
  34543. */
  34544. getProgressive: function () {
  34545. // Do not support progressive in normal mode.
  34546. return this.get('large')
  34547. ? this.get('progressive')
  34548. : false;
  34549. },
  34550. /**
  34551. * @override
  34552. */
  34553. getProgressiveThreshold: function () {
  34554. // Do not support progressive in normal mode.
  34555. var progressiveThreshold = this.get('progressiveThreshold');
  34556. var largeThreshold = this.get('largeThreshold');
  34557. if (largeThreshold > progressiveThreshold) {
  34558. progressiveThreshold = largeThreshold;
  34559. }
  34560. return progressiveThreshold;
  34561. }
  34562. });
  34563. /*
  34564. * Licensed to the Apache Software Foundation (ASF) under one
  34565. * or more contributor license agreements. See the NOTICE file
  34566. * distributed with this work for additional information
  34567. * regarding copyright ownership. The ASF licenses this file
  34568. * to you under the Apache License, Version 2.0 (the
  34569. * "License"); you may not use this file except in compliance
  34570. * with the License. You may obtain a copy of the License at
  34571. *
  34572. * http://www.apache.org/licenses/LICENSE-2.0
  34573. *
  34574. * Unless required by applicable law or agreed to in writing,
  34575. * software distributed under the License is distributed on an
  34576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34577. * KIND, either express or implied. See the License for the
  34578. * specific language governing permissions and limitations
  34579. * under the License.
  34580. */
  34581. function setLabel(
  34582. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  34583. ) {
  34584. var labelModel = itemModel.getModel('label');
  34585. var hoverLabelModel = itemModel.getModel('emphasis.label');
  34586. setLabelStyle(
  34587. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  34588. {
  34589. labelFetcher: seriesModel,
  34590. labelDataIndex: dataIndex,
  34591. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  34592. isRectText: true,
  34593. autoColor: color
  34594. }
  34595. );
  34596. fixPosition(normalStyle);
  34597. fixPosition(hoverStyle);
  34598. }
  34599. function fixPosition(style, labelPositionOutside) {
  34600. if (style.textPosition === 'outside') {
  34601. style.textPosition = labelPositionOutside;
  34602. }
  34603. }
  34604. /*
  34605. * Licensed to the Apache Software Foundation (ASF) under one
  34606. * or more contributor license agreements. See the NOTICE file
  34607. * distributed with this work for additional information
  34608. * regarding copyright ownership. The ASF licenses this file
  34609. * to you under the Apache License, Version 2.0 (the
  34610. * "License"); you may not use this file except in compliance
  34611. * with the License. You may obtain a copy of the License at
  34612. *
  34613. * http://www.apache.org/licenses/LICENSE-2.0
  34614. *
  34615. * Unless required by applicable law or agreed to in writing,
  34616. * software distributed under the License is distributed on an
  34617. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34618. * KIND, either express or implied. See the License for the
  34619. * specific language governing permissions and limitations
  34620. * under the License.
  34621. */
  34622. var getBarItemStyle = makeStyleMapper(
  34623. [
  34624. ['fill', 'color'],
  34625. ['stroke', 'borderColor'],
  34626. ['lineWidth', 'borderWidth'],
  34627. // Compatitable with 2
  34628. ['stroke', 'barBorderColor'],
  34629. ['lineWidth', 'barBorderWidth'],
  34630. ['opacity'],
  34631. ['shadowBlur'],
  34632. ['shadowOffsetX'],
  34633. ['shadowOffsetY'],
  34634. ['shadowColor']
  34635. ]
  34636. );
  34637. var barItemStyle = {
  34638. getBarItemStyle: function (excludes) {
  34639. var style = getBarItemStyle(this, excludes);
  34640. if (this.getBorderLineDash) {
  34641. var lineDash = this.getBorderLineDash();
  34642. lineDash && (style.lineDash = lineDash);
  34643. }
  34644. return style;
  34645. }
  34646. };
  34647. /*
  34648. * Licensed to the Apache Software Foundation (ASF) under one
  34649. * or more contributor license agreements. See the NOTICE file
  34650. * distributed with this work for additional information
  34651. * regarding copyright ownership. The ASF licenses this file
  34652. * to you under the Apache License, Version 2.0 (the
  34653. * "License"); you may not use this file except in compliance
  34654. * with the License. You may obtain a copy of the License at
  34655. *
  34656. * http://www.apache.org/licenses/LICENSE-2.0
  34657. *
  34658. * Unless required by applicable law or agreed to in writing,
  34659. * software distributed under the License is distributed on an
  34660. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34661. * KIND, either express or implied. See the License for the
  34662. * specific language governing permissions and limitations
  34663. * under the License.
  34664. */
  34665. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  34666. // FIXME
  34667. // Just for compatible with ec2.
  34668. extend(Model.prototype, barItemStyle);
  34669. extendChartView({
  34670. type: 'bar',
  34671. render: function (seriesModel, ecModel, api) {
  34672. this._updateDrawMode(seriesModel);
  34673. var coordinateSystemType = seriesModel.get('coordinateSystem');
  34674. if (coordinateSystemType === 'cartesian2d'
  34675. || coordinateSystemType === 'polar'
  34676. ) {
  34677. this._isLargeDraw
  34678. ? this._renderLarge(seriesModel, ecModel, api)
  34679. : this._renderNormal(seriesModel, ecModel, api);
  34680. }
  34681. else if (__DEV__) {
  34682. console.warn('Only cartesian2d and polar supported for bar.');
  34683. }
  34684. return this.group;
  34685. },
  34686. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  34687. this._clear();
  34688. this._updateDrawMode(seriesModel);
  34689. },
  34690. incrementalRender: function (params, seriesModel, ecModel, api) {
  34691. // Do not support progressive in normal mode.
  34692. this._incrementalRenderLarge(params, seriesModel);
  34693. },
  34694. _updateDrawMode: function (seriesModel) {
  34695. var isLargeDraw = seriesModel.pipelineContext.large;
  34696. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  34697. this._isLargeDraw = isLargeDraw;
  34698. this._clear();
  34699. }
  34700. },
  34701. _renderNormal: function (seriesModel, ecModel, api) {
  34702. var group = this.group;
  34703. var data = seriesModel.getData();
  34704. var oldData = this._data;
  34705. var coord = seriesModel.coordinateSystem;
  34706. var baseAxis = coord.getBaseAxis();
  34707. var isHorizontalOrRadial;
  34708. if (coord.type === 'cartesian2d') {
  34709. isHorizontalOrRadial = baseAxis.isHorizontal();
  34710. }
  34711. else if (coord.type === 'polar') {
  34712. isHorizontalOrRadial = baseAxis.dim === 'angle';
  34713. }
  34714. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  34715. data.diff(oldData)
  34716. .add(function (dataIndex) {
  34717. if (!data.hasValue(dataIndex)) {
  34718. return;
  34719. }
  34720. var itemModel = data.getItemModel(dataIndex);
  34721. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  34722. var el = elementCreator[coord.type](
  34723. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  34724. );
  34725. data.setItemGraphicEl(dataIndex, el);
  34726. group.add(el);
  34727. updateStyle(
  34728. el, data, dataIndex, itemModel, layout,
  34729. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34730. );
  34731. })
  34732. .update(function (newIndex, oldIndex) {
  34733. var el = oldData.getItemGraphicEl(oldIndex);
  34734. if (!data.hasValue(newIndex)) {
  34735. group.remove(el);
  34736. return;
  34737. }
  34738. var itemModel = data.getItemModel(newIndex);
  34739. var layout = getLayout[coord.type](data, newIndex, itemModel);
  34740. if (el) {
  34741. updateProps(el, {shape: layout}, animationModel, newIndex);
  34742. }
  34743. else {
  34744. el = elementCreator[coord.type](
  34745. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  34746. );
  34747. }
  34748. data.setItemGraphicEl(newIndex, el);
  34749. // Add back
  34750. group.add(el);
  34751. updateStyle(
  34752. el, data, newIndex, itemModel, layout,
  34753. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34754. );
  34755. })
  34756. .remove(function (dataIndex) {
  34757. var el = oldData.getItemGraphicEl(dataIndex);
  34758. if (coord.type === 'cartesian2d') {
  34759. el && removeRect(dataIndex, animationModel, el);
  34760. }
  34761. else {
  34762. el && removeSector(dataIndex, animationModel, el);
  34763. }
  34764. })
  34765. .execute();
  34766. this._data = data;
  34767. },
  34768. _renderLarge: function (seriesModel, ecModel, api) {
  34769. this._clear();
  34770. createLarge(seriesModel, this.group);
  34771. },
  34772. _incrementalRenderLarge: function (params, seriesModel) {
  34773. createLarge(seriesModel, this.group, true);
  34774. },
  34775. dispose: noop,
  34776. remove: function (ecModel) {
  34777. this._clear(ecModel);
  34778. },
  34779. _clear: function (ecModel) {
  34780. var group = this.group;
  34781. var data = this._data;
  34782. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  34783. data.eachItemGraphicEl(function (el) {
  34784. if (el.type === 'sector') {
  34785. removeSector(el.dataIndex, ecModel, el);
  34786. }
  34787. else {
  34788. removeRect(el.dataIndex, ecModel, el);
  34789. }
  34790. });
  34791. }
  34792. else {
  34793. group.removeAll();
  34794. }
  34795. this._data = null;
  34796. }
  34797. });
  34798. var elementCreator = {
  34799. cartesian2d: function (
  34800. data, dataIndex, itemModel, layout, isHorizontal,
  34801. animationModel, isUpdate
  34802. ) {
  34803. var rect = new Rect({shape: extend({}, layout)});
  34804. // Animation
  34805. if (animationModel) {
  34806. var rectShape = rect.shape;
  34807. var animateProperty = isHorizontal ? 'height' : 'width';
  34808. var animateTarget = {};
  34809. rectShape[animateProperty] = 0;
  34810. animateTarget[animateProperty] = layout[animateProperty];
  34811. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  34812. shape: animateTarget
  34813. }, animationModel, dataIndex);
  34814. }
  34815. return rect;
  34816. },
  34817. polar: function (
  34818. data, dataIndex, itemModel, layout, isRadial,
  34819. animationModel, isUpdate
  34820. ) {
  34821. // Keep the same logic with bar in catesion: use end value to control
  34822. // direction. Notice that if clockwise is true (by default), the sector
  34823. // will always draw clockwisely, no matter whether endAngle is greater
  34824. // or less than startAngle.
  34825. var clockwise = layout.startAngle < layout.endAngle;
  34826. var sector = new Sector({
  34827. shape: defaults({clockwise: clockwise}, layout)
  34828. });
  34829. // Animation
  34830. if (animationModel) {
  34831. var sectorShape = sector.shape;
  34832. var animateProperty = isRadial ? 'r' : 'endAngle';
  34833. var animateTarget = {};
  34834. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  34835. animateTarget[animateProperty] = layout[animateProperty];
  34836. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  34837. shape: animateTarget
  34838. }, animationModel, dataIndex);
  34839. }
  34840. return sector;
  34841. }
  34842. };
  34843. function removeRect(dataIndex, animationModel, el) {
  34844. // Not show text when animating
  34845. el.style.text = null;
  34846. updateProps(el, {
  34847. shape: {
  34848. width: 0
  34849. }
  34850. }, animationModel, dataIndex, function () {
  34851. el.parent && el.parent.remove(el);
  34852. });
  34853. }
  34854. function removeSector(dataIndex, animationModel, el) {
  34855. // Not show text when animating
  34856. el.style.text = null;
  34857. updateProps(el, {
  34858. shape: {
  34859. r: el.shape.r0
  34860. }
  34861. }, animationModel, dataIndex, function () {
  34862. el.parent && el.parent.remove(el);
  34863. });
  34864. }
  34865. var getLayout = {
  34866. cartesian2d: function (data, dataIndex, itemModel) {
  34867. var layout = data.getItemLayout(dataIndex);
  34868. var fixedLineWidth = getLineWidth(itemModel, layout);
  34869. // fix layout with lineWidth
  34870. var signX = layout.width > 0 ? 1 : -1;
  34871. var signY = layout.height > 0 ? 1 : -1;
  34872. return {
  34873. x: layout.x + signX * fixedLineWidth / 2,
  34874. y: layout.y + signY * fixedLineWidth / 2,
  34875. width: layout.width - signX * fixedLineWidth,
  34876. height: layout.height - signY * fixedLineWidth
  34877. };
  34878. },
  34879. polar: function (data, dataIndex, itemModel) {
  34880. var layout = data.getItemLayout(dataIndex);
  34881. return {
  34882. cx: layout.cx,
  34883. cy: layout.cy,
  34884. r0: layout.r0,
  34885. r: layout.r,
  34886. startAngle: layout.startAngle,
  34887. endAngle: layout.endAngle
  34888. };
  34889. }
  34890. };
  34891. function updateStyle(
  34892. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  34893. ) {
  34894. var color = data.getItemVisual(dataIndex, 'color');
  34895. var opacity = data.getItemVisual(dataIndex, 'opacity');
  34896. var itemStyleModel = itemModel.getModel('itemStyle');
  34897. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  34898. if (!isPolar) {
  34899. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  34900. }
  34901. el.useStyle(defaults(
  34902. {
  34903. fill: color,
  34904. opacity: opacity
  34905. },
  34906. itemStyleModel.getBarItemStyle()
  34907. ));
  34908. var cursorStyle = itemModel.getShallow('cursor');
  34909. cursorStyle && el.attr('cursor', cursorStyle);
  34910. var labelPositionOutside = isHorizontal
  34911. ? (layout.height > 0 ? 'bottom' : 'top')
  34912. : (layout.width > 0 ? 'left' : 'right');
  34913. if (!isPolar) {
  34914. setLabel(
  34915. el.style, hoverStyle, itemModel, color,
  34916. seriesModel, dataIndex, labelPositionOutside
  34917. );
  34918. }
  34919. setHoverStyle(el, hoverStyle);
  34920. }
  34921. // In case width or height are too small.
  34922. function getLineWidth(itemModel, rawLayout) {
  34923. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  34924. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  34925. }
  34926. var LargePath = Path.extend({
  34927. type: 'largeBar',
  34928. shape: {points: []},
  34929. buildPath: function (ctx, shape) {
  34930. // Drawing lines is more efficient than drawing
  34931. // a whole line or drawing rects.
  34932. var points = shape.points;
  34933. var startPoint = this.__startPoint;
  34934. var valueIdx = this.__valueIdx;
  34935. for (var i = 0; i < points.length; i += 2) {
  34936. startPoint[this.__valueIdx] = points[i + valueIdx];
  34937. ctx.moveTo(startPoint[0], startPoint[1]);
  34938. ctx.lineTo(points[i], points[i + 1]);
  34939. }
  34940. }
  34941. });
  34942. function createLarge(seriesModel, group, incremental) {
  34943. // TODO support polar
  34944. var data = seriesModel.getData();
  34945. var startPoint = [];
  34946. var valueIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  34947. startPoint[1 - valueIdx] = data.getLayout('valueAxisStart');
  34948. var el = new LargePath({
  34949. shape: {points: data.getLayout('largePoints')},
  34950. incremental: !!incremental,
  34951. __startPoint: startPoint,
  34952. __valueIdx: valueIdx
  34953. });
  34954. group.add(el);
  34955. setLargeStyle(el, seriesModel, data);
  34956. }
  34957. function setLargeStyle(el, seriesModel, data) {
  34958. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  34959. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  34960. el.useStyle(itemStyle);
  34961. el.style.fill = null;
  34962. el.style.stroke = borderColor;
  34963. el.style.lineWidth = data.getLayout('barWidth');
  34964. }
  34965. /*
  34966. * Licensed to the Apache Software Foundation (ASF) under one
  34967. * or more contributor license agreements. See the NOTICE file
  34968. * distributed with this work for additional information
  34969. * regarding copyright ownership. The ASF licenses this file
  34970. * to you under the Apache License, Version 2.0 (the
  34971. * "License"); you may not use this file except in compliance
  34972. * with the License. You may obtain a copy of the License at
  34973. *
  34974. * http://www.apache.org/licenses/LICENSE-2.0
  34975. *
  34976. * Unless required by applicable law or agreed to in writing,
  34977. * software distributed under the License is distributed on an
  34978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34979. * KIND, either express or implied. See the License for the
  34980. * specific language governing permissions and limitations
  34981. * under the License.
  34982. */
  34983. // In case developer forget to include grid component
  34984. registerLayout(curry(layout, 'bar'));
  34985. // Should after normal bar layout, otherwise it is blocked by normal bar layout.
  34986. registerLayout(largeLayout);
  34987. registerVisual({
  34988. seriesType: 'bar',
  34989. reset: function (seriesModel) {
  34990. // Visual coding for legend
  34991. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  34992. }
  34993. });
  34994. /*
  34995. * Licensed to the Apache Software Foundation (ASF) under one
  34996. * or more contributor license agreements. See the NOTICE file
  34997. * distributed with this work for additional information
  34998. * regarding copyright ownership. The ASF licenses this file
  34999. * to you under the Apache License, Version 2.0 (the
  35000. * "License"); you may not use this file except in compliance
  35001. * with the License. You may obtain a copy of the License at
  35002. *
  35003. * http://www.apache.org/licenses/LICENSE-2.0
  35004. *
  35005. * Unless required by applicable law or agreed to in writing,
  35006. * software distributed under the License is distributed on an
  35007. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35008. * KIND, either express or implied. See the License for the
  35009. * specific language governing permissions and limitations
  35010. * under the License.
  35011. */
  35012. /**
  35013. * [Usage]:
  35014. * (1)
  35015. * createListSimply(seriesModel, ['value']);
  35016. * (2)
  35017. * createListSimply(seriesModel, {
  35018. * coordDimensions: ['value'],
  35019. * dimensionsCount: 5
  35020. * });
  35021. *
  35022. * @param {module:echarts/model/Series} seriesModel
  35023. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  35024. * The options in opt, see `echarts/data/helper/createDimensions`
  35025. * @param {Array.<string>} [nameList]
  35026. * @return {module:echarts/data/List}
  35027. */
  35028. var createListSimply = function (seriesModel, opt, nameList) {
  35029. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  35030. var source = seriesModel.getSource();
  35031. var dimensionsInfo = createDimensions(source, opt);
  35032. var list = new List(dimensionsInfo, seriesModel);
  35033. list.initData(source, nameList);
  35034. return list;
  35035. };
  35036. /*
  35037. * Licensed to the Apache Software Foundation (ASF) under one
  35038. * or more contributor license agreements. See the NOTICE file
  35039. * distributed with this work for additional information
  35040. * regarding copyright ownership. The ASF licenses this file
  35041. * to you under the Apache License, Version 2.0 (the
  35042. * "License"); you may not use this file except in compliance
  35043. * with the License. You may obtain a copy of the License at
  35044. *
  35045. * http://www.apache.org/licenses/LICENSE-2.0
  35046. *
  35047. * Unless required by applicable law or agreed to in writing,
  35048. * software distributed under the License is distributed on an
  35049. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35050. * KIND, either express or implied. See the License for the
  35051. * specific language governing permissions and limitations
  35052. * under the License.
  35053. */
  35054. /**
  35055. * Data selectable mixin for chart series.
  35056. * To eanble data select, option of series must have `selectedMode`.
  35057. * And each data item will use `selected` to toggle itself selected status
  35058. */
  35059. var dataSelectableMixin = {
  35060. /**
  35061. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  35062. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  35063. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  35064. */
  35065. updateSelectedMap: function (targetList) {
  35066. this._targetList = isArray(targetList) ? targetList.slice() : [];
  35067. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  35068. targetMap.set(target.name, target);
  35069. return targetMap;
  35070. }, createHashMap());
  35071. },
  35072. /**
  35073. * Either name or id should be passed as input here.
  35074. * If both of them are defined, id is used.
  35075. *
  35076. * @param {string|undefined} name name of data
  35077. * @param {number|undefined} id dataIndex of data
  35078. */
  35079. // PENGING If selectedMode is null ?
  35080. select: function (name, id) {
  35081. var target = id != null
  35082. ? this._targetList[id]
  35083. : this._selectTargetMap.get(name);
  35084. var selectedMode = this.get('selectedMode');
  35085. if (selectedMode === 'single') {
  35086. this._selectTargetMap.each(function (target) {
  35087. target.selected = false;
  35088. });
  35089. }
  35090. target && (target.selected = true);
  35091. },
  35092. /**
  35093. * Either name or id should be passed as input here.
  35094. * If both of them are defined, id is used.
  35095. *
  35096. * @param {string|undefined} name name of data
  35097. * @param {number|undefined} id dataIndex of data
  35098. */
  35099. unSelect: function (name, id) {
  35100. var target = id != null
  35101. ? this._targetList[id]
  35102. : this._selectTargetMap.get(name);
  35103. // var selectedMode = this.get('selectedMode');
  35104. // selectedMode !== 'single' && target && (target.selected = false);
  35105. target && (target.selected = false);
  35106. },
  35107. /**
  35108. * Either name or id should be passed as input here.
  35109. * If both of them are defined, id is used.
  35110. *
  35111. * @param {string|undefined} name name of data
  35112. * @param {number|undefined} id dataIndex of data
  35113. */
  35114. toggleSelected: function (name, id) {
  35115. var target = id != null
  35116. ? this._targetList[id]
  35117. : this._selectTargetMap.get(name);
  35118. if (target != null) {
  35119. this[target.selected ? 'unSelect' : 'select'](name, id);
  35120. return target.selected;
  35121. }
  35122. },
  35123. /**
  35124. * Either name or id should be passed as input here.
  35125. * If both of them are defined, id is used.
  35126. *
  35127. * @param {string|undefined} name name of data
  35128. * @param {number|undefined} id dataIndex of data
  35129. */
  35130. isSelected: function (name, id) {
  35131. var target = id != null
  35132. ? this._targetList[id]
  35133. : this._selectTargetMap.get(name);
  35134. return target && target.selected;
  35135. }
  35136. };
  35137. /*
  35138. * Licensed to the Apache Software Foundation (ASF) under one
  35139. * or more contributor license agreements. See the NOTICE file
  35140. * distributed with this work for additional information
  35141. * regarding copyright ownership. The ASF licenses this file
  35142. * to you under the Apache License, Version 2.0 (the
  35143. * "License"); you may not use this file except in compliance
  35144. * with the License. You may obtain a copy of the License at
  35145. *
  35146. * http://www.apache.org/licenses/LICENSE-2.0
  35147. *
  35148. * Unless required by applicable law or agreed to in writing,
  35149. * software distributed under the License is distributed on an
  35150. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35151. * KIND, either express or implied. See the License for the
  35152. * specific language governing permissions and limitations
  35153. * under the License.
  35154. */
  35155. var PieSeries = extendSeriesModel({
  35156. type: 'series.pie',
  35157. // Overwrite
  35158. init: function (option) {
  35159. PieSeries.superApply(this, 'init', arguments);
  35160. // Enable legend selection for each data item
  35161. // Use a function instead of direct access because data reference may changed
  35162. this.legendDataProvider = function () {
  35163. return this.getRawData();
  35164. };
  35165. this.updateSelectedMap(this._createSelectableList());
  35166. this._defaultLabelLine(option);
  35167. },
  35168. // Overwrite
  35169. mergeOption: function (newOption) {
  35170. PieSeries.superCall(this, 'mergeOption', newOption);
  35171. this.updateSelectedMap(this._createSelectableList());
  35172. },
  35173. getInitialData: function (option, ecModel) {
  35174. return createListSimply(this, ['value']);
  35175. },
  35176. _createSelectableList: function () {
  35177. var data = this.getRawData();
  35178. var valueDim = data.mapDimension('value');
  35179. var targetList = [];
  35180. for (var i = 0, len = data.count(); i < len; i++) {
  35181. targetList.push({
  35182. name: data.getName(i),
  35183. value: data.get(valueDim, i),
  35184. selected: retrieveRawAttr(data, i, 'selected')
  35185. });
  35186. }
  35187. return targetList;
  35188. },
  35189. // Overwrite
  35190. getDataParams: function (dataIndex) {
  35191. var data = this.getData();
  35192. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  35193. // FIXME toFixed?
  35194. var valueList = [];
  35195. data.each(data.mapDimension('value'), function (value) {
  35196. valueList.push(value);
  35197. });
  35198. params.percent = getPercentWithPrecision(
  35199. valueList,
  35200. dataIndex,
  35201. data.hostModel.get('percentPrecision')
  35202. );
  35203. params.$vars.push('percent');
  35204. return params;
  35205. },
  35206. _defaultLabelLine: function (option) {
  35207. // Extend labelLine emphasis
  35208. defaultEmphasis(option, 'labelLine', ['show']);
  35209. var labelLineNormalOpt = option.labelLine;
  35210. var labelLineEmphasisOpt = option.emphasis.labelLine;
  35211. // Not show label line if `label.normal.show = false`
  35212. labelLineNormalOpt.show = labelLineNormalOpt.show
  35213. && option.label.show;
  35214. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  35215. && option.emphasis.label.show;
  35216. },
  35217. defaultOption: {
  35218. zlevel: 0,
  35219. z: 2,
  35220. legendHoverLink: true,
  35221. hoverAnimation: true,
  35222. // 默认全局居中
  35223. center: ['50%', '50%'],
  35224. radius: [0, '75%'],
  35225. // 默认顺时针
  35226. clockwise: true,
  35227. startAngle: 90,
  35228. // 最小角度改为0
  35229. minAngle: 0,
  35230. // 选中时扇区偏移量
  35231. selectedOffset: 10,
  35232. // 高亮扇区偏移量
  35233. hoverOffset: 10,
  35234. // If use strategy to avoid label overlapping
  35235. avoidLabelOverlap: true,
  35236. // 选择模式,默认关闭,可选single,multiple
  35237. // selectedMode: false,
  35238. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  35239. // roseType: null,
  35240. percentPrecision: 2,
  35241. // If still show when all data zero.
  35242. stillShowZeroSum: true,
  35243. // cursor: null,
  35244. label: {
  35245. // If rotate around circle
  35246. rotate: false,
  35247. show: true,
  35248. // 'outer', 'inside', 'center'
  35249. position: 'outer'
  35250. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  35251. // 默认使用全局文本样式,详见TEXTSTYLE
  35252. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  35253. },
  35254. // Enabled when label.normal.position is 'outer'
  35255. labelLine: {
  35256. show: true,
  35257. // 引导线两段中的第一段长度
  35258. length: 15,
  35259. // 引导线两段中的第二段长度
  35260. length2: 15,
  35261. smooth: false,
  35262. lineStyle: {
  35263. // color: 各异,
  35264. width: 1,
  35265. type: 'solid'
  35266. }
  35267. },
  35268. itemStyle: {
  35269. borderWidth: 1
  35270. },
  35271. // Animation type canbe expansion, scale
  35272. animationType: 'expansion',
  35273. animationEasing: 'cubicOut'
  35274. }
  35275. });
  35276. mixin(PieSeries, dataSelectableMixin);
  35277. /*
  35278. * Licensed to the Apache Software Foundation (ASF) under one
  35279. * or more contributor license agreements. See the NOTICE file
  35280. * distributed with this work for additional information
  35281. * regarding copyright ownership. The ASF licenses this file
  35282. * to you under the Apache License, Version 2.0 (the
  35283. * "License"); you may not use this file except in compliance
  35284. * with the License. You may obtain a copy of the License at
  35285. *
  35286. * http://www.apache.org/licenses/LICENSE-2.0
  35287. *
  35288. * Unless required by applicable law or agreed to in writing,
  35289. * software distributed under the License is distributed on an
  35290. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35291. * KIND, either express or implied. See the License for the
  35292. * specific language governing permissions and limitations
  35293. * under the License.
  35294. */
  35295. /**
  35296. * @param {module:echarts/model/Series} seriesModel
  35297. * @param {boolean} hasAnimation
  35298. * @inner
  35299. */
  35300. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  35301. var data = seriesModel.getData();
  35302. var dataIndex = this.dataIndex;
  35303. var name = data.getName(dataIndex);
  35304. var selectedOffset = seriesModel.get('selectedOffset');
  35305. api.dispatchAction({
  35306. type: 'pieToggleSelect',
  35307. from: uid,
  35308. name: name,
  35309. seriesId: seriesModel.id
  35310. });
  35311. data.each(function (idx) {
  35312. toggleItemSelected(
  35313. data.getItemGraphicEl(idx),
  35314. data.getItemLayout(idx),
  35315. seriesModel.isSelected(data.getName(idx)),
  35316. selectedOffset,
  35317. hasAnimation
  35318. );
  35319. });
  35320. }
  35321. /**
  35322. * @param {module:zrender/graphic/Sector} el
  35323. * @param {Object} layout
  35324. * @param {boolean} isSelected
  35325. * @param {number} selectedOffset
  35326. * @param {boolean} hasAnimation
  35327. * @inner
  35328. */
  35329. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  35330. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  35331. var dx = Math.cos(midAngle);
  35332. var dy = Math.sin(midAngle);
  35333. var offset = isSelected ? selectedOffset : 0;
  35334. var position = [dx * offset, dy * offset];
  35335. hasAnimation
  35336. // animateTo will stop revious animation like update transition
  35337. ? el.animate()
  35338. .when(200, {
  35339. position: position
  35340. })
  35341. .start('bounceOut')
  35342. : el.attr('position', position);
  35343. }
  35344. /**
  35345. * Piece of pie including Sector, Label, LabelLine
  35346. * @constructor
  35347. * @extends {module:zrender/graphic/Group}
  35348. */
  35349. function PiePiece(data, idx) {
  35350. Group.call(this);
  35351. var sector = new Sector({
  35352. z2: 2
  35353. });
  35354. var polyline = new Polyline();
  35355. var text = new Text();
  35356. this.add(sector);
  35357. this.add(polyline);
  35358. this.add(text);
  35359. this.updateData(data, idx, true);
  35360. // Hover to change label and labelLine
  35361. function onEmphasis() {
  35362. polyline.ignore = polyline.hoverIgnore;
  35363. text.ignore = text.hoverIgnore;
  35364. }
  35365. function onNormal() {
  35366. polyline.ignore = polyline.normalIgnore;
  35367. text.ignore = text.normalIgnore;
  35368. }
  35369. this.on('emphasis', onEmphasis)
  35370. .on('normal', onNormal)
  35371. .on('mouseover', onEmphasis)
  35372. .on('mouseout', onNormal);
  35373. }
  35374. var piePieceProto = PiePiece.prototype;
  35375. piePieceProto.updateData = function (data, idx, firstCreate) {
  35376. var sector = this.childAt(0);
  35377. var seriesModel = data.hostModel;
  35378. var itemModel = data.getItemModel(idx);
  35379. var layout = data.getItemLayout(idx);
  35380. var sectorShape = extend({}, layout);
  35381. sectorShape.label = null;
  35382. if (firstCreate) {
  35383. sector.setShape(sectorShape);
  35384. var animationType = seriesModel.getShallow('animationType');
  35385. if (animationType === 'scale') {
  35386. sector.shape.r = layout.r0;
  35387. initProps(sector, {
  35388. shape: {
  35389. r: layout.r
  35390. }
  35391. }, seriesModel, idx);
  35392. }
  35393. // Expansion
  35394. else {
  35395. sector.shape.endAngle = layout.startAngle;
  35396. updateProps(sector, {
  35397. shape: {
  35398. endAngle: layout.endAngle
  35399. }
  35400. }, seriesModel, idx);
  35401. }
  35402. }
  35403. else {
  35404. updateProps(sector, {
  35405. shape: sectorShape
  35406. }, seriesModel, idx);
  35407. }
  35408. // Update common style
  35409. var visualColor = data.getItemVisual(idx, 'color');
  35410. sector.useStyle(
  35411. defaults(
  35412. {
  35413. lineJoin: 'bevel',
  35414. fill: visualColor
  35415. },
  35416. itemModel.getModel('itemStyle').getItemStyle()
  35417. )
  35418. );
  35419. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  35420. var cursorStyle = itemModel.getShallow('cursor');
  35421. cursorStyle && sector.attr('cursor', cursorStyle);
  35422. // Toggle selected
  35423. toggleItemSelected(
  35424. this,
  35425. data.getItemLayout(idx),
  35426. seriesModel.isSelected(null, idx),
  35427. seriesModel.get('selectedOffset'),
  35428. seriesModel.get('animation')
  35429. );
  35430. function onEmphasis() {
  35431. // Sector may has animation of updating data. Force to move to the last frame
  35432. // Or it may stopped on the wrong shape
  35433. sector.stopAnimation(true);
  35434. sector.animateTo({
  35435. shape: {
  35436. r: layout.r + seriesModel.get('hoverOffset')
  35437. }
  35438. }, 300, 'elasticOut');
  35439. }
  35440. function onNormal() {
  35441. sector.stopAnimation(true);
  35442. sector.animateTo({
  35443. shape: {
  35444. r: layout.r
  35445. }
  35446. }, 300, 'elasticOut');
  35447. }
  35448. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  35449. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  35450. sector
  35451. .on('mouseover', onEmphasis)
  35452. .on('mouseout', onNormal)
  35453. .on('emphasis', onEmphasis)
  35454. .on('normal', onNormal);
  35455. }
  35456. this._updateLabel(data, idx);
  35457. setHoverStyle(this);
  35458. };
  35459. piePieceProto._updateLabel = function (data, idx) {
  35460. var labelLine = this.childAt(1);
  35461. var labelText = this.childAt(2);
  35462. var seriesModel = data.hostModel;
  35463. var itemModel = data.getItemModel(idx);
  35464. var layout = data.getItemLayout(idx);
  35465. var labelLayout = layout.label;
  35466. var visualColor = data.getItemVisual(idx, 'color');
  35467. updateProps(labelLine, {
  35468. shape: {
  35469. points: labelLayout.linePoints || [
  35470. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  35471. ]
  35472. }
  35473. }, seriesModel, idx);
  35474. updateProps(labelText, {
  35475. style: {
  35476. x: labelLayout.x,
  35477. y: labelLayout.y
  35478. }
  35479. }, seriesModel, idx);
  35480. labelText.attr({
  35481. rotation: labelLayout.rotation,
  35482. origin: [labelLayout.x, labelLayout.y],
  35483. z2: 10
  35484. });
  35485. var labelModel = itemModel.getModel('label');
  35486. var labelHoverModel = itemModel.getModel('emphasis.label');
  35487. var labelLineModel = itemModel.getModel('labelLine');
  35488. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  35489. var visualColor = data.getItemVisual(idx, 'color');
  35490. setLabelStyle(
  35491. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  35492. {
  35493. labelFetcher: data.hostModel,
  35494. labelDataIndex: idx,
  35495. defaultText: data.getName(idx),
  35496. autoColor: visualColor,
  35497. useInsideStyle: !!labelLayout.inside
  35498. },
  35499. {
  35500. textAlign: labelLayout.textAlign,
  35501. textVerticalAlign: labelLayout.verticalAlign,
  35502. opacity: data.getItemVisual(idx, 'opacity')
  35503. }
  35504. );
  35505. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  35506. labelText.hoverIgnore = !labelHoverModel.get('show');
  35507. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  35508. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  35509. // Default use item visual color
  35510. labelLine.setStyle({
  35511. stroke: visualColor,
  35512. opacity: data.getItemVisual(idx, 'opacity')
  35513. });
  35514. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  35515. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  35516. var smooth = labelLineModel.get('smooth');
  35517. if (smooth && smooth === true) {
  35518. smooth = 0.4;
  35519. }
  35520. labelLine.setShape({
  35521. smooth: smooth
  35522. });
  35523. };
  35524. inherits(PiePiece, Group);
  35525. // Pie view
  35526. var PieView = Chart.extend({
  35527. type: 'pie',
  35528. init: function () {
  35529. var sectorGroup = new Group();
  35530. this._sectorGroup = sectorGroup;
  35531. },
  35532. render: function (seriesModel, ecModel, api, payload) {
  35533. if (payload && (payload.from === this.uid)) {
  35534. return;
  35535. }
  35536. var data = seriesModel.getData();
  35537. var oldData = this._data;
  35538. var group = this.group;
  35539. var hasAnimation = ecModel.get('animation');
  35540. var isFirstRender = !oldData;
  35541. var animationType = seriesModel.get('animationType');
  35542. var onSectorClick = curry(
  35543. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  35544. );
  35545. var selectedMode = seriesModel.get('selectedMode');
  35546. data.diff(oldData)
  35547. .add(function (idx) {
  35548. var piePiece = new PiePiece(data, idx);
  35549. // Default expansion animation
  35550. if (isFirstRender && animationType !== 'scale') {
  35551. piePiece.eachChild(function (child) {
  35552. child.stopAnimation(true);
  35553. });
  35554. }
  35555. selectedMode && piePiece.on('click', onSectorClick);
  35556. data.setItemGraphicEl(idx, piePiece);
  35557. group.add(piePiece);
  35558. })
  35559. .update(function (newIdx, oldIdx) {
  35560. var piePiece = oldData.getItemGraphicEl(oldIdx);
  35561. piePiece.updateData(data, newIdx);
  35562. piePiece.off('click');
  35563. selectedMode && piePiece.on('click', onSectorClick);
  35564. group.add(piePiece);
  35565. data.setItemGraphicEl(newIdx, piePiece);
  35566. })
  35567. .remove(function (idx) {
  35568. var piePiece = oldData.getItemGraphicEl(idx);
  35569. group.remove(piePiece);
  35570. })
  35571. .execute();
  35572. if (
  35573. hasAnimation && isFirstRender && data.count() > 0
  35574. // Default expansion animation
  35575. && animationType !== 'scale'
  35576. ) {
  35577. var shape = data.getItemLayout(0);
  35578. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  35579. var removeClipPath = bind(group.removeClipPath, group);
  35580. group.setClipPath(this._createClipPath(
  35581. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  35582. ));
  35583. }
  35584. else {
  35585. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  35586. group.removeClipPath();
  35587. }
  35588. this._data = data;
  35589. },
  35590. dispose: function () {},
  35591. _createClipPath: function (
  35592. cx, cy, r, startAngle, clockwise, cb, seriesModel
  35593. ) {
  35594. var clipPath = new Sector({
  35595. shape: {
  35596. cx: cx,
  35597. cy: cy,
  35598. r0: 0,
  35599. r: r,
  35600. startAngle: startAngle,
  35601. endAngle: startAngle,
  35602. clockwise: clockwise
  35603. }
  35604. });
  35605. initProps(clipPath, {
  35606. shape: {
  35607. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  35608. }
  35609. }, seriesModel, cb);
  35610. return clipPath;
  35611. },
  35612. /**
  35613. * @implement
  35614. */
  35615. containPoint: function (point, seriesModel) {
  35616. var data = seriesModel.getData();
  35617. var itemLayout = data.getItemLayout(0);
  35618. if (itemLayout) {
  35619. var dx = point[0] - itemLayout.cx;
  35620. var dy = point[1] - itemLayout.cy;
  35621. var radius = Math.sqrt(dx * dx + dy * dy);
  35622. return radius <= itemLayout.r && radius >= itemLayout.r0;
  35623. }
  35624. }
  35625. });
  35626. /*
  35627. * Licensed to the Apache Software Foundation (ASF) under one
  35628. * or more contributor license agreements. See the NOTICE file
  35629. * distributed with this work for additional information
  35630. * regarding copyright ownership. The ASF licenses this file
  35631. * to you under the Apache License, Version 2.0 (the
  35632. * "License"); you may not use this file except in compliance
  35633. * with the License. You may obtain a copy of the License at
  35634. *
  35635. * http://www.apache.org/licenses/LICENSE-2.0
  35636. *
  35637. * Unless required by applicable law or agreed to in writing,
  35638. * software distributed under the License is distributed on an
  35639. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35640. * KIND, either express or implied. See the License for the
  35641. * specific language governing permissions and limitations
  35642. * under the License.
  35643. */
  35644. var createDataSelectAction = function (seriesType, actionInfos) {
  35645. each$1(actionInfos, function (actionInfo) {
  35646. actionInfo.update = 'updateView';
  35647. /**
  35648. * @payload
  35649. * @property {string} seriesName
  35650. * @property {string} name
  35651. */
  35652. registerAction(actionInfo, function (payload, ecModel) {
  35653. var selected = {};
  35654. ecModel.eachComponent(
  35655. {mainType: 'series', subType: seriesType, query: payload},
  35656. function (seriesModel) {
  35657. if (seriesModel[actionInfo.method]) {
  35658. seriesModel[actionInfo.method](
  35659. payload.name,
  35660. payload.dataIndex
  35661. );
  35662. }
  35663. var data = seriesModel.getData();
  35664. // Create selected map
  35665. data.each(function (idx) {
  35666. var name = data.getName(idx);
  35667. selected[name] = seriesModel.isSelected(name)
  35668. || false;
  35669. });
  35670. }
  35671. );
  35672. return {
  35673. name: payload.name,
  35674. selected: selected
  35675. };
  35676. });
  35677. });
  35678. };
  35679. /*
  35680. * Licensed to the Apache Software Foundation (ASF) under one
  35681. * or more contributor license agreements. See the NOTICE file
  35682. * distributed with this work for additional information
  35683. * regarding copyright ownership. The ASF licenses this file
  35684. * to you under the Apache License, Version 2.0 (the
  35685. * "License"); you may not use this file except in compliance
  35686. * with the License. You may obtain a copy of the License at
  35687. *
  35688. * http://www.apache.org/licenses/LICENSE-2.0
  35689. *
  35690. * Unless required by applicable law or agreed to in writing,
  35691. * software distributed under the License is distributed on an
  35692. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35693. * KIND, either express or implied. See the License for the
  35694. * specific language governing permissions and limitations
  35695. * under the License.
  35696. */
  35697. // Pick color from palette for each data item.
  35698. // Applicable for charts that require applying color palette
  35699. // in data level (like pie, funnel, chord).
  35700. var dataColor = function (seriesType) {
  35701. return {
  35702. getTargetSeries: function (ecModel) {
  35703. // Pie and funnel may use diferrent scope
  35704. var paletteScope = {};
  35705. var seiresModelMap = createHashMap();
  35706. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35707. seriesModel.__paletteScope = paletteScope;
  35708. seiresModelMap.set(seriesModel.uid, seriesModel);
  35709. });
  35710. return seiresModelMap;
  35711. },
  35712. reset: function (seriesModel, ecModel) {
  35713. var dataAll = seriesModel.getRawData();
  35714. var idxMap = {};
  35715. var data = seriesModel.getData();
  35716. data.each(function (idx) {
  35717. var rawIdx = data.getRawIndex(idx);
  35718. idxMap[rawIdx] = idx;
  35719. });
  35720. dataAll.each(function (rawIdx) {
  35721. var filteredIdx = idxMap[rawIdx];
  35722. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  35723. var singleDataColor = filteredIdx != null
  35724. && data.getItemVisual(filteredIdx, 'color', true);
  35725. if (!singleDataColor) {
  35726. // FIXME Performance
  35727. var itemModel = dataAll.getItemModel(rawIdx);
  35728. var color = itemModel.get('itemStyle.color')
  35729. || seriesModel.getColorFromPalette(
  35730. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  35731. dataAll.count()
  35732. );
  35733. // Legend may use the visual info in data before processed
  35734. dataAll.setItemVisual(rawIdx, 'color', color);
  35735. // Data is not filtered
  35736. if (filteredIdx != null) {
  35737. data.setItemVisual(filteredIdx, 'color', color);
  35738. }
  35739. }
  35740. else {
  35741. // Set data all color for legend
  35742. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  35743. }
  35744. });
  35745. }
  35746. };
  35747. };
  35748. /*
  35749. * Licensed to the Apache Software Foundation (ASF) under one
  35750. * or more contributor license agreements. See the NOTICE file
  35751. * distributed with this work for additional information
  35752. * regarding copyright ownership. The ASF licenses this file
  35753. * to you under the Apache License, Version 2.0 (the
  35754. * "License"); you may not use this file except in compliance
  35755. * with the License. You may obtain a copy of the License at
  35756. *
  35757. * http://www.apache.org/licenses/LICENSE-2.0
  35758. *
  35759. * Unless required by applicable law or agreed to in writing,
  35760. * software distributed under the License is distributed on an
  35761. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35762. * KIND, either express or implied. See the License for the
  35763. * specific language governing permissions and limitations
  35764. * under the License.
  35765. */
  35766. // FIXME emphasis label position is not same with normal label position
  35767. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  35768. list.sort(function (a, b) {
  35769. return a.y - b.y;
  35770. });
  35771. function shiftDown(start, end, delta, dir) {
  35772. for (var j = start; j < end; j++) {
  35773. list[j].y += delta;
  35774. if (j > start
  35775. && j + 1 < end
  35776. && list[j + 1].y > list[j].y + list[j].height
  35777. ) {
  35778. shiftUp(j, delta / 2);
  35779. return;
  35780. }
  35781. }
  35782. shiftUp(end - 1, delta / 2);
  35783. }
  35784. function shiftUp(end, delta) {
  35785. for (var j = end; j >= 0; j--) {
  35786. list[j].y -= delta;
  35787. if (j > 0
  35788. && list[j].y > list[j - 1].y + list[j - 1].height
  35789. ) {
  35790. break;
  35791. }
  35792. }
  35793. }
  35794. function changeX(list, isDownList, cx, cy, r, dir) {
  35795. var lastDeltaX = dir > 0
  35796. ? isDownList // right-side
  35797. ? Number.MAX_VALUE // down
  35798. : 0 // up
  35799. : isDownList // left-side
  35800. ? Number.MAX_VALUE // down
  35801. : 0; // up
  35802. for (var i = 0, l = list.length; i < l; i++) {
  35803. var deltaY = Math.abs(list[i].y - cy);
  35804. var length = list[i].len;
  35805. var length2 = list[i].len2;
  35806. var deltaX = (deltaY < r + length)
  35807. ? Math.sqrt(
  35808. (r + length + length2) * (r + length + length2)
  35809. - deltaY * deltaY
  35810. )
  35811. : Math.abs(list[i].x - cx);
  35812. if (isDownList && deltaX >= lastDeltaX) {
  35813. // right-down, left-down
  35814. deltaX = lastDeltaX - 10;
  35815. }
  35816. if (!isDownList && deltaX <= lastDeltaX) {
  35817. // right-up, left-up
  35818. deltaX = lastDeltaX + 10;
  35819. }
  35820. list[i].x = cx + deltaX * dir;
  35821. lastDeltaX = deltaX;
  35822. }
  35823. }
  35824. var lastY = 0;
  35825. var delta;
  35826. var len = list.length;
  35827. var upList = [];
  35828. var downList = [];
  35829. for (var i = 0; i < len; i++) {
  35830. delta = list[i].y - lastY;
  35831. if (delta < 0) {
  35832. shiftDown(i, len, -delta, dir);
  35833. }
  35834. lastY = list[i].y + list[i].height;
  35835. }
  35836. if (viewHeight - lastY < 0) {
  35837. shiftUp(len - 1, lastY - viewHeight);
  35838. }
  35839. for (var i = 0; i < len; i++) {
  35840. if (list[i].y >= cy) {
  35841. downList.push(list[i]);
  35842. }
  35843. else {
  35844. upList.push(list[i]);
  35845. }
  35846. }
  35847. changeX(upList, false, cx, cy, r, dir);
  35848. changeX(downList, true, cx, cy, r, dir);
  35849. }
  35850. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  35851. var leftList = [];
  35852. var rightList = [];
  35853. for (var i = 0; i < labelLayoutList.length; i++) {
  35854. if (isPositionCenter(labelLayoutList[i])) {
  35855. continue;
  35856. }
  35857. if (labelLayoutList[i].x < cx) {
  35858. leftList.push(labelLayoutList[i]);
  35859. }
  35860. else {
  35861. rightList.push(labelLayoutList[i]);
  35862. }
  35863. }
  35864. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  35865. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  35866. for (var i = 0; i < labelLayoutList.length; i++) {
  35867. if (isPositionCenter(labelLayoutList[i])) {
  35868. continue;
  35869. }
  35870. var linePoints = labelLayoutList[i].linePoints;
  35871. if (linePoints) {
  35872. var dist = linePoints[1][0] - linePoints[2][0];
  35873. if (labelLayoutList[i].x < cx) {
  35874. linePoints[2][0] = labelLayoutList[i].x + 3;
  35875. }
  35876. else {
  35877. linePoints[2][0] = labelLayoutList[i].x - 3;
  35878. }
  35879. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  35880. linePoints[1][0] = linePoints[2][0] + dist;
  35881. }
  35882. }
  35883. }
  35884. function isPositionCenter(layout) {
  35885. // Not change x for center label
  35886. return layout.position === 'center';
  35887. }
  35888. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  35889. var data = seriesModel.getData();
  35890. var labelLayoutList = [];
  35891. var cx;
  35892. var cy;
  35893. var hasLabelRotate = false;
  35894. data.each(function (idx) {
  35895. var layout = data.getItemLayout(idx);
  35896. var itemModel = data.getItemModel(idx);
  35897. var labelModel = itemModel.getModel('label');
  35898. // Use position in normal or emphasis
  35899. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  35900. var labelLineModel = itemModel.getModel('labelLine');
  35901. var labelLineLen = labelLineModel.get('length');
  35902. var labelLineLen2 = labelLineModel.get('length2');
  35903. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  35904. var dx = Math.cos(midAngle);
  35905. var dy = Math.sin(midAngle);
  35906. var textX;
  35907. var textY;
  35908. var linePoints;
  35909. var textAlign;
  35910. cx = layout.cx;
  35911. cy = layout.cy;
  35912. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  35913. if (labelPosition === 'center') {
  35914. textX = layout.cx;
  35915. textY = layout.cy;
  35916. textAlign = 'center';
  35917. }
  35918. else {
  35919. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  35920. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  35921. textX = x1 + dx * 3;
  35922. textY = y1 + dy * 3;
  35923. if (!isLabelInside) {
  35924. // For roseType
  35925. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  35926. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  35927. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  35928. var y3 = y2;
  35929. textX = x3 + (dx < 0 ? -5 : 5);
  35930. textY = y3;
  35931. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  35932. }
  35933. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  35934. }
  35935. var font = labelModel.getFont();
  35936. var labelRotate = labelModel.get('rotate')
  35937. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  35938. var text = seriesModel.getFormattedLabel(idx, 'normal')
  35939. || data.getName(idx);
  35940. var textRect = getBoundingRect(
  35941. text, font, textAlign, 'top'
  35942. );
  35943. hasLabelRotate = !!labelRotate;
  35944. layout.label = {
  35945. x: textX,
  35946. y: textY,
  35947. position: labelPosition,
  35948. height: textRect.height,
  35949. len: labelLineLen,
  35950. len2: labelLineLen2,
  35951. linePoints: linePoints,
  35952. textAlign: textAlign,
  35953. verticalAlign: 'middle',
  35954. rotation: labelRotate,
  35955. inside: isLabelInside
  35956. };
  35957. // Not layout the inside label
  35958. if (!isLabelInside) {
  35959. labelLayoutList.push(layout.label);
  35960. }
  35961. });
  35962. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  35963. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  35964. }
  35965. };
  35966. /*
  35967. * Licensed to the Apache Software Foundation (ASF) under one
  35968. * or more contributor license agreements. See the NOTICE file
  35969. * distributed with this work for additional information
  35970. * regarding copyright ownership. The ASF licenses this file
  35971. * to you under the Apache License, Version 2.0 (the
  35972. * "License"); you may not use this file except in compliance
  35973. * with the License. You may obtain a copy of the License at
  35974. *
  35975. * http://www.apache.org/licenses/LICENSE-2.0
  35976. *
  35977. * Unless required by applicable law or agreed to in writing,
  35978. * software distributed under the License is distributed on an
  35979. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35980. * KIND, either express or implied. See the License for the
  35981. * specific language governing permissions and limitations
  35982. * under the License.
  35983. */
  35984. var PI2$4 = Math.PI * 2;
  35985. var RADIAN = Math.PI / 180;
  35986. var pieLayout = function (seriesType, ecModel, api, payload) {
  35987. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35988. var data = seriesModel.getData();
  35989. var valueDim = data.mapDimension('value');
  35990. var center = seriesModel.get('center');
  35991. var radius = seriesModel.get('radius');
  35992. if (!isArray(radius)) {
  35993. radius = [0, radius];
  35994. }
  35995. if (!isArray(center)) {
  35996. center = [center, center];
  35997. }
  35998. var width = api.getWidth();
  35999. var height = api.getHeight();
  36000. var size = Math.min(width, height);
  36001. var cx = parsePercent$1(center[0], width);
  36002. var cy = parsePercent$1(center[1], height);
  36003. var r0 = parsePercent$1(radius[0], size / 2);
  36004. var r = parsePercent$1(radius[1], size / 2);
  36005. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  36006. var minAngle = seriesModel.get('minAngle') * RADIAN;
  36007. var validDataCount = 0;
  36008. data.each(valueDim, function (value) {
  36009. !isNaN(value) && validDataCount++;
  36010. });
  36011. var sum = data.getSum(valueDim);
  36012. // Sum may be 0
  36013. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  36014. var clockwise = seriesModel.get('clockwise');
  36015. var roseType = seriesModel.get('roseType');
  36016. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  36017. // [0...max]
  36018. var extent = data.getDataExtent(valueDim);
  36019. extent[0] = 0;
  36020. // In the case some sector angle is smaller than minAngle
  36021. var restAngle = PI2$4;
  36022. var valueSumLargerThanMinAngle = 0;
  36023. var currentAngle = startAngle;
  36024. var dir = clockwise ? 1 : -1;
  36025. data.each(valueDim, function (value, idx) {
  36026. var angle;
  36027. if (isNaN(value)) {
  36028. data.setItemLayout(idx, {
  36029. angle: NaN,
  36030. startAngle: NaN,
  36031. endAngle: NaN,
  36032. clockwise: clockwise,
  36033. cx: cx,
  36034. cy: cy,
  36035. r0: r0,
  36036. r: roseType
  36037. ? NaN
  36038. : r
  36039. });
  36040. return;
  36041. }
  36042. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  36043. if (roseType !== 'area') {
  36044. angle = (sum === 0 && stillShowZeroSum)
  36045. ? unitRadian : (value * unitRadian);
  36046. }
  36047. else {
  36048. angle = PI2$4 / validDataCount;
  36049. }
  36050. if (angle < minAngle) {
  36051. angle = minAngle;
  36052. restAngle -= minAngle;
  36053. }
  36054. else {
  36055. valueSumLargerThanMinAngle += value;
  36056. }
  36057. var endAngle = currentAngle + dir * angle;
  36058. data.setItemLayout(idx, {
  36059. angle: angle,
  36060. startAngle: currentAngle,
  36061. endAngle: endAngle,
  36062. clockwise: clockwise,
  36063. cx: cx,
  36064. cy: cy,
  36065. r0: r0,
  36066. r: roseType
  36067. ? linearMap(value, extent, [r0, r])
  36068. : r
  36069. });
  36070. currentAngle = endAngle;
  36071. });
  36072. // Some sector is constrained by minAngle
  36073. // Rest sectors needs recalculate angle
  36074. if (restAngle < PI2$4 && validDataCount) {
  36075. // Average the angle if rest angle is not enough after all angles is
  36076. // Constrained by minAngle
  36077. if (restAngle <= 1e-3) {
  36078. var angle = PI2$4 / validDataCount;
  36079. data.each(valueDim, function (value, idx) {
  36080. if (!isNaN(value)) {
  36081. var layout = data.getItemLayout(idx);
  36082. layout.angle = angle;
  36083. layout.startAngle = startAngle + dir * idx * angle;
  36084. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  36085. }
  36086. });
  36087. }
  36088. else {
  36089. unitRadian = restAngle / valueSumLargerThanMinAngle;
  36090. currentAngle = startAngle;
  36091. data.each(valueDim, function (value, idx) {
  36092. if (!isNaN(value)) {
  36093. var layout = data.getItemLayout(idx);
  36094. var angle = layout.angle === minAngle
  36095. ? minAngle : value * unitRadian;
  36096. layout.startAngle = currentAngle;
  36097. layout.endAngle = currentAngle + dir * angle;
  36098. currentAngle += dir * angle;
  36099. }
  36100. });
  36101. }
  36102. }
  36103. labelLayout(seriesModel, r, width, height);
  36104. });
  36105. };
  36106. /*
  36107. * Licensed to the Apache Software Foundation (ASF) under one
  36108. * or more contributor license agreements. See the NOTICE file
  36109. * distributed with this work for additional information
  36110. * regarding copyright ownership. The ASF licenses this file
  36111. * to you under the Apache License, Version 2.0 (the
  36112. * "License"); you may not use this file except in compliance
  36113. * with the License. You may obtain a copy of the License at
  36114. *
  36115. * http://www.apache.org/licenses/LICENSE-2.0
  36116. *
  36117. * Unless required by applicable law or agreed to in writing,
  36118. * software distributed under the License is distributed on an
  36119. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36120. * KIND, either express or implied. See the License for the
  36121. * specific language governing permissions and limitations
  36122. * under the License.
  36123. */
  36124. var dataFilter = function (seriesType) {
  36125. return {
  36126. seriesType: seriesType,
  36127. reset: function (seriesModel, ecModel) {
  36128. var legendModels = ecModel.findComponents({
  36129. mainType: 'legend'
  36130. });
  36131. if (!legendModels || !legendModels.length) {
  36132. return;
  36133. }
  36134. var data = seriesModel.getData();
  36135. data.filterSelf(function (idx) {
  36136. var name = data.getName(idx);
  36137. // If in any legend component the status is not selected.
  36138. for (var i = 0; i < legendModels.length; i++) {
  36139. if (!legendModels[i].isSelected(name)) {
  36140. return false;
  36141. }
  36142. }
  36143. return true;
  36144. });
  36145. }
  36146. };
  36147. };
  36148. /*
  36149. * Licensed to the Apache Software Foundation (ASF) under one
  36150. * or more contributor license agreements. See the NOTICE file
  36151. * distributed with this work for additional information
  36152. * regarding copyright ownership. The ASF licenses this file
  36153. * to you under the Apache License, Version 2.0 (the
  36154. * "License"); you may not use this file except in compliance
  36155. * with the License. You may obtain a copy of the License at
  36156. *
  36157. * http://www.apache.org/licenses/LICENSE-2.0
  36158. *
  36159. * Unless required by applicable law or agreed to in writing,
  36160. * software distributed under the License is distributed on an
  36161. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36162. * KIND, either express or implied. See the License for the
  36163. * specific language governing permissions and limitations
  36164. * under the License.
  36165. */
  36166. createDataSelectAction('pie', [{
  36167. type: 'pieToggleSelect',
  36168. event: 'pieselectchanged',
  36169. method: 'toggleSelected'
  36170. }, {
  36171. type: 'pieSelect',
  36172. event: 'pieselected',
  36173. method: 'select'
  36174. }, {
  36175. type: 'pieUnSelect',
  36176. event: 'pieunselected',
  36177. method: 'unSelect'
  36178. }]);
  36179. registerVisual(dataColor('pie'));
  36180. registerLayout(curry(pieLayout, 'pie'));
  36181. registerProcessor(dataFilter('pie'));
  36182. /*
  36183. * Licensed to the Apache Software Foundation (ASF) under one
  36184. * or more contributor license agreements. See the NOTICE file
  36185. * distributed with this work for additional information
  36186. * regarding copyright ownership. The ASF licenses this file
  36187. * to you under the Apache License, Version 2.0 (the
  36188. * "License"); you may not use this file except in compliance
  36189. * with the License. You may obtain a copy of the License at
  36190. *
  36191. * http://www.apache.org/licenses/LICENSE-2.0
  36192. *
  36193. * Unless required by applicable law or agreed to in writing,
  36194. * software distributed under the License is distributed on an
  36195. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36196. * KIND, either express or implied. See the License for the
  36197. * specific language governing permissions and limitations
  36198. * under the License.
  36199. */
  36200. exports.version = version;
  36201. exports.dependencies = dependencies;
  36202. exports.PRIORITY = PRIORITY;
  36203. exports.init = init;
  36204. exports.connect = connect;
  36205. exports.disConnect = disConnect;
  36206. exports.disconnect = disconnect;
  36207. exports.dispose = dispose;
  36208. exports.getInstanceByDom = getInstanceByDom;
  36209. exports.getInstanceById = getInstanceById;
  36210. exports.registerTheme = registerTheme;
  36211. exports.registerPreprocessor = registerPreprocessor;
  36212. exports.registerProcessor = registerProcessor;
  36213. exports.registerPostUpdate = registerPostUpdate;
  36214. exports.registerAction = registerAction;
  36215. exports.registerCoordinateSystem = registerCoordinateSystem;
  36216. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  36217. exports.registerLayout = registerLayout;
  36218. exports.registerVisual = registerVisual;
  36219. exports.registerLoading = registerLoading;
  36220. exports.extendComponentModel = extendComponentModel;
  36221. exports.extendComponentView = extendComponentView;
  36222. exports.extendSeriesModel = extendSeriesModel;
  36223. exports.extendChartView = extendChartView;
  36224. exports.setCanvasCreator = setCanvasCreator;
  36225. exports.registerMap = registerMap;
  36226. exports.getMap = getMap;
  36227. exports.dataTool = dataTool;
  36228. })));