echarts.common.js 1.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149
  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. function find(obj, cb, context) {
  567. if (!(obj && cb)) {
  568. return;
  569. }
  570. for (var i = 0, len = obj.length; i < len; i++) {
  571. if (cb.call(context, obj[i], i, obj)) {
  572. return obj[i];
  573. }
  574. }
  575. }
  576. /**
  577. * @memberOf module:zrender/core/util
  578. * @param {Function} func
  579. * @param {*} context
  580. * @return {Function}
  581. */
  582. function bind(func, context) {
  583. var args = nativeSlice.call(arguments, 2);
  584. return function () {
  585. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  586. };
  587. }
  588. /**
  589. * @memberOf module:zrender/core/util
  590. * @param {Function} func
  591. * @return {Function}
  592. */
  593. function curry(func) {
  594. var args = nativeSlice.call(arguments, 1);
  595. return function () {
  596. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  597. };
  598. }
  599. /**
  600. * @memberOf module:zrender/core/util
  601. * @param {*} value
  602. * @return {boolean}
  603. */
  604. function isArray(value) {
  605. return objToString.call(value) === '[object Array]';
  606. }
  607. /**
  608. * @memberOf module:zrender/core/util
  609. * @param {*} value
  610. * @return {boolean}
  611. */
  612. function isFunction$1(value) {
  613. return typeof value === 'function';
  614. }
  615. /**
  616. * @memberOf module:zrender/core/util
  617. * @param {*} value
  618. * @return {boolean}
  619. */
  620. function isString(value) {
  621. return objToString.call(value) === '[object String]';
  622. }
  623. /**
  624. * @memberOf module:zrender/core/util
  625. * @param {*} value
  626. * @return {boolean}
  627. */
  628. function isObject$1(value) {
  629. // Avoid a V8 JIT bug in Chrome 19-20.
  630. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  631. var type = typeof value;
  632. return type === 'function' || (!!value && type === 'object');
  633. }
  634. /**
  635. * @memberOf module:zrender/core/util
  636. * @param {*} value
  637. * @return {boolean}
  638. */
  639. function isBuiltInObject(value) {
  640. return !!BUILTIN_OBJECT[objToString.call(value)];
  641. }
  642. /**
  643. * @memberOf module:zrender/core/util
  644. * @param {*} value
  645. * @return {boolean}
  646. */
  647. function isTypedArray(value) {
  648. return !!TYPED_ARRAY[objToString.call(value)];
  649. }
  650. /**
  651. * @memberOf module:zrender/core/util
  652. * @param {*} value
  653. * @return {boolean}
  654. */
  655. function isDom(value) {
  656. return typeof value === 'object'
  657. && typeof value.nodeType === 'number'
  658. && typeof value.ownerDocument === 'object';
  659. }
  660. /**
  661. * Whether is exactly NaN. Notice isNaN('a') returns true.
  662. * @param {*} value
  663. * @return {boolean}
  664. */
  665. function eqNaN(value) {
  666. return value !== value;
  667. }
  668. /**
  669. * If value1 is not null, then return value1, otherwise judget rest of values.
  670. * Low performance.
  671. * @memberOf module:zrender/core/util
  672. * @return {*} Final value
  673. */
  674. function retrieve(values) {
  675. for (var i = 0, len = arguments.length; i < len; i++) {
  676. if (arguments[i] != null) {
  677. return arguments[i];
  678. }
  679. }
  680. }
  681. function retrieve2(value0, value1) {
  682. return value0 != null
  683. ? value0
  684. : value1;
  685. }
  686. function retrieve3(value0, value1, value2) {
  687. return value0 != null
  688. ? value0
  689. : value1 != null
  690. ? value1
  691. : value2;
  692. }
  693. /**
  694. * @memberOf module:zrender/core/util
  695. * @param {Array} arr
  696. * @param {number} startIndex
  697. * @param {number} endIndex
  698. * @return {Array}
  699. */
  700. function slice() {
  701. return Function.call.apply(nativeSlice, arguments);
  702. }
  703. /**
  704. * Normalize css liked array configuration
  705. * e.g.
  706. * 3 => [3, 3, 3, 3]
  707. * [4, 2] => [4, 2, 4, 2]
  708. * [4, 3, 2] => [4, 3, 2, 3]
  709. * @param {number|Array.<number>} val
  710. * @return {Array.<number>}
  711. */
  712. function normalizeCssArray(val) {
  713. if (typeof (val) === 'number') {
  714. return [val, val, val, val];
  715. }
  716. var len = val.length;
  717. if (len === 2) {
  718. // vertical | horizontal
  719. return [val[0], val[1], val[0], val[1]];
  720. }
  721. else if (len === 3) {
  722. // top | horizontal | bottom
  723. return [val[0], val[1], val[2], val[1]];
  724. }
  725. return val;
  726. }
  727. /**
  728. * @memberOf module:zrender/core/util
  729. * @param {boolean} condition
  730. * @param {string} message
  731. */
  732. function assert$1(condition, message) {
  733. if (!condition) {
  734. throw new Error(message);
  735. }
  736. }
  737. /**
  738. * @memberOf module:zrender/core/util
  739. * @param {string} str string to be trimed
  740. * @return {string} trimed string
  741. */
  742. function trim(str) {
  743. if (str == null) {
  744. return null;
  745. }
  746. else if (typeof str.trim === 'function') {
  747. return str.trim();
  748. }
  749. else {
  750. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  751. }
  752. }
  753. var primitiveKey = '__ec_primitive__';
  754. /**
  755. * Set an object as primitive to be ignored traversing children in clone or merge
  756. */
  757. function setAsPrimitive(obj) {
  758. obj[primitiveKey] = true;
  759. }
  760. function isPrimitive(obj) {
  761. return obj[primitiveKey];
  762. }
  763. /**
  764. * @constructor
  765. * @param {Object} obj Only apply `ownProperty`.
  766. */
  767. function HashMap(obj) {
  768. var isArr = isArray(obj);
  769. // Key should not be set on this, otherwise
  770. // methods get/set/... may be overrided.
  771. this.data = {};
  772. var thisMap = this;
  773. (obj instanceof HashMap)
  774. ? obj.each(visit)
  775. : (obj && each$1(obj, visit));
  776. function visit(value, key) {
  777. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  778. }
  779. }
  780. HashMap.prototype = {
  781. constructor: HashMap,
  782. // Do not provide `has` method to avoid defining what is `has`.
  783. // (We usually treat `null` and `undefined` as the same, different
  784. // from ES6 Map).
  785. get: function (key) {
  786. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  787. },
  788. set: function (key, value) {
  789. // Comparing with invocation chaining, `return value` is more commonly
  790. // used in this case: `var someVal = map.set('a', genVal());`
  791. return (this.data[key] = value);
  792. },
  793. // Although util.each can be performed on this hashMap directly, user
  794. // should not use the exposed keys, who are prefixed.
  795. each: function (cb, context) {
  796. context !== void 0 && (cb = bind(cb, context));
  797. for (var key in this.data) {
  798. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  799. }
  800. },
  801. // Do not use this method if performance sensitive.
  802. removeKey: function (key) {
  803. delete this.data[key];
  804. }
  805. };
  806. function createHashMap(obj) {
  807. return new HashMap(obj);
  808. }
  809. function concatArray(a, b) {
  810. var newArray = new a.constructor(a.length + b.length);
  811. for (var i = 0; i < a.length; i++) {
  812. newArray[i] = a[i];
  813. }
  814. var offset = a.length;
  815. for (i = 0; i < b.length; i++) {
  816. newArray[i + offset] = b[i];
  817. }
  818. return newArray;
  819. }
  820. function noop() {}
  821. var zrUtil = (Object.freeze || Object)({
  822. $override: $override,
  823. clone: clone,
  824. merge: merge,
  825. mergeAll: mergeAll,
  826. extend: extend,
  827. defaults: defaults,
  828. createCanvas: createCanvas,
  829. getContext: getContext,
  830. indexOf: indexOf,
  831. inherits: inherits,
  832. mixin: mixin,
  833. isArrayLike: isArrayLike,
  834. each: each$1,
  835. map: map,
  836. reduce: reduce,
  837. filter: filter,
  838. find: find,
  839. bind: bind,
  840. curry: curry,
  841. isArray: isArray,
  842. isFunction: isFunction$1,
  843. isString: isString,
  844. isObject: isObject$1,
  845. isBuiltInObject: isBuiltInObject,
  846. isTypedArray: isTypedArray,
  847. isDom: isDom,
  848. eqNaN: eqNaN,
  849. retrieve: retrieve,
  850. retrieve2: retrieve2,
  851. retrieve3: retrieve3,
  852. slice: slice,
  853. normalizeCssArray: normalizeCssArray,
  854. assert: assert$1,
  855. trim: trim,
  856. setAsPrimitive: setAsPrimitive,
  857. isPrimitive: isPrimitive,
  858. createHashMap: createHashMap,
  859. concatArray: concatArray,
  860. noop: noop
  861. });
  862. var ArrayCtor = typeof Float32Array === 'undefined'
  863. ? Array
  864. : Float32Array;
  865. /**
  866. * 创建一个向量
  867. * @param {number} [x=0]
  868. * @param {number} [y=0]
  869. * @return {Vector2}
  870. */
  871. function create(x, y) {
  872. var out = new ArrayCtor(2);
  873. if (x == null) {
  874. x = 0;
  875. }
  876. if (y == null) {
  877. y = 0;
  878. }
  879. out[0] = x;
  880. out[1] = y;
  881. return out;
  882. }
  883. /**
  884. * 复制向量数据
  885. * @param {Vector2} out
  886. * @param {Vector2} v
  887. * @return {Vector2}
  888. */
  889. function copy(out, v) {
  890. out[0] = v[0];
  891. out[1] = v[1];
  892. return out;
  893. }
  894. /**
  895. * 克隆一个向量
  896. * @param {Vector2} v
  897. * @return {Vector2}
  898. */
  899. function clone$1(v) {
  900. var out = new ArrayCtor(2);
  901. out[0] = v[0];
  902. out[1] = v[1];
  903. return out;
  904. }
  905. /**
  906. * 设置向量的两个项
  907. * @param {Vector2} out
  908. * @param {number} a
  909. * @param {number} b
  910. * @return {Vector2} 结果
  911. */
  912. function set(out, a, b) {
  913. out[0] = a;
  914. out[1] = b;
  915. return out;
  916. }
  917. /**
  918. * 向量相加
  919. * @param {Vector2} out
  920. * @param {Vector2} v1
  921. * @param {Vector2} v2
  922. */
  923. function add(out, v1, v2) {
  924. out[0] = v1[0] + v2[0];
  925. out[1] = v1[1] + v2[1];
  926. return out;
  927. }
  928. /**
  929. * 向量缩放后相加
  930. * @param {Vector2} out
  931. * @param {Vector2} v1
  932. * @param {Vector2} v2
  933. * @param {number} a
  934. */
  935. function scaleAndAdd(out, v1, v2, a) {
  936. out[0] = v1[0] + v2[0] * a;
  937. out[1] = v1[1] + v2[1] * a;
  938. return out;
  939. }
  940. /**
  941. * 向量相减
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. */
  946. function sub(out, v1, v2) {
  947. out[0] = v1[0] - v2[0];
  948. out[1] = v1[1] - v2[1];
  949. return out;
  950. }
  951. /**
  952. * 向量长度
  953. * @param {Vector2} v
  954. * @return {number}
  955. */
  956. function len(v) {
  957. return Math.sqrt(lenSquare(v));
  958. }
  959. var length = len; // jshint ignore:line
  960. /**
  961. * 向量长度平方
  962. * @param {Vector2} v
  963. * @return {number}
  964. */
  965. function lenSquare(v) {
  966. return v[0] * v[0] + v[1] * v[1];
  967. }
  968. var lengthSquare = lenSquare;
  969. /**
  970. * 向量乘法
  971. * @param {Vector2} out
  972. * @param {Vector2} v1
  973. * @param {Vector2} v2
  974. */
  975. function mul(out, v1, v2) {
  976. out[0] = v1[0] * v2[0];
  977. out[1] = v1[1] * v2[1];
  978. return out;
  979. }
  980. /**
  981. * 向量除法
  982. * @param {Vector2} out
  983. * @param {Vector2} v1
  984. * @param {Vector2} v2
  985. */
  986. function div(out, v1, v2) {
  987. out[0] = v1[0] / v2[0];
  988. out[1] = v1[1] / v2[1];
  989. return out;
  990. }
  991. /**
  992. * 向量点乘
  993. * @param {Vector2} v1
  994. * @param {Vector2} v2
  995. * @return {number}
  996. */
  997. function dot(v1, v2) {
  998. return v1[0] * v2[0] + v1[1] * v2[1];
  999. }
  1000. /**
  1001. * 向量缩放
  1002. * @param {Vector2} out
  1003. * @param {Vector2} v
  1004. * @param {number} s
  1005. */
  1006. function scale(out, v, s) {
  1007. out[0] = v[0] * s;
  1008. out[1] = v[1] * s;
  1009. return out;
  1010. }
  1011. /**
  1012. * 向量归一化
  1013. * @param {Vector2} out
  1014. * @param {Vector2} v
  1015. */
  1016. function normalize(out, v) {
  1017. var d = len(v);
  1018. if (d === 0) {
  1019. out[0] = 0;
  1020. out[1] = 0;
  1021. }
  1022. else {
  1023. out[0] = v[0] / d;
  1024. out[1] = v[1] / d;
  1025. }
  1026. return out;
  1027. }
  1028. /**
  1029. * 计算向量间距离
  1030. * @param {Vector2} v1
  1031. * @param {Vector2} v2
  1032. * @return {number}
  1033. */
  1034. function distance(v1, v2) {
  1035. return Math.sqrt(
  1036. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1037. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1038. );
  1039. }
  1040. var dist = distance;
  1041. /**
  1042. * 向量距离平方
  1043. * @param {Vector2} v1
  1044. * @param {Vector2} v2
  1045. * @return {number}
  1046. */
  1047. function distanceSquare(v1, v2) {
  1048. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1049. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1050. }
  1051. var distSquare = distanceSquare;
  1052. /**
  1053. * 求负向量
  1054. * @param {Vector2} out
  1055. * @param {Vector2} v
  1056. */
  1057. function negate(out, v) {
  1058. out[0] = -v[0];
  1059. out[1] = -v[1];
  1060. return out;
  1061. }
  1062. /**
  1063. * 插值两个点
  1064. * @param {Vector2} out
  1065. * @param {Vector2} v1
  1066. * @param {Vector2} v2
  1067. * @param {number} t
  1068. */
  1069. function lerp(out, v1, v2, t) {
  1070. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1071. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1072. return out;
  1073. }
  1074. /**
  1075. * 矩阵左乘向量
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v
  1078. * @param {Vector2} m
  1079. */
  1080. function applyTransform(out, v, m) {
  1081. var x = v[0];
  1082. var y = v[1];
  1083. out[0] = m[0] * x + m[2] * y + m[4];
  1084. out[1] = m[1] * x + m[3] * y + m[5];
  1085. return out;
  1086. }
  1087. /**
  1088. * 求两个向量最小值
  1089. * @param {Vector2} out
  1090. * @param {Vector2} v1
  1091. * @param {Vector2} v2
  1092. */
  1093. function min(out, v1, v2) {
  1094. out[0] = Math.min(v1[0], v2[0]);
  1095. out[1] = Math.min(v1[1], v2[1]);
  1096. return out;
  1097. }
  1098. /**
  1099. * 求两个向量最大值
  1100. * @param {Vector2} out
  1101. * @param {Vector2} v1
  1102. * @param {Vector2} v2
  1103. */
  1104. function max(out, v1, v2) {
  1105. out[0] = Math.max(v1[0], v2[0]);
  1106. out[1] = Math.max(v1[1], v2[1]);
  1107. return out;
  1108. }
  1109. var vector = (Object.freeze || Object)({
  1110. create: create,
  1111. copy: copy,
  1112. clone: clone$1,
  1113. set: set,
  1114. add: add,
  1115. scaleAndAdd: scaleAndAdd,
  1116. sub: sub,
  1117. len: len,
  1118. length: length,
  1119. lenSquare: lenSquare,
  1120. lengthSquare: lengthSquare,
  1121. mul: mul,
  1122. div: div,
  1123. dot: dot,
  1124. scale: scale,
  1125. normalize: normalize,
  1126. distance: distance,
  1127. dist: dist,
  1128. distanceSquare: distanceSquare,
  1129. distSquare: distSquare,
  1130. negate: negate,
  1131. lerp: lerp,
  1132. applyTransform: applyTransform,
  1133. min: min,
  1134. max: max
  1135. });
  1136. // TODO Draggable for group
  1137. // FIXME Draggable on element which has parent rotation or scale
  1138. function Draggable() {
  1139. this.on('mousedown', this._dragStart, this);
  1140. this.on('mousemove', this._drag, this);
  1141. this.on('mouseup', this._dragEnd, this);
  1142. this.on('globalout', this._dragEnd, this);
  1143. // this._dropTarget = null;
  1144. // this._draggingTarget = null;
  1145. // this._x = 0;
  1146. // this._y = 0;
  1147. }
  1148. Draggable.prototype = {
  1149. constructor: Draggable,
  1150. _dragStart: function (e) {
  1151. var draggingTarget = e.target;
  1152. if (draggingTarget && draggingTarget.draggable) {
  1153. this._draggingTarget = draggingTarget;
  1154. draggingTarget.dragging = true;
  1155. this._x = e.offsetX;
  1156. this._y = e.offsetY;
  1157. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1158. }
  1159. },
  1160. _drag: function (e) {
  1161. var draggingTarget = this._draggingTarget;
  1162. if (draggingTarget) {
  1163. var x = e.offsetX;
  1164. var y = e.offsetY;
  1165. var dx = x - this._x;
  1166. var dy = y - this._y;
  1167. this._x = x;
  1168. this._y = y;
  1169. draggingTarget.drift(dx, dy, e);
  1170. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1171. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1172. var lastDropTarget = this._dropTarget;
  1173. this._dropTarget = dropTarget;
  1174. if (draggingTarget !== dropTarget) {
  1175. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1176. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1177. }
  1178. if (dropTarget && dropTarget !== lastDropTarget) {
  1179. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1180. }
  1181. }
  1182. }
  1183. },
  1184. _dragEnd: function (e) {
  1185. var draggingTarget = this._draggingTarget;
  1186. if (draggingTarget) {
  1187. draggingTarget.dragging = false;
  1188. }
  1189. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1190. if (this._dropTarget) {
  1191. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1192. }
  1193. this._draggingTarget = null;
  1194. this._dropTarget = null;
  1195. }
  1196. };
  1197. function param(target, e) {
  1198. return {target: target, topTarget: e && e.topTarget};
  1199. }
  1200. /**
  1201. * Event Mixin
  1202. * @module zrender/mixin/Eventful
  1203. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1204. * pissang (https://www.github.com/pissang)
  1205. */
  1206. var arrySlice = Array.prototype.slice;
  1207. /**
  1208. * Event dispatcher.
  1209. *
  1210. * @alias module:zrender/mixin/Eventful
  1211. * @constructor
  1212. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1213. * `eventProcessor.xxx` called.
  1214. * @param {Function} [eventProcessor.normalizeQuery]
  1215. * param: {string|Object} Raw query.
  1216. * return: {string|Object} Normalized query.
  1217. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1218. * if it returns `true`.
  1219. * param: {string} eventType
  1220. * param: {string|Object} query
  1221. * return: {boolean}
  1222. * @param {Function} [eventProcessor.afterTrigger] Call after all handlers called.
  1223. * param: {string} eventType
  1224. */
  1225. var Eventful = function (eventProcessor) {
  1226. this._$handlers = {};
  1227. this._$eventProcessor = eventProcessor;
  1228. };
  1229. Eventful.prototype = {
  1230. constructor: Eventful,
  1231. /**
  1232. * The handler can only be triggered once, then removed.
  1233. *
  1234. * @param {string} event The event name.
  1235. * @param {string|Object} [query] Condition used on event filter.
  1236. * @param {Function} handler The event handler.
  1237. * @param {Object} context
  1238. */
  1239. one: function (event, query, handler, context) {
  1240. return on(this, event, query, handler, context, true);
  1241. },
  1242. /**
  1243. * Bind a handler.
  1244. *
  1245. * @param {string} event The event name.
  1246. * @param {string|Object} [query] Condition used on event filter.
  1247. * @param {Function} handler The event handler.
  1248. * @param {Object} [context]
  1249. */
  1250. on: function (event, query, handler, context) {
  1251. return on(this, event, query, handler, context, false);
  1252. },
  1253. /**
  1254. * Whether any handler has bound.
  1255. *
  1256. * @param {string} event
  1257. * @return {boolean}
  1258. */
  1259. isSilent: function (event) {
  1260. var _h = this._$handlers;
  1261. return !_h[event] || !_h[event].length;
  1262. },
  1263. /**
  1264. * Unbind a event.
  1265. *
  1266. * @param {string} event The event name.
  1267. * @param {Function} [handler] The event handler.
  1268. */
  1269. off: function (event, handler) {
  1270. var _h = this._$handlers;
  1271. if (!event) {
  1272. this._$handlers = {};
  1273. return this;
  1274. }
  1275. if (handler) {
  1276. if (_h[event]) {
  1277. var newList = [];
  1278. for (var i = 0, l = _h[event].length; i < l; i++) {
  1279. if (_h[event][i].h !== handler) {
  1280. newList.push(_h[event][i]);
  1281. }
  1282. }
  1283. _h[event] = newList;
  1284. }
  1285. if (_h[event] && _h[event].length === 0) {
  1286. delete _h[event];
  1287. }
  1288. }
  1289. else {
  1290. delete _h[event];
  1291. }
  1292. return this;
  1293. },
  1294. /**
  1295. * Dispatch a event.
  1296. *
  1297. * @param {string} type The event name.
  1298. */
  1299. trigger: function (type) {
  1300. var _h = this._$handlers[type];
  1301. var eventProcessor = this._$eventProcessor;
  1302. if (_h) {
  1303. var args = arguments;
  1304. var argLen = args.length;
  1305. if (argLen > 3) {
  1306. args = arrySlice.call(args, 1);
  1307. }
  1308. var len = _h.length;
  1309. for (var i = 0; i < len;) {
  1310. var hItem = _h[i];
  1311. if (eventProcessor
  1312. && eventProcessor.filter
  1313. && hItem.query != null
  1314. && !eventProcessor.filter(type, hItem.query)
  1315. ) {
  1316. i++;
  1317. continue;
  1318. }
  1319. // Optimize advise from backbone
  1320. switch (argLen) {
  1321. case 1:
  1322. hItem.h.call(hItem.ctx);
  1323. break;
  1324. case 2:
  1325. hItem.h.call(hItem.ctx, args[1]);
  1326. break;
  1327. case 3:
  1328. hItem.h.call(hItem.ctx, args[1], args[2]);
  1329. break;
  1330. default:
  1331. // have more than 2 given arguments
  1332. hItem.h.apply(hItem.ctx, args);
  1333. break;
  1334. }
  1335. if (hItem.one) {
  1336. _h.splice(i, 1);
  1337. len--;
  1338. }
  1339. else {
  1340. i++;
  1341. }
  1342. }
  1343. }
  1344. eventProcessor && eventProcessor.afterTrigger
  1345. && eventProcessor.afterTrigger(type);
  1346. return this;
  1347. },
  1348. /**
  1349. * Dispatch a event with context, which is specified at the last parameter.
  1350. *
  1351. * @param {string} type The event name.
  1352. */
  1353. triggerWithContext: function (type) {
  1354. var _h = this._$handlers[type];
  1355. var eventProcessor = this._$eventProcessor;
  1356. if (_h) {
  1357. var args = arguments;
  1358. var argLen = args.length;
  1359. if (argLen > 4) {
  1360. args = arrySlice.call(args, 1, args.length - 1);
  1361. }
  1362. var ctx = args[args.length - 1];
  1363. var len = _h.length;
  1364. for (var i = 0; i < len;) {
  1365. var hItem = _h[i];
  1366. if (eventProcessor
  1367. && eventProcessor.filter
  1368. && hItem.query != null
  1369. && !eventProcessor.filter(type, hItem.query)
  1370. ) {
  1371. i++;
  1372. continue;
  1373. }
  1374. // Optimize advise from backbone
  1375. switch (argLen) {
  1376. case 1:
  1377. hItem.h.call(ctx);
  1378. break;
  1379. case 2:
  1380. hItem.h.call(ctx, args[1]);
  1381. break;
  1382. case 3:
  1383. hItem.h.call(ctx, args[1], args[2]);
  1384. break;
  1385. default:
  1386. // have more than 2 given arguments
  1387. hItem.h.apply(ctx, args);
  1388. break;
  1389. }
  1390. if (hItem.one) {
  1391. _h.splice(i, 1);
  1392. len--;
  1393. }
  1394. else {
  1395. i++;
  1396. }
  1397. }
  1398. }
  1399. eventProcessor && eventProcessor.afterTrigger
  1400. && eventProcessor.afterTrigger(type);
  1401. return this;
  1402. }
  1403. };
  1404. function normalizeQuery(host, query) {
  1405. var eventProcessor = host._$eventProcessor;
  1406. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1407. query = eventProcessor.normalizeQuery(query);
  1408. }
  1409. return query;
  1410. }
  1411. function on(eventful, event, query, handler, context, isOnce) {
  1412. var _h = eventful._$handlers;
  1413. if (typeof query === 'function') {
  1414. context = handler;
  1415. handler = query;
  1416. query = null;
  1417. }
  1418. if (!handler || !event) {
  1419. return eventful;
  1420. }
  1421. query = normalizeQuery(eventful, query);
  1422. if (!_h[event]) {
  1423. _h[event] = [];
  1424. }
  1425. for (var i = 0; i < _h[event].length; i++) {
  1426. if (_h[event][i].h === handler) {
  1427. return eventful;
  1428. }
  1429. }
  1430. var wrap = {
  1431. h: handler,
  1432. one: isOnce,
  1433. query: query,
  1434. ctx: context || eventful,
  1435. // FIXME
  1436. // Do not publish this feature util it is proved that it makes sense.
  1437. callAtLast: handler.zrEventfulCallAtLast
  1438. };
  1439. var lastIndex = _h[event].length - 1;
  1440. var lastWrap = _h[event][lastIndex];
  1441. (lastWrap && lastWrap.callAtLast)
  1442. ? _h[event].splice(lastIndex, 0, wrap)
  1443. : _h[event].push(wrap);
  1444. return eventful;
  1445. }
  1446. /**
  1447. * 事件辅助类
  1448. * @module zrender/core/event
  1449. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1450. */
  1451. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1452. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1453. function getBoundingClientRect(el) {
  1454. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  1455. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  1456. }
  1457. // `calculate` is optional, default false
  1458. function clientToLocal(el, e, out, calculate) {
  1459. out = out || {};
  1460. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1461. // to the padding edge of the target element. The only browser using this convention
  1462. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1463. // not support the properties.
  1464. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1465. // In zr painter.dom, padding edge equals to border edge.
  1466. // FIXME
  1467. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  1468. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  1469. // is too complex. So css-transfrom dont support in this case temporarily.
  1470. if (calculate || !env$1.canvasSupported) {
  1471. defaultGetZrXY(el, e, out);
  1472. }
  1473. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1474. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1475. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1476. // zoom-factor, overflow / opacity layers, transforms ...)
  1477. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1478. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1479. // BTW3, In ff, offsetX/offsetY is always 0.
  1480. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1481. out.zrX = e.layerX;
  1482. out.zrY = e.layerY;
  1483. }
  1484. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1485. else if (e.offsetX != null) {
  1486. out.zrX = e.offsetX;
  1487. out.zrY = e.offsetY;
  1488. }
  1489. // For some other device, e.g., IOS safari.
  1490. else {
  1491. defaultGetZrXY(el, e, out);
  1492. }
  1493. return out;
  1494. }
  1495. function defaultGetZrXY(el, e, out) {
  1496. // This well-known method below does not support css transform.
  1497. var box = getBoundingClientRect(el);
  1498. out.zrX = e.clientX - box.left;
  1499. out.zrY = e.clientY - box.top;
  1500. }
  1501. /**
  1502. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  1503. * `calculate` is optional, default false.
  1504. */
  1505. function normalizeEvent(el, e, calculate) {
  1506. e = e || window.event;
  1507. if (e.zrX != null) {
  1508. return e;
  1509. }
  1510. var eventType = e.type;
  1511. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1512. if (!isTouch) {
  1513. clientToLocal(el, e, e, calculate);
  1514. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1515. }
  1516. else {
  1517. var touch = eventType !== 'touchend'
  1518. ? e.targetTouches[0]
  1519. : e.changedTouches[0];
  1520. touch && clientToLocal(el, touch, e, calculate);
  1521. }
  1522. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1523. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1524. // If e.which has been defined, if may be readonly,
  1525. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1526. var button = e.button;
  1527. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1528. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1529. }
  1530. // [Caution]: `e.which` from browser is not always reliable. For example,
  1531. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1532. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1533. // `mousedown (pointerdown)` is the same as Chrome does.
  1534. return e;
  1535. }
  1536. /**
  1537. * @param {HTMLElement} el
  1538. * @param {string} name
  1539. * @param {Function} handler
  1540. */
  1541. function addEventListener(el, name, handler) {
  1542. if (isDomLevel2) {
  1543. // Reproduct the console warning:
  1544. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1545. // Consider marking event handler as 'passive' to make the page more responsive.
  1546. // Just set console log level: verbose in chrome dev tool.
  1547. // then the warning log will be printed when addEventListener called.
  1548. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1549. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1550. // listener delegate all of the upper events of element. Some of those events need
  1551. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1552. // Before passive can be adopted, these issues should be considered:
  1553. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1554. // passive or not.
  1555. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1556. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1557. // compatibility should be handled.
  1558. // var opts = (env.passiveSupported && name === 'mousewheel')
  1559. // ? {passive: true}
  1560. // // By default, the third param of el.addEventListener is `capture: false`.
  1561. // : void 0;
  1562. // el.addEventListener(name, handler /* , opts */);
  1563. el.addEventListener(name, handler);
  1564. }
  1565. else {
  1566. el.attachEvent('on' + name, handler);
  1567. }
  1568. }
  1569. function removeEventListener(el, name, handler) {
  1570. if (isDomLevel2) {
  1571. el.removeEventListener(name, handler);
  1572. }
  1573. else {
  1574. el.detachEvent('on' + name, handler);
  1575. }
  1576. }
  1577. /**
  1578. * preventDefault and stopPropagation.
  1579. * Notice: do not do that in zrender. Upper application
  1580. * do that if necessary.
  1581. *
  1582. * @memberOf module:zrender/core/event
  1583. * @method
  1584. * @param {Event} e : event对象
  1585. */
  1586. var stop = isDomLevel2
  1587. ? function (e) {
  1588. e.preventDefault();
  1589. e.stopPropagation();
  1590. e.cancelBubble = true;
  1591. }
  1592. : function (e) {
  1593. e.returnValue = false;
  1594. e.cancelBubble = true;
  1595. };
  1596. /**
  1597. * This method only works for mouseup and mousedown. The functionality is restricted
  1598. * for fault tolerance, See the `e.which` compatibility above.
  1599. *
  1600. * @param {MouseEvent} e
  1601. * @return {boolean}
  1602. */
  1603. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1604. return e.which === 2 || e.which === 3;
  1605. }
  1606. /**
  1607. * To be removed.
  1608. * @deprecated
  1609. */
  1610. /**
  1611. * Only implements needed gestures for mobile.
  1612. */
  1613. var GestureMgr = function () {
  1614. /**
  1615. * @private
  1616. * @type {Array.<Object>}
  1617. */
  1618. this._track = [];
  1619. };
  1620. GestureMgr.prototype = {
  1621. constructor: GestureMgr,
  1622. recognize: function (event, target, root) {
  1623. this._doTrack(event, target, root);
  1624. return this._recognize(event);
  1625. },
  1626. clear: function () {
  1627. this._track.length = 0;
  1628. return this;
  1629. },
  1630. _doTrack: function (event, target, root) {
  1631. var touches = event.touches;
  1632. if (!touches) {
  1633. return;
  1634. }
  1635. var trackItem = {
  1636. points: [],
  1637. touches: [],
  1638. target: target,
  1639. event: event
  1640. };
  1641. for (var i = 0, len = touches.length; i < len; i++) {
  1642. var touch = touches[i];
  1643. var pos = clientToLocal(root, touch, {});
  1644. trackItem.points.push([pos.zrX, pos.zrY]);
  1645. trackItem.touches.push(touch);
  1646. }
  1647. this._track.push(trackItem);
  1648. },
  1649. _recognize: function (event) {
  1650. for (var eventName in recognizers) {
  1651. if (recognizers.hasOwnProperty(eventName)) {
  1652. var gestureInfo = recognizers[eventName](this._track, event);
  1653. if (gestureInfo) {
  1654. return gestureInfo;
  1655. }
  1656. }
  1657. }
  1658. }
  1659. };
  1660. function dist$1(pointPair) {
  1661. var dx = pointPair[1][0] - pointPair[0][0];
  1662. var dy = pointPair[1][1] - pointPair[0][1];
  1663. return Math.sqrt(dx * dx + dy * dy);
  1664. }
  1665. function center(pointPair) {
  1666. return [
  1667. (pointPair[0][0] + pointPair[1][0]) / 2,
  1668. (pointPair[0][1] + pointPair[1][1]) / 2
  1669. ];
  1670. }
  1671. var recognizers = {
  1672. pinch: function (track, event) {
  1673. var trackLen = track.length;
  1674. if (!trackLen) {
  1675. return;
  1676. }
  1677. var pinchEnd = (track[trackLen - 1] || {}).points;
  1678. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1679. if (pinchPre
  1680. && pinchPre.length > 1
  1681. && pinchEnd
  1682. && pinchEnd.length > 1
  1683. ) {
  1684. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1685. !isFinite(pinchScale) && (pinchScale = 1);
  1686. event.pinchScale = pinchScale;
  1687. var pinchCenter = center(pinchEnd);
  1688. event.pinchX = pinchCenter[0];
  1689. event.pinchY = pinchCenter[1];
  1690. return {
  1691. type: 'pinch',
  1692. target: track[0].target,
  1693. event: event
  1694. };
  1695. }
  1696. }
  1697. // Only pinch currently.
  1698. };
  1699. var SILENT = 'silent';
  1700. function makeEventPacket(eveType, targetInfo, event) {
  1701. return {
  1702. type: eveType,
  1703. event: event,
  1704. // target can only be an element that is not silent.
  1705. target: targetInfo.target,
  1706. // topTarget can be a silent element.
  1707. topTarget: targetInfo.topTarget,
  1708. cancelBubble: false,
  1709. offsetX: event.zrX,
  1710. offsetY: event.zrY,
  1711. gestureEvent: event.gestureEvent,
  1712. pinchX: event.pinchX,
  1713. pinchY: event.pinchY,
  1714. pinchScale: event.pinchScale,
  1715. wheelDelta: event.zrDelta,
  1716. zrByTouch: event.zrByTouch,
  1717. which: event.which,
  1718. stop: stopEvent
  1719. };
  1720. }
  1721. function stopEvent(event) {
  1722. stop(this.event);
  1723. }
  1724. function EmptyProxy() {}
  1725. EmptyProxy.prototype.dispose = function () {};
  1726. var handlerNames = [
  1727. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1728. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1729. ];
  1730. /**
  1731. * @alias module:zrender/Handler
  1732. * @constructor
  1733. * @extends module:zrender/mixin/Eventful
  1734. * @param {module:zrender/Storage} storage Storage instance.
  1735. * @param {module:zrender/Painter} painter Painter instance.
  1736. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1737. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1738. */
  1739. var Handler = function (storage, painter, proxy, painterRoot) {
  1740. Eventful.call(this);
  1741. this.storage = storage;
  1742. this.painter = painter;
  1743. this.painterRoot = painterRoot;
  1744. proxy = proxy || new EmptyProxy();
  1745. /**
  1746. * Proxy of event. can be Dom, WebGLSurface, etc.
  1747. */
  1748. this.proxy = null;
  1749. /**
  1750. * {target, topTarget, x, y}
  1751. * @private
  1752. * @type {Object}
  1753. */
  1754. this._hovered = {};
  1755. /**
  1756. * @private
  1757. * @type {Date}
  1758. */
  1759. this._lastTouchMoment;
  1760. /**
  1761. * @private
  1762. * @type {number}
  1763. */
  1764. this._lastX;
  1765. /**
  1766. * @private
  1767. * @type {number}
  1768. */
  1769. this._lastY;
  1770. /**
  1771. * @private
  1772. * @type {module:zrender/core/GestureMgr}
  1773. */
  1774. this._gestureMgr;
  1775. Draggable.call(this);
  1776. this.setHandlerProxy(proxy);
  1777. };
  1778. Handler.prototype = {
  1779. constructor: Handler,
  1780. setHandlerProxy: function (proxy) {
  1781. if (this.proxy) {
  1782. this.proxy.dispose();
  1783. }
  1784. if (proxy) {
  1785. each$1(handlerNames, function (name) {
  1786. proxy.on && proxy.on(name, this[name], this);
  1787. }, this);
  1788. // Attach handler
  1789. proxy.handler = this;
  1790. }
  1791. this.proxy = proxy;
  1792. },
  1793. mousemove: function (event) {
  1794. var x = event.zrX;
  1795. var y = event.zrY;
  1796. var lastHovered = this._hovered;
  1797. var lastHoveredTarget = lastHovered.target;
  1798. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1799. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1800. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1801. // See #6198.
  1802. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1803. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1804. lastHoveredTarget = lastHovered.target;
  1805. }
  1806. var hovered = this._hovered = this.findHover(x, y);
  1807. var hoveredTarget = hovered.target;
  1808. var proxy = this.proxy;
  1809. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1810. // Mouse out on previous hovered element
  1811. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1812. this.dispatchToElement(lastHovered, 'mouseout', event);
  1813. }
  1814. // Mouse moving on one element
  1815. this.dispatchToElement(hovered, 'mousemove', event);
  1816. // Mouse over on a new element
  1817. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1818. this.dispatchToElement(hovered, 'mouseover', event);
  1819. }
  1820. },
  1821. mouseout: function (event) {
  1822. this.dispatchToElement(this._hovered, 'mouseout', event);
  1823. // There might be some doms created by upper layer application
  1824. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1825. // dom created by echarts), where 'globalout' event should not
  1826. // be triggered when mouse enters these doms. (But 'mouseout'
  1827. // should be triggered at the original hovered element as usual).
  1828. var element = event.toElement || event.relatedTarget;
  1829. var innerDom;
  1830. do {
  1831. element = element && element.parentNode;
  1832. }
  1833. while (element && element.nodeType !== 9 && !(
  1834. innerDom = element === this.painterRoot
  1835. ));
  1836. !innerDom && this.trigger('globalout', {event: event});
  1837. },
  1838. /**
  1839. * Resize
  1840. */
  1841. resize: function (event) {
  1842. this._hovered = {};
  1843. },
  1844. /**
  1845. * Dispatch event
  1846. * @param {string} eventName
  1847. * @param {event=} eventArgs
  1848. */
  1849. dispatch: function (eventName, eventArgs) {
  1850. var handler = this[eventName];
  1851. handler && handler.call(this, eventArgs);
  1852. },
  1853. /**
  1854. * Dispose
  1855. */
  1856. dispose: function () {
  1857. this.proxy.dispose();
  1858. this.storage =
  1859. this.proxy =
  1860. this.painter = null;
  1861. },
  1862. /**
  1863. * 设置默认的cursor style
  1864. * @param {string} [cursorStyle='default'] 例如 crosshair
  1865. */
  1866. setCursorStyle: function (cursorStyle) {
  1867. var proxy = this.proxy;
  1868. proxy.setCursor && proxy.setCursor(cursorStyle);
  1869. },
  1870. /**
  1871. * 事件分发代理
  1872. *
  1873. * @private
  1874. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1875. * @param {string} eventName 事件名称
  1876. * @param {Object} event 事件对象
  1877. */
  1878. dispatchToElement: function (targetInfo, eventName, event) {
  1879. targetInfo = targetInfo || {};
  1880. var el = targetInfo.target;
  1881. if (el && el.silent) {
  1882. return;
  1883. }
  1884. var eventHandler = 'on' + eventName;
  1885. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1886. while (el) {
  1887. el[eventHandler]
  1888. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1889. el.trigger(eventName, eventPacket);
  1890. el = el.parent;
  1891. if (eventPacket.cancelBubble) {
  1892. break;
  1893. }
  1894. }
  1895. if (!eventPacket.cancelBubble) {
  1896. // 冒泡到顶级 zrender 对象
  1897. this.trigger(eventName, eventPacket);
  1898. // 分发事件到用户自定义层
  1899. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1900. this.painter && this.painter.eachOtherLayer(function (layer) {
  1901. if (typeof (layer[eventHandler]) === 'function') {
  1902. layer[eventHandler].call(layer, eventPacket);
  1903. }
  1904. if (layer.trigger) {
  1905. layer.trigger(eventName, eventPacket);
  1906. }
  1907. });
  1908. }
  1909. },
  1910. /**
  1911. * @private
  1912. * @param {number} x
  1913. * @param {number} y
  1914. * @param {module:zrender/graphic/Displayable} exclude
  1915. * @return {model:zrender/Element}
  1916. * @method
  1917. */
  1918. findHover: function (x, y, exclude) {
  1919. var list = this.storage.getDisplayList();
  1920. var out = {x: x, y: y};
  1921. for (var i = list.length - 1; i >= 0; i--) {
  1922. var hoverCheckResult;
  1923. if (list[i] !== exclude
  1924. // getDisplayList may include ignored item in VML mode
  1925. && !list[i].ignore
  1926. && (hoverCheckResult = isHover(list[i], x, y))
  1927. ) {
  1928. !out.topTarget && (out.topTarget = list[i]);
  1929. if (hoverCheckResult !== SILENT) {
  1930. out.target = list[i];
  1931. break;
  1932. }
  1933. }
  1934. }
  1935. return out;
  1936. },
  1937. processGesture: function (event, stage) {
  1938. if (!this._gestureMgr) {
  1939. this._gestureMgr = new GestureMgr();
  1940. }
  1941. var gestureMgr = this._gestureMgr;
  1942. stage === 'start' && gestureMgr.clear();
  1943. var gestureInfo = gestureMgr.recognize(
  1944. event,
  1945. this.findHover(event.zrX, event.zrY, null).target,
  1946. this.proxy.dom
  1947. );
  1948. stage === 'end' && gestureMgr.clear();
  1949. // Do not do any preventDefault here. Upper application do that if necessary.
  1950. if (gestureInfo) {
  1951. var type = gestureInfo.type;
  1952. event.gestureEvent = type;
  1953. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  1954. }
  1955. }
  1956. };
  1957. // Common handlers
  1958. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1959. Handler.prototype[name] = function (event) {
  1960. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1961. var hovered = this.findHover(event.zrX, event.zrY);
  1962. var hoveredTarget = hovered.target;
  1963. if (name === 'mousedown') {
  1964. this._downEl = hoveredTarget;
  1965. this._downPoint = [event.zrX, event.zrY];
  1966. // In case click triggered before mouseup
  1967. this._upEl = hoveredTarget;
  1968. }
  1969. else if (name === 'mouseup') {
  1970. this._upEl = hoveredTarget;
  1971. }
  1972. else if (name === 'click') {
  1973. if (this._downEl !== this._upEl
  1974. // Original click event is triggered on the whole canvas element,
  1975. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1976. // which should be filtered, otherwise it will bring trouble to
  1977. // pan and zoom.
  1978. || !this._downPoint
  1979. // Arbitrary value
  1980. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1981. ) {
  1982. return;
  1983. }
  1984. this._downPoint = null;
  1985. }
  1986. this.dispatchToElement(hovered, name, event);
  1987. };
  1988. });
  1989. function isHover(displayable, x, y) {
  1990. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1991. var el = displayable;
  1992. var isSilent;
  1993. while (el) {
  1994. // If clipped by ancestor.
  1995. // FIXME: If clipPath has neither stroke nor fill,
  1996. // el.clipPath.contain(x, y) will always return false.
  1997. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1998. return false;
  1999. }
  2000. if (el.silent) {
  2001. isSilent = true;
  2002. }
  2003. el = el.parent;
  2004. }
  2005. return isSilent ? SILENT : true;
  2006. }
  2007. return false;
  2008. }
  2009. mixin(Handler, Eventful);
  2010. mixin(Handler, Draggable);
  2011. /**
  2012. * 3x2矩阵操作类
  2013. * @exports zrender/tool/matrix
  2014. */
  2015. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2016. ? Array
  2017. : Float32Array;
  2018. /**
  2019. * Create a identity matrix.
  2020. * @return {Float32Array|Array.<number>}
  2021. */
  2022. function create$1() {
  2023. var out = new ArrayCtor$1(6);
  2024. identity(out);
  2025. return out;
  2026. }
  2027. /**
  2028. * 设置矩阵为单位矩阵
  2029. * @param {Float32Array|Array.<number>} out
  2030. */
  2031. function identity(out) {
  2032. out[0] = 1;
  2033. out[1] = 0;
  2034. out[2] = 0;
  2035. out[3] = 1;
  2036. out[4] = 0;
  2037. out[5] = 0;
  2038. return out;
  2039. }
  2040. /**
  2041. * 复制矩阵
  2042. * @param {Float32Array|Array.<number>} out
  2043. * @param {Float32Array|Array.<number>} m
  2044. */
  2045. function copy$1(out, m) {
  2046. out[0] = m[0];
  2047. out[1] = m[1];
  2048. out[2] = m[2];
  2049. out[3] = m[3];
  2050. out[4] = m[4];
  2051. out[5] = m[5];
  2052. return out;
  2053. }
  2054. /**
  2055. * 矩阵相乘
  2056. * @param {Float32Array|Array.<number>} out
  2057. * @param {Float32Array|Array.<number>} m1
  2058. * @param {Float32Array|Array.<number>} m2
  2059. */
  2060. function mul$1(out, m1, m2) {
  2061. // Consider matrix.mul(m, m2, m);
  2062. // where out is the same as m2.
  2063. // So use temp variable to escape error.
  2064. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2065. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2066. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2067. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2068. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2069. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2070. out[0] = out0;
  2071. out[1] = out1;
  2072. out[2] = out2;
  2073. out[3] = out3;
  2074. out[4] = out4;
  2075. out[5] = out5;
  2076. return out;
  2077. }
  2078. /**
  2079. * 平移变换
  2080. * @param {Float32Array|Array.<number>} out
  2081. * @param {Float32Array|Array.<number>} a
  2082. * @param {Float32Array|Array.<number>} v
  2083. */
  2084. function translate(out, a, v) {
  2085. out[0] = a[0];
  2086. out[1] = a[1];
  2087. out[2] = a[2];
  2088. out[3] = a[3];
  2089. out[4] = a[4] + v[0];
  2090. out[5] = a[5] + v[1];
  2091. return out;
  2092. }
  2093. /**
  2094. * 旋转变换
  2095. * @param {Float32Array|Array.<number>} out
  2096. * @param {Float32Array|Array.<number>} a
  2097. * @param {number} rad
  2098. */
  2099. function rotate(out, a, rad) {
  2100. var aa = a[0];
  2101. var ac = a[2];
  2102. var atx = a[4];
  2103. var ab = a[1];
  2104. var ad = a[3];
  2105. var aty = a[5];
  2106. var st = Math.sin(rad);
  2107. var ct = Math.cos(rad);
  2108. out[0] = aa * ct + ab * st;
  2109. out[1] = -aa * st + ab * ct;
  2110. out[2] = ac * ct + ad * st;
  2111. out[3] = -ac * st + ct * ad;
  2112. out[4] = ct * atx + st * aty;
  2113. out[5] = ct * aty - st * atx;
  2114. return out;
  2115. }
  2116. /**
  2117. * 缩放变换
  2118. * @param {Float32Array|Array.<number>} out
  2119. * @param {Float32Array|Array.<number>} a
  2120. * @param {Float32Array|Array.<number>} v
  2121. */
  2122. function scale$1(out, a, v) {
  2123. var vx = v[0];
  2124. var vy = v[1];
  2125. out[0] = a[0] * vx;
  2126. out[1] = a[1] * vy;
  2127. out[2] = a[2] * vx;
  2128. out[3] = a[3] * vy;
  2129. out[4] = a[4] * vx;
  2130. out[5] = a[5] * vy;
  2131. return out;
  2132. }
  2133. /**
  2134. * 求逆矩阵
  2135. * @param {Float32Array|Array.<number>} out
  2136. * @param {Float32Array|Array.<number>} a
  2137. */
  2138. function invert(out, a) {
  2139. var aa = a[0];
  2140. var ac = a[2];
  2141. var atx = a[4];
  2142. var ab = a[1];
  2143. var ad = a[3];
  2144. var aty = a[5];
  2145. var det = aa * ad - ab * ac;
  2146. if (!det) {
  2147. return null;
  2148. }
  2149. det = 1.0 / det;
  2150. out[0] = ad * det;
  2151. out[1] = -ab * det;
  2152. out[2] = -ac * det;
  2153. out[3] = aa * det;
  2154. out[4] = (ac * aty - ad * atx) * det;
  2155. out[5] = (ab * atx - aa * aty) * det;
  2156. return out;
  2157. }
  2158. /**
  2159. * Clone a new matrix.
  2160. * @param {Float32Array|Array.<number>} a
  2161. */
  2162. function clone$2(a) {
  2163. var b = create$1();
  2164. copy$1(b, a);
  2165. return b;
  2166. }
  2167. var matrix = (Object.freeze || Object)({
  2168. create: create$1,
  2169. identity: identity,
  2170. copy: copy$1,
  2171. mul: mul$1,
  2172. translate: translate,
  2173. rotate: rotate,
  2174. scale: scale$1,
  2175. invert: invert,
  2176. clone: clone$2
  2177. });
  2178. /**
  2179. * 提供变换扩展
  2180. * @module zrender/mixin/Transformable
  2181. * @author pissang (https://www.github.com/pissang)
  2182. */
  2183. var mIdentity = identity;
  2184. var EPSILON = 5e-5;
  2185. function isNotAroundZero(val) {
  2186. return val > EPSILON || val < -EPSILON;
  2187. }
  2188. /**
  2189. * @alias module:zrender/mixin/Transformable
  2190. * @constructor
  2191. */
  2192. var Transformable = function (opts) {
  2193. opts = opts || {};
  2194. // If there are no given position, rotation, scale
  2195. if (!opts.position) {
  2196. /**
  2197. * 平移
  2198. * @type {Array.<number>}
  2199. * @default [0, 0]
  2200. */
  2201. this.position = [0, 0];
  2202. }
  2203. if (opts.rotation == null) {
  2204. /**
  2205. * 旋转
  2206. * @type {Array.<number>}
  2207. * @default 0
  2208. */
  2209. this.rotation = 0;
  2210. }
  2211. if (!opts.scale) {
  2212. /**
  2213. * 缩放
  2214. * @type {Array.<number>}
  2215. * @default [1, 1]
  2216. */
  2217. this.scale = [1, 1];
  2218. }
  2219. /**
  2220. * 旋转和缩放的原点
  2221. * @type {Array.<number>}
  2222. * @default null
  2223. */
  2224. this.origin = this.origin || null;
  2225. };
  2226. var transformableProto = Transformable.prototype;
  2227. transformableProto.transform = null;
  2228. /**
  2229. * 判断是否需要有坐标变换
  2230. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2231. */
  2232. transformableProto.needLocalTransform = function () {
  2233. return isNotAroundZero(this.rotation)
  2234. || isNotAroundZero(this.position[0])
  2235. || isNotAroundZero(this.position[1])
  2236. || isNotAroundZero(this.scale[0] - 1)
  2237. || isNotAroundZero(this.scale[1] - 1);
  2238. };
  2239. var scaleTmp = [];
  2240. transformableProto.updateTransform = function () {
  2241. var parent = this.parent;
  2242. var parentHasTransform = parent && parent.transform;
  2243. var needLocalTransform = this.needLocalTransform();
  2244. var m = this.transform;
  2245. if (!(needLocalTransform || parentHasTransform)) {
  2246. m && mIdentity(m);
  2247. return;
  2248. }
  2249. m = m || create$1();
  2250. if (needLocalTransform) {
  2251. this.getLocalTransform(m);
  2252. }
  2253. else {
  2254. mIdentity(m);
  2255. }
  2256. // 应用父节点变换
  2257. if (parentHasTransform) {
  2258. if (needLocalTransform) {
  2259. mul$1(m, parent.transform, m);
  2260. }
  2261. else {
  2262. copy$1(m, parent.transform);
  2263. }
  2264. }
  2265. // 保存这个变换矩阵
  2266. this.transform = m;
  2267. var globalScaleRatio = this.globalScaleRatio;
  2268. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2269. this.getGlobalScale(scaleTmp);
  2270. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2271. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2272. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2273. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2274. m[0] *= sx;
  2275. m[1] *= sx;
  2276. m[2] *= sy;
  2277. m[3] *= sy;
  2278. }
  2279. this.invTransform = this.invTransform || create$1();
  2280. invert(this.invTransform, m);
  2281. };
  2282. transformableProto.getLocalTransform = function (m) {
  2283. return Transformable.getLocalTransform(this, m);
  2284. };
  2285. /**
  2286. * 将自己的transform应用到context上
  2287. * @param {CanvasRenderingContext2D} ctx
  2288. */
  2289. transformableProto.setTransform = function (ctx) {
  2290. var m = this.transform;
  2291. var dpr = ctx.dpr || 1;
  2292. if (m) {
  2293. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2294. }
  2295. else {
  2296. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2297. }
  2298. };
  2299. transformableProto.restoreTransform = function (ctx) {
  2300. var dpr = ctx.dpr || 1;
  2301. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2302. };
  2303. var tmpTransform = [];
  2304. var originTransform = create$1();
  2305. transformableProto.setLocalTransform = function (m) {
  2306. if (!m) {
  2307. // TODO return or set identity?
  2308. return;
  2309. }
  2310. var sx = m[0] * m[0] + m[1] * m[1];
  2311. var sy = m[2] * m[2] + m[3] * m[3];
  2312. var position = this.position;
  2313. var scale$$1 = this.scale;
  2314. if (isNotAroundZero(sx - 1)) {
  2315. sx = Math.sqrt(sx);
  2316. }
  2317. if (isNotAroundZero(sy - 1)) {
  2318. sy = Math.sqrt(sy);
  2319. }
  2320. if (m[0] < 0) {
  2321. sx = -sx;
  2322. }
  2323. if (m[3] < 0) {
  2324. sy = -sy;
  2325. }
  2326. position[0] = m[4];
  2327. position[1] = m[5];
  2328. scale$$1[0] = sx;
  2329. scale$$1[1] = sy;
  2330. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2331. };
  2332. /**
  2333. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2334. */
  2335. transformableProto.decomposeTransform = function () {
  2336. if (!this.transform) {
  2337. return;
  2338. }
  2339. var parent = this.parent;
  2340. var m = this.transform;
  2341. if (parent && parent.transform) {
  2342. // Get local transform and decompose them to position, scale, rotation
  2343. mul$1(tmpTransform, parent.invTransform, m);
  2344. m = tmpTransform;
  2345. }
  2346. var origin = this.origin;
  2347. if (origin && (origin[0] || origin[1])) {
  2348. originTransform[4] = origin[0];
  2349. originTransform[5] = origin[1];
  2350. mul$1(tmpTransform, m, originTransform);
  2351. tmpTransform[4] -= origin[0];
  2352. tmpTransform[5] -= origin[1];
  2353. m = tmpTransform;
  2354. }
  2355. this.setLocalTransform(m);
  2356. };
  2357. /**
  2358. * Get global scale
  2359. * @return {Array.<number>}
  2360. */
  2361. transformableProto.getGlobalScale = function (out) {
  2362. var m = this.transform;
  2363. out = out || [];
  2364. if (!m) {
  2365. out[0] = 1;
  2366. out[1] = 1;
  2367. return out;
  2368. }
  2369. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2370. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2371. if (m[0] < 0) {
  2372. out[0] = -out[0];
  2373. }
  2374. if (m[3] < 0) {
  2375. out[1] = -out[1];
  2376. }
  2377. return out;
  2378. };
  2379. /**
  2380. * 变换坐标位置到 shape 的局部坐标空间
  2381. * @method
  2382. * @param {number} x
  2383. * @param {number} y
  2384. * @return {Array.<number>}
  2385. */
  2386. transformableProto.transformCoordToLocal = function (x, y) {
  2387. var v2 = [x, y];
  2388. var invTransform = this.invTransform;
  2389. if (invTransform) {
  2390. applyTransform(v2, v2, invTransform);
  2391. }
  2392. return v2;
  2393. };
  2394. /**
  2395. * 变换局部坐标位置到全局坐标空间
  2396. * @method
  2397. * @param {number} x
  2398. * @param {number} y
  2399. * @return {Array.<number>}
  2400. */
  2401. transformableProto.transformCoordToGlobal = function (x, y) {
  2402. var v2 = [x, y];
  2403. var transform = this.transform;
  2404. if (transform) {
  2405. applyTransform(v2, v2, transform);
  2406. }
  2407. return v2;
  2408. };
  2409. /**
  2410. * @static
  2411. * @param {Object} target
  2412. * @param {Array.<number>} target.origin
  2413. * @param {number} target.rotation
  2414. * @param {Array.<number>} target.position
  2415. * @param {Array.<number>} [m]
  2416. */
  2417. Transformable.getLocalTransform = function (target, m) {
  2418. m = m || [];
  2419. mIdentity(m);
  2420. var origin = target.origin;
  2421. var scale$$1 = target.scale || [1, 1];
  2422. var rotation = target.rotation || 0;
  2423. var position = target.position || [0, 0];
  2424. if (origin) {
  2425. // Translate to origin
  2426. m[4] -= origin[0];
  2427. m[5] -= origin[1];
  2428. }
  2429. scale$1(m, m, scale$$1);
  2430. if (rotation) {
  2431. rotate(m, m, rotation);
  2432. }
  2433. if (origin) {
  2434. // Translate back from origin
  2435. m[4] += origin[0];
  2436. m[5] += origin[1];
  2437. }
  2438. m[4] += position[0];
  2439. m[5] += position[1];
  2440. return m;
  2441. };
  2442. /**
  2443. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2444. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2445. * @exports zrender/animation/easing
  2446. */
  2447. var easing = {
  2448. /**
  2449. * @param {number} k
  2450. * @return {number}
  2451. */
  2452. linear: function (k) {
  2453. return k;
  2454. },
  2455. /**
  2456. * @param {number} k
  2457. * @return {number}
  2458. */
  2459. quadraticIn: function (k) {
  2460. return k * k;
  2461. },
  2462. /**
  2463. * @param {number} k
  2464. * @return {number}
  2465. */
  2466. quadraticOut: function (k) {
  2467. return k * (2 - k);
  2468. },
  2469. /**
  2470. * @param {number} k
  2471. * @return {number}
  2472. */
  2473. quadraticInOut: function (k) {
  2474. if ((k *= 2) < 1) {
  2475. return 0.5 * k * k;
  2476. }
  2477. return -0.5 * (--k * (k - 2) - 1);
  2478. },
  2479. // 三次方的缓动(t^3)
  2480. /**
  2481. * @param {number} k
  2482. * @return {number}
  2483. */
  2484. cubicIn: function (k) {
  2485. return k * k * k;
  2486. },
  2487. /**
  2488. * @param {number} k
  2489. * @return {number}
  2490. */
  2491. cubicOut: function (k) {
  2492. return --k * k * k + 1;
  2493. },
  2494. /**
  2495. * @param {number} k
  2496. * @return {number}
  2497. */
  2498. cubicInOut: function (k) {
  2499. if ((k *= 2) < 1) {
  2500. return 0.5 * k * k * k;
  2501. }
  2502. return 0.5 * ((k -= 2) * k * k + 2);
  2503. },
  2504. // 四次方的缓动(t^4)
  2505. /**
  2506. * @param {number} k
  2507. * @return {number}
  2508. */
  2509. quarticIn: function (k) {
  2510. return k * k * k * k;
  2511. },
  2512. /**
  2513. * @param {number} k
  2514. * @return {number}
  2515. */
  2516. quarticOut: function (k) {
  2517. return 1 - (--k * k * k * k);
  2518. },
  2519. /**
  2520. * @param {number} k
  2521. * @return {number}
  2522. */
  2523. quarticInOut: function (k) {
  2524. if ((k *= 2) < 1) {
  2525. return 0.5 * k * k * k * k;
  2526. }
  2527. return -0.5 * ((k -= 2) * k * k * k - 2);
  2528. },
  2529. // 五次方的缓动(t^5)
  2530. /**
  2531. * @param {number} k
  2532. * @return {number}
  2533. */
  2534. quinticIn: function (k) {
  2535. return k * k * k * k * k;
  2536. },
  2537. /**
  2538. * @param {number} k
  2539. * @return {number}
  2540. */
  2541. quinticOut: function (k) {
  2542. return --k * k * k * k * k + 1;
  2543. },
  2544. /**
  2545. * @param {number} k
  2546. * @return {number}
  2547. */
  2548. quinticInOut: function (k) {
  2549. if ((k *= 2) < 1) {
  2550. return 0.5 * k * k * k * k * k;
  2551. }
  2552. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2553. },
  2554. // 正弦曲线的缓动(sin(t))
  2555. /**
  2556. * @param {number} k
  2557. * @return {number}
  2558. */
  2559. sinusoidalIn: function (k) {
  2560. return 1 - Math.cos(k * Math.PI / 2);
  2561. },
  2562. /**
  2563. * @param {number} k
  2564. * @return {number}
  2565. */
  2566. sinusoidalOut: function (k) {
  2567. return Math.sin(k * Math.PI / 2);
  2568. },
  2569. /**
  2570. * @param {number} k
  2571. * @return {number}
  2572. */
  2573. sinusoidalInOut: function (k) {
  2574. return 0.5 * (1 - Math.cos(Math.PI * k));
  2575. },
  2576. // 指数曲线的缓动(2^t)
  2577. /**
  2578. * @param {number} k
  2579. * @return {number}
  2580. */
  2581. exponentialIn: function (k) {
  2582. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2583. },
  2584. /**
  2585. * @param {number} k
  2586. * @return {number}
  2587. */
  2588. exponentialOut: function (k) {
  2589. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2590. },
  2591. /**
  2592. * @param {number} k
  2593. * @return {number}
  2594. */
  2595. exponentialInOut: function (k) {
  2596. if (k === 0) {
  2597. return 0;
  2598. }
  2599. if (k === 1) {
  2600. return 1;
  2601. }
  2602. if ((k *= 2) < 1) {
  2603. return 0.5 * Math.pow(1024, k - 1);
  2604. }
  2605. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2606. },
  2607. // 圆形曲线的缓动(sqrt(1-t^2))
  2608. /**
  2609. * @param {number} k
  2610. * @return {number}
  2611. */
  2612. circularIn: function (k) {
  2613. return 1 - Math.sqrt(1 - k * k);
  2614. },
  2615. /**
  2616. * @param {number} k
  2617. * @return {number}
  2618. */
  2619. circularOut: function (k) {
  2620. return Math.sqrt(1 - (--k * k));
  2621. },
  2622. /**
  2623. * @param {number} k
  2624. * @return {number}
  2625. */
  2626. circularInOut: function (k) {
  2627. if ((k *= 2) < 1) {
  2628. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2629. }
  2630. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2631. },
  2632. // 创建类似于弹簧在停止前来回振荡的动画
  2633. /**
  2634. * @param {number} k
  2635. * @return {number}
  2636. */
  2637. elasticIn: function (k) {
  2638. var s;
  2639. var a = 0.1;
  2640. var p = 0.4;
  2641. if (k === 0) {
  2642. return 0;
  2643. }
  2644. if (k === 1) {
  2645. return 1;
  2646. }
  2647. if (!a || a < 1) {
  2648. a = 1;
  2649. s = p / 4;
  2650. }
  2651. else {
  2652. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2653. }
  2654. return -(a * Math.pow(2, 10 * (k -= 1))
  2655. * Math.sin((k - s) * (2 * Math.PI) / p));
  2656. },
  2657. /**
  2658. * @param {number} k
  2659. * @return {number}
  2660. */
  2661. elasticOut: function (k) {
  2662. var s;
  2663. var a = 0.1;
  2664. var p = 0.4;
  2665. if (k === 0) {
  2666. return 0;
  2667. }
  2668. if (k === 1) {
  2669. return 1;
  2670. }
  2671. if (!a || a < 1) {
  2672. a = 1;
  2673. s = p / 4;
  2674. }
  2675. else {
  2676. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2677. }
  2678. return (a * Math.pow(2, -10 * k)
  2679. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2680. },
  2681. /**
  2682. * @param {number} k
  2683. * @return {number}
  2684. */
  2685. elasticInOut: function (k) {
  2686. var s;
  2687. var a = 0.1;
  2688. var p = 0.4;
  2689. if (k === 0) {
  2690. return 0;
  2691. }
  2692. if (k === 1) {
  2693. return 1;
  2694. }
  2695. if (!a || a < 1) {
  2696. a = 1;
  2697. s = p / 4;
  2698. }
  2699. else {
  2700. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2701. }
  2702. if ((k *= 2) < 1) {
  2703. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2704. * Math.sin((k - s) * (2 * Math.PI) / p));
  2705. }
  2706. return a * Math.pow(2, -10 * (k -= 1))
  2707. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2708. },
  2709. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2710. /**
  2711. * @param {number} k
  2712. * @return {number}
  2713. */
  2714. backIn: function (k) {
  2715. var s = 1.70158;
  2716. return k * k * ((s + 1) * k - s);
  2717. },
  2718. /**
  2719. * @param {number} k
  2720. * @return {number}
  2721. */
  2722. backOut: function (k) {
  2723. var s = 1.70158;
  2724. return --k * k * ((s + 1) * k + s) + 1;
  2725. },
  2726. /**
  2727. * @param {number} k
  2728. * @return {number}
  2729. */
  2730. backInOut: function (k) {
  2731. var s = 1.70158 * 1.525;
  2732. if ((k *= 2) < 1) {
  2733. return 0.5 * (k * k * ((s + 1) * k - s));
  2734. }
  2735. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2736. },
  2737. // 创建弹跳效果
  2738. /**
  2739. * @param {number} k
  2740. * @return {number}
  2741. */
  2742. bounceIn: function (k) {
  2743. return 1 - easing.bounceOut(1 - k);
  2744. },
  2745. /**
  2746. * @param {number} k
  2747. * @return {number}
  2748. */
  2749. bounceOut: function (k) {
  2750. if (k < (1 / 2.75)) {
  2751. return 7.5625 * k * k;
  2752. }
  2753. else if (k < (2 / 2.75)) {
  2754. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2755. }
  2756. else if (k < (2.5 / 2.75)) {
  2757. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2758. }
  2759. else {
  2760. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2761. }
  2762. },
  2763. /**
  2764. * @param {number} k
  2765. * @return {number}
  2766. */
  2767. bounceInOut: function (k) {
  2768. if (k < 0.5) {
  2769. return easing.bounceIn(k * 2) * 0.5;
  2770. }
  2771. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2772. }
  2773. };
  2774. /**
  2775. * 动画主控制器
  2776. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2777. * @config life(1000) 动画时长
  2778. * @config delay(0) 动画延迟时间
  2779. * @config loop(true)
  2780. * @config gap(0) 循环的间隔时间
  2781. * @config onframe
  2782. * @config easing(optional)
  2783. * @config ondestroy(optional)
  2784. * @config onrestart(optional)
  2785. *
  2786. * TODO pause
  2787. */
  2788. function Clip(options) {
  2789. this._target = options.target;
  2790. // 生命周期
  2791. this._life = options.life || 1000;
  2792. // 延时
  2793. this._delay = options.delay || 0;
  2794. // 开始时间
  2795. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2796. this._initialized = false;
  2797. // 是否循环
  2798. this.loop = options.loop == null ? false : options.loop;
  2799. this.gap = options.gap || 0;
  2800. this.easing = options.easing || 'Linear';
  2801. this.onframe = options.onframe;
  2802. this.ondestroy = options.ondestroy;
  2803. this.onrestart = options.onrestart;
  2804. this._pausedTime = 0;
  2805. this._paused = false;
  2806. }
  2807. Clip.prototype = {
  2808. constructor: Clip,
  2809. step: function (globalTime, deltaTime) {
  2810. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2811. // PENDING
  2812. if (!this._initialized) {
  2813. this._startTime = globalTime + this._delay;
  2814. this._initialized = true;
  2815. }
  2816. if (this._paused) {
  2817. this._pausedTime += deltaTime;
  2818. return;
  2819. }
  2820. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2821. // 还没开始
  2822. if (percent < 0) {
  2823. return;
  2824. }
  2825. percent = Math.min(percent, 1);
  2826. var easing$$1 = this.easing;
  2827. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  2828. var schedule = typeof easingFunc === 'function'
  2829. ? easingFunc(percent)
  2830. : percent;
  2831. this.fire('frame', schedule);
  2832. // 结束
  2833. if (percent === 1) {
  2834. if (this.loop) {
  2835. this.restart(globalTime);
  2836. // 重新开始周期
  2837. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2838. return 'restart';
  2839. }
  2840. // 动画完成将这个控制器标识为待删除
  2841. // 在Animation.update中进行批量删除
  2842. this._needsRemove = true;
  2843. return 'destroy';
  2844. }
  2845. return null;
  2846. },
  2847. restart: function (globalTime) {
  2848. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2849. this._startTime = globalTime - remainder + this.gap;
  2850. this._pausedTime = 0;
  2851. this._needsRemove = false;
  2852. },
  2853. fire: function (eventType, arg) {
  2854. eventType = 'on' + eventType;
  2855. if (this[eventType]) {
  2856. this[eventType](this._target, arg);
  2857. }
  2858. },
  2859. pause: function () {
  2860. this._paused = true;
  2861. },
  2862. resume: function () {
  2863. this._paused = false;
  2864. }
  2865. };
  2866. // Simple LRU cache use doubly linked list
  2867. // @module zrender/core/LRU
  2868. /**
  2869. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2870. * @constructor
  2871. */
  2872. var LinkedList = function () {
  2873. /**
  2874. * @type {module:zrender/core/LRU~Entry}
  2875. */
  2876. this.head = null;
  2877. /**
  2878. * @type {module:zrender/core/LRU~Entry}
  2879. */
  2880. this.tail = null;
  2881. this._len = 0;
  2882. };
  2883. var linkedListProto = LinkedList.prototype;
  2884. /**
  2885. * Insert a new value at the tail
  2886. * @param {} val
  2887. * @return {module:zrender/core/LRU~Entry}
  2888. */
  2889. linkedListProto.insert = function (val) {
  2890. var entry = new Entry(val);
  2891. this.insertEntry(entry);
  2892. return entry;
  2893. };
  2894. /**
  2895. * Insert an entry at the tail
  2896. * @param {module:zrender/core/LRU~Entry} entry
  2897. */
  2898. linkedListProto.insertEntry = function (entry) {
  2899. if (!this.head) {
  2900. this.head = this.tail = entry;
  2901. }
  2902. else {
  2903. this.tail.next = entry;
  2904. entry.prev = this.tail;
  2905. entry.next = null;
  2906. this.tail = entry;
  2907. }
  2908. this._len++;
  2909. };
  2910. /**
  2911. * Remove entry.
  2912. * @param {module:zrender/core/LRU~Entry} entry
  2913. */
  2914. linkedListProto.remove = function (entry) {
  2915. var prev = entry.prev;
  2916. var next = entry.next;
  2917. if (prev) {
  2918. prev.next = next;
  2919. }
  2920. else {
  2921. // Is head
  2922. this.head = next;
  2923. }
  2924. if (next) {
  2925. next.prev = prev;
  2926. }
  2927. else {
  2928. // Is tail
  2929. this.tail = prev;
  2930. }
  2931. entry.next = entry.prev = null;
  2932. this._len--;
  2933. };
  2934. /**
  2935. * @return {number}
  2936. */
  2937. linkedListProto.len = function () {
  2938. return this._len;
  2939. };
  2940. /**
  2941. * Clear list
  2942. */
  2943. linkedListProto.clear = function () {
  2944. this.head = this.tail = null;
  2945. this._len = 0;
  2946. };
  2947. /**
  2948. * @constructor
  2949. * @param {} val
  2950. */
  2951. var Entry = function (val) {
  2952. /**
  2953. * @type {}
  2954. */
  2955. this.value = val;
  2956. /**
  2957. * @type {module:zrender/core/LRU~Entry}
  2958. */
  2959. this.next;
  2960. /**
  2961. * @type {module:zrender/core/LRU~Entry}
  2962. */
  2963. this.prev;
  2964. };
  2965. /**
  2966. * LRU Cache
  2967. * @constructor
  2968. * @alias module:zrender/core/LRU
  2969. */
  2970. var LRU = function (maxSize) {
  2971. this._list = new LinkedList();
  2972. this._map = {};
  2973. this._maxSize = maxSize || 10;
  2974. this._lastRemovedEntry = null;
  2975. };
  2976. var LRUProto = LRU.prototype;
  2977. /**
  2978. * @param {string} key
  2979. * @param {} value
  2980. * @return {} Removed value
  2981. */
  2982. LRUProto.put = function (key, value) {
  2983. var list = this._list;
  2984. var map = this._map;
  2985. var removed = null;
  2986. if (map[key] == null) {
  2987. var len = list.len();
  2988. // Reuse last removed entry
  2989. var entry = this._lastRemovedEntry;
  2990. if (len >= this._maxSize && len > 0) {
  2991. // Remove the least recently used
  2992. var leastUsedEntry = list.head;
  2993. list.remove(leastUsedEntry);
  2994. delete map[leastUsedEntry.key];
  2995. removed = leastUsedEntry.value;
  2996. this._lastRemovedEntry = leastUsedEntry;
  2997. }
  2998. if (entry) {
  2999. entry.value = value;
  3000. }
  3001. else {
  3002. entry = new Entry(value);
  3003. }
  3004. entry.key = key;
  3005. list.insertEntry(entry);
  3006. map[key] = entry;
  3007. }
  3008. return removed;
  3009. };
  3010. /**
  3011. * @param {string} key
  3012. * @return {}
  3013. */
  3014. LRUProto.get = function (key) {
  3015. var entry = this._map[key];
  3016. var list = this._list;
  3017. if (entry != null) {
  3018. // Put the latest used entry in the tail
  3019. if (entry !== list.tail) {
  3020. list.remove(entry);
  3021. list.insertEntry(entry);
  3022. }
  3023. return entry.value;
  3024. }
  3025. };
  3026. /**
  3027. * Clear the cache
  3028. */
  3029. LRUProto.clear = function () {
  3030. this._list.clear();
  3031. this._map = {};
  3032. };
  3033. var kCSSColorTable = {
  3034. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3035. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3036. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3037. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3038. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3039. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3040. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3041. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3042. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3043. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3044. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3045. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3046. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3047. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3048. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3049. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3050. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3051. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3052. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3053. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3054. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3055. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3056. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3057. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3058. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3059. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3060. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3061. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3062. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3063. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3064. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3065. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3066. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3067. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3068. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3069. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3070. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3071. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3072. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3073. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3074. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3075. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3076. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3077. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3078. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3079. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3080. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3081. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3082. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3083. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3084. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3085. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3086. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3087. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3088. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3089. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3090. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3091. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3092. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3093. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3094. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3095. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3096. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3097. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3098. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3099. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3100. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3101. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3102. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3103. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3104. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3105. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3106. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3107. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3108. };
  3109. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3110. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3111. return i < 0 ? 0 : i > 255 ? 255 : i;
  3112. }
  3113. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  3114. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3115. return i < 0 ? 0 : i > 360 ? 360 : i;
  3116. }
  3117. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3118. return f < 0 ? 0 : f > 1 ? 1 : f;
  3119. }
  3120. function parseCssInt(str) { // int or percentage.
  3121. if (str.length && str.charAt(str.length - 1) === '%') {
  3122. return clampCssByte(parseFloat(str) / 100 * 255);
  3123. }
  3124. return clampCssByte(parseInt(str, 10));
  3125. }
  3126. function parseCssFloat(str) { // float or percentage.
  3127. if (str.length && str.charAt(str.length - 1) === '%') {
  3128. return clampCssFloat(parseFloat(str) / 100);
  3129. }
  3130. return clampCssFloat(parseFloat(str));
  3131. }
  3132. function cssHueToRgb(m1, m2, h) {
  3133. if (h < 0) {
  3134. h += 1;
  3135. }
  3136. else if (h > 1) {
  3137. h -= 1;
  3138. }
  3139. if (h * 6 < 1) {
  3140. return m1 + (m2 - m1) * h * 6;
  3141. }
  3142. if (h * 2 < 1) {
  3143. return m2;
  3144. }
  3145. if (h * 3 < 2) {
  3146. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3147. }
  3148. return m1;
  3149. }
  3150. function lerpNumber(a, b, p) {
  3151. return a + (b - a) * p;
  3152. }
  3153. function setRgba(out, r, g, b, a) {
  3154. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  3155. return out;
  3156. }
  3157. function copyRgba(out, a) {
  3158. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  3159. return out;
  3160. }
  3161. var colorCache = new LRU(20);
  3162. var lastRemovedArr = null;
  3163. function putToCache(colorStr, rgbaArr) {
  3164. // Reuse removed array
  3165. if (lastRemovedArr) {
  3166. copyRgba(lastRemovedArr, rgbaArr);
  3167. }
  3168. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3169. }
  3170. /**
  3171. * @param {string} colorStr
  3172. * @param {Array.<number>} out
  3173. * @return {Array.<number>}
  3174. * @memberOf module:zrender/util/color
  3175. */
  3176. function parse(colorStr, rgbaArr) {
  3177. if (!colorStr) {
  3178. return;
  3179. }
  3180. rgbaArr = rgbaArr || [];
  3181. var cached = colorCache.get(colorStr);
  3182. if (cached) {
  3183. return copyRgba(rgbaArr, cached);
  3184. }
  3185. // colorStr may be not string
  3186. colorStr = colorStr + '';
  3187. // Remove all whitespace, not compliant, but should just be more accepting.
  3188. var str = colorStr.replace(/ /g, '').toLowerCase();
  3189. // Color keywords (and transparent) lookup.
  3190. if (str in kCSSColorTable) {
  3191. copyRgba(rgbaArr, kCSSColorTable[str]);
  3192. putToCache(colorStr, rgbaArr);
  3193. return rgbaArr;
  3194. }
  3195. // #abc and #abc123 syntax.
  3196. if (str.charAt(0) === '#') {
  3197. if (str.length === 4) {
  3198. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3199. if (!(iv >= 0 && iv <= 0xfff)) {
  3200. setRgba(rgbaArr, 0, 0, 0, 1);
  3201. return; // Covers NaN.
  3202. }
  3203. setRgba(rgbaArr,
  3204. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3205. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3206. (iv & 0xf) | ((iv & 0xf) << 4),
  3207. 1
  3208. );
  3209. putToCache(colorStr, rgbaArr);
  3210. return rgbaArr;
  3211. }
  3212. else if (str.length === 7) {
  3213. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3214. if (!(iv >= 0 && iv <= 0xffffff)) {
  3215. setRgba(rgbaArr, 0, 0, 0, 1);
  3216. return; // Covers NaN.
  3217. }
  3218. setRgba(rgbaArr,
  3219. (iv & 0xff0000) >> 16,
  3220. (iv & 0xff00) >> 8,
  3221. iv & 0xff,
  3222. 1
  3223. );
  3224. putToCache(colorStr, rgbaArr);
  3225. return rgbaArr;
  3226. }
  3227. return;
  3228. }
  3229. var op = str.indexOf('(');
  3230. var ep = str.indexOf(')');
  3231. if (op !== -1 && ep + 1 === str.length) {
  3232. var fname = str.substr(0, op);
  3233. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3234. var alpha = 1; // To allow case fallthrough.
  3235. switch (fname) {
  3236. case 'rgba':
  3237. if (params.length !== 4) {
  3238. setRgba(rgbaArr, 0, 0, 0, 1);
  3239. return;
  3240. }
  3241. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3242. // Fall through.
  3243. case 'rgb':
  3244. if (params.length !== 3) {
  3245. setRgba(rgbaArr, 0, 0, 0, 1);
  3246. return;
  3247. }
  3248. setRgba(rgbaArr,
  3249. parseCssInt(params[0]),
  3250. parseCssInt(params[1]),
  3251. parseCssInt(params[2]),
  3252. alpha
  3253. );
  3254. putToCache(colorStr, rgbaArr);
  3255. return rgbaArr;
  3256. case 'hsla':
  3257. if (params.length !== 4) {
  3258. setRgba(rgbaArr, 0, 0, 0, 1);
  3259. return;
  3260. }
  3261. params[3] = parseCssFloat(params[3]);
  3262. hsla2rgba(params, rgbaArr);
  3263. putToCache(colorStr, rgbaArr);
  3264. return rgbaArr;
  3265. case 'hsl':
  3266. if (params.length !== 3) {
  3267. setRgba(rgbaArr, 0, 0, 0, 1);
  3268. return;
  3269. }
  3270. hsla2rgba(params, rgbaArr);
  3271. putToCache(colorStr, rgbaArr);
  3272. return rgbaArr;
  3273. default:
  3274. return;
  3275. }
  3276. }
  3277. setRgba(rgbaArr, 0, 0, 0, 1);
  3278. return;
  3279. }
  3280. /**
  3281. * @param {Array.<number>} hsla
  3282. * @param {Array.<number>} rgba
  3283. * @return {Array.<number>} rgba
  3284. */
  3285. function hsla2rgba(hsla, rgba) {
  3286. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3287. // NOTE(deanm): According to the CSS spec s/l should only be
  3288. // percentages, but we don't bother and let float or percentage.
  3289. var s = parseCssFloat(hsla[1]);
  3290. var l = parseCssFloat(hsla[2]);
  3291. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3292. var m1 = l * 2 - m2;
  3293. rgba = rgba || [];
  3294. setRgba(rgba,
  3295. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3296. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3297. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3298. 1
  3299. );
  3300. if (hsla.length === 4) {
  3301. rgba[3] = hsla[3];
  3302. }
  3303. return rgba;
  3304. }
  3305. /**
  3306. * @param {Array.<number>} rgba
  3307. * @return {Array.<number>} hsla
  3308. */
  3309. function rgba2hsla(rgba) {
  3310. if (!rgba) {
  3311. return;
  3312. }
  3313. // RGB from 0 to 255
  3314. var R = rgba[0] / 255;
  3315. var G = rgba[1] / 255;
  3316. var B = rgba[2] / 255;
  3317. var vMin = Math.min(R, G, B); // Min. value of RGB
  3318. var vMax = Math.max(R, G, B); // Max. value of RGB
  3319. var delta = vMax - vMin; // Delta RGB value
  3320. var L = (vMax + vMin) / 2;
  3321. var H;
  3322. var S;
  3323. // HSL results from 0 to 1
  3324. if (delta === 0) {
  3325. H = 0;
  3326. S = 0;
  3327. }
  3328. else {
  3329. if (L < 0.5) {
  3330. S = delta / (vMax + vMin);
  3331. }
  3332. else {
  3333. S = delta / (2 - vMax - vMin);
  3334. }
  3335. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3336. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3337. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3338. if (R === vMax) {
  3339. H = deltaB - deltaG;
  3340. }
  3341. else if (G === vMax) {
  3342. H = (1 / 3) + deltaR - deltaB;
  3343. }
  3344. else if (B === vMax) {
  3345. H = (2 / 3) + deltaG - deltaR;
  3346. }
  3347. if (H < 0) {
  3348. H += 1;
  3349. }
  3350. if (H > 1) {
  3351. H -= 1;
  3352. }
  3353. }
  3354. var hsla = [H * 360, S, L];
  3355. if (rgba[3] != null) {
  3356. hsla.push(rgba[3]);
  3357. }
  3358. return hsla;
  3359. }
  3360. /**
  3361. * @param {string} color
  3362. * @param {number} level
  3363. * @return {string}
  3364. * @memberOf module:zrender/util/color
  3365. */
  3366. function lift(color, level) {
  3367. var colorArr = parse(color);
  3368. if (colorArr) {
  3369. for (var i = 0; i < 3; i++) {
  3370. if (level < 0) {
  3371. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3372. }
  3373. else {
  3374. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3375. }
  3376. if (colorArr[i] > 255) {
  3377. colorArr[i] = 255;
  3378. }
  3379. else if (color[i] < 0) {
  3380. colorArr[i] = 0;
  3381. }
  3382. }
  3383. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3384. }
  3385. }
  3386. /**
  3387. * @param {string} color
  3388. * @return {string}
  3389. * @memberOf module:zrender/util/color
  3390. */
  3391. function toHex(color) {
  3392. var colorArr = parse(color);
  3393. if (colorArr) {
  3394. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3395. }
  3396. }
  3397. /**
  3398. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3399. * @param {number} normalizedValue A float between 0 and 1.
  3400. * @param {Array.<Array.<number>>} colors List of rgba color array
  3401. * @param {Array.<number>} [out] Mapped gba color array
  3402. * @return {Array.<number>} will be null/undefined if input illegal.
  3403. */
  3404. function fastLerp(normalizedValue, colors, out) {
  3405. if (!(colors && colors.length)
  3406. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3407. ) {
  3408. return;
  3409. }
  3410. out = out || [];
  3411. var value = normalizedValue * (colors.length - 1);
  3412. var leftIndex = Math.floor(value);
  3413. var rightIndex = Math.ceil(value);
  3414. var leftColor = colors[leftIndex];
  3415. var rightColor = colors[rightIndex];
  3416. var dv = value - leftIndex;
  3417. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3418. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3419. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3420. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3421. return out;
  3422. }
  3423. /**
  3424. * @deprecated
  3425. */
  3426. var fastMapToColor = fastLerp;
  3427. /**
  3428. * @param {number} normalizedValue A float between 0 and 1.
  3429. * @param {Array.<string>} colors Color list.
  3430. * @param {boolean=} fullOutput Default false.
  3431. * @return {(string|Object)} Result color. If fullOutput,
  3432. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3433. * @memberOf module:zrender/util/color
  3434. */
  3435. function lerp$1(normalizedValue, colors, fullOutput) {
  3436. if (!(colors && colors.length)
  3437. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3438. ) {
  3439. return;
  3440. }
  3441. var value = normalizedValue * (colors.length - 1);
  3442. var leftIndex = Math.floor(value);
  3443. var rightIndex = Math.ceil(value);
  3444. var leftColor = parse(colors[leftIndex]);
  3445. var rightColor = parse(colors[rightIndex]);
  3446. var dv = value - leftIndex;
  3447. var color = stringify(
  3448. [
  3449. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3450. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3451. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3452. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3453. ],
  3454. 'rgba'
  3455. );
  3456. return fullOutput
  3457. ? {
  3458. color: color,
  3459. leftIndex: leftIndex,
  3460. rightIndex: rightIndex,
  3461. value: value
  3462. }
  3463. : color;
  3464. }
  3465. /**
  3466. * @deprecated
  3467. */
  3468. var mapToColor = lerp$1;
  3469. /**
  3470. * @param {string} color
  3471. * @param {number=} h 0 ~ 360, ignore when null.
  3472. * @param {number=} s 0 ~ 1, ignore when null.
  3473. * @param {number=} l 0 ~ 1, ignore when null.
  3474. * @return {string} Color string in rgba format.
  3475. * @memberOf module:zrender/util/color
  3476. */
  3477. function modifyHSL(color, h, s, l) {
  3478. color = parse(color);
  3479. if (color) {
  3480. color = rgba2hsla(color);
  3481. h != null && (color[0] = clampCssAngle(h));
  3482. s != null && (color[1] = parseCssFloat(s));
  3483. l != null && (color[2] = parseCssFloat(l));
  3484. return stringify(hsla2rgba(color), 'rgba');
  3485. }
  3486. }
  3487. /**
  3488. * @param {string} color
  3489. * @param {number=} alpha 0 ~ 1
  3490. * @return {string} Color string in rgba format.
  3491. * @memberOf module:zrender/util/color
  3492. */
  3493. function modifyAlpha(color, alpha) {
  3494. color = parse(color);
  3495. if (color && alpha != null) {
  3496. color[3] = clampCssFloat(alpha);
  3497. return stringify(color, 'rgba');
  3498. }
  3499. }
  3500. /**
  3501. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3502. * @param {string} type 'rgba', 'hsva', ...
  3503. * @return {string} Result color. (If input illegal, return undefined).
  3504. */
  3505. function stringify(arrColor, type) {
  3506. if (!arrColor || !arrColor.length) {
  3507. return;
  3508. }
  3509. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3510. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3511. colorStr += ',' + arrColor[3];
  3512. }
  3513. return type + '(' + colorStr + ')';
  3514. }
  3515. var color = (Object.freeze || Object)({
  3516. parse: parse,
  3517. lift: lift,
  3518. toHex: toHex,
  3519. fastLerp: fastLerp,
  3520. fastMapToColor: fastMapToColor,
  3521. lerp: lerp$1,
  3522. mapToColor: mapToColor,
  3523. modifyHSL: modifyHSL,
  3524. modifyAlpha: modifyAlpha,
  3525. stringify: stringify
  3526. });
  3527. /**
  3528. * @module echarts/animation/Animator
  3529. */
  3530. var arraySlice = Array.prototype.slice;
  3531. function defaultGetter(target, key) {
  3532. return target[key];
  3533. }
  3534. function defaultSetter(target, key, value) {
  3535. target[key] = value;
  3536. }
  3537. /**
  3538. * @param {number} p0
  3539. * @param {number} p1
  3540. * @param {number} percent
  3541. * @return {number}
  3542. */
  3543. function interpolateNumber(p0, p1, percent) {
  3544. return (p1 - p0) * percent + p0;
  3545. }
  3546. /**
  3547. * @param {string} p0
  3548. * @param {string} p1
  3549. * @param {number} percent
  3550. * @return {string}
  3551. */
  3552. function interpolateString(p0, p1, percent) {
  3553. return percent > 0.5 ? p1 : p0;
  3554. }
  3555. /**
  3556. * @param {Array} p0
  3557. * @param {Array} p1
  3558. * @param {number} percent
  3559. * @param {Array} out
  3560. * @param {number} arrDim
  3561. */
  3562. function interpolateArray(p0, p1, percent, out, arrDim) {
  3563. var len = p0.length;
  3564. if (arrDim === 1) {
  3565. for (var i = 0; i < len; i++) {
  3566. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3567. }
  3568. }
  3569. else {
  3570. var len2 = len && p0[0].length;
  3571. for (var i = 0; i < len; i++) {
  3572. for (var j = 0; j < len2; j++) {
  3573. out[i][j] = interpolateNumber(
  3574. p0[i][j], p1[i][j], percent
  3575. );
  3576. }
  3577. }
  3578. }
  3579. }
  3580. // arr0 is source array, arr1 is target array.
  3581. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3582. function fillArr(arr0, arr1, arrDim) {
  3583. var arr0Len = arr0.length;
  3584. var arr1Len = arr1.length;
  3585. if (arr0Len !== arr1Len) {
  3586. // FIXME Not work for TypedArray
  3587. var isPreviousLarger = arr0Len > arr1Len;
  3588. if (isPreviousLarger) {
  3589. // Cut the previous
  3590. arr0.length = arr1Len;
  3591. }
  3592. else {
  3593. // Fill the previous
  3594. for (var i = arr0Len; i < arr1Len; i++) {
  3595. arr0.push(
  3596. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3597. );
  3598. }
  3599. }
  3600. }
  3601. // Handling NaN value
  3602. var len2 = arr0[0] && arr0[0].length;
  3603. for (var i = 0; i < arr0.length; i++) {
  3604. if (arrDim === 1) {
  3605. if (isNaN(arr0[i])) {
  3606. arr0[i] = arr1[i];
  3607. }
  3608. }
  3609. else {
  3610. for (var j = 0; j < len2; j++) {
  3611. if (isNaN(arr0[i][j])) {
  3612. arr0[i][j] = arr1[i][j];
  3613. }
  3614. }
  3615. }
  3616. }
  3617. }
  3618. /**
  3619. * @param {Array} arr0
  3620. * @param {Array} arr1
  3621. * @param {number} arrDim
  3622. * @return {boolean}
  3623. */
  3624. function isArraySame(arr0, arr1, arrDim) {
  3625. if (arr0 === arr1) {
  3626. return true;
  3627. }
  3628. var len = arr0.length;
  3629. if (len !== arr1.length) {
  3630. return false;
  3631. }
  3632. if (arrDim === 1) {
  3633. for (var i = 0; i < len; i++) {
  3634. if (arr0[i] !== arr1[i]) {
  3635. return false;
  3636. }
  3637. }
  3638. }
  3639. else {
  3640. var len2 = arr0[0].length;
  3641. for (var i = 0; i < len; i++) {
  3642. for (var j = 0; j < len2; j++) {
  3643. if (arr0[i][j] !== arr1[i][j]) {
  3644. return false;
  3645. }
  3646. }
  3647. }
  3648. }
  3649. return true;
  3650. }
  3651. /**
  3652. * Catmull Rom interpolate array
  3653. * @param {Array} p0
  3654. * @param {Array} p1
  3655. * @param {Array} p2
  3656. * @param {Array} p3
  3657. * @param {number} t
  3658. * @param {number} t2
  3659. * @param {number} t3
  3660. * @param {Array} out
  3661. * @param {number} arrDim
  3662. */
  3663. function catmullRomInterpolateArray(
  3664. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3665. ) {
  3666. var len = p0.length;
  3667. if (arrDim === 1) {
  3668. for (var i = 0; i < len; i++) {
  3669. out[i] = catmullRomInterpolate(
  3670. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3671. );
  3672. }
  3673. }
  3674. else {
  3675. var len2 = p0[0].length;
  3676. for (var i = 0; i < len; i++) {
  3677. for (var j = 0; j < len2; j++) {
  3678. out[i][j] = catmullRomInterpolate(
  3679. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3680. t, t2, t3
  3681. );
  3682. }
  3683. }
  3684. }
  3685. }
  3686. /**
  3687. * Catmull Rom interpolate number
  3688. * @param {number} p0
  3689. * @param {number} p1
  3690. * @param {number} p2
  3691. * @param {number} p3
  3692. * @param {number} t
  3693. * @param {number} t2
  3694. * @param {number} t3
  3695. * @return {number}
  3696. */
  3697. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3698. var v0 = (p2 - p0) * 0.5;
  3699. var v1 = (p3 - p1) * 0.5;
  3700. return (2 * (p1 - p2) + v0 + v1) * t3
  3701. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3702. + v0 * t + p1;
  3703. }
  3704. function cloneValue(value) {
  3705. if (isArrayLike(value)) {
  3706. var len = value.length;
  3707. if (isArrayLike(value[0])) {
  3708. var ret = [];
  3709. for (var i = 0; i < len; i++) {
  3710. ret.push(arraySlice.call(value[i]));
  3711. }
  3712. return ret;
  3713. }
  3714. return arraySlice.call(value);
  3715. }
  3716. return value;
  3717. }
  3718. function rgba2String(rgba) {
  3719. rgba[0] = Math.floor(rgba[0]);
  3720. rgba[1] = Math.floor(rgba[1]);
  3721. rgba[2] = Math.floor(rgba[2]);
  3722. return 'rgba(' + rgba.join(',') + ')';
  3723. }
  3724. function getArrayDim(keyframes) {
  3725. var lastValue = keyframes[keyframes.length - 1].value;
  3726. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3727. }
  3728. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3729. var getter = animator._getter;
  3730. var setter = animator._setter;
  3731. var useSpline = easing === 'spline';
  3732. var trackLen = keyframes.length;
  3733. if (!trackLen) {
  3734. return;
  3735. }
  3736. // Guess data type
  3737. var firstVal = keyframes[0].value;
  3738. var isValueArray = isArrayLike(firstVal);
  3739. var isValueColor = false;
  3740. var isValueString = false;
  3741. // For vertices morphing
  3742. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3743. var trackMaxTime;
  3744. // Sort keyframe as ascending
  3745. keyframes.sort(function (a, b) {
  3746. return a.time - b.time;
  3747. });
  3748. trackMaxTime = keyframes[trackLen - 1].time;
  3749. // Percents of each keyframe
  3750. var kfPercents = [];
  3751. // Value of each keyframe
  3752. var kfValues = [];
  3753. var prevValue = keyframes[0].value;
  3754. var isAllValueEqual = true;
  3755. for (var i = 0; i < trackLen; i++) {
  3756. kfPercents.push(keyframes[i].time / trackMaxTime);
  3757. // Assume value is a color when it is a string
  3758. var value = keyframes[i].value;
  3759. // Check if value is equal, deep check if value is array
  3760. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3761. || (!isValueArray && value === prevValue))) {
  3762. isAllValueEqual = false;
  3763. }
  3764. prevValue = value;
  3765. // Try converting a string to a color array
  3766. if (typeof value === 'string') {
  3767. var colorArray = parse(value);
  3768. if (colorArray) {
  3769. value = colorArray;
  3770. isValueColor = true;
  3771. }
  3772. else {
  3773. isValueString = true;
  3774. }
  3775. }
  3776. kfValues.push(value);
  3777. }
  3778. if (!forceAnimate && isAllValueEqual) {
  3779. return;
  3780. }
  3781. var lastValue = kfValues[trackLen - 1];
  3782. // Polyfill array and NaN value
  3783. for (var i = 0; i < trackLen - 1; i++) {
  3784. if (isValueArray) {
  3785. fillArr(kfValues[i], lastValue, arrDim);
  3786. }
  3787. else {
  3788. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3789. kfValues[i] = lastValue;
  3790. }
  3791. }
  3792. }
  3793. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3794. // Cache the key of last frame to speed up when
  3795. // animation playback is sequency
  3796. var lastFrame = 0;
  3797. var lastFramePercent = 0;
  3798. var start;
  3799. var w;
  3800. var p0;
  3801. var p1;
  3802. var p2;
  3803. var p3;
  3804. if (isValueColor) {
  3805. var rgba = [0, 0, 0, 0];
  3806. }
  3807. var onframe = function (target, percent) {
  3808. // Find the range keyframes
  3809. // kf1-----kf2---------current--------kf3
  3810. // find kf2 and kf3 and do interpolation
  3811. var frame;
  3812. // In the easing function like elasticOut, percent may less than 0
  3813. if (percent < 0) {
  3814. frame = 0;
  3815. }
  3816. else if (percent < lastFramePercent) {
  3817. // Start from next key
  3818. // PENDING start from lastFrame ?
  3819. start = Math.min(lastFrame + 1, trackLen - 1);
  3820. for (frame = start; frame >= 0; frame--) {
  3821. if (kfPercents[frame] <= percent) {
  3822. break;
  3823. }
  3824. }
  3825. // PENDING really need to do this ?
  3826. frame = Math.min(frame, trackLen - 2);
  3827. }
  3828. else {
  3829. for (frame = lastFrame; frame < trackLen; frame++) {
  3830. if (kfPercents[frame] > percent) {
  3831. break;
  3832. }
  3833. }
  3834. frame = Math.min(frame - 1, trackLen - 2);
  3835. }
  3836. lastFrame = frame;
  3837. lastFramePercent = percent;
  3838. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3839. if (range === 0) {
  3840. return;
  3841. }
  3842. else {
  3843. w = (percent - kfPercents[frame]) / range;
  3844. }
  3845. if (useSpline) {
  3846. p1 = kfValues[frame];
  3847. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3848. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3849. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3850. if (isValueArray) {
  3851. catmullRomInterpolateArray(
  3852. p0, p1, p2, p3, w, w * w, w * w * w,
  3853. getter(target, propName),
  3854. arrDim
  3855. );
  3856. }
  3857. else {
  3858. var value;
  3859. if (isValueColor) {
  3860. value = catmullRomInterpolateArray(
  3861. p0, p1, p2, p3, w, w * w, w * w * w,
  3862. rgba, 1
  3863. );
  3864. value = rgba2String(rgba);
  3865. }
  3866. else if (isValueString) {
  3867. // String is step(0.5)
  3868. return interpolateString(p1, p2, w);
  3869. }
  3870. else {
  3871. value = catmullRomInterpolate(
  3872. p0, p1, p2, p3, w, w * w, w * w * w
  3873. );
  3874. }
  3875. setter(
  3876. target,
  3877. propName,
  3878. value
  3879. );
  3880. }
  3881. }
  3882. else {
  3883. if (isValueArray) {
  3884. interpolateArray(
  3885. kfValues[frame], kfValues[frame + 1], w,
  3886. getter(target, propName),
  3887. arrDim
  3888. );
  3889. }
  3890. else {
  3891. var value;
  3892. if (isValueColor) {
  3893. interpolateArray(
  3894. kfValues[frame], kfValues[frame + 1], w,
  3895. rgba, 1
  3896. );
  3897. value = rgba2String(rgba);
  3898. }
  3899. else if (isValueString) {
  3900. // String is step(0.5)
  3901. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3902. }
  3903. else {
  3904. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3905. }
  3906. setter(
  3907. target,
  3908. propName,
  3909. value
  3910. );
  3911. }
  3912. }
  3913. };
  3914. var clip = new Clip({
  3915. target: animator._target,
  3916. life: trackMaxTime,
  3917. loop: animator._loop,
  3918. delay: animator._delay,
  3919. onframe: onframe,
  3920. ondestroy: oneTrackDone
  3921. });
  3922. if (easing && easing !== 'spline') {
  3923. clip.easing = easing;
  3924. }
  3925. return clip;
  3926. }
  3927. /**
  3928. * @alias module:zrender/animation/Animator
  3929. * @constructor
  3930. * @param {Object} target
  3931. * @param {boolean} loop
  3932. * @param {Function} getter
  3933. * @param {Function} setter
  3934. */
  3935. var Animator = function (target, loop, getter, setter) {
  3936. this._tracks = {};
  3937. this._target = target;
  3938. this._loop = loop || false;
  3939. this._getter = getter || defaultGetter;
  3940. this._setter = setter || defaultSetter;
  3941. this._clipCount = 0;
  3942. this._delay = 0;
  3943. this._doneList = [];
  3944. this._onframeList = [];
  3945. this._clipList = [];
  3946. };
  3947. Animator.prototype = {
  3948. /**
  3949. * 设置动画关键帧
  3950. * @param {number} time 关键帧时间,单位是ms
  3951. * @param {Object} props 关键帧的属性值,key-value表示
  3952. * @return {module:zrender/animation/Animator}
  3953. */
  3954. when: function (time /* ms */, props) {
  3955. var tracks = this._tracks;
  3956. for (var propName in props) {
  3957. if (!props.hasOwnProperty(propName)) {
  3958. continue;
  3959. }
  3960. if (!tracks[propName]) {
  3961. tracks[propName] = [];
  3962. // Invalid value
  3963. var value = this._getter(this._target, propName);
  3964. if (value == null) {
  3965. // zrLog('Invalid property ' + propName);
  3966. continue;
  3967. }
  3968. // If time is 0
  3969. // Then props is given initialize value
  3970. // Else
  3971. // Initialize value from current prop value
  3972. if (time !== 0) {
  3973. tracks[propName].push({
  3974. time: 0,
  3975. value: cloneValue(value)
  3976. });
  3977. }
  3978. }
  3979. tracks[propName].push({
  3980. time: time,
  3981. value: props[propName]
  3982. });
  3983. }
  3984. return this;
  3985. },
  3986. /**
  3987. * 添加动画每一帧的回调函数
  3988. * @param {Function} callback
  3989. * @return {module:zrender/animation/Animator}
  3990. */
  3991. during: function (callback) {
  3992. this._onframeList.push(callback);
  3993. return this;
  3994. },
  3995. pause: function () {
  3996. for (var i = 0; i < this._clipList.length; i++) {
  3997. this._clipList[i].pause();
  3998. }
  3999. this._paused = true;
  4000. },
  4001. resume: function () {
  4002. for (var i = 0; i < this._clipList.length; i++) {
  4003. this._clipList[i].resume();
  4004. }
  4005. this._paused = false;
  4006. },
  4007. isPaused: function () {
  4008. return !!this._paused;
  4009. },
  4010. _doneCallback: function () {
  4011. // Clear all tracks
  4012. this._tracks = {};
  4013. // Clear all clips
  4014. this._clipList.length = 0;
  4015. var doneList = this._doneList;
  4016. var len = doneList.length;
  4017. for (var i = 0; i < len; i++) {
  4018. doneList[i].call(this);
  4019. }
  4020. },
  4021. /**
  4022. * 开始执行动画
  4023. * @param {string|Function} [easing]
  4024. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4025. * @param {boolean} forceAnimate
  4026. * @return {module:zrender/animation/Animator}
  4027. */
  4028. start: function (easing, forceAnimate) {
  4029. var self = this;
  4030. var clipCount = 0;
  4031. var oneTrackDone = function () {
  4032. clipCount--;
  4033. if (!clipCount) {
  4034. self._doneCallback();
  4035. }
  4036. };
  4037. var lastClip;
  4038. for (var propName in this._tracks) {
  4039. if (!this._tracks.hasOwnProperty(propName)) {
  4040. continue;
  4041. }
  4042. var clip = createTrackClip(
  4043. this, easing, oneTrackDone,
  4044. this._tracks[propName], propName, forceAnimate
  4045. );
  4046. if (clip) {
  4047. this._clipList.push(clip);
  4048. clipCount++;
  4049. // If start after added to animation
  4050. if (this.animation) {
  4051. this.animation.addClip(clip);
  4052. }
  4053. lastClip = clip;
  4054. }
  4055. }
  4056. // Add during callback on the last clip
  4057. if (lastClip) {
  4058. var oldOnFrame = lastClip.onframe;
  4059. lastClip.onframe = function (target, percent) {
  4060. oldOnFrame(target, percent);
  4061. for (var i = 0; i < self._onframeList.length; i++) {
  4062. self._onframeList[i](target, percent);
  4063. }
  4064. };
  4065. }
  4066. // This optimization will help the case that in the upper application
  4067. // the view may be refreshed frequently, where animation will be
  4068. // called repeatly but nothing changed.
  4069. if (!clipCount) {
  4070. this._doneCallback();
  4071. }
  4072. return this;
  4073. },
  4074. /**
  4075. * 停止动画
  4076. * @param {boolean} forwardToLast If move to last frame before stop
  4077. */
  4078. stop: function (forwardToLast) {
  4079. var clipList = this._clipList;
  4080. var animation = this.animation;
  4081. for (var i = 0; i < clipList.length; i++) {
  4082. var clip = clipList[i];
  4083. if (forwardToLast) {
  4084. // Move to last frame before stop
  4085. clip.onframe(this._target, 1);
  4086. }
  4087. animation && animation.removeClip(clip);
  4088. }
  4089. clipList.length = 0;
  4090. },
  4091. /**
  4092. * 设置动画延迟开始的时间
  4093. * @param {number} time 单位ms
  4094. * @return {module:zrender/animation/Animator}
  4095. */
  4096. delay: function (time) {
  4097. this._delay = time;
  4098. return this;
  4099. },
  4100. /**
  4101. * 添加动画结束的回调
  4102. * @param {Function} cb
  4103. * @return {module:zrender/animation/Animator}
  4104. */
  4105. done: function (cb) {
  4106. if (cb) {
  4107. this._doneList.push(cb);
  4108. }
  4109. return this;
  4110. },
  4111. /**
  4112. * @return {Array.<module:zrender/animation/Clip>}
  4113. */
  4114. getClips: function () {
  4115. return this._clipList;
  4116. }
  4117. };
  4118. var dpr = 1;
  4119. // If in browser environment
  4120. if (typeof window !== 'undefined') {
  4121. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4122. }
  4123. /**
  4124. * config默认配置项
  4125. * @exports zrender/config
  4126. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4127. */
  4128. /**
  4129. * debug日志选项:catchBrushException为true下有效
  4130. * 0 : 不生成debug数据,发布用
  4131. * 1 : 异常抛出,调试用
  4132. * 2 : 控制台输出,调试用
  4133. */
  4134. var debugMode = 0;
  4135. // retina 屏幕优化
  4136. var devicePixelRatio = dpr;
  4137. var log = function () {
  4138. };
  4139. if (debugMode === 1) {
  4140. log = function () {
  4141. for (var k in arguments) {
  4142. throw new Error(arguments[k]);
  4143. }
  4144. };
  4145. }
  4146. else if (debugMode > 1) {
  4147. log = function () {
  4148. for (var k in arguments) {
  4149. console.log(arguments[k]);
  4150. }
  4151. };
  4152. }
  4153. var zrLog = log;
  4154. /**
  4155. * @alias modue:zrender/mixin/Animatable
  4156. * @constructor
  4157. */
  4158. var Animatable = function () {
  4159. /**
  4160. * @type {Array.<module:zrender/animation/Animator>}
  4161. * @readOnly
  4162. */
  4163. this.animators = [];
  4164. };
  4165. Animatable.prototype = {
  4166. constructor: Animatable,
  4167. /**
  4168. * 动画
  4169. *
  4170. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4171. * @param {boolean} [loop] Whether to loop animation.
  4172. * @return {module:zrender/animation/Animator}
  4173. * @example:
  4174. * el.animate('style', false)
  4175. * .when(1000, {x: 10} )
  4176. * .done(function(){ // Animation done })
  4177. * .start()
  4178. */
  4179. animate: function (path, loop) {
  4180. var target;
  4181. var animatingShape = false;
  4182. var el = this;
  4183. var zr = this.__zr;
  4184. if (path) {
  4185. var pathSplitted = path.split('.');
  4186. var prop = el;
  4187. // If animating shape
  4188. animatingShape = pathSplitted[0] === 'shape';
  4189. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4190. if (!prop) {
  4191. continue;
  4192. }
  4193. prop = prop[pathSplitted[i]];
  4194. }
  4195. if (prop) {
  4196. target = prop;
  4197. }
  4198. }
  4199. else {
  4200. target = el;
  4201. }
  4202. if (!target) {
  4203. zrLog(
  4204. 'Property "'
  4205. + path
  4206. + '" is not existed in element '
  4207. + el.id
  4208. );
  4209. return;
  4210. }
  4211. var animators = el.animators;
  4212. var animator = new Animator(target, loop);
  4213. animator.during(function (target) {
  4214. el.dirty(animatingShape);
  4215. })
  4216. .done(function () {
  4217. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4218. animators.splice(indexOf(animators, animator), 1);
  4219. });
  4220. animators.push(animator);
  4221. // If animate after added to the zrender
  4222. if (zr) {
  4223. zr.animation.addAnimator(animator);
  4224. }
  4225. return animator;
  4226. },
  4227. /**
  4228. * 停止动画
  4229. * @param {boolean} forwardToLast If move to last frame before stop
  4230. */
  4231. stopAnimation: function (forwardToLast) {
  4232. var animators = this.animators;
  4233. var len = animators.length;
  4234. for (var i = 0; i < len; i++) {
  4235. animators[i].stop(forwardToLast);
  4236. }
  4237. animators.length = 0;
  4238. return this;
  4239. },
  4240. /**
  4241. * Caution: this method will stop previous animation.
  4242. * So do not use this method to one element twice before
  4243. * animation starts, unless you know what you are doing.
  4244. * @param {Object} target
  4245. * @param {number} [time=500] Time in ms
  4246. * @param {string} [easing='linear']
  4247. * @param {number} [delay=0]
  4248. * @param {Function} [callback]
  4249. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4250. * immediently when target values are the same as current values.
  4251. *
  4252. * @example
  4253. * // Animate position
  4254. * el.animateTo({
  4255. * position: [10, 10]
  4256. * }, function () { // done })
  4257. *
  4258. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4259. * el.animateTo({
  4260. * shape: {
  4261. * width: 500
  4262. * },
  4263. * style: {
  4264. * fill: 'red'
  4265. * }
  4266. * position: [10, 10]
  4267. * }, 100, 100, 'cubicOut', function () { // done })
  4268. */
  4269. // TODO Return animation key
  4270. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4271. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4272. },
  4273. /**
  4274. * Animate from the target state to current state.
  4275. * The params and the return value are the same as `this.animateTo`.
  4276. */
  4277. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4278. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4279. }
  4280. };
  4281. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4282. // animateTo(target, time, easing, callback);
  4283. if (isString(delay)) {
  4284. callback = easing;
  4285. easing = delay;
  4286. delay = 0;
  4287. }
  4288. // animateTo(target, time, delay, callback);
  4289. else if (isFunction$1(easing)) {
  4290. callback = easing;
  4291. easing = 'linear';
  4292. delay = 0;
  4293. }
  4294. // animateTo(target, time, callback);
  4295. else if (isFunction$1(delay)) {
  4296. callback = delay;
  4297. delay = 0;
  4298. }
  4299. // animateTo(target, callback)
  4300. else if (isFunction$1(time)) {
  4301. callback = time;
  4302. time = 500;
  4303. }
  4304. // animateTo(target)
  4305. else if (!time) {
  4306. time = 500;
  4307. }
  4308. // Stop all previous animations
  4309. animatable.stopAnimation();
  4310. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4311. // Animators may be removed immediately after start
  4312. // if there is nothing to animate
  4313. var animators = animatable.animators.slice();
  4314. var count = animators.length;
  4315. function done() {
  4316. count--;
  4317. if (!count) {
  4318. callback && callback();
  4319. }
  4320. }
  4321. // No animators. This should be checked before animators[i].start(),
  4322. // because 'done' may be executed immediately if no need to animate.
  4323. if (!count) {
  4324. callback && callback();
  4325. }
  4326. // Start after all animators created
  4327. // Incase any animator is done immediately when all animation properties are not changed
  4328. for (var i = 0; i < animators.length; i++) {
  4329. animators[i]
  4330. .done(done)
  4331. .start(easing, forceAnimate);
  4332. }
  4333. }
  4334. /**
  4335. * @param {string} path=''
  4336. * @param {Object} source=animatable
  4337. * @param {Object} target
  4338. * @param {number} [time=500]
  4339. * @param {number} [delay=0]
  4340. * @param {boolean} [reverse] If `true`, animate
  4341. * from the `target` to current state.
  4342. *
  4343. * @example
  4344. * // Animate position
  4345. * el._animateToShallow({
  4346. * position: [10, 10]
  4347. * })
  4348. *
  4349. * // Animate shape, style and position in 100ms, delayed 100ms
  4350. * el._animateToShallow({
  4351. * shape: {
  4352. * width: 500
  4353. * },
  4354. * style: {
  4355. * fill: 'red'
  4356. * }
  4357. * position: [10, 10]
  4358. * }, 100, 100)
  4359. */
  4360. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4361. var objShallow = {};
  4362. var propertyCount = 0;
  4363. for (var name in target) {
  4364. if (!target.hasOwnProperty(name)) {
  4365. continue;
  4366. }
  4367. if (source[name] != null) {
  4368. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4369. animateToShallow(
  4370. animatable,
  4371. path ? path + '.' + name : name,
  4372. source[name],
  4373. target[name],
  4374. time,
  4375. delay,
  4376. reverse
  4377. );
  4378. }
  4379. else {
  4380. if (reverse) {
  4381. objShallow[name] = source[name];
  4382. setAttrByPath(animatable, path, name, target[name]);
  4383. }
  4384. else {
  4385. objShallow[name] = target[name];
  4386. }
  4387. propertyCount++;
  4388. }
  4389. }
  4390. else if (target[name] != null && !reverse) {
  4391. setAttrByPath(animatable, path, name, target[name]);
  4392. }
  4393. }
  4394. if (propertyCount > 0) {
  4395. animatable.animate(path, false)
  4396. .when(time == null ? 500 : time, objShallow)
  4397. .delay(delay || 0);
  4398. }
  4399. }
  4400. function setAttrByPath(el, path, name, value) {
  4401. // Attr directly if not has property
  4402. // FIXME, if some property not needed for element ?
  4403. if (!path) {
  4404. el.attr(name, value);
  4405. }
  4406. else {
  4407. // Only support set shape or style
  4408. var props = {};
  4409. props[path] = {};
  4410. props[path][name] = value;
  4411. el.attr(props);
  4412. }
  4413. }
  4414. /**
  4415. * @alias module:zrender/Element
  4416. * @constructor
  4417. * @extends {module:zrender/mixin/Animatable}
  4418. * @extends {module:zrender/mixin/Transformable}
  4419. * @extends {module:zrender/mixin/Eventful}
  4420. */
  4421. var Element = function (opts) { // jshint ignore:line
  4422. Transformable.call(this, opts);
  4423. Eventful.call(this, opts);
  4424. Animatable.call(this, opts);
  4425. /**
  4426. * 画布元素ID
  4427. * @type {string}
  4428. */
  4429. this.id = opts.id || guid();
  4430. };
  4431. Element.prototype = {
  4432. /**
  4433. * 元素类型
  4434. * Element type
  4435. * @type {string}
  4436. */
  4437. type: 'element',
  4438. /**
  4439. * 元素名字
  4440. * Element name
  4441. * @type {string}
  4442. */
  4443. name: '',
  4444. /**
  4445. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4446. * ZRender instance will be assigned when element is associated with zrender
  4447. * @name module:/zrender/Element#__zr
  4448. * @type {module:zrender/ZRender}
  4449. */
  4450. __zr: null,
  4451. /**
  4452. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4453. * If ignore drawing and events of the element object
  4454. * @name module:/zrender/Element#ignore
  4455. * @type {boolean}
  4456. * @default false
  4457. */
  4458. ignore: false,
  4459. /**
  4460. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4461. * 该路径会继承被裁减对象的变换
  4462. * @type {module:zrender/graphic/Path}
  4463. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4464. * @readOnly
  4465. */
  4466. clipPath: null,
  4467. /**
  4468. * 是否是 Group
  4469. * @type {boolean}
  4470. */
  4471. isGroup: false,
  4472. /**
  4473. * Drift element
  4474. * @param {number} dx dx on the global space
  4475. * @param {number} dy dy on the global space
  4476. */
  4477. drift: function (dx, dy) {
  4478. switch (this.draggable) {
  4479. case 'horizontal':
  4480. dy = 0;
  4481. break;
  4482. case 'vertical':
  4483. dx = 0;
  4484. break;
  4485. }
  4486. var m = this.transform;
  4487. if (!m) {
  4488. m = this.transform = [1, 0, 0, 1, 0, 0];
  4489. }
  4490. m[4] += dx;
  4491. m[5] += dy;
  4492. this.decomposeTransform();
  4493. this.dirty(false);
  4494. },
  4495. /**
  4496. * Hook before update
  4497. */
  4498. beforeUpdate: function () {},
  4499. /**
  4500. * Hook after update
  4501. */
  4502. afterUpdate: function () {},
  4503. /**
  4504. * Update each frame
  4505. */
  4506. update: function () {
  4507. this.updateTransform();
  4508. },
  4509. /**
  4510. * @param {Function} cb
  4511. * @param {} context
  4512. */
  4513. traverse: function (cb, context) {},
  4514. /**
  4515. * @protected
  4516. */
  4517. attrKV: function (key, value) {
  4518. if (key === 'position' || key === 'scale' || key === 'origin') {
  4519. // Copy the array
  4520. if (value) {
  4521. var target = this[key];
  4522. if (!target) {
  4523. target = this[key] = [];
  4524. }
  4525. target[0] = value[0];
  4526. target[1] = value[1];
  4527. }
  4528. }
  4529. else {
  4530. this[key] = value;
  4531. }
  4532. },
  4533. /**
  4534. * Hide the element
  4535. */
  4536. hide: function () {
  4537. this.ignore = true;
  4538. this.__zr && this.__zr.refresh();
  4539. },
  4540. /**
  4541. * Show the element
  4542. */
  4543. show: function () {
  4544. this.ignore = false;
  4545. this.__zr && this.__zr.refresh();
  4546. },
  4547. /**
  4548. * @param {string|Object} key
  4549. * @param {*} value
  4550. */
  4551. attr: function (key, value) {
  4552. if (typeof key === 'string') {
  4553. this.attrKV(key, value);
  4554. }
  4555. else if (isObject$1(key)) {
  4556. for (var name in key) {
  4557. if (key.hasOwnProperty(name)) {
  4558. this.attrKV(name, key[name]);
  4559. }
  4560. }
  4561. }
  4562. this.dirty(false);
  4563. return this;
  4564. },
  4565. /**
  4566. * @param {module:zrender/graphic/Path} clipPath
  4567. */
  4568. setClipPath: function (clipPath) {
  4569. var zr = this.__zr;
  4570. if (zr) {
  4571. clipPath.addSelfToZr(zr);
  4572. }
  4573. // Remove previous clip path
  4574. if (this.clipPath && this.clipPath !== clipPath) {
  4575. this.removeClipPath();
  4576. }
  4577. this.clipPath = clipPath;
  4578. clipPath.__zr = zr;
  4579. clipPath.__clipTarget = this;
  4580. this.dirty(false);
  4581. },
  4582. /**
  4583. */
  4584. removeClipPath: function () {
  4585. var clipPath = this.clipPath;
  4586. if (clipPath) {
  4587. if (clipPath.__zr) {
  4588. clipPath.removeSelfFromZr(clipPath.__zr);
  4589. }
  4590. clipPath.__zr = null;
  4591. clipPath.__clipTarget = null;
  4592. this.clipPath = null;
  4593. this.dirty(false);
  4594. }
  4595. },
  4596. /**
  4597. * Add self from zrender instance.
  4598. * Not recursively because it will be invoked when element added to storage.
  4599. * @param {module:zrender/ZRender} zr
  4600. */
  4601. addSelfToZr: function (zr) {
  4602. this.__zr = zr;
  4603. // 添加动画
  4604. var animators = this.animators;
  4605. if (animators) {
  4606. for (var i = 0; i < animators.length; i++) {
  4607. zr.animation.addAnimator(animators[i]);
  4608. }
  4609. }
  4610. if (this.clipPath) {
  4611. this.clipPath.addSelfToZr(zr);
  4612. }
  4613. },
  4614. /**
  4615. * Remove self from zrender instance.
  4616. * Not recursively because it will be invoked when element added to storage.
  4617. * @param {module:zrender/ZRender} zr
  4618. */
  4619. removeSelfFromZr: function (zr) {
  4620. this.__zr = null;
  4621. // 移除动画
  4622. var animators = this.animators;
  4623. if (animators) {
  4624. for (var i = 0; i < animators.length; i++) {
  4625. zr.animation.removeAnimator(animators[i]);
  4626. }
  4627. }
  4628. if (this.clipPath) {
  4629. this.clipPath.removeSelfFromZr(zr);
  4630. }
  4631. }
  4632. };
  4633. mixin(Element, Animatable);
  4634. mixin(Element, Transformable);
  4635. mixin(Element, Eventful);
  4636. /**
  4637. * @module echarts/core/BoundingRect
  4638. */
  4639. var v2ApplyTransform = applyTransform;
  4640. var mathMin = Math.min;
  4641. var mathMax = Math.max;
  4642. /**
  4643. * @alias module:echarts/core/BoundingRect
  4644. */
  4645. function BoundingRect(x, y, width, height) {
  4646. if (width < 0) {
  4647. x = x + width;
  4648. width = -width;
  4649. }
  4650. if (height < 0) {
  4651. y = y + height;
  4652. height = -height;
  4653. }
  4654. /**
  4655. * @type {number}
  4656. */
  4657. this.x = x;
  4658. /**
  4659. * @type {number}
  4660. */
  4661. this.y = y;
  4662. /**
  4663. * @type {number}
  4664. */
  4665. this.width = width;
  4666. /**
  4667. * @type {number}
  4668. */
  4669. this.height = height;
  4670. }
  4671. BoundingRect.prototype = {
  4672. constructor: BoundingRect,
  4673. /**
  4674. * @param {module:echarts/core/BoundingRect} other
  4675. */
  4676. union: function (other) {
  4677. var x = mathMin(other.x, this.x);
  4678. var y = mathMin(other.y, this.y);
  4679. this.width = mathMax(
  4680. other.x + other.width,
  4681. this.x + this.width
  4682. ) - x;
  4683. this.height = mathMax(
  4684. other.y + other.height,
  4685. this.y + this.height
  4686. ) - y;
  4687. this.x = x;
  4688. this.y = y;
  4689. },
  4690. /**
  4691. * @param {Array.<number>} m
  4692. * @methods
  4693. */
  4694. applyTransform: (function () {
  4695. var lt = [];
  4696. var rb = [];
  4697. var lb = [];
  4698. var rt = [];
  4699. return function (m) {
  4700. // In case usage like this
  4701. // el.getBoundingRect().applyTransform(el.transform)
  4702. // And element has no transform
  4703. if (!m) {
  4704. return;
  4705. }
  4706. lt[0] = lb[0] = this.x;
  4707. lt[1] = rt[1] = this.y;
  4708. rb[0] = rt[0] = this.x + this.width;
  4709. rb[1] = lb[1] = this.y + this.height;
  4710. v2ApplyTransform(lt, lt, m);
  4711. v2ApplyTransform(rb, rb, m);
  4712. v2ApplyTransform(lb, lb, m);
  4713. v2ApplyTransform(rt, rt, m);
  4714. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4715. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4716. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4717. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4718. this.width = maxX - this.x;
  4719. this.height = maxY - this.y;
  4720. };
  4721. })(),
  4722. /**
  4723. * Calculate matrix of transforming from self to target rect
  4724. * @param {module:zrender/core/BoundingRect} b
  4725. * @return {Array.<number>}
  4726. */
  4727. calculateTransform: function (b) {
  4728. var a = this;
  4729. var sx = b.width / a.width;
  4730. var sy = b.height / a.height;
  4731. var m = create$1();
  4732. // 矩阵右乘
  4733. translate(m, m, [-a.x, -a.y]);
  4734. scale$1(m, m, [sx, sy]);
  4735. translate(m, m, [b.x, b.y]);
  4736. return m;
  4737. },
  4738. /**
  4739. * @param {(module:echarts/core/BoundingRect|Object)} b
  4740. * @return {boolean}
  4741. */
  4742. intersect: function (b) {
  4743. if (!b) {
  4744. return false;
  4745. }
  4746. if (!(b instanceof BoundingRect)) {
  4747. // Normalize negative width/height.
  4748. b = BoundingRect.create(b);
  4749. }
  4750. var a = this;
  4751. var ax0 = a.x;
  4752. var ax1 = a.x + a.width;
  4753. var ay0 = a.y;
  4754. var ay1 = a.y + a.height;
  4755. var bx0 = b.x;
  4756. var bx1 = b.x + b.width;
  4757. var by0 = b.y;
  4758. var by1 = b.y + b.height;
  4759. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4760. },
  4761. contain: function (x, y) {
  4762. var rect = this;
  4763. return x >= rect.x
  4764. && x <= (rect.x + rect.width)
  4765. && y >= rect.y
  4766. && y <= (rect.y + rect.height);
  4767. },
  4768. /**
  4769. * @return {module:echarts/core/BoundingRect}
  4770. */
  4771. clone: function () {
  4772. return new BoundingRect(this.x, this.y, this.width, this.height);
  4773. },
  4774. /**
  4775. * Copy from another rect
  4776. */
  4777. copy: function (other) {
  4778. this.x = other.x;
  4779. this.y = other.y;
  4780. this.width = other.width;
  4781. this.height = other.height;
  4782. },
  4783. plain: function () {
  4784. return {
  4785. x: this.x,
  4786. y: this.y,
  4787. width: this.width,
  4788. height: this.height
  4789. };
  4790. }
  4791. };
  4792. /**
  4793. * @param {Object|module:zrender/core/BoundingRect} rect
  4794. * @param {number} rect.x
  4795. * @param {number} rect.y
  4796. * @param {number} rect.width
  4797. * @param {number} rect.height
  4798. * @return {module:zrender/core/BoundingRect}
  4799. */
  4800. BoundingRect.create = function (rect) {
  4801. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4802. };
  4803. /**
  4804. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4805. * @module zrender/graphic/Group
  4806. * @example
  4807. * var Group = require('zrender/container/Group');
  4808. * var Circle = require('zrender/graphic/shape/Circle');
  4809. * var g = new Group();
  4810. * g.position[0] = 100;
  4811. * g.position[1] = 100;
  4812. * g.add(new Circle({
  4813. * style: {
  4814. * x: 100,
  4815. * y: 100,
  4816. * r: 20,
  4817. * }
  4818. * }));
  4819. * zr.add(g);
  4820. */
  4821. /**
  4822. * @alias module:zrender/graphic/Group
  4823. * @constructor
  4824. * @extends module:zrender/mixin/Transformable
  4825. * @extends module:zrender/mixin/Eventful
  4826. */
  4827. var Group = function (opts) {
  4828. opts = opts || {};
  4829. Element.call(this, opts);
  4830. for (var key in opts) {
  4831. if (opts.hasOwnProperty(key)) {
  4832. this[key] = opts[key];
  4833. }
  4834. }
  4835. this._children = [];
  4836. this.__storage = null;
  4837. this.__dirty = true;
  4838. };
  4839. Group.prototype = {
  4840. constructor: Group,
  4841. isGroup: true,
  4842. /**
  4843. * @type {string}
  4844. */
  4845. type: 'group',
  4846. /**
  4847. * 所有子孙元素是否响应鼠标事件
  4848. * @name module:/zrender/container/Group#silent
  4849. * @type {boolean}
  4850. * @default false
  4851. */
  4852. silent: false,
  4853. /**
  4854. * @return {Array.<module:zrender/Element>}
  4855. */
  4856. children: function () {
  4857. return this._children.slice();
  4858. },
  4859. /**
  4860. * 获取指定 index 的儿子节点
  4861. * @param {number} idx
  4862. * @return {module:zrender/Element}
  4863. */
  4864. childAt: function (idx) {
  4865. return this._children[idx];
  4866. },
  4867. /**
  4868. * 获取指定名字的儿子节点
  4869. * @param {string} name
  4870. * @return {module:zrender/Element}
  4871. */
  4872. childOfName: function (name) {
  4873. var children = this._children;
  4874. for (var i = 0; i < children.length; i++) {
  4875. if (children[i].name === name) {
  4876. return children[i];
  4877. }
  4878. }
  4879. },
  4880. /**
  4881. * @return {number}
  4882. */
  4883. childCount: function () {
  4884. return this._children.length;
  4885. },
  4886. /**
  4887. * 添加子节点到最后
  4888. * @param {module:zrender/Element} child
  4889. */
  4890. add: function (child) {
  4891. if (child && child !== this && child.parent !== this) {
  4892. this._children.push(child);
  4893. this._doAdd(child);
  4894. }
  4895. return this;
  4896. },
  4897. /**
  4898. * 添加子节点在 nextSibling 之前
  4899. * @param {module:zrender/Element} child
  4900. * @param {module:zrender/Element} nextSibling
  4901. */
  4902. addBefore: function (child, nextSibling) {
  4903. if (child && child !== this && child.parent !== this
  4904. && nextSibling && nextSibling.parent === this) {
  4905. var children = this._children;
  4906. var idx = children.indexOf(nextSibling);
  4907. if (idx >= 0) {
  4908. children.splice(idx, 0, child);
  4909. this._doAdd(child);
  4910. }
  4911. }
  4912. return this;
  4913. },
  4914. _doAdd: function (child) {
  4915. if (child.parent) {
  4916. child.parent.remove(child);
  4917. }
  4918. child.parent = this;
  4919. var storage = this.__storage;
  4920. var zr = this.__zr;
  4921. if (storage && storage !== child.__storage) {
  4922. storage.addToStorage(child);
  4923. if (child instanceof Group) {
  4924. child.addChildrenToStorage(storage);
  4925. }
  4926. }
  4927. zr && zr.refresh();
  4928. },
  4929. /**
  4930. * 移除子节点
  4931. * @param {module:zrender/Element} child
  4932. */
  4933. remove: function (child) {
  4934. var zr = this.__zr;
  4935. var storage = this.__storage;
  4936. var children = this._children;
  4937. var idx = indexOf(children, child);
  4938. if (idx < 0) {
  4939. return this;
  4940. }
  4941. children.splice(idx, 1);
  4942. child.parent = null;
  4943. if (storage) {
  4944. storage.delFromStorage(child);
  4945. if (child instanceof Group) {
  4946. child.delChildrenFromStorage(storage);
  4947. }
  4948. }
  4949. zr && zr.refresh();
  4950. return this;
  4951. },
  4952. /**
  4953. * 移除所有子节点
  4954. */
  4955. removeAll: function () {
  4956. var children = this._children;
  4957. var storage = this.__storage;
  4958. var child;
  4959. var i;
  4960. for (i = 0; i < children.length; i++) {
  4961. child = children[i];
  4962. if (storage) {
  4963. storage.delFromStorage(child);
  4964. if (child instanceof Group) {
  4965. child.delChildrenFromStorage(storage);
  4966. }
  4967. }
  4968. child.parent = null;
  4969. }
  4970. children.length = 0;
  4971. return this;
  4972. },
  4973. /**
  4974. * 遍历所有子节点
  4975. * @param {Function} cb
  4976. * @param {} context
  4977. */
  4978. eachChild: function (cb, context) {
  4979. var children = this._children;
  4980. for (var i = 0; i < children.length; i++) {
  4981. var child = children[i];
  4982. cb.call(context, child, i);
  4983. }
  4984. return this;
  4985. },
  4986. /**
  4987. * 深度优先遍历所有子孙节点
  4988. * @param {Function} cb
  4989. * @param {} context
  4990. */
  4991. traverse: function (cb, context) {
  4992. for (var i = 0; i < this._children.length; i++) {
  4993. var child = this._children[i];
  4994. cb.call(context, child);
  4995. if (child.type === 'group') {
  4996. child.traverse(cb, context);
  4997. }
  4998. }
  4999. return this;
  5000. },
  5001. addChildrenToStorage: function (storage) {
  5002. for (var i = 0; i < this._children.length; i++) {
  5003. var child = this._children[i];
  5004. storage.addToStorage(child);
  5005. if (child instanceof Group) {
  5006. child.addChildrenToStorage(storage);
  5007. }
  5008. }
  5009. },
  5010. delChildrenFromStorage: function (storage) {
  5011. for (var i = 0; i < this._children.length; i++) {
  5012. var child = this._children[i];
  5013. storage.delFromStorage(child);
  5014. if (child instanceof Group) {
  5015. child.delChildrenFromStorage(storage);
  5016. }
  5017. }
  5018. },
  5019. dirty: function () {
  5020. this.__dirty = true;
  5021. this.__zr && this.__zr.refresh();
  5022. return this;
  5023. },
  5024. /**
  5025. * @return {module:zrender/core/BoundingRect}
  5026. */
  5027. getBoundingRect: function (includeChildren) {
  5028. // TODO Caching
  5029. var rect = null;
  5030. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5031. var children = includeChildren || this._children;
  5032. var tmpMat = [];
  5033. for (var i = 0; i < children.length; i++) {
  5034. var child = children[i];
  5035. if (child.ignore || child.invisible) {
  5036. continue;
  5037. }
  5038. var childRect = child.getBoundingRect();
  5039. var transform = child.getLocalTransform(tmpMat);
  5040. // TODO
  5041. // The boundingRect cacluated by transforming original
  5042. // rect may be bigger than the actual bundingRect when rotation
  5043. // is used. (Consider a circle rotated aginst its center, where
  5044. // the actual boundingRect should be the same as that not be
  5045. // rotated.) But we can not find better approach to calculate
  5046. // actual boundingRect yet, considering performance.
  5047. if (transform) {
  5048. tmpRect.copy(childRect);
  5049. tmpRect.applyTransform(transform);
  5050. rect = rect || tmpRect.clone();
  5051. rect.union(tmpRect);
  5052. }
  5053. else {
  5054. rect = rect || childRect.clone();
  5055. rect.union(childRect);
  5056. }
  5057. }
  5058. return rect || tmpRect;
  5059. }
  5060. };
  5061. inherits(Group, Element);
  5062. // https://github.com/mziccard/node-timsort
  5063. var DEFAULT_MIN_MERGE = 32;
  5064. var DEFAULT_MIN_GALLOPING = 7;
  5065. function minRunLength(n) {
  5066. var r = 0;
  5067. while (n >= DEFAULT_MIN_MERGE) {
  5068. r |= n & 1;
  5069. n >>= 1;
  5070. }
  5071. return n + r;
  5072. }
  5073. function makeAscendingRun(array, lo, hi, compare) {
  5074. var runHi = lo + 1;
  5075. if (runHi === hi) {
  5076. return 1;
  5077. }
  5078. if (compare(array[runHi++], array[lo]) < 0) {
  5079. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5080. runHi++;
  5081. }
  5082. reverseRun(array, lo, runHi);
  5083. }
  5084. else {
  5085. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5086. runHi++;
  5087. }
  5088. }
  5089. return runHi - lo;
  5090. }
  5091. function reverseRun(array, lo, hi) {
  5092. hi--;
  5093. while (lo < hi) {
  5094. var t = array[lo];
  5095. array[lo++] = array[hi];
  5096. array[hi--] = t;
  5097. }
  5098. }
  5099. function binaryInsertionSort(array, lo, hi, start, compare) {
  5100. if (start === lo) {
  5101. start++;
  5102. }
  5103. for (; start < hi; start++) {
  5104. var pivot = array[start];
  5105. var left = lo;
  5106. var right = start;
  5107. var mid;
  5108. while (left < right) {
  5109. mid = left + right >>> 1;
  5110. if (compare(pivot, array[mid]) < 0) {
  5111. right = mid;
  5112. }
  5113. else {
  5114. left = mid + 1;
  5115. }
  5116. }
  5117. var n = start - left;
  5118. switch (n) {
  5119. case 3:
  5120. array[left + 3] = array[left + 2];
  5121. case 2:
  5122. array[left + 2] = array[left + 1];
  5123. case 1:
  5124. array[left + 1] = array[left];
  5125. break;
  5126. default:
  5127. while (n > 0) {
  5128. array[left + n] = array[left + n - 1];
  5129. n--;
  5130. }
  5131. }
  5132. array[left] = pivot;
  5133. }
  5134. }
  5135. function gallopLeft(value, array, start, length, hint, compare) {
  5136. var lastOffset = 0;
  5137. var maxOffset = 0;
  5138. var offset = 1;
  5139. if (compare(value, array[start + hint]) > 0) {
  5140. maxOffset = length - hint;
  5141. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5142. lastOffset = offset;
  5143. offset = (offset << 1) + 1;
  5144. if (offset <= 0) {
  5145. offset = maxOffset;
  5146. }
  5147. }
  5148. if (offset > maxOffset) {
  5149. offset = maxOffset;
  5150. }
  5151. lastOffset += hint;
  5152. offset += hint;
  5153. }
  5154. else {
  5155. maxOffset = hint + 1;
  5156. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5157. lastOffset = offset;
  5158. offset = (offset << 1) + 1;
  5159. if (offset <= 0) {
  5160. offset = maxOffset;
  5161. }
  5162. }
  5163. if (offset > maxOffset) {
  5164. offset = maxOffset;
  5165. }
  5166. var tmp = lastOffset;
  5167. lastOffset = hint - offset;
  5168. offset = hint - tmp;
  5169. }
  5170. lastOffset++;
  5171. while (lastOffset < offset) {
  5172. var m = lastOffset + (offset - lastOffset >>> 1);
  5173. if (compare(value, array[start + m]) > 0) {
  5174. lastOffset = m + 1;
  5175. }
  5176. else {
  5177. offset = m;
  5178. }
  5179. }
  5180. return offset;
  5181. }
  5182. function gallopRight(value, array, start, length, hint, compare) {
  5183. var lastOffset = 0;
  5184. var maxOffset = 0;
  5185. var offset = 1;
  5186. if (compare(value, array[start + hint]) < 0) {
  5187. maxOffset = hint + 1;
  5188. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5189. lastOffset = offset;
  5190. offset = (offset << 1) + 1;
  5191. if (offset <= 0) {
  5192. offset = maxOffset;
  5193. }
  5194. }
  5195. if (offset > maxOffset) {
  5196. offset = maxOffset;
  5197. }
  5198. var tmp = lastOffset;
  5199. lastOffset = hint - offset;
  5200. offset = hint - tmp;
  5201. }
  5202. else {
  5203. maxOffset = length - hint;
  5204. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5205. lastOffset = offset;
  5206. offset = (offset << 1) + 1;
  5207. if (offset <= 0) {
  5208. offset = maxOffset;
  5209. }
  5210. }
  5211. if (offset > maxOffset) {
  5212. offset = maxOffset;
  5213. }
  5214. lastOffset += hint;
  5215. offset += hint;
  5216. }
  5217. lastOffset++;
  5218. while (lastOffset < offset) {
  5219. var m = lastOffset + (offset - lastOffset >>> 1);
  5220. if (compare(value, array[start + m]) < 0) {
  5221. offset = m;
  5222. }
  5223. else {
  5224. lastOffset = m + 1;
  5225. }
  5226. }
  5227. return offset;
  5228. }
  5229. function TimSort(array, compare) {
  5230. var minGallop = DEFAULT_MIN_GALLOPING;
  5231. var runStart;
  5232. var runLength;
  5233. var stackSize = 0;
  5234. var tmp = [];
  5235. runStart = [];
  5236. runLength = [];
  5237. function pushRun(_runStart, _runLength) {
  5238. runStart[stackSize] = _runStart;
  5239. runLength[stackSize] = _runLength;
  5240. stackSize += 1;
  5241. }
  5242. function mergeRuns() {
  5243. while (stackSize > 1) {
  5244. var n = stackSize - 2;
  5245. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  5246. if (runLength[n - 1] < runLength[n + 1]) {
  5247. n--;
  5248. }
  5249. }
  5250. else if (runLength[n] > runLength[n + 1]) {
  5251. break;
  5252. }
  5253. mergeAt(n);
  5254. }
  5255. }
  5256. function forceMergeRuns() {
  5257. while (stackSize > 1) {
  5258. var n = stackSize - 2;
  5259. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5260. n--;
  5261. }
  5262. mergeAt(n);
  5263. }
  5264. }
  5265. function mergeAt(i) {
  5266. var start1 = runStart[i];
  5267. var length1 = runLength[i];
  5268. var start2 = runStart[i + 1];
  5269. var length2 = runLength[i + 1];
  5270. runLength[i] = length1 + length2;
  5271. if (i === stackSize - 3) {
  5272. runStart[i + 1] = runStart[i + 2];
  5273. runLength[i + 1] = runLength[i + 2];
  5274. }
  5275. stackSize--;
  5276. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5277. start1 += k;
  5278. length1 -= k;
  5279. if (length1 === 0) {
  5280. return;
  5281. }
  5282. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5283. if (length2 === 0) {
  5284. return;
  5285. }
  5286. if (length1 <= length2) {
  5287. mergeLow(start1, length1, start2, length2);
  5288. }
  5289. else {
  5290. mergeHigh(start1, length1, start2, length2);
  5291. }
  5292. }
  5293. function mergeLow(start1, length1, start2, length2) {
  5294. var i = 0;
  5295. for (i = 0; i < length1; i++) {
  5296. tmp[i] = array[start1 + i];
  5297. }
  5298. var cursor1 = 0;
  5299. var cursor2 = start2;
  5300. var dest = start1;
  5301. array[dest++] = array[cursor2++];
  5302. if (--length2 === 0) {
  5303. for (i = 0; i < length1; i++) {
  5304. array[dest + i] = tmp[cursor1 + i];
  5305. }
  5306. return;
  5307. }
  5308. if (length1 === 1) {
  5309. for (i = 0; i < length2; i++) {
  5310. array[dest + i] = array[cursor2 + i];
  5311. }
  5312. array[dest + length2] = tmp[cursor1];
  5313. return;
  5314. }
  5315. var _minGallop = minGallop;
  5316. var count1, count2, exit;
  5317. while (1) {
  5318. count1 = 0;
  5319. count2 = 0;
  5320. exit = false;
  5321. do {
  5322. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5323. array[dest++] = array[cursor2++];
  5324. count2++;
  5325. count1 = 0;
  5326. if (--length2 === 0) {
  5327. exit = true;
  5328. break;
  5329. }
  5330. }
  5331. else {
  5332. array[dest++] = tmp[cursor1++];
  5333. count1++;
  5334. count2 = 0;
  5335. if (--length1 === 1) {
  5336. exit = true;
  5337. break;
  5338. }
  5339. }
  5340. } while ((count1 | count2) < _minGallop);
  5341. if (exit) {
  5342. break;
  5343. }
  5344. do {
  5345. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5346. if (count1 !== 0) {
  5347. for (i = 0; i < count1; i++) {
  5348. array[dest + i] = tmp[cursor1 + i];
  5349. }
  5350. dest += count1;
  5351. cursor1 += count1;
  5352. length1 -= count1;
  5353. if (length1 <= 1) {
  5354. exit = true;
  5355. break;
  5356. }
  5357. }
  5358. array[dest++] = array[cursor2++];
  5359. if (--length2 === 0) {
  5360. exit = true;
  5361. break;
  5362. }
  5363. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5364. if (count2 !== 0) {
  5365. for (i = 0; i < count2; i++) {
  5366. array[dest + i] = array[cursor2 + i];
  5367. }
  5368. dest += count2;
  5369. cursor2 += count2;
  5370. length2 -= count2;
  5371. if (length2 === 0) {
  5372. exit = true;
  5373. break;
  5374. }
  5375. }
  5376. array[dest++] = tmp[cursor1++];
  5377. if (--length1 === 1) {
  5378. exit = true;
  5379. break;
  5380. }
  5381. _minGallop--;
  5382. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5383. if (exit) {
  5384. break;
  5385. }
  5386. if (_minGallop < 0) {
  5387. _minGallop = 0;
  5388. }
  5389. _minGallop += 2;
  5390. }
  5391. minGallop = _minGallop;
  5392. minGallop < 1 && (minGallop = 1);
  5393. if (length1 === 1) {
  5394. for (i = 0; i < length2; i++) {
  5395. array[dest + i] = array[cursor2 + i];
  5396. }
  5397. array[dest + length2] = tmp[cursor1];
  5398. }
  5399. else if (length1 === 0) {
  5400. throw new Error();
  5401. // throw new Error('mergeLow preconditions were not respected');
  5402. }
  5403. else {
  5404. for (i = 0; i < length1; i++) {
  5405. array[dest + i] = tmp[cursor1 + i];
  5406. }
  5407. }
  5408. }
  5409. function mergeHigh(start1, length1, start2, length2) {
  5410. var i = 0;
  5411. for (i = 0; i < length2; i++) {
  5412. tmp[i] = array[start2 + i];
  5413. }
  5414. var cursor1 = start1 + length1 - 1;
  5415. var cursor2 = length2 - 1;
  5416. var dest = start2 + length2 - 1;
  5417. var customCursor = 0;
  5418. var customDest = 0;
  5419. array[dest--] = array[cursor1--];
  5420. if (--length1 === 0) {
  5421. customCursor = dest - (length2 - 1);
  5422. for (i = 0; i < length2; i++) {
  5423. array[customCursor + i] = tmp[i];
  5424. }
  5425. return;
  5426. }
  5427. if (length2 === 1) {
  5428. dest -= length1;
  5429. cursor1 -= length1;
  5430. customDest = dest + 1;
  5431. customCursor = cursor1 + 1;
  5432. for (i = length1 - 1; i >= 0; i--) {
  5433. array[customDest + i] = array[customCursor + i];
  5434. }
  5435. array[dest] = tmp[cursor2];
  5436. return;
  5437. }
  5438. var _minGallop = minGallop;
  5439. while (true) {
  5440. var count1 = 0;
  5441. var count2 = 0;
  5442. var exit = false;
  5443. do {
  5444. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5445. array[dest--] = array[cursor1--];
  5446. count1++;
  5447. count2 = 0;
  5448. if (--length1 === 0) {
  5449. exit = true;
  5450. break;
  5451. }
  5452. }
  5453. else {
  5454. array[dest--] = tmp[cursor2--];
  5455. count2++;
  5456. count1 = 0;
  5457. if (--length2 === 1) {
  5458. exit = true;
  5459. break;
  5460. }
  5461. }
  5462. } while ((count1 | count2) < _minGallop);
  5463. if (exit) {
  5464. break;
  5465. }
  5466. do {
  5467. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5468. if (count1 !== 0) {
  5469. dest -= count1;
  5470. cursor1 -= count1;
  5471. length1 -= count1;
  5472. customDest = dest + 1;
  5473. customCursor = cursor1 + 1;
  5474. for (i = count1 - 1; i >= 0; i--) {
  5475. array[customDest + i] = array[customCursor + i];
  5476. }
  5477. if (length1 === 0) {
  5478. exit = true;
  5479. break;
  5480. }
  5481. }
  5482. array[dest--] = tmp[cursor2--];
  5483. if (--length2 === 1) {
  5484. exit = true;
  5485. break;
  5486. }
  5487. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5488. if (count2 !== 0) {
  5489. dest -= count2;
  5490. cursor2 -= count2;
  5491. length2 -= count2;
  5492. customDest = dest + 1;
  5493. customCursor = cursor2 + 1;
  5494. for (i = 0; i < count2; i++) {
  5495. array[customDest + i] = tmp[customCursor + i];
  5496. }
  5497. if (length2 <= 1) {
  5498. exit = true;
  5499. break;
  5500. }
  5501. }
  5502. array[dest--] = array[cursor1--];
  5503. if (--length1 === 0) {
  5504. exit = true;
  5505. break;
  5506. }
  5507. _minGallop--;
  5508. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5509. if (exit) {
  5510. break;
  5511. }
  5512. if (_minGallop < 0) {
  5513. _minGallop = 0;
  5514. }
  5515. _minGallop += 2;
  5516. }
  5517. minGallop = _minGallop;
  5518. if (minGallop < 1) {
  5519. minGallop = 1;
  5520. }
  5521. if (length2 === 1) {
  5522. dest -= length1;
  5523. cursor1 -= length1;
  5524. customDest = dest + 1;
  5525. customCursor = cursor1 + 1;
  5526. for (i = length1 - 1; i >= 0; i--) {
  5527. array[customDest + i] = array[customCursor + i];
  5528. }
  5529. array[dest] = tmp[cursor2];
  5530. }
  5531. else if (length2 === 0) {
  5532. throw new Error();
  5533. // throw new Error('mergeHigh preconditions were not respected');
  5534. }
  5535. else {
  5536. customCursor = dest - (length2 - 1);
  5537. for (i = 0; i < length2; i++) {
  5538. array[customCursor + i] = tmp[i];
  5539. }
  5540. }
  5541. }
  5542. this.mergeRuns = mergeRuns;
  5543. this.forceMergeRuns = forceMergeRuns;
  5544. this.pushRun = pushRun;
  5545. }
  5546. function sort(array, compare, lo, hi) {
  5547. if (!lo) {
  5548. lo = 0;
  5549. }
  5550. if (!hi) {
  5551. hi = array.length;
  5552. }
  5553. var remaining = hi - lo;
  5554. if (remaining < 2) {
  5555. return;
  5556. }
  5557. var runLength = 0;
  5558. if (remaining < DEFAULT_MIN_MERGE) {
  5559. runLength = makeAscendingRun(array, lo, hi, compare);
  5560. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5561. return;
  5562. }
  5563. var ts = new TimSort(array, compare);
  5564. var minRun = minRunLength(remaining);
  5565. do {
  5566. runLength = makeAscendingRun(array, lo, hi, compare);
  5567. if (runLength < minRun) {
  5568. var force = remaining;
  5569. if (force > minRun) {
  5570. force = minRun;
  5571. }
  5572. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5573. runLength = force;
  5574. }
  5575. ts.pushRun(lo, runLength);
  5576. ts.mergeRuns();
  5577. remaining -= runLength;
  5578. lo += runLength;
  5579. } while (remaining !== 0);
  5580. ts.forceMergeRuns();
  5581. }
  5582. // Use timsort because in most case elements are partially sorted
  5583. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5584. function shapeCompareFunc(a, b) {
  5585. if (a.zlevel === b.zlevel) {
  5586. if (a.z === b.z) {
  5587. // if (a.z2 === b.z2) {
  5588. // // FIXME Slow has renderidx compare
  5589. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5590. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5591. // return a.__renderidx - b.__renderidx;
  5592. // }
  5593. return a.z2 - b.z2;
  5594. }
  5595. return a.z - b.z;
  5596. }
  5597. return a.zlevel - b.zlevel;
  5598. }
  5599. /**
  5600. * 内容仓库 (M)
  5601. * @alias module:zrender/Storage
  5602. * @constructor
  5603. */
  5604. var Storage = function () { // jshint ignore:line
  5605. this._roots = [];
  5606. this._displayList = [];
  5607. this._displayListLen = 0;
  5608. };
  5609. Storage.prototype = {
  5610. constructor: Storage,
  5611. /**
  5612. * @param {Function} cb
  5613. *
  5614. */
  5615. traverse: function (cb, context) {
  5616. for (var i = 0; i < this._roots.length; i++) {
  5617. this._roots[i].traverse(cb, context);
  5618. }
  5619. },
  5620. /**
  5621. * 返回所有图形的绘制队列
  5622. * @param {boolean} [update=false] 是否在返回前更新该数组
  5623. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5624. *
  5625. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5626. * @return {Array.<module:zrender/graphic/Displayable>}
  5627. */
  5628. getDisplayList: function (update, includeIgnore) {
  5629. includeIgnore = includeIgnore || false;
  5630. if (update) {
  5631. this.updateDisplayList(includeIgnore);
  5632. }
  5633. return this._displayList;
  5634. },
  5635. /**
  5636. * 更新图形的绘制队列。
  5637. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5638. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5639. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5640. */
  5641. updateDisplayList: function (includeIgnore) {
  5642. this._displayListLen = 0;
  5643. var roots = this._roots;
  5644. var displayList = this._displayList;
  5645. for (var i = 0, len = roots.length; i < len; i++) {
  5646. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5647. }
  5648. displayList.length = this._displayListLen;
  5649. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5650. },
  5651. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5652. if (el.ignore && !includeIgnore) {
  5653. return;
  5654. }
  5655. el.beforeUpdate();
  5656. if (el.__dirty) {
  5657. el.update();
  5658. }
  5659. el.afterUpdate();
  5660. var userSetClipPath = el.clipPath;
  5661. if (userSetClipPath) {
  5662. // FIXME 效率影响
  5663. if (clipPaths) {
  5664. clipPaths = clipPaths.slice();
  5665. }
  5666. else {
  5667. clipPaths = [];
  5668. }
  5669. var currentClipPath = userSetClipPath;
  5670. var parentClipPath = el;
  5671. // Recursively add clip path
  5672. while (currentClipPath) {
  5673. // clipPath 的变换是基于使用这个 clipPath 的元素
  5674. currentClipPath.parent = parentClipPath;
  5675. currentClipPath.updateTransform();
  5676. clipPaths.push(currentClipPath);
  5677. parentClipPath = currentClipPath;
  5678. currentClipPath = currentClipPath.clipPath;
  5679. }
  5680. }
  5681. if (el.isGroup) {
  5682. var children = el._children;
  5683. for (var i = 0; i < children.length; i++) {
  5684. var child = children[i];
  5685. // Force to mark as dirty if group is dirty
  5686. // FIXME __dirtyPath ?
  5687. if (el.__dirty) {
  5688. child.__dirty = true;
  5689. }
  5690. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5691. }
  5692. // Mark group clean here
  5693. el.__dirty = false;
  5694. }
  5695. else {
  5696. el.__clipPaths = clipPaths;
  5697. this._displayList[this._displayListLen++] = el;
  5698. }
  5699. },
  5700. /**
  5701. * 添加图形(Shape)或者组(Group)到根节点
  5702. * @param {module:zrender/Element} el
  5703. */
  5704. addRoot: function (el) {
  5705. if (el.__storage === this) {
  5706. return;
  5707. }
  5708. if (el instanceof Group) {
  5709. el.addChildrenToStorage(this);
  5710. }
  5711. this.addToStorage(el);
  5712. this._roots.push(el);
  5713. },
  5714. /**
  5715. * 删除指定的图形(Shape)或者组(Group)
  5716. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5717. */
  5718. delRoot: function (el) {
  5719. if (el == null) {
  5720. // 不指定el清空
  5721. for (var i = 0; i < this._roots.length; i++) {
  5722. var root = this._roots[i];
  5723. if (root instanceof Group) {
  5724. root.delChildrenFromStorage(this);
  5725. }
  5726. }
  5727. this._roots = [];
  5728. this._displayList = [];
  5729. this._displayListLen = 0;
  5730. return;
  5731. }
  5732. if (el instanceof Array) {
  5733. for (var i = 0, l = el.length; i < l; i++) {
  5734. this.delRoot(el[i]);
  5735. }
  5736. return;
  5737. }
  5738. var idx = indexOf(this._roots, el);
  5739. if (idx >= 0) {
  5740. this.delFromStorage(el);
  5741. this._roots.splice(idx, 1);
  5742. if (el instanceof Group) {
  5743. el.delChildrenFromStorage(this);
  5744. }
  5745. }
  5746. },
  5747. addToStorage: function (el) {
  5748. if (el) {
  5749. el.__storage = this;
  5750. el.dirty(false);
  5751. }
  5752. return this;
  5753. },
  5754. delFromStorage: function (el) {
  5755. if (el) {
  5756. el.__storage = null;
  5757. }
  5758. return this;
  5759. },
  5760. /**
  5761. * 清空并且释放Storage
  5762. */
  5763. dispose: function () {
  5764. this._renderList =
  5765. this._roots = null;
  5766. },
  5767. displayableSortFunc: shapeCompareFunc
  5768. };
  5769. var SHADOW_PROPS = {
  5770. 'shadowBlur': 1,
  5771. 'shadowOffsetX': 1,
  5772. 'shadowOffsetY': 1,
  5773. 'textShadowBlur': 1,
  5774. 'textShadowOffsetX': 1,
  5775. 'textShadowOffsetY': 1,
  5776. 'textBoxShadowBlur': 1,
  5777. 'textBoxShadowOffsetX': 1,
  5778. 'textBoxShadowOffsetY': 1
  5779. };
  5780. var fixShadow = function (ctx, propName, value) {
  5781. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5782. return value *= ctx.dpr;
  5783. }
  5784. return value;
  5785. };
  5786. var ContextCachedBy = {
  5787. NONE: 0,
  5788. STYLE_BIND: 1,
  5789. PLAIN_TEXT: 2
  5790. };
  5791. // Avoid confused with 0/false.
  5792. var WILL_BE_RESTORED = 9;
  5793. var STYLE_COMMON_PROPS = [
  5794. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5795. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5796. ];
  5797. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5798. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5799. var Style = function (opts) {
  5800. this.extendFrom(opts, false);
  5801. };
  5802. function createLinearGradient(ctx, obj, rect) {
  5803. var x = obj.x == null ? 0 : obj.x;
  5804. var x2 = obj.x2 == null ? 1 : obj.x2;
  5805. var y = obj.y == null ? 0 : obj.y;
  5806. var y2 = obj.y2 == null ? 0 : obj.y2;
  5807. if (!obj.global) {
  5808. x = x * rect.width + rect.x;
  5809. x2 = x2 * rect.width + rect.x;
  5810. y = y * rect.height + rect.y;
  5811. y2 = y2 * rect.height + rect.y;
  5812. }
  5813. // Fix NaN when rect is Infinity
  5814. x = isNaN(x) ? 0 : x;
  5815. x2 = isNaN(x2) ? 1 : x2;
  5816. y = isNaN(y) ? 0 : y;
  5817. y2 = isNaN(y2) ? 0 : y2;
  5818. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5819. return canvasGradient;
  5820. }
  5821. function createRadialGradient(ctx, obj, rect) {
  5822. var width = rect.width;
  5823. var height = rect.height;
  5824. var min = Math.min(width, height);
  5825. var x = obj.x == null ? 0.5 : obj.x;
  5826. var y = obj.y == null ? 0.5 : obj.y;
  5827. var r = obj.r == null ? 0.5 : obj.r;
  5828. if (!obj.global) {
  5829. x = x * width + rect.x;
  5830. y = y * height + rect.y;
  5831. r = r * min;
  5832. }
  5833. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5834. return canvasGradient;
  5835. }
  5836. Style.prototype = {
  5837. constructor: Style,
  5838. /**
  5839. * @type {string}
  5840. */
  5841. fill: '#000',
  5842. /**
  5843. * @type {string}
  5844. */
  5845. stroke: null,
  5846. /**
  5847. * @type {number}
  5848. */
  5849. opacity: 1,
  5850. /**
  5851. * @type {number}
  5852. */
  5853. fillOpacity: null,
  5854. /**
  5855. * @type {number}
  5856. */
  5857. strokeOpacity: null,
  5858. /**
  5859. * @type {Array.<number>}
  5860. */
  5861. lineDash: null,
  5862. /**
  5863. * @type {number}
  5864. */
  5865. lineDashOffset: 0,
  5866. /**
  5867. * @type {number}
  5868. */
  5869. shadowBlur: 0,
  5870. /**
  5871. * @type {number}
  5872. */
  5873. shadowOffsetX: 0,
  5874. /**
  5875. * @type {number}
  5876. */
  5877. shadowOffsetY: 0,
  5878. /**
  5879. * @type {number}
  5880. */
  5881. lineWidth: 1,
  5882. /**
  5883. * If stroke ignore scale
  5884. * @type {Boolean}
  5885. */
  5886. strokeNoScale: false,
  5887. // Bounding rect text configuration
  5888. // Not affected by element transform
  5889. /**
  5890. * @type {string}
  5891. */
  5892. text: null,
  5893. /**
  5894. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5895. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5896. * So do not visit it directly in upper application (like echarts),
  5897. * but use `contain/text#makeFont` instead.
  5898. * @type {string}
  5899. */
  5900. font: null,
  5901. /**
  5902. * The same as font. Use font please.
  5903. * @deprecated
  5904. * @type {string}
  5905. */
  5906. textFont: null,
  5907. /**
  5908. * It helps merging respectively, rather than parsing an entire font string.
  5909. * @type {string}
  5910. */
  5911. fontStyle: null,
  5912. /**
  5913. * It helps merging respectively, rather than parsing an entire font string.
  5914. * @type {string}
  5915. */
  5916. fontWeight: null,
  5917. /**
  5918. * It helps merging respectively, rather than parsing an entire font string.
  5919. * Should be 12 but not '12px'.
  5920. * @type {number}
  5921. */
  5922. fontSize: null,
  5923. /**
  5924. * It helps merging respectively, rather than parsing an entire font string.
  5925. * @type {string}
  5926. */
  5927. fontFamily: null,
  5928. /**
  5929. * Reserved for special functinality, like 'hr'.
  5930. * @type {string}
  5931. */
  5932. textTag: null,
  5933. /**
  5934. * @type {string}
  5935. */
  5936. textFill: '#000',
  5937. /**
  5938. * @type {string}
  5939. */
  5940. textStroke: null,
  5941. /**
  5942. * @type {number}
  5943. */
  5944. textWidth: null,
  5945. /**
  5946. * Only for textBackground.
  5947. * @type {number}
  5948. */
  5949. textHeight: null,
  5950. /**
  5951. * textStroke may be set as some color as a default
  5952. * value in upper applicaion, where the default value
  5953. * of textStrokeWidth should be 0 to make sure that
  5954. * user can choose to do not use text stroke.
  5955. * @type {number}
  5956. */
  5957. textStrokeWidth: 0,
  5958. /**
  5959. * @type {number}
  5960. */
  5961. textLineHeight: null,
  5962. /**
  5963. * 'inside', 'left', 'right', 'top', 'bottom'
  5964. * [x, y]
  5965. * Based on x, y of rect.
  5966. * @type {string|Array.<number>}
  5967. * @default 'inside'
  5968. */
  5969. textPosition: 'inside',
  5970. /**
  5971. * If not specified, use the boundingRect of a `displayable`.
  5972. * @type {Object}
  5973. */
  5974. textRect: null,
  5975. /**
  5976. * [x, y]
  5977. * @type {Array.<number>}
  5978. */
  5979. textOffset: null,
  5980. /**
  5981. * @type {string}
  5982. */
  5983. textAlign: null,
  5984. /**
  5985. * @type {string}
  5986. */
  5987. textVerticalAlign: null,
  5988. /**
  5989. * @type {number}
  5990. */
  5991. textDistance: 5,
  5992. /**
  5993. * @type {string}
  5994. */
  5995. textShadowColor: 'transparent',
  5996. /**
  5997. * @type {number}
  5998. */
  5999. textShadowBlur: 0,
  6000. /**
  6001. * @type {number}
  6002. */
  6003. textShadowOffsetX: 0,
  6004. /**
  6005. * @type {number}
  6006. */
  6007. textShadowOffsetY: 0,
  6008. /**
  6009. * @type {string}
  6010. */
  6011. textBoxShadowColor: 'transparent',
  6012. /**
  6013. * @type {number}
  6014. */
  6015. textBoxShadowBlur: 0,
  6016. /**
  6017. * @type {number}
  6018. */
  6019. textBoxShadowOffsetX: 0,
  6020. /**
  6021. * @type {number}
  6022. */
  6023. textBoxShadowOffsetY: 0,
  6024. /**
  6025. * Whether transform text.
  6026. * Only useful in Path and Image element
  6027. * @type {boolean}
  6028. */
  6029. transformText: false,
  6030. /**
  6031. * Text rotate around position of Path or Image
  6032. * Only useful in Path and Image element and transformText is false.
  6033. */
  6034. textRotation: 0,
  6035. /**
  6036. * Text origin of text rotation, like [10, 40].
  6037. * Based on x, y of rect.
  6038. * Useful in label rotation of circular symbol.
  6039. * By default, this origin is textPosition.
  6040. * Can be 'center'.
  6041. * @type {string|Array.<number>}
  6042. */
  6043. textOrigin: null,
  6044. /**
  6045. * @type {string}
  6046. */
  6047. textBackgroundColor: null,
  6048. /**
  6049. * @type {string}
  6050. */
  6051. textBorderColor: null,
  6052. /**
  6053. * @type {number}
  6054. */
  6055. textBorderWidth: 0,
  6056. /**
  6057. * @type {number}
  6058. */
  6059. textBorderRadius: 0,
  6060. /**
  6061. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6062. * @type {number|Array.<number>}
  6063. */
  6064. textPadding: null,
  6065. /**
  6066. * Text styles for rich text.
  6067. * @type {Object}
  6068. */
  6069. rich: null,
  6070. /**
  6071. * {outerWidth, outerHeight, ellipsis, placeholder}
  6072. * @type {Object}
  6073. */
  6074. truncate: null,
  6075. /**
  6076. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6077. * @type {string}
  6078. */
  6079. blend: null,
  6080. /**
  6081. * @param {CanvasRenderingContext2D} ctx
  6082. */
  6083. bind: function (ctx, el, prevEl) {
  6084. var style = this;
  6085. var prevStyle = prevEl && prevEl.style;
  6086. // If no prevStyle, it means first draw.
  6087. // Only apply cache if the last time cachced by this function.
  6088. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6089. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6090. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6091. var prop = STYLE_COMMON_PROPS[i];
  6092. var styleName = prop[0];
  6093. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6094. // FIXME Invalid property value will cause style leak from previous element.
  6095. ctx[styleName] =
  6096. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6097. }
  6098. }
  6099. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6100. ctx.fillStyle = style.fill;
  6101. }
  6102. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6103. ctx.strokeStyle = style.stroke;
  6104. }
  6105. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6106. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6107. }
  6108. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6109. ctx.globalCompositeOperation = style.blend || 'source-over';
  6110. }
  6111. if (this.hasStroke()) {
  6112. var lineWidth = style.lineWidth;
  6113. ctx.lineWidth = lineWidth / (
  6114. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6115. );
  6116. }
  6117. },
  6118. hasFill: function () {
  6119. var fill = this.fill;
  6120. return fill != null && fill !== 'none';
  6121. },
  6122. hasStroke: function () {
  6123. var stroke = this.stroke;
  6124. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6125. },
  6126. /**
  6127. * Extend from other style
  6128. * @param {zrender/graphic/Style} otherStyle
  6129. * @param {boolean} overwrite true: overwrirte any way.
  6130. * false: overwrite only when !target.hasOwnProperty
  6131. * others: overwrite when property is not null/undefined.
  6132. */
  6133. extendFrom: function (otherStyle, overwrite) {
  6134. if (otherStyle) {
  6135. for (var name in otherStyle) {
  6136. if (otherStyle.hasOwnProperty(name)
  6137. && (overwrite === true
  6138. || (
  6139. overwrite === false
  6140. ? !this.hasOwnProperty(name)
  6141. : otherStyle[name] != null
  6142. )
  6143. )
  6144. ) {
  6145. this[name] = otherStyle[name];
  6146. }
  6147. }
  6148. }
  6149. },
  6150. /**
  6151. * Batch setting style with a given object
  6152. * @param {Object|string} obj
  6153. * @param {*} [obj]
  6154. */
  6155. set: function (obj, value) {
  6156. if (typeof obj === 'string') {
  6157. this[obj] = value;
  6158. }
  6159. else {
  6160. this.extendFrom(obj, true);
  6161. }
  6162. },
  6163. /**
  6164. * Clone
  6165. * @return {zrender/graphic/Style} [description]
  6166. */
  6167. clone: function () {
  6168. var newStyle = new this.constructor();
  6169. newStyle.extendFrom(this, true);
  6170. return newStyle;
  6171. },
  6172. getGradient: function (ctx, obj, rect) {
  6173. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6174. var canvasGradient = method(ctx, obj, rect);
  6175. var colorStops = obj.colorStops;
  6176. for (var i = 0; i < colorStops.length; i++) {
  6177. canvasGradient.addColorStop(
  6178. colorStops[i].offset, colorStops[i].color
  6179. );
  6180. }
  6181. return canvasGradient;
  6182. }
  6183. };
  6184. var styleProto = Style.prototype;
  6185. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6186. var prop = STYLE_COMMON_PROPS[i];
  6187. if (!(prop[0] in styleProto)) {
  6188. styleProto[prop[0]] = prop[1];
  6189. }
  6190. }
  6191. // Provide for others
  6192. Style.getGradient = styleProto.getGradient;
  6193. var Pattern = function (image, repeat) {
  6194. // Should do nothing more in this constructor. Because gradient can be
  6195. // declard by `color: {image: ...}`, where this constructor will not be called.
  6196. this.image = image;
  6197. this.repeat = repeat;
  6198. // Can be cloned
  6199. this.type = 'pattern';
  6200. };
  6201. Pattern.prototype.getCanvasPattern = function (ctx) {
  6202. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6203. };
  6204. /**
  6205. * @module zrender/Layer
  6206. * @author pissang(https://www.github.com/pissang)
  6207. */
  6208. function returnFalse() {
  6209. return false;
  6210. }
  6211. /**
  6212. * 创建dom
  6213. *
  6214. * @inner
  6215. * @param {string} id dom id 待用
  6216. * @param {Painter} painter painter instance
  6217. * @param {number} number
  6218. */
  6219. function createDom(id, painter, dpr) {
  6220. var newDom = createCanvas();
  6221. var width = painter.getWidth();
  6222. var height = painter.getHeight();
  6223. var newDomStyle = newDom.style;
  6224. if (newDomStyle) { // In node or some other non-browser environment
  6225. newDomStyle.position = 'absolute';
  6226. newDomStyle.left = 0;
  6227. newDomStyle.top = 0;
  6228. newDomStyle.width = width + 'px';
  6229. newDomStyle.height = height + 'px';
  6230. newDom.setAttribute('data-zr-dom-id', id);
  6231. }
  6232. newDom.width = width * dpr;
  6233. newDom.height = height * dpr;
  6234. return newDom;
  6235. }
  6236. /**
  6237. * @alias module:zrender/Layer
  6238. * @constructor
  6239. * @extends module:zrender/mixin/Transformable
  6240. * @param {string} id
  6241. * @param {module:zrender/Painter} painter
  6242. * @param {number} [dpr]
  6243. */
  6244. var Layer = function (id, painter, dpr) {
  6245. var dom;
  6246. dpr = dpr || devicePixelRatio;
  6247. if (typeof id === 'string') {
  6248. dom = createDom(id, painter, dpr);
  6249. }
  6250. // Not using isDom because in node it will return false
  6251. else if (isObject$1(id)) {
  6252. dom = id;
  6253. id = dom.id;
  6254. }
  6255. this.id = id;
  6256. this.dom = dom;
  6257. var domStyle = dom.style;
  6258. if (domStyle) { // Not in node
  6259. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6260. domStyle['-webkit-user-select'] = 'none';
  6261. domStyle['user-select'] = 'none';
  6262. domStyle['-webkit-touch-callout'] = 'none';
  6263. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6264. domStyle['padding'] = 0;
  6265. domStyle['margin'] = 0;
  6266. domStyle['border-width'] = 0;
  6267. }
  6268. this.domBack = null;
  6269. this.ctxBack = null;
  6270. this.painter = painter;
  6271. this.config = null;
  6272. // Configs
  6273. /**
  6274. * 每次清空画布的颜色
  6275. * @type {string}
  6276. * @default 0
  6277. */
  6278. this.clearColor = 0;
  6279. /**
  6280. * 是否开启动态模糊
  6281. * @type {boolean}
  6282. * @default false
  6283. */
  6284. this.motionBlur = false;
  6285. /**
  6286. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6287. * @type {number}
  6288. * @default 0.7
  6289. */
  6290. this.lastFrameAlpha = 0.7;
  6291. /**
  6292. * Layer dpr
  6293. * @type {number}
  6294. */
  6295. this.dpr = dpr;
  6296. };
  6297. Layer.prototype = {
  6298. constructor: Layer,
  6299. __dirty: true,
  6300. __used: false,
  6301. __drawIndex: 0,
  6302. __startIndex: 0,
  6303. __endIndex: 0,
  6304. incremental: false,
  6305. getElementCount: function () {
  6306. return this.__endIndex - this.__startIndex;
  6307. },
  6308. initContext: function () {
  6309. this.ctx = this.dom.getContext('2d');
  6310. this.ctx.dpr = this.dpr;
  6311. },
  6312. createBackBuffer: function () {
  6313. var dpr = this.dpr;
  6314. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6315. this.ctxBack = this.domBack.getContext('2d');
  6316. if (dpr !== 1) {
  6317. this.ctxBack.scale(dpr, dpr);
  6318. }
  6319. },
  6320. /**
  6321. * @param {number} width
  6322. * @param {number} height
  6323. */
  6324. resize: function (width, height) {
  6325. var dpr = this.dpr;
  6326. var dom = this.dom;
  6327. var domStyle = dom.style;
  6328. var domBack = this.domBack;
  6329. if (domStyle) {
  6330. domStyle.width = width + 'px';
  6331. domStyle.height = height + 'px';
  6332. }
  6333. dom.width = width * dpr;
  6334. dom.height = height * dpr;
  6335. if (domBack) {
  6336. domBack.width = width * dpr;
  6337. domBack.height = height * dpr;
  6338. if (dpr !== 1) {
  6339. this.ctxBack.scale(dpr, dpr);
  6340. }
  6341. }
  6342. },
  6343. /**
  6344. * 清空该层画布
  6345. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6346. * @param {Color} [clearColor]
  6347. */
  6348. clear: function (clearAll, clearColor) {
  6349. var dom = this.dom;
  6350. var ctx = this.ctx;
  6351. var width = dom.width;
  6352. var height = dom.height;
  6353. var clearColor = clearColor || this.clearColor;
  6354. var haveMotionBLur = this.motionBlur && !clearAll;
  6355. var lastFrameAlpha = this.lastFrameAlpha;
  6356. var dpr = this.dpr;
  6357. if (haveMotionBLur) {
  6358. if (!this.domBack) {
  6359. this.createBackBuffer();
  6360. }
  6361. this.ctxBack.globalCompositeOperation = 'copy';
  6362. this.ctxBack.drawImage(
  6363. dom, 0, 0,
  6364. width / dpr,
  6365. height / dpr
  6366. );
  6367. }
  6368. ctx.clearRect(0, 0, width, height);
  6369. if (clearColor && clearColor !== 'transparent') {
  6370. var clearColorGradientOrPattern;
  6371. // Gradient
  6372. if (clearColor.colorStops) {
  6373. // Cache canvas gradient
  6374. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6375. x: 0,
  6376. y: 0,
  6377. width: width,
  6378. height: height
  6379. });
  6380. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6381. }
  6382. // Pattern
  6383. else if (clearColor.image) {
  6384. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6385. }
  6386. ctx.save();
  6387. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6388. ctx.fillRect(0, 0, width, height);
  6389. ctx.restore();
  6390. }
  6391. if (haveMotionBLur) {
  6392. var domBack = this.domBack;
  6393. ctx.save();
  6394. ctx.globalAlpha = lastFrameAlpha;
  6395. ctx.drawImage(domBack, 0, 0, width, height);
  6396. ctx.restore();
  6397. }
  6398. }
  6399. };
  6400. var requestAnimationFrame = (
  6401. typeof window !== 'undefined'
  6402. && (
  6403. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6404. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6405. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6406. || window.mozRequestAnimationFrame
  6407. || window.webkitRequestAnimationFrame
  6408. )
  6409. ) || function (func) {
  6410. setTimeout(func, 16);
  6411. };
  6412. var globalImageCache = new LRU(50);
  6413. /**
  6414. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6415. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6416. */
  6417. function findExistImage(newImageOrSrc) {
  6418. if (typeof newImageOrSrc === 'string') {
  6419. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6420. return cachedImgObj && cachedImgObj.image;
  6421. }
  6422. else {
  6423. return newImageOrSrc;
  6424. }
  6425. }
  6426. /**
  6427. * Caution: User should cache loaded images, but not just count on LRU.
  6428. * Consider if required images more than LRU size, will dead loop occur?
  6429. *
  6430. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6431. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6432. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6433. * @param {Function} [cb] params: (image, cbPayload)
  6434. * @param {Object} [cbPayload] Payload on cb calling.
  6435. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6436. */
  6437. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6438. if (!newImageOrSrc) {
  6439. return image;
  6440. }
  6441. else if (typeof newImageOrSrc === 'string') {
  6442. // Image should not be loaded repeatly.
  6443. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6444. return image;
  6445. }
  6446. // Only when there is no existent image or existent image src
  6447. // is different, this method is responsible for load.
  6448. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6449. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6450. if (cachedImgObj) {
  6451. image = cachedImgObj.image;
  6452. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6453. }
  6454. else {
  6455. image = new Image();
  6456. image.onload = image.onerror = imageOnLoad;
  6457. globalImageCache.put(
  6458. newImageOrSrc,
  6459. image.__cachedImgObj = {
  6460. image: image,
  6461. pending: [pendingWrap]
  6462. }
  6463. );
  6464. image.src = image.__zrImageSrc = newImageOrSrc;
  6465. }
  6466. return image;
  6467. }
  6468. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6469. else {
  6470. return newImageOrSrc;
  6471. }
  6472. }
  6473. function imageOnLoad() {
  6474. var cachedImgObj = this.__cachedImgObj;
  6475. this.onload = this.onerror = this.__cachedImgObj = null;
  6476. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6477. var pendingWrap = cachedImgObj.pending[i];
  6478. var cb = pendingWrap.cb;
  6479. cb && cb(this, pendingWrap.cbPayload);
  6480. pendingWrap.hostEl.dirty();
  6481. }
  6482. cachedImgObj.pending.length = 0;
  6483. }
  6484. function isImageReady(image) {
  6485. return image && image.width && image.height;
  6486. }
  6487. var textWidthCache = {};
  6488. var textWidthCacheCounter = 0;
  6489. var TEXT_CACHE_MAX = 5000;
  6490. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6491. var DEFAULT_FONT$1 = '12px sans-serif';
  6492. // Avoid assign to an exported variable, for transforming to cjs.
  6493. var methods$1 = {};
  6494. function $override$1(name, fn) {
  6495. methods$1[name] = fn;
  6496. }
  6497. /**
  6498. * @public
  6499. * @param {string} text
  6500. * @param {string} font
  6501. * @return {number} width
  6502. */
  6503. function getWidth(text, font) {
  6504. font = font || DEFAULT_FONT$1;
  6505. var key = text + ':' + font;
  6506. if (textWidthCache[key]) {
  6507. return textWidthCache[key];
  6508. }
  6509. var textLines = (text + '').split('\n');
  6510. var width = 0;
  6511. for (var i = 0, l = textLines.length; i < l; i++) {
  6512. // textContain.measureText may be overrided in SVG or VML
  6513. width = Math.max(measureText(textLines[i], font).width, width);
  6514. }
  6515. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6516. textWidthCacheCounter = 0;
  6517. textWidthCache = {};
  6518. }
  6519. textWidthCacheCounter++;
  6520. textWidthCache[key] = width;
  6521. return width;
  6522. }
  6523. /**
  6524. * @public
  6525. * @param {string} text
  6526. * @param {string} font
  6527. * @param {string} [textAlign='left']
  6528. * @param {string} [textVerticalAlign='top']
  6529. * @param {Array.<number>} [textPadding]
  6530. * @param {Object} [rich]
  6531. * @param {Object} [truncate]
  6532. * @return {Object} {x, y, width, height, lineHeight}
  6533. */
  6534. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6535. return rich
  6536. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6537. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6538. }
  6539. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6540. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6541. var outerWidth = getWidth(text, font);
  6542. if (textPadding) {
  6543. outerWidth += textPadding[1] + textPadding[3];
  6544. }
  6545. var outerHeight = contentBlock.outerHeight;
  6546. var x = adjustTextX(0, outerWidth, textAlign);
  6547. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6548. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6549. rect.lineHeight = contentBlock.lineHeight;
  6550. return rect;
  6551. }
  6552. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6553. var contentBlock = parseRichText(text, {
  6554. rich: rich,
  6555. truncate: truncate,
  6556. font: font,
  6557. textAlign: textAlign,
  6558. textPadding: textPadding,
  6559. textLineHeight: textLineHeight
  6560. });
  6561. var outerWidth = contentBlock.outerWidth;
  6562. var outerHeight = contentBlock.outerHeight;
  6563. var x = adjustTextX(0, outerWidth, textAlign);
  6564. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6565. return new BoundingRect(x, y, outerWidth, outerHeight);
  6566. }
  6567. /**
  6568. * @public
  6569. * @param {number} x
  6570. * @param {number} width
  6571. * @param {string} [textAlign='left']
  6572. * @return {number} Adjusted x.
  6573. */
  6574. function adjustTextX(x, width, textAlign) {
  6575. // FIXME Right to left language
  6576. if (textAlign === 'right') {
  6577. x -= width;
  6578. }
  6579. else if (textAlign === 'center') {
  6580. x -= width / 2;
  6581. }
  6582. return x;
  6583. }
  6584. /**
  6585. * @public
  6586. * @param {number} y
  6587. * @param {number} height
  6588. * @param {string} [textVerticalAlign='top']
  6589. * @return {number} Adjusted y.
  6590. */
  6591. function adjustTextY(y, height, textVerticalAlign) {
  6592. if (textVerticalAlign === 'middle') {
  6593. y -= height / 2;
  6594. }
  6595. else if (textVerticalAlign === 'bottom') {
  6596. y -= height;
  6597. }
  6598. return y;
  6599. }
  6600. /**
  6601. * @public
  6602. * @param {stirng} textPosition
  6603. * @param {Object} rect {x, y, width, height}
  6604. * @param {number} distance
  6605. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6606. */
  6607. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6608. var x = rect.x;
  6609. var y = rect.y;
  6610. var height = rect.height;
  6611. var width = rect.width;
  6612. var halfHeight = height / 2;
  6613. var textAlign = 'left';
  6614. var textVerticalAlign = 'top';
  6615. switch (textPosition) {
  6616. case 'left':
  6617. x -= distance;
  6618. y += halfHeight;
  6619. textAlign = 'right';
  6620. textVerticalAlign = 'middle';
  6621. break;
  6622. case 'right':
  6623. x += distance + width;
  6624. y += halfHeight;
  6625. textVerticalAlign = 'middle';
  6626. break;
  6627. case 'top':
  6628. x += width / 2;
  6629. y -= distance;
  6630. textAlign = 'center';
  6631. textVerticalAlign = 'bottom';
  6632. break;
  6633. case 'bottom':
  6634. x += width / 2;
  6635. y += height + distance;
  6636. textAlign = 'center';
  6637. break;
  6638. case 'inside':
  6639. x += width / 2;
  6640. y += halfHeight;
  6641. textAlign = 'center';
  6642. textVerticalAlign = 'middle';
  6643. break;
  6644. case 'insideLeft':
  6645. x += distance;
  6646. y += halfHeight;
  6647. textVerticalAlign = 'middle';
  6648. break;
  6649. case 'insideRight':
  6650. x += width - distance;
  6651. y += halfHeight;
  6652. textAlign = 'right';
  6653. textVerticalAlign = 'middle';
  6654. break;
  6655. case 'insideTop':
  6656. x += width / 2;
  6657. y += distance;
  6658. textAlign = 'center';
  6659. break;
  6660. case 'insideBottom':
  6661. x += width / 2;
  6662. y += height - distance;
  6663. textAlign = 'center';
  6664. textVerticalAlign = 'bottom';
  6665. break;
  6666. case 'insideTopLeft':
  6667. x += distance;
  6668. y += distance;
  6669. break;
  6670. case 'insideTopRight':
  6671. x += width - distance;
  6672. y += distance;
  6673. textAlign = 'right';
  6674. break;
  6675. case 'insideBottomLeft':
  6676. x += distance;
  6677. y += height - distance;
  6678. textVerticalAlign = 'bottom';
  6679. break;
  6680. case 'insideBottomRight':
  6681. x += width - distance;
  6682. y += height - distance;
  6683. textAlign = 'right';
  6684. textVerticalAlign = 'bottom';
  6685. break;
  6686. }
  6687. return {
  6688. x: x,
  6689. y: y,
  6690. textAlign: textAlign,
  6691. textVerticalAlign: textVerticalAlign
  6692. };
  6693. }
  6694. /**
  6695. * Show ellipsis if overflow.
  6696. *
  6697. * @public
  6698. * @param {string} text
  6699. * @param {string} containerWidth
  6700. * @param {string} font
  6701. * @param {number} [ellipsis='...']
  6702. * @param {Object} [options]
  6703. * @param {number} [options.maxIterations=3]
  6704. * @param {number} [options.minChar=0] If truncate result are less
  6705. * then minChar, ellipsis will not show, which is
  6706. * better for user hint in some cases.
  6707. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6708. * @return {string}
  6709. */
  6710. function truncateText(text, containerWidth, font, ellipsis, options) {
  6711. if (!containerWidth) {
  6712. return '';
  6713. }
  6714. var textLines = (text + '').split('\n');
  6715. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6716. // FIXME
  6717. // It is not appropriate that every line has '...' when truncate multiple lines.
  6718. for (var i = 0, len = textLines.length; i < len; i++) {
  6719. textLines[i] = truncateSingleLine(textLines[i], options);
  6720. }
  6721. return textLines.join('\n');
  6722. }
  6723. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6724. options = extend({}, options);
  6725. options.font = font;
  6726. var ellipsis = retrieve2(ellipsis, '...');
  6727. options.maxIterations = retrieve2(options.maxIterations, 2);
  6728. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6729. // FIXME
  6730. // Other languages?
  6731. options.cnCharWidth = getWidth('国', font);
  6732. // FIXME
  6733. // Consider proportional font?
  6734. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6735. options.placeholder = retrieve2(options.placeholder, '');
  6736. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6737. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6738. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6739. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6740. contentWidth -= ascCharWidth;
  6741. }
  6742. var ellipsisWidth = getWidth(ellipsis, font);
  6743. if (ellipsisWidth > contentWidth) {
  6744. ellipsis = '';
  6745. ellipsisWidth = 0;
  6746. }
  6747. contentWidth = containerWidth - ellipsisWidth;
  6748. options.ellipsis = ellipsis;
  6749. options.ellipsisWidth = ellipsisWidth;
  6750. options.contentWidth = contentWidth;
  6751. options.containerWidth = containerWidth;
  6752. return options;
  6753. }
  6754. function truncateSingleLine(textLine, options) {
  6755. var containerWidth = options.containerWidth;
  6756. var font = options.font;
  6757. var contentWidth = options.contentWidth;
  6758. if (!containerWidth) {
  6759. return '';
  6760. }
  6761. var lineWidth = getWidth(textLine, font);
  6762. if (lineWidth <= containerWidth) {
  6763. return textLine;
  6764. }
  6765. for (var j = 0; ; j++) {
  6766. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6767. textLine += options.ellipsis;
  6768. break;
  6769. }
  6770. var subLength = j === 0
  6771. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6772. : lineWidth > 0
  6773. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6774. : 0;
  6775. textLine = textLine.substr(0, subLength);
  6776. lineWidth = getWidth(textLine, font);
  6777. }
  6778. if (textLine === '') {
  6779. textLine = options.placeholder;
  6780. }
  6781. return textLine;
  6782. }
  6783. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6784. var width = 0;
  6785. var i = 0;
  6786. for (var len = text.length; i < len && width < contentWidth; i++) {
  6787. var charCode = text.charCodeAt(i);
  6788. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6789. }
  6790. return i;
  6791. }
  6792. /**
  6793. * @public
  6794. * @param {string} font
  6795. * @return {number} line height
  6796. */
  6797. function getLineHeight(font) {
  6798. // FIXME A rough approach.
  6799. return getWidth('国', font);
  6800. }
  6801. /**
  6802. * @public
  6803. * @param {string} text
  6804. * @param {string} font
  6805. * @return {Object} width
  6806. */
  6807. function measureText(text, font) {
  6808. return methods$1.measureText(text, font);
  6809. }
  6810. // Avoid assign to an exported variable, for transforming to cjs.
  6811. methods$1.measureText = function (text, font) {
  6812. var ctx = getContext();
  6813. ctx.font = font || DEFAULT_FONT$1;
  6814. return ctx.measureText(text);
  6815. };
  6816. /**
  6817. * @public
  6818. * @param {string} text
  6819. * @param {string} font
  6820. * @param {Object} [truncate]
  6821. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6822. * Notice: for performance, do not calculate outerWidth util needed.
  6823. */
  6824. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  6825. text != null && (text += '');
  6826. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  6827. var lines = text ? text.split('\n') : [];
  6828. var height = lines.length * lineHeight;
  6829. var outerHeight = height;
  6830. if (padding) {
  6831. outerHeight += padding[0] + padding[2];
  6832. }
  6833. if (text && truncate) {
  6834. var truncOuterHeight = truncate.outerHeight;
  6835. var truncOuterWidth = truncate.outerWidth;
  6836. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6837. text = '';
  6838. lines = [];
  6839. }
  6840. else if (truncOuterWidth != null) {
  6841. var options = prepareTruncateOptions(
  6842. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6843. font,
  6844. truncate.ellipsis,
  6845. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6846. );
  6847. // FIXME
  6848. // It is not appropriate that every line has '...' when truncate multiple lines.
  6849. for (var i = 0, len = lines.length; i < len; i++) {
  6850. lines[i] = truncateSingleLine(lines[i], options);
  6851. }
  6852. }
  6853. }
  6854. return {
  6855. lines: lines,
  6856. height: height,
  6857. outerHeight: outerHeight,
  6858. lineHeight: lineHeight
  6859. };
  6860. }
  6861. /**
  6862. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6863. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6864. *
  6865. * @public
  6866. * @param {string} text
  6867. * @param {Object} style
  6868. * @return {Object} block
  6869. * {
  6870. * width,
  6871. * height,
  6872. * lines: [{
  6873. * lineHeight,
  6874. * width,
  6875. * tokens: [[{
  6876. * styleName,
  6877. * text,
  6878. * width, // include textPadding
  6879. * height, // include textPadding
  6880. * textWidth, // pure text width
  6881. * textHeight, // pure text height
  6882. * lineHeihgt,
  6883. * font,
  6884. * textAlign,
  6885. * textVerticalAlign
  6886. * }], [...], ...]
  6887. * }, ...]
  6888. * }
  6889. * If styleName is undefined, it is plain text.
  6890. */
  6891. function parseRichText(text, style) {
  6892. var contentBlock = {lines: [], width: 0, height: 0};
  6893. text != null && (text += '');
  6894. if (!text) {
  6895. return contentBlock;
  6896. }
  6897. var lastIndex = STYLE_REG.lastIndex = 0;
  6898. var result;
  6899. while ((result = STYLE_REG.exec(text)) != null) {
  6900. var matchedIndex = result.index;
  6901. if (matchedIndex > lastIndex) {
  6902. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6903. }
  6904. pushTokens(contentBlock, result[2], result[1]);
  6905. lastIndex = STYLE_REG.lastIndex;
  6906. }
  6907. if (lastIndex < text.length) {
  6908. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6909. }
  6910. var lines = contentBlock.lines;
  6911. var contentHeight = 0;
  6912. var contentWidth = 0;
  6913. // For `textWidth: 100%`
  6914. var pendingList = [];
  6915. var stlPadding = style.textPadding;
  6916. var truncate = style.truncate;
  6917. var truncateWidth = truncate && truncate.outerWidth;
  6918. var truncateHeight = truncate && truncate.outerHeight;
  6919. if (stlPadding) {
  6920. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6921. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6922. }
  6923. // Calculate layout info of tokens.
  6924. for (var i = 0; i < lines.length; i++) {
  6925. var line = lines[i];
  6926. var lineHeight = 0;
  6927. var lineWidth = 0;
  6928. for (var j = 0; j < line.tokens.length; j++) {
  6929. var token = line.tokens[j];
  6930. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6931. // textPadding should not inherit from style.
  6932. var textPadding = token.textPadding = tokenStyle.textPadding;
  6933. // textFont has been asigned to font by `normalizeStyle`.
  6934. var font = token.font = tokenStyle.font || style.font;
  6935. // textHeight can be used when textVerticalAlign is specified in token.
  6936. var tokenHeight = token.textHeight = retrieve2(
  6937. // textHeight should not be inherited, consider it can be specified
  6938. // as box height of the block.
  6939. tokenStyle.textHeight, getLineHeight(font)
  6940. );
  6941. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6942. token.height = tokenHeight;
  6943. token.lineHeight = retrieve3(
  6944. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6945. );
  6946. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6947. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6948. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6949. return {lines: [], width: 0, height: 0};
  6950. }
  6951. token.textWidth = getWidth(token.text, font);
  6952. var tokenWidth = tokenStyle.textWidth;
  6953. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6954. // Percent width, can be `100%`, can be used in drawing separate
  6955. // line when box width is needed to be auto.
  6956. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6957. token.percentWidth = tokenWidth;
  6958. pendingList.push(token);
  6959. tokenWidth = 0;
  6960. // Do not truncate in this case, because there is no user case
  6961. // and it is too complicated.
  6962. }
  6963. else {
  6964. if (tokenWidthNotSpecified) {
  6965. tokenWidth = token.textWidth;
  6966. // FIXME: If image is not loaded and textWidth is not specified, calling
  6967. // `getBoundingRect()` will not get correct result.
  6968. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6969. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6970. // Use cases:
  6971. // (1) If image is not loaded, it will be loaded at render phase and call
  6972. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6973. // image, and then the right size will be calculated here at the next tick.
  6974. // See `graphic/helper/text.js`.
  6975. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6976. // use `imageHelper.findExistImage` to find cached image.
  6977. // `imageHelper.findExistImage` will always be called here before
  6978. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6979. // which ensures that image will not be rendered before correct size calcualted.
  6980. if (bgImg) {
  6981. bgImg = findExistImage(bgImg);
  6982. if (isImageReady(bgImg)) {
  6983. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6984. }
  6985. }
  6986. }
  6987. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6988. tokenWidth += paddingW;
  6989. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6990. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6991. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6992. token.text = '';
  6993. token.textWidth = tokenWidth = 0;
  6994. }
  6995. else {
  6996. token.text = truncateText(
  6997. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6998. {minChar: truncate.minChar}
  6999. );
  7000. token.textWidth = getWidth(token.text, font);
  7001. tokenWidth = token.textWidth + paddingW;
  7002. }
  7003. }
  7004. }
  7005. lineWidth += (token.width = tokenWidth);
  7006. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7007. }
  7008. line.width = lineWidth;
  7009. line.lineHeight = lineHeight;
  7010. contentHeight += lineHeight;
  7011. contentWidth = Math.max(contentWidth, lineWidth);
  7012. }
  7013. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7014. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7015. if (stlPadding) {
  7016. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7017. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7018. }
  7019. for (var i = 0; i < pendingList.length; i++) {
  7020. var token = pendingList[i];
  7021. var percentWidth = token.percentWidth;
  7022. // Should not base on outerWidth, because token can not be placed out of padding.
  7023. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7024. }
  7025. return contentBlock;
  7026. }
  7027. function pushTokens(block, str, styleName) {
  7028. var isEmptyStr = str === '';
  7029. var strs = str.split('\n');
  7030. var lines = block.lines;
  7031. for (var i = 0; i < strs.length; i++) {
  7032. var text = strs[i];
  7033. var token = {
  7034. styleName: styleName,
  7035. text: text,
  7036. isLineHolder: !text && !isEmptyStr
  7037. };
  7038. // The first token should be appended to the last line.
  7039. if (!i) {
  7040. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7041. // Consider cases:
  7042. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7043. // (which is a placeholder) should be replaced by new token.
  7044. // (2) A image backage, where token likes {a|}.
  7045. // (3) A redundant '' will affect textAlign in line.
  7046. // (4) tokens with the same tplName should not be merged, because
  7047. // they should be displayed in different box (with border and padding).
  7048. var tokensLen = tokens.length;
  7049. (tokensLen === 1 && tokens[0].isLineHolder)
  7050. ? (tokens[0] = token)
  7051. // Consider text is '', only insert when it is the "lineHolder" or
  7052. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7053. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7054. }
  7055. // Other tokens always start a new line.
  7056. else {
  7057. // If there is '', insert it as a placeholder.
  7058. lines.push({tokens: [token]});
  7059. }
  7060. }
  7061. }
  7062. function makeFont(style) {
  7063. // FIXME in node-canvas fontWeight is before fontStyle
  7064. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7065. var font = (style.fontSize || style.fontFamily) && [
  7066. style.fontStyle,
  7067. style.fontWeight,
  7068. (style.fontSize || 12) + 'px',
  7069. // If font properties are defined, `fontFamily` should not be ignored.
  7070. style.fontFamily || 'sans-serif'
  7071. ].join(' ');
  7072. return font && trim(font) || style.textFont || style.font;
  7073. }
  7074. /**
  7075. * @param {Object} ctx
  7076. * @param {Object} shape
  7077. * @param {number} shape.x
  7078. * @param {number} shape.y
  7079. * @param {number} shape.width
  7080. * @param {number} shape.height
  7081. * @param {number} shape.r
  7082. */
  7083. function buildPath(ctx, shape) {
  7084. var x = shape.x;
  7085. var y = shape.y;
  7086. var width = shape.width;
  7087. var height = shape.height;
  7088. var r = shape.r;
  7089. var r1;
  7090. var r2;
  7091. var r3;
  7092. var r4;
  7093. // Convert width and height to positive for better borderRadius
  7094. if (width < 0) {
  7095. x = x + width;
  7096. width = -width;
  7097. }
  7098. if (height < 0) {
  7099. y = y + height;
  7100. height = -height;
  7101. }
  7102. if (typeof r === 'number') {
  7103. r1 = r2 = r3 = r4 = r;
  7104. }
  7105. else if (r instanceof Array) {
  7106. if (r.length === 1) {
  7107. r1 = r2 = r3 = r4 = r[0];
  7108. }
  7109. else if (r.length === 2) {
  7110. r1 = r3 = r[0];
  7111. r2 = r4 = r[1];
  7112. }
  7113. else if (r.length === 3) {
  7114. r1 = r[0];
  7115. r2 = r4 = r[1];
  7116. r3 = r[2];
  7117. }
  7118. else {
  7119. r1 = r[0];
  7120. r2 = r[1];
  7121. r3 = r[2];
  7122. r4 = r[3];
  7123. }
  7124. }
  7125. else {
  7126. r1 = r2 = r3 = r4 = 0;
  7127. }
  7128. var total;
  7129. if (r1 + r2 > width) {
  7130. total = r1 + r2;
  7131. r1 *= width / total;
  7132. r2 *= width / total;
  7133. }
  7134. if (r3 + r4 > width) {
  7135. total = r3 + r4;
  7136. r3 *= width / total;
  7137. r4 *= width / total;
  7138. }
  7139. if (r2 + r3 > height) {
  7140. total = r2 + r3;
  7141. r2 *= height / total;
  7142. r3 *= height / total;
  7143. }
  7144. if (r1 + r4 > height) {
  7145. total = r1 + r4;
  7146. r1 *= height / total;
  7147. r4 *= height / total;
  7148. }
  7149. ctx.moveTo(x + r1, y);
  7150. ctx.lineTo(x + width - r2, y);
  7151. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7152. ctx.lineTo(x + width, y + height - r3);
  7153. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7154. ctx.lineTo(x + r4, y + height);
  7155. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7156. ctx.lineTo(x, y + r1);
  7157. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7158. }
  7159. var DEFAULT_FONT = DEFAULT_FONT$1;
  7160. // TODO: Have not support 'start', 'end' yet.
  7161. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7162. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7163. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7164. // the default value of shadowColor is `'transparent'`.
  7165. var SHADOW_STYLE_COMMON_PROPS = [
  7166. ['textShadowBlur', 'shadowBlur', 0],
  7167. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7168. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7169. ['textShadowColor', 'shadowColor', 'transparent']
  7170. ];
  7171. /**
  7172. * @param {module:zrender/graphic/Style} style
  7173. * @return {module:zrender/graphic/Style} The input style.
  7174. */
  7175. function normalizeTextStyle(style) {
  7176. normalizeStyle(style);
  7177. each$1(style.rich, normalizeStyle);
  7178. return style;
  7179. }
  7180. function normalizeStyle(style) {
  7181. if (style) {
  7182. style.font = makeFont(style);
  7183. var textAlign = style.textAlign;
  7184. textAlign === 'middle' && (textAlign = 'center');
  7185. style.textAlign = (
  7186. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7187. ) ? textAlign : 'left';
  7188. // Compatible with textBaseline.
  7189. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7190. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7191. style.textVerticalAlign = (
  7192. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7193. ) ? textVerticalAlign : 'top';
  7194. var textPadding = style.textPadding;
  7195. if (textPadding) {
  7196. style.textPadding = normalizeCssArray(style.textPadding);
  7197. }
  7198. }
  7199. }
  7200. /**
  7201. * @param {CanvasRenderingContext2D} ctx
  7202. * @param {string} text
  7203. * @param {module:zrender/graphic/Style} style
  7204. * @param {Object|boolean} [rect] {x, y, width, height}
  7205. * If set false, rect text is not used.
  7206. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7207. */
  7208. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7209. style.rich
  7210. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7211. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7212. }
  7213. // Avoid setting to ctx according to prevEl if possible for
  7214. // performance in scenarios of large amount text.
  7215. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7216. 'use strict';
  7217. var needDrawBg = needDrawBackground(style);
  7218. var prevStyle;
  7219. var checkCache = false;
  7220. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7221. // Only take and check cache for `Text` el, but not RectText.
  7222. if (prevEl !== WILL_BE_RESTORED) {
  7223. if (prevEl) {
  7224. prevStyle = prevEl.style;
  7225. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7226. }
  7227. // Prevent from using cache in `Style::bind`, because of the case:
  7228. // ctx property is modified by other properties than `Style::bind`
  7229. // used, and Style::bind is called next.
  7230. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7231. }
  7232. // Since this will be restored, prevent from using these props to check cache in the next
  7233. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7234. else if (cachedByMe) {
  7235. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7236. }
  7237. var styleFont = style.font || DEFAULT_FONT;
  7238. // PENDING
  7239. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7240. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7241. // But layer save/restore needed to be considered.
  7242. // if (styleFont !== ctx.__fontCache) {
  7243. // ctx.font = styleFont;
  7244. // if (prevEl !== WILL_BE_RESTORED) {
  7245. // ctx.__fontCache = styleFont;
  7246. // }
  7247. // }
  7248. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7249. ctx.font = styleFont;
  7250. }
  7251. // Use the final font from context-2d, because the final
  7252. // font might not be the style.font when it is illegal.
  7253. // But get `ctx.font` might be time consuming.
  7254. var computedFont = hostEl.__computedFont;
  7255. if (hostEl.__styleFont !== styleFont) {
  7256. hostEl.__styleFont = styleFont;
  7257. computedFont = hostEl.__computedFont = ctx.font;
  7258. }
  7259. var textPadding = style.textPadding;
  7260. var textLineHeight = style.textLineHeight;
  7261. var contentBlock = hostEl.__textCotentBlock;
  7262. if (!contentBlock || hostEl.__dirtyText) {
  7263. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7264. text, computedFont, textPadding, textLineHeight, style.truncate
  7265. );
  7266. }
  7267. var outerHeight = contentBlock.outerHeight;
  7268. var textLines = contentBlock.lines;
  7269. var lineHeight = contentBlock.lineHeight;
  7270. var boxPos = getBoxPosition(outerHeight, style, rect);
  7271. var baseX = boxPos.baseX;
  7272. var baseY = boxPos.baseY;
  7273. var textAlign = boxPos.textAlign || 'left';
  7274. var textVerticalAlign = boxPos.textVerticalAlign;
  7275. // Origin of textRotation should be the base point of text drawing.
  7276. applyTextRotation(ctx, style, rect, baseX, baseY);
  7277. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7278. var textX = baseX;
  7279. var textY = boxY;
  7280. if (needDrawBg || textPadding) {
  7281. // Consider performance, do not call getTextWidth util necessary.
  7282. var textWidth = getWidth(text, computedFont);
  7283. var outerWidth = textWidth;
  7284. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7285. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7286. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7287. if (textPadding) {
  7288. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7289. textY += textPadding[0];
  7290. }
  7291. }
  7292. // Always set textAlign and textBase line, because it is difficute to calculate
  7293. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7294. // font set happened.
  7295. ctx.textAlign = textAlign;
  7296. // Force baseline to be "middle". Otherwise, if using "top", the
  7297. // text will offset downward a little bit in font "Microsoft YaHei".
  7298. ctx.textBaseline = 'middle';
  7299. // Set text opacity
  7300. ctx.globalAlpha = style.opacity || 1;
  7301. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7302. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7303. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7304. var styleProp = propItem[0];
  7305. var ctxProp = propItem[1];
  7306. var val = style[styleProp];
  7307. if (!checkCache || val !== prevStyle[styleProp]) {
  7308. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7309. }
  7310. }
  7311. // `textBaseline` is set as 'middle'.
  7312. textY += lineHeight / 2;
  7313. var textStrokeWidth = style.textStrokeWidth;
  7314. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7315. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7316. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7317. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7318. var textFill = getFill(style.textFill);
  7319. if (textStroke) {
  7320. if (strokeWidthChanged) {
  7321. ctx.lineWidth = textStrokeWidth;
  7322. }
  7323. if (strokeChanged) {
  7324. ctx.strokeStyle = textStroke;
  7325. }
  7326. }
  7327. if (textFill) {
  7328. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7329. ctx.fillStyle = textFill;
  7330. }
  7331. }
  7332. // Optimize simply, in most cases only one line exists.
  7333. if (textLines.length === 1) {
  7334. // Fill after stroke so the outline will not cover the main part.
  7335. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7336. textFill && ctx.fillText(textLines[0], textX, textY);
  7337. }
  7338. else {
  7339. for (var i = 0; i < textLines.length; i++) {
  7340. // Fill after stroke so the outline will not cover the main part.
  7341. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7342. textFill && ctx.fillText(textLines[i], textX, textY);
  7343. textY += lineHeight;
  7344. }
  7345. }
  7346. }
  7347. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7348. // Do not do cache for rich text because of the complexity.
  7349. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7350. if (prevEl !== WILL_BE_RESTORED) {
  7351. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7352. }
  7353. var contentBlock = hostEl.__textCotentBlock;
  7354. if (!contentBlock || hostEl.__dirtyText) {
  7355. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7356. }
  7357. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7358. }
  7359. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7360. var contentWidth = contentBlock.width;
  7361. var outerWidth = contentBlock.outerWidth;
  7362. var outerHeight = contentBlock.outerHeight;
  7363. var textPadding = style.textPadding;
  7364. var boxPos = getBoxPosition(outerHeight, style, rect);
  7365. var baseX = boxPos.baseX;
  7366. var baseY = boxPos.baseY;
  7367. var textAlign = boxPos.textAlign;
  7368. var textVerticalAlign = boxPos.textVerticalAlign;
  7369. // Origin of textRotation should be the base point of text drawing.
  7370. applyTextRotation(ctx, style, rect, baseX, baseY);
  7371. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7372. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7373. var xLeft = boxX;
  7374. var lineTop = boxY;
  7375. if (textPadding) {
  7376. xLeft += textPadding[3];
  7377. lineTop += textPadding[0];
  7378. }
  7379. var xRight = xLeft + contentWidth;
  7380. needDrawBackground(style) && drawBackground(
  7381. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7382. );
  7383. for (var i = 0; i < contentBlock.lines.length; i++) {
  7384. var line = contentBlock.lines[i];
  7385. var tokens = line.tokens;
  7386. var tokenCount = tokens.length;
  7387. var lineHeight = line.lineHeight;
  7388. var usedWidth = line.width;
  7389. var leftIndex = 0;
  7390. var lineXLeft = xLeft;
  7391. var lineXRight = xRight;
  7392. var rightIndex = tokenCount - 1;
  7393. var token;
  7394. while (
  7395. leftIndex < tokenCount
  7396. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7397. ) {
  7398. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7399. usedWidth -= token.width;
  7400. lineXLeft += token.width;
  7401. leftIndex++;
  7402. }
  7403. while (
  7404. rightIndex >= 0
  7405. && (token = tokens[rightIndex], token.textAlign === 'right')
  7406. ) {
  7407. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7408. usedWidth -= token.width;
  7409. lineXRight -= token.width;
  7410. rightIndex--;
  7411. }
  7412. // The other tokens are placed as textAlign 'center' if there is enough space.
  7413. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7414. while (leftIndex <= rightIndex) {
  7415. token = tokens[leftIndex];
  7416. // Consider width specified by user, use 'center' rather than 'left'.
  7417. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7418. lineXLeft += token.width;
  7419. leftIndex++;
  7420. }
  7421. lineTop += lineHeight;
  7422. }
  7423. }
  7424. function applyTextRotation(ctx, style, rect, x, y) {
  7425. // textRotation only apply in RectText.
  7426. if (rect && style.textRotation) {
  7427. var origin = style.textOrigin;
  7428. if (origin === 'center') {
  7429. x = rect.width / 2 + rect.x;
  7430. y = rect.height / 2 + rect.y;
  7431. }
  7432. else if (origin) {
  7433. x = origin[0] + rect.x;
  7434. y = origin[1] + rect.y;
  7435. }
  7436. ctx.translate(x, y);
  7437. // Positive: anticlockwise
  7438. ctx.rotate(-style.textRotation);
  7439. ctx.translate(-x, -y);
  7440. }
  7441. }
  7442. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7443. var tokenStyle = style.rich[token.styleName] || {};
  7444. tokenStyle.text = token.text;
  7445. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7446. // the bias of "Microsoft YaHei".
  7447. var textVerticalAlign = token.textVerticalAlign;
  7448. var y = lineTop + lineHeight / 2;
  7449. if (textVerticalAlign === 'top') {
  7450. y = lineTop + token.height / 2;
  7451. }
  7452. else if (textVerticalAlign === 'bottom') {
  7453. y = lineTop + lineHeight - token.height / 2;
  7454. }
  7455. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7456. hostEl,
  7457. ctx,
  7458. tokenStyle,
  7459. textAlign === 'right'
  7460. ? x - token.width
  7461. : textAlign === 'center'
  7462. ? x - token.width / 2
  7463. : x,
  7464. y - token.height / 2,
  7465. token.width,
  7466. token.height
  7467. );
  7468. var textPadding = token.textPadding;
  7469. if (textPadding) {
  7470. x = getTextXForPadding(x, textAlign, textPadding);
  7471. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7472. }
  7473. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7474. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7475. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7476. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7477. setCtx(ctx, 'textAlign', textAlign);
  7478. // Force baseline to be "middle". Otherwise, if using "top", the
  7479. // text will offset downward a little bit in font "Microsoft YaHei".
  7480. setCtx(ctx, 'textBaseline', 'middle');
  7481. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7482. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7483. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7484. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7485. // Fill after stroke so the outline will not cover the main part.
  7486. if (textStroke) {
  7487. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7488. setCtx(ctx, 'strokeStyle', textStroke);
  7489. ctx.strokeText(token.text, x, y);
  7490. }
  7491. if (textFill) {
  7492. setCtx(ctx, 'fillStyle', textFill);
  7493. ctx.fillText(token.text, x, y);
  7494. }
  7495. }
  7496. function needDrawBackground(style) {
  7497. return !!(
  7498. style.textBackgroundColor
  7499. || (style.textBorderWidth && style.textBorderColor)
  7500. );
  7501. }
  7502. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7503. // shape: {x, y, width, height}
  7504. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7505. var textBackgroundColor = style.textBackgroundColor;
  7506. var textBorderWidth = style.textBorderWidth;
  7507. var textBorderColor = style.textBorderColor;
  7508. var isPlainBg = isString(textBackgroundColor);
  7509. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7510. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7511. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7512. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7513. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7514. ctx.beginPath();
  7515. var textBorderRadius = style.textBorderRadius;
  7516. if (!textBorderRadius) {
  7517. ctx.rect(x, y, width, height);
  7518. }
  7519. else {
  7520. buildPath(ctx, {
  7521. x: x, y: y, width: width, height: height, r: textBorderRadius
  7522. });
  7523. }
  7524. ctx.closePath();
  7525. }
  7526. if (isPlainBg) {
  7527. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7528. if (style.fillOpacity != null) {
  7529. var originalGlobalAlpha = ctx.globalAlpha;
  7530. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7531. ctx.fill();
  7532. ctx.globalAlpha = originalGlobalAlpha;
  7533. }
  7534. else {
  7535. ctx.fill();
  7536. }
  7537. }
  7538. else if (isObject$1(textBackgroundColor)) {
  7539. var image = textBackgroundColor.image;
  7540. image = createOrUpdateImage(
  7541. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7542. );
  7543. if (image && isImageReady(image)) {
  7544. ctx.drawImage(image, x, y, width, height);
  7545. }
  7546. }
  7547. if (textBorderWidth && textBorderColor) {
  7548. setCtx(ctx, 'lineWidth', textBorderWidth);
  7549. setCtx(ctx, 'strokeStyle', textBorderColor);
  7550. if (style.strokeOpacity != null) {
  7551. var originalGlobalAlpha = ctx.globalAlpha;
  7552. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7553. ctx.stroke();
  7554. ctx.globalAlpha = originalGlobalAlpha;
  7555. }
  7556. else {
  7557. ctx.stroke();
  7558. }
  7559. }
  7560. }
  7561. function onBgImageLoaded(image, textBackgroundColor) {
  7562. // Replace image, so that `contain/text.js#parseRichText`
  7563. // will get correct result in next tick.
  7564. textBackgroundColor.image = image;
  7565. }
  7566. function getBoxPosition(blockHeiht, style, rect) {
  7567. var baseX = style.x || 0;
  7568. var baseY = style.y || 0;
  7569. var textAlign = style.textAlign;
  7570. var textVerticalAlign = style.textVerticalAlign;
  7571. // Text position represented by coord
  7572. if (rect) {
  7573. var textPosition = style.textPosition;
  7574. if (textPosition instanceof Array) {
  7575. // Percent
  7576. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7577. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7578. }
  7579. else {
  7580. var res = adjustTextPositionOnRect(
  7581. textPosition, rect, style.textDistance
  7582. );
  7583. baseX = res.x;
  7584. baseY = res.y;
  7585. // Default align and baseline when has textPosition
  7586. textAlign = textAlign || res.textAlign;
  7587. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7588. }
  7589. // textOffset is only support in RectText, otherwise
  7590. // we have to adjust boundingRect for textOffset.
  7591. var textOffset = style.textOffset;
  7592. if (textOffset) {
  7593. baseX += textOffset[0];
  7594. baseY += textOffset[1];
  7595. }
  7596. }
  7597. return {
  7598. baseX: baseX,
  7599. baseY: baseY,
  7600. textAlign: textAlign,
  7601. textVerticalAlign: textVerticalAlign
  7602. };
  7603. }
  7604. function setCtx(ctx, prop, value) {
  7605. ctx[prop] = fixShadow(ctx, prop, value);
  7606. return ctx[prop];
  7607. }
  7608. /**
  7609. * @param {string} [stroke] If specified, do not check style.textStroke.
  7610. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7611. * @param {number} style
  7612. */
  7613. function getStroke(stroke, lineWidth) {
  7614. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7615. ? null
  7616. // TODO pattern and gradient?
  7617. : (stroke.image || stroke.colorStops)
  7618. ? '#000'
  7619. : stroke;
  7620. }
  7621. function getFill(fill) {
  7622. return (fill == null || fill === 'none')
  7623. ? null
  7624. // TODO pattern and gradient?
  7625. : (fill.image || fill.colorStops)
  7626. ? '#000'
  7627. : fill;
  7628. }
  7629. function parsePercent(value, maxValue) {
  7630. if (typeof value === 'string') {
  7631. if (value.lastIndexOf('%') >= 0) {
  7632. return parseFloat(value) / 100 * maxValue;
  7633. }
  7634. return parseFloat(value);
  7635. }
  7636. return value;
  7637. }
  7638. function getTextXForPadding(x, textAlign, textPadding) {
  7639. return textAlign === 'right'
  7640. ? (x - textPadding[1])
  7641. : textAlign === 'center'
  7642. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7643. : (x + textPadding[3]);
  7644. }
  7645. /**
  7646. * @param {string} text
  7647. * @param {module:zrender/Style} style
  7648. * @return {boolean}
  7649. */
  7650. function needDrawText(text, style) {
  7651. return text != null
  7652. && (text
  7653. || style.textBackgroundColor
  7654. || (style.textBorderWidth && style.textBorderColor)
  7655. || style.textPadding
  7656. );
  7657. }
  7658. /**
  7659. * Mixin for drawing text in a element bounding rect
  7660. * @module zrender/mixin/RectText
  7661. */
  7662. var tmpRect$1 = new BoundingRect();
  7663. var RectText = function () {};
  7664. RectText.prototype = {
  7665. constructor: RectText,
  7666. /**
  7667. * Draw text in a rect with specified position.
  7668. * @param {CanvasRenderingContext2D} ctx
  7669. * @param {Object} rect Displayable rect
  7670. */
  7671. drawRectText: function (ctx, rect) {
  7672. var style = this.style;
  7673. rect = style.textRect || rect;
  7674. // Optimize, avoid normalize every time.
  7675. this.__dirty && normalizeTextStyle(style, true);
  7676. var text = style.text;
  7677. // Convert to string
  7678. text != null && (text += '');
  7679. if (!needDrawText(text, style)) {
  7680. return;
  7681. }
  7682. // FIXME
  7683. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7684. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7685. // text propably break the cache for its host elements.
  7686. ctx.save();
  7687. // Transform rect to view space
  7688. var transform = this.transform;
  7689. if (!style.transformText) {
  7690. if (transform) {
  7691. tmpRect$1.copy(rect);
  7692. tmpRect$1.applyTransform(transform);
  7693. rect = tmpRect$1;
  7694. }
  7695. }
  7696. else {
  7697. this.setTransform(ctx);
  7698. }
  7699. // transformText and textRotation can not be used at the same time.
  7700. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  7701. ctx.restore();
  7702. }
  7703. };
  7704. /**
  7705. * 可绘制的图形基类
  7706. * Base class of all displayable graphic objects
  7707. * @module zrender/graphic/Displayable
  7708. */
  7709. /**
  7710. * @alias module:zrender/graphic/Displayable
  7711. * @extends module:zrender/Element
  7712. * @extends module:zrender/graphic/mixin/RectText
  7713. */
  7714. function Displayable(opts) {
  7715. opts = opts || {};
  7716. Element.call(this, opts);
  7717. // Extend properties
  7718. for (var name in opts) {
  7719. if (
  7720. opts.hasOwnProperty(name)
  7721. && name !== 'style'
  7722. ) {
  7723. this[name] = opts[name];
  7724. }
  7725. }
  7726. /**
  7727. * @type {module:zrender/graphic/Style}
  7728. */
  7729. this.style = new Style(opts.style, this);
  7730. this._rect = null;
  7731. // Shapes for cascade clipping.
  7732. this.__clipPaths = [];
  7733. // FIXME Stateful must be mixined after style is setted
  7734. // Stateful.call(this, opts);
  7735. }
  7736. Displayable.prototype = {
  7737. constructor: Displayable,
  7738. type: 'displayable',
  7739. /**
  7740. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7741. * Dirty flag. From which painter will determine if this displayable object needs brush
  7742. * @name module:zrender/graphic/Displayable#__dirty
  7743. * @type {boolean}
  7744. */
  7745. __dirty: true,
  7746. /**
  7747. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7748. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7749. * @name module:/zrender/graphic/Displayable#invisible
  7750. * @type {boolean}
  7751. * @default false
  7752. */
  7753. invisible: false,
  7754. /**
  7755. * @name module:/zrender/graphic/Displayable#z
  7756. * @type {number}
  7757. * @default 0
  7758. */
  7759. z: 0,
  7760. /**
  7761. * @name module:/zrender/graphic/Displayable#z
  7762. * @type {number}
  7763. * @default 0
  7764. */
  7765. z2: 0,
  7766. /**
  7767. * z层level,决定绘画在哪层canvas中
  7768. * @name module:/zrender/graphic/Displayable#zlevel
  7769. * @type {number}
  7770. * @default 0
  7771. */
  7772. zlevel: 0,
  7773. /**
  7774. * 是否可拖拽
  7775. * @name module:/zrender/graphic/Displayable#draggable
  7776. * @type {boolean}
  7777. * @default false
  7778. */
  7779. draggable: false,
  7780. /**
  7781. * 是否正在拖拽
  7782. * @name module:/zrender/graphic/Displayable#draggable
  7783. * @type {boolean}
  7784. * @default false
  7785. */
  7786. dragging: false,
  7787. /**
  7788. * 是否相应鼠标事件
  7789. * @name module:/zrender/graphic/Displayable#silent
  7790. * @type {boolean}
  7791. * @default false
  7792. */
  7793. silent: false,
  7794. /**
  7795. * If enable culling
  7796. * @type {boolean}
  7797. * @default false
  7798. */
  7799. culling: false,
  7800. /**
  7801. * Mouse cursor when hovered
  7802. * @name module:/zrender/graphic/Displayable#cursor
  7803. * @type {string}
  7804. */
  7805. cursor: 'pointer',
  7806. /**
  7807. * If hover area is bounding rect
  7808. * @name module:/zrender/graphic/Displayable#rectHover
  7809. * @type {string}
  7810. */
  7811. rectHover: false,
  7812. /**
  7813. * Render the element progressively when the value >= 0,
  7814. * usefull for large data.
  7815. * @type {boolean}
  7816. */
  7817. progressive: false,
  7818. /**
  7819. * @type {boolean}
  7820. */
  7821. incremental: false,
  7822. /**
  7823. * Scale ratio for global scale.
  7824. * @type {boolean}
  7825. */
  7826. globalScaleRatio: 1,
  7827. beforeBrush: function (ctx) {},
  7828. afterBrush: function (ctx) {},
  7829. /**
  7830. * 图形绘制方法
  7831. * @param {CanvasRenderingContext2D} ctx
  7832. */
  7833. // Interface
  7834. brush: function (ctx, prevEl) {},
  7835. /**
  7836. * 获取最小包围盒
  7837. * @return {module:zrender/core/BoundingRect}
  7838. */
  7839. // Interface
  7840. getBoundingRect: function () {},
  7841. /**
  7842. * 判断坐标 x, y 是否在图形上
  7843. * If displayable element contain coord x, y
  7844. * @param {number} x
  7845. * @param {number} y
  7846. * @return {boolean}
  7847. */
  7848. contain: function (x, y) {
  7849. return this.rectContain(x, y);
  7850. },
  7851. /**
  7852. * @param {Function} cb
  7853. * @param {} context
  7854. */
  7855. traverse: function (cb, context) {
  7856. cb.call(context, this);
  7857. },
  7858. /**
  7859. * 判断坐标 x, y 是否在图形的包围盒上
  7860. * If bounding rect of element contain coord x, y
  7861. * @param {number} x
  7862. * @param {number} y
  7863. * @return {boolean}
  7864. */
  7865. rectContain: function (x, y) {
  7866. var coord = this.transformCoordToLocal(x, y);
  7867. var rect = this.getBoundingRect();
  7868. return rect.contain(coord[0], coord[1]);
  7869. },
  7870. /**
  7871. * 标记图形元素为脏,并且在下一帧重绘
  7872. * Mark displayable element dirty and refresh next frame
  7873. */
  7874. dirty: function () {
  7875. this.__dirty = this.__dirtyText = true;
  7876. this._rect = null;
  7877. this.__zr && this.__zr.refresh();
  7878. },
  7879. /**
  7880. * 图形是否会触发事件
  7881. * If displayable object binded any event
  7882. * @return {boolean}
  7883. */
  7884. // TODO, 通过 bind 绑定的事件
  7885. // isSilent: function () {
  7886. // return !(
  7887. // this.hoverable || this.draggable
  7888. // || this.onmousemove || this.onmouseover || this.onmouseout
  7889. // || this.onmousedown || this.onmouseup || this.onclick
  7890. // || this.ondragenter || this.ondragover || this.ondragleave
  7891. // || this.ondrop
  7892. // );
  7893. // },
  7894. /**
  7895. * Alias for animate('style')
  7896. * @param {boolean} loop
  7897. */
  7898. animateStyle: function (loop) {
  7899. return this.animate('style', loop);
  7900. },
  7901. attrKV: function (key, value) {
  7902. if (key !== 'style') {
  7903. Element.prototype.attrKV.call(this, key, value);
  7904. }
  7905. else {
  7906. this.style.set(value);
  7907. }
  7908. },
  7909. /**
  7910. * @param {Object|string} key
  7911. * @param {*} value
  7912. */
  7913. setStyle: function (key, value) {
  7914. this.style.set(key, value);
  7915. this.dirty(false);
  7916. return this;
  7917. },
  7918. /**
  7919. * Use given style object
  7920. * @param {Object} obj
  7921. */
  7922. useStyle: function (obj) {
  7923. this.style = new Style(obj, this);
  7924. this.dirty(false);
  7925. return this;
  7926. }
  7927. };
  7928. inherits(Displayable, Element);
  7929. mixin(Displayable, RectText);
  7930. /**
  7931. * @alias zrender/graphic/Image
  7932. * @extends module:zrender/graphic/Displayable
  7933. * @constructor
  7934. * @param {Object} opts
  7935. */
  7936. function ZImage(opts) {
  7937. Displayable.call(this, opts);
  7938. }
  7939. ZImage.prototype = {
  7940. constructor: ZImage,
  7941. type: 'image',
  7942. brush: function (ctx, prevEl) {
  7943. var style = this.style;
  7944. var src = style.image;
  7945. // Must bind each time
  7946. style.bind(ctx, this, prevEl);
  7947. var image = this._image = createOrUpdateImage(
  7948. src,
  7949. this._image,
  7950. this,
  7951. this.onload
  7952. );
  7953. if (!image || !isImageReady(image)) {
  7954. return;
  7955. }
  7956. // 图片已经加载完成
  7957. // if (image.nodeName.toUpperCase() == 'IMG') {
  7958. // if (!image.complete) {
  7959. // return;
  7960. // }
  7961. // }
  7962. // Else is canvas
  7963. var x = style.x || 0;
  7964. var y = style.y || 0;
  7965. var width = style.width;
  7966. var height = style.height;
  7967. var aspect = image.width / image.height;
  7968. if (width == null && height != null) {
  7969. // Keep image/height ratio
  7970. width = height * aspect;
  7971. }
  7972. else if (height == null && width != null) {
  7973. height = width / aspect;
  7974. }
  7975. else if (width == null && height == null) {
  7976. width = image.width;
  7977. height = image.height;
  7978. }
  7979. // 设置transform
  7980. this.setTransform(ctx);
  7981. if (style.sWidth && style.sHeight) {
  7982. var sx = style.sx || 0;
  7983. var sy = style.sy || 0;
  7984. ctx.drawImage(
  7985. image,
  7986. sx, sy, style.sWidth, style.sHeight,
  7987. x, y, width, height
  7988. );
  7989. }
  7990. else if (style.sx && style.sy) {
  7991. var sx = style.sx;
  7992. var sy = style.sy;
  7993. var sWidth = width - sx;
  7994. var sHeight = height - sy;
  7995. ctx.drawImage(
  7996. image,
  7997. sx, sy, sWidth, sHeight,
  7998. x, y, width, height
  7999. );
  8000. }
  8001. else {
  8002. ctx.drawImage(image, x, y, width, height);
  8003. }
  8004. // Draw rect text
  8005. if (style.text != null) {
  8006. // Only restore transform when needs draw text.
  8007. this.restoreTransform(ctx);
  8008. this.drawRectText(ctx, this.getBoundingRect());
  8009. }
  8010. },
  8011. getBoundingRect: function () {
  8012. var style = this.style;
  8013. if (!this._rect) {
  8014. this._rect = new BoundingRect(
  8015. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8016. );
  8017. }
  8018. return this._rect;
  8019. }
  8020. };
  8021. inherits(ZImage, Displayable);
  8022. var HOVER_LAYER_ZLEVEL = 1e5;
  8023. var CANVAS_ZLEVEL = 314159;
  8024. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8025. var INCREMENTAL_INC = 0.001;
  8026. function parseInt10(val) {
  8027. return parseInt(val, 10);
  8028. }
  8029. function isLayerValid(layer) {
  8030. if (!layer) {
  8031. return false;
  8032. }
  8033. if (layer.__builtin__) {
  8034. return true;
  8035. }
  8036. if (typeof (layer.resize) !== 'function'
  8037. || typeof (layer.refresh) !== 'function'
  8038. ) {
  8039. return false;
  8040. }
  8041. return true;
  8042. }
  8043. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8044. var viewRect = new BoundingRect(0, 0, 0, 0);
  8045. function isDisplayableCulled(el, width, height) {
  8046. tmpRect.copy(el.getBoundingRect());
  8047. if (el.transform) {
  8048. tmpRect.applyTransform(el.transform);
  8049. }
  8050. viewRect.width = width;
  8051. viewRect.height = height;
  8052. return !tmpRect.intersect(viewRect);
  8053. }
  8054. function isClipPathChanged(clipPaths, prevClipPaths) {
  8055. if (clipPaths === prevClipPaths) { // Can both be null or undefined
  8056. return false;
  8057. }
  8058. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8059. return true;
  8060. }
  8061. for (var i = 0; i < clipPaths.length; i++) {
  8062. if (clipPaths[i] !== prevClipPaths[i]) {
  8063. return true;
  8064. }
  8065. }
  8066. }
  8067. function doClip(clipPaths, ctx) {
  8068. for (var i = 0; i < clipPaths.length; i++) {
  8069. var clipPath = clipPaths[i];
  8070. clipPath.setTransform(ctx);
  8071. ctx.beginPath();
  8072. clipPath.buildPath(ctx, clipPath.shape);
  8073. ctx.clip();
  8074. // Transform back
  8075. clipPath.restoreTransform(ctx);
  8076. }
  8077. }
  8078. function createRoot(width, height) {
  8079. var domRoot = document.createElement('div');
  8080. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  8081. domRoot.style.cssText = [
  8082. 'position:relative',
  8083. 'overflow:hidden',
  8084. 'width:' + width + 'px',
  8085. 'height:' + height + 'px',
  8086. 'padding:0',
  8087. 'margin:0',
  8088. 'border-width:0'
  8089. ].join(';') + ';';
  8090. return domRoot;
  8091. }
  8092. /**
  8093. * @alias module:zrender/Painter
  8094. * @constructor
  8095. * @param {HTMLElement} root 绘图容器
  8096. * @param {module:zrender/Storage} storage
  8097. * @param {Object} opts
  8098. */
  8099. var Painter = function (root, storage, opts) {
  8100. this.type = 'canvas';
  8101. // In node environment using node-canvas
  8102. var singleCanvas = !root.nodeName // In node ?
  8103. || root.nodeName.toUpperCase() === 'CANVAS';
  8104. this._opts = opts = extend({}, opts || {});
  8105. /**
  8106. * @type {number}
  8107. */
  8108. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8109. /**
  8110. * @type {boolean}
  8111. * @private
  8112. */
  8113. this._singleCanvas = singleCanvas;
  8114. /**
  8115. * 绘图容器
  8116. * @type {HTMLElement}
  8117. */
  8118. this.root = root;
  8119. var rootStyle = root.style;
  8120. if (rootStyle) {
  8121. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8122. rootStyle['-webkit-user-select'] =
  8123. rootStyle['user-select'] =
  8124. rootStyle['-webkit-touch-callout'] = 'none';
  8125. root.innerHTML = '';
  8126. }
  8127. /**
  8128. * @type {module:zrender/Storage}
  8129. */
  8130. this.storage = storage;
  8131. /**
  8132. * @type {Array.<number>}
  8133. * @private
  8134. */
  8135. var zlevelList = this._zlevelList = [];
  8136. /**
  8137. * @type {Object.<string, module:zrender/Layer>}
  8138. * @private
  8139. */
  8140. var layers = this._layers = {};
  8141. /**
  8142. * @type {Object.<string, Object>}
  8143. * @private
  8144. */
  8145. this._layerConfig = {};
  8146. /**
  8147. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8148. */
  8149. this._needsManuallyCompositing = false;
  8150. if (!singleCanvas) {
  8151. this._width = this._getSize(0);
  8152. this._height = this._getSize(1);
  8153. var domRoot = this._domRoot = createRoot(
  8154. this._width, this._height
  8155. );
  8156. root.appendChild(domRoot);
  8157. }
  8158. else {
  8159. var width = root.width;
  8160. var height = root.height;
  8161. if (opts.width != null) {
  8162. width = opts.width;
  8163. }
  8164. if (opts.height != null) {
  8165. height = opts.height;
  8166. }
  8167. this.dpr = opts.devicePixelRatio || 1;
  8168. // Use canvas width and height directly
  8169. root.width = width * this.dpr;
  8170. root.height = height * this.dpr;
  8171. this._width = width;
  8172. this._height = height;
  8173. // Create layer if only one given canvas
  8174. // Device can be specified to create a high dpi image.
  8175. var mainLayer = new Layer(root, this, this.dpr);
  8176. mainLayer.__builtin__ = true;
  8177. mainLayer.initContext();
  8178. // FIXME Use canvas width and height
  8179. // mainLayer.resize(width, height);
  8180. layers[CANVAS_ZLEVEL] = mainLayer;
  8181. mainLayer.zlevel = CANVAS_ZLEVEL;
  8182. // Not use common zlevel.
  8183. zlevelList.push(CANVAS_ZLEVEL);
  8184. this._domRoot = root;
  8185. }
  8186. /**
  8187. * @type {module:zrender/Layer}
  8188. * @private
  8189. */
  8190. this._hoverlayer = null;
  8191. this._hoverElements = [];
  8192. };
  8193. Painter.prototype = {
  8194. constructor: Painter,
  8195. getType: function () {
  8196. return 'canvas';
  8197. },
  8198. /**
  8199. * If painter use a single canvas
  8200. * @return {boolean}
  8201. */
  8202. isSingleCanvas: function () {
  8203. return this._singleCanvas;
  8204. },
  8205. /**
  8206. * @return {HTMLDivElement}
  8207. */
  8208. getViewportRoot: function () {
  8209. return this._domRoot;
  8210. },
  8211. getViewportRootOffset: function () {
  8212. var viewportRoot = this.getViewportRoot();
  8213. if (viewportRoot) {
  8214. return {
  8215. offsetLeft: viewportRoot.offsetLeft || 0,
  8216. offsetTop: viewportRoot.offsetTop || 0
  8217. };
  8218. }
  8219. },
  8220. /**
  8221. * 刷新
  8222. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8223. */
  8224. refresh: function (paintAll) {
  8225. var list = this.storage.getDisplayList(true);
  8226. var zlevelList = this._zlevelList;
  8227. this._redrawId = Math.random();
  8228. this._paintList(list, paintAll, this._redrawId);
  8229. // Paint custum layers
  8230. for (var i = 0; i < zlevelList.length; i++) {
  8231. var z = zlevelList[i];
  8232. var layer = this._layers[z];
  8233. if (!layer.__builtin__ && layer.refresh) {
  8234. var clearColor = i === 0 ? this._backgroundColor : null;
  8235. layer.refresh(clearColor);
  8236. }
  8237. }
  8238. this.refreshHover();
  8239. return this;
  8240. },
  8241. addHover: function (el, hoverStyle) {
  8242. if (el.__hoverMir) {
  8243. return;
  8244. }
  8245. var elMirror = new el.constructor({
  8246. style: el.style,
  8247. shape: el.shape,
  8248. z: el.z,
  8249. z2: el.z2,
  8250. silent: el.silent
  8251. });
  8252. elMirror.__from = el;
  8253. el.__hoverMir = elMirror;
  8254. hoverStyle && elMirror.setStyle(hoverStyle);
  8255. this._hoverElements.push(elMirror);
  8256. return elMirror;
  8257. },
  8258. removeHover: function (el) {
  8259. var elMirror = el.__hoverMir;
  8260. var hoverElements = this._hoverElements;
  8261. var idx = indexOf(hoverElements, elMirror);
  8262. if (idx >= 0) {
  8263. hoverElements.splice(idx, 1);
  8264. }
  8265. el.__hoverMir = null;
  8266. },
  8267. clearHover: function (el) {
  8268. var hoverElements = this._hoverElements;
  8269. for (var i = 0; i < hoverElements.length; i++) {
  8270. var from = hoverElements[i].__from;
  8271. if (from) {
  8272. from.__hoverMir = null;
  8273. }
  8274. }
  8275. hoverElements.length = 0;
  8276. },
  8277. refreshHover: function () {
  8278. var hoverElements = this._hoverElements;
  8279. var len = hoverElements.length;
  8280. var hoverLayer = this._hoverlayer;
  8281. hoverLayer && hoverLayer.clear();
  8282. if (!len) {
  8283. return;
  8284. }
  8285. sort(hoverElements, this.storage.displayableSortFunc);
  8286. // Use a extream large zlevel
  8287. // FIXME?
  8288. if (!hoverLayer) {
  8289. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8290. }
  8291. var scope = {};
  8292. hoverLayer.ctx.save();
  8293. for (var i = 0; i < len;) {
  8294. var el = hoverElements[i];
  8295. var originalEl = el.__from;
  8296. // Original el is removed
  8297. // PENDING
  8298. if (!(originalEl && originalEl.__zr)) {
  8299. hoverElements.splice(i, 1);
  8300. originalEl.__hoverMir = null;
  8301. len--;
  8302. continue;
  8303. }
  8304. i++;
  8305. // Use transform
  8306. // FIXME style and shape ?
  8307. if (!originalEl.invisible) {
  8308. el.transform = originalEl.transform;
  8309. el.invTransform = originalEl.invTransform;
  8310. el.__clipPaths = originalEl.__clipPaths;
  8311. // el.
  8312. this._doPaintEl(el, hoverLayer, true, scope);
  8313. }
  8314. }
  8315. hoverLayer.ctx.restore();
  8316. },
  8317. getHoverLayer: function () {
  8318. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8319. },
  8320. _paintList: function (list, paintAll, redrawId) {
  8321. if (this._redrawId !== redrawId) {
  8322. return;
  8323. }
  8324. paintAll = paintAll || false;
  8325. this._updateLayerStatus(list);
  8326. var finished = this._doPaintList(list, paintAll);
  8327. if (this._needsManuallyCompositing) {
  8328. this._compositeManually();
  8329. }
  8330. if (!finished) {
  8331. var self = this;
  8332. requestAnimationFrame(function () {
  8333. self._paintList(list, paintAll, redrawId);
  8334. });
  8335. }
  8336. },
  8337. _compositeManually: function () {
  8338. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8339. var width = this._domRoot.width;
  8340. var height = this._domRoot.height;
  8341. ctx.clearRect(0, 0, width, height);
  8342. // PENDING, If only builtin layer?
  8343. this.eachBuiltinLayer(function (layer) {
  8344. if (layer.virtual) {
  8345. ctx.drawImage(layer.dom, 0, 0, width, height);
  8346. }
  8347. });
  8348. },
  8349. _doPaintList: function (list, paintAll) {
  8350. var layerList = [];
  8351. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8352. var zlevel = this._zlevelList[zi];
  8353. var layer = this._layers[zlevel];
  8354. if (layer.__builtin__
  8355. && layer !== this._hoverlayer
  8356. && (layer.__dirty || paintAll)
  8357. ) {
  8358. layerList.push(layer);
  8359. }
  8360. }
  8361. var finished = true;
  8362. for (var k = 0; k < layerList.length; k++) {
  8363. var layer = layerList[k];
  8364. var ctx = layer.ctx;
  8365. var scope = {};
  8366. ctx.save();
  8367. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8368. var useTimer = !paintAll && layer.incremental && Date.now;
  8369. var startTime = useTimer && Date.now();
  8370. var clearColor = layer.zlevel === this._zlevelList[0]
  8371. ? this._backgroundColor : null;
  8372. // All elements in this layer are cleared.
  8373. if (layer.__startIndex === layer.__endIndex) {
  8374. layer.clear(false, clearColor);
  8375. }
  8376. else if (start === layer.__startIndex) {
  8377. var firstEl = list[start];
  8378. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8379. layer.clear(false, clearColor);
  8380. }
  8381. }
  8382. if (start === -1) {
  8383. console.error('For some unknown reason. drawIndex is -1');
  8384. start = layer.__startIndex;
  8385. }
  8386. for (var i = start; i < layer.__endIndex; i++) {
  8387. var el = list[i];
  8388. this._doPaintEl(el, layer, paintAll, scope);
  8389. el.__dirty = el.__dirtyText = false;
  8390. if (useTimer) {
  8391. // Date.now can be executed in 13,025,305 ops/second.
  8392. var dTime = Date.now() - startTime;
  8393. // Give 15 millisecond to draw.
  8394. // The rest elements will be drawn in the next frame.
  8395. if (dTime > 15) {
  8396. break;
  8397. }
  8398. }
  8399. }
  8400. layer.__drawIndex = i;
  8401. if (layer.__drawIndex < layer.__endIndex) {
  8402. finished = false;
  8403. }
  8404. if (scope.prevElClipPaths) {
  8405. // Needs restore the state. If last drawn element is in the clipping area.
  8406. ctx.restore();
  8407. }
  8408. ctx.restore();
  8409. }
  8410. if (env$1.wxa) {
  8411. // Flush for weixin application
  8412. each$1(this._layers, function (layer) {
  8413. if (layer && layer.ctx && layer.ctx.draw) {
  8414. layer.ctx.draw();
  8415. }
  8416. });
  8417. }
  8418. return finished;
  8419. },
  8420. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8421. var ctx = currentLayer.ctx;
  8422. var m = el.transform;
  8423. if (
  8424. (currentLayer.__dirty || forcePaint)
  8425. // Ignore invisible element
  8426. && !el.invisible
  8427. // Ignore transparent element
  8428. && el.style.opacity !== 0
  8429. // Ignore scale 0 element, in some environment like node-canvas
  8430. // Draw a scale 0 element can cause all following draw wrong
  8431. // And setTransform with scale 0 will cause set back transform failed.
  8432. && !(m && !m[0] && !m[3])
  8433. // Ignore culled element
  8434. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8435. ) {
  8436. var clipPaths = el.__clipPaths;
  8437. // Optimize when clipping on group with several elements
  8438. if (!scope.prevElClipPaths
  8439. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  8440. ) {
  8441. // If has previous clipping state, restore from it
  8442. if (scope.prevElClipPaths) {
  8443. currentLayer.ctx.restore();
  8444. scope.prevElClipPaths = null;
  8445. // Reset prevEl since context has been restored
  8446. scope.prevEl = null;
  8447. }
  8448. // New clipping state
  8449. if (clipPaths) {
  8450. ctx.save();
  8451. doClip(clipPaths, ctx);
  8452. scope.prevElClipPaths = clipPaths;
  8453. }
  8454. }
  8455. el.beforeBrush && el.beforeBrush(ctx);
  8456. el.brush(ctx, scope.prevEl || null);
  8457. scope.prevEl = el;
  8458. el.afterBrush && el.afterBrush(ctx);
  8459. }
  8460. },
  8461. /**
  8462. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8463. * @param {number} zlevel
  8464. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8465. * @return {module:zrender/Layer}
  8466. */
  8467. getLayer: function (zlevel, virtual) {
  8468. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8469. zlevel = CANVAS_ZLEVEL;
  8470. }
  8471. var layer = this._layers[zlevel];
  8472. if (!layer) {
  8473. // Create a new layer
  8474. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8475. layer.zlevel = zlevel;
  8476. layer.__builtin__ = true;
  8477. if (this._layerConfig[zlevel]) {
  8478. merge(layer, this._layerConfig[zlevel], true);
  8479. }
  8480. if (virtual) {
  8481. layer.virtual = virtual;
  8482. }
  8483. this.insertLayer(zlevel, layer);
  8484. // Context is created after dom inserted to document
  8485. // Or excanvas will get 0px clientWidth and clientHeight
  8486. layer.initContext();
  8487. }
  8488. return layer;
  8489. },
  8490. insertLayer: function (zlevel, layer) {
  8491. var layersMap = this._layers;
  8492. var zlevelList = this._zlevelList;
  8493. var len = zlevelList.length;
  8494. var prevLayer = null;
  8495. var i = -1;
  8496. var domRoot = this._domRoot;
  8497. if (layersMap[zlevel]) {
  8498. zrLog('ZLevel ' + zlevel + ' has been used already');
  8499. return;
  8500. }
  8501. // Check if is a valid layer
  8502. if (!isLayerValid(layer)) {
  8503. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  8504. return;
  8505. }
  8506. if (len > 0 && zlevel > zlevelList[0]) {
  8507. for (i = 0; i < len - 1; i++) {
  8508. if (
  8509. zlevelList[i] < zlevel
  8510. && zlevelList[i + 1] > zlevel
  8511. ) {
  8512. break;
  8513. }
  8514. }
  8515. prevLayer = layersMap[zlevelList[i]];
  8516. }
  8517. zlevelList.splice(i + 1, 0, zlevel);
  8518. layersMap[zlevel] = layer;
  8519. // Vitual layer will not directly show on the screen.
  8520. // (It can be a WebGL layer and assigned to a ZImage element)
  8521. // But it still under management of zrender.
  8522. if (!layer.virtual) {
  8523. if (prevLayer) {
  8524. var prevDom = prevLayer.dom;
  8525. if (prevDom.nextSibling) {
  8526. domRoot.insertBefore(
  8527. layer.dom,
  8528. prevDom.nextSibling
  8529. );
  8530. }
  8531. else {
  8532. domRoot.appendChild(layer.dom);
  8533. }
  8534. }
  8535. else {
  8536. if (domRoot.firstChild) {
  8537. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8538. }
  8539. else {
  8540. domRoot.appendChild(layer.dom);
  8541. }
  8542. }
  8543. }
  8544. },
  8545. // Iterate each layer
  8546. eachLayer: function (cb, context) {
  8547. var zlevelList = this._zlevelList;
  8548. var z;
  8549. var i;
  8550. for (i = 0; i < zlevelList.length; i++) {
  8551. z = zlevelList[i];
  8552. cb.call(context, this._layers[z], z);
  8553. }
  8554. },
  8555. // Iterate each buildin layer
  8556. eachBuiltinLayer: function (cb, context) {
  8557. var zlevelList = this._zlevelList;
  8558. var layer;
  8559. var z;
  8560. var i;
  8561. for (i = 0; i < zlevelList.length; i++) {
  8562. z = zlevelList[i];
  8563. layer = this._layers[z];
  8564. if (layer.__builtin__) {
  8565. cb.call(context, layer, z);
  8566. }
  8567. }
  8568. },
  8569. // Iterate each other layer except buildin layer
  8570. eachOtherLayer: function (cb, context) {
  8571. var zlevelList = this._zlevelList;
  8572. var layer;
  8573. var z;
  8574. var i;
  8575. for (i = 0; i < zlevelList.length; i++) {
  8576. z = zlevelList[i];
  8577. layer = this._layers[z];
  8578. if (!layer.__builtin__) {
  8579. cb.call(context, layer, z);
  8580. }
  8581. }
  8582. },
  8583. /**
  8584. * 获取所有已创建的层
  8585. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8586. */
  8587. getLayers: function () {
  8588. return this._layers;
  8589. },
  8590. _updateLayerStatus: function (list) {
  8591. this.eachBuiltinLayer(function (layer, z) {
  8592. layer.__dirty = layer.__used = false;
  8593. });
  8594. function updatePrevLayer(idx) {
  8595. if (prevLayer) {
  8596. if (prevLayer.__endIndex !== idx) {
  8597. prevLayer.__dirty = true;
  8598. }
  8599. prevLayer.__endIndex = idx;
  8600. }
  8601. }
  8602. if (this._singleCanvas) {
  8603. for (var i = 1; i < list.length; i++) {
  8604. var el = list[i];
  8605. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8606. this._needsManuallyCompositing = true;
  8607. break;
  8608. }
  8609. }
  8610. }
  8611. var prevLayer = null;
  8612. var incrementalLayerCount = 0;
  8613. for (var i = 0; i < list.length; i++) {
  8614. var el = list[i];
  8615. var zlevel = el.zlevel;
  8616. var layer;
  8617. // PENDING If change one incremental element style ?
  8618. // TODO Where there are non-incremental elements between incremental elements.
  8619. if (el.incremental) {
  8620. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8621. layer.incremental = true;
  8622. incrementalLayerCount = 1;
  8623. }
  8624. else {
  8625. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8626. }
  8627. if (!layer.__builtin__) {
  8628. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8629. }
  8630. if (layer !== prevLayer) {
  8631. layer.__used = true;
  8632. if (layer.__startIndex !== i) {
  8633. layer.__dirty = true;
  8634. }
  8635. layer.__startIndex = i;
  8636. if (!layer.incremental) {
  8637. layer.__drawIndex = i;
  8638. }
  8639. else {
  8640. // Mark layer draw index needs to update.
  8641. layer.__drawIndex = -1;
  8642. }
  8643. updatePrevLayer(i);
  8644. prevLayer = layer;
  8645. }
  8646. if (el.__dirty) {
  8647. layer.__dirty = true;
  8648. if (layer.incremental && layer.__drawIndex < 0) {
  8649. // Start draw from the first dirty element.
  8650. layer.__drawIndex = i;
  8651. }
  8652. }
  8653. }
  8654. updatePrevLayer(i);
  8655. this.eachBuiltinLayer(function (layer, z) {
  8656. // Used in last frame but not in this frame. Needs clear
  8657. if (!layer.__used && layer.getElementCount() > 0) {
  8658. layer.__dirty = true;
  8659. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8660. }
  8661. // For incremental layer. In case start index changed and no elements are dirty.
  8662. if (layer.__dirty && layer.__drawIndex < 0) {
  8663. layer.__drawIndex = layer.__startIndex;
  8664. }
  8665. });
  8666. },
  8667. /**
  8668. * 清除hover层外所有内容
  8669. */
  8670. clear: function () {
  8671. this.eachBuiltinLayer(this._clearLayer);
  8672. return this;
  8673. },
  8674. _clearLayer: function (layer) {
  8675. layer.clear();
  8676. },
  8677. setBackgroundColor: function (backgroundColor) {
  8678. this._backgroundColor = backgroundColor;
  8679. },
  8680. /**
  8681. * 修改指定zlevel的绘制参数
  8682. *
  8683. * @param {string} zlevel
  8684. * @param {Object} config 配置对象
  8685. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8686. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8687. * @param {number} [config.lastFrameAlpha=0.7]
  8688. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8689. */
  8690. configLayer: function (zlevel, config) {
  8691. if (config) {
  8692. var layerConfig = this._layerConfig;
  8693. if (!layerConfig[zlevel]) {
  8694. layerConfig[zlevel] = config;
  8695. }
  8696. else {
  8697. merge(layerConfig[zlevel], config, true);
  8698. }
  8699. for (var i = 0; i < this._zlevelList.length; i++) {
  8700. var _zlevel = this._zlevelList[i];
  8701. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8702. var layer = this._layers[_zlevel];
  8703. merge(layer, layerConfig[zlevel], true);
  8704. }
  8705. }
  8706. }
  8707. },
  8708. /**
  8709. * 删除指定层
  8710. * @param {number} zlevel 层所在的zlevel
  8711. */
  8712. delLayer: function (zlevel) {
  8713. var layers = this._layers;
  8714. var zlevelList = this._zlevelList;
  8715. var layer = layers[zlevel];
  8716. if (!layer) {
  8717. return;
  8718. }
  8719. layer.dom.parentNode.removeChild(layer.dom);
  8720. delete layers[zlevel];
  8721. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8722. },
  8723. /**
  8724. * 区域大小变化后重绘
  8725. */
  8726. resize: function (width, height) {
  8727. if (!this._domRoot.style) { // Maybe in node or worker
  8728. if (width == null || height == null) {
  8729. return;
  8730. }
  8731. this._width = width;
  8732. this._height = height;
  8733. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8734. }
  8735. else {
  8736. var domRoot = this._domRoot;
  8737. // FIXME Why ?
  8738. domRoot.style.display = 'none';
  8739. // Save input w/h
  8740. var opts = this._opts;
  8741. width != null && (opts.width = width);
  8742. height != null && (opts.height = height);
  8743. width = this._getSize(0);
  8744. height = this._getSize(1);
  8745. domRoot.style.display = '';
  8746. // 优化没有实际改变的resize
  8747. if (this._width !== width || height !== this._height) {
  8748. domRoot.style.width = width + 'px';
  8749. domRoot.style.height = height + 'px';
  8750. for (var id in this._layers) {
  8751. if (this._layers.hasOwnProperty(id)) {
  8752. this._layers[id].resize(width, height);
  8753. }
  8754. }
  8755. each$1(this._progressiveLayers, function (layer) {
  8756. layer.resize(width, height);
  8757. });
  8758. this.refresh(true);
  8759. }
  8760. this._width = width;
  8761. this._height = height;
  8762. }
  8763. return this;
  8764. },
  8765. /**
  8766. * 清除单独的一个层
  8767. * @param {number} zlevel
  8768. */
  8769. clearLayer: function (zlevel) {
  8770. var layer = this._layers[zlevel];
  8771. if (layer) {
  8772. layer.clear();
  8773. }
  8774. },
  8775. /**
  8776. * 释放
  8777. */
  8778. dispose: function () {
  8779. this.root.innerHTML = '';
  8780. this.root =
  8781. this.storage =
  8782. this._domRoot =
  8783. this._layers = null;
  8784. },
  8785. /**
  8786. * Get canvas which has all thing rendered
  8787. * @param {Object} opts
  8788. * @param {string} [opts.backgroundColor]
  8789. * @param {number} [opts.pixelRatio]
  8790. */
  8791. getRenderedCanvas: function (opts) {
  8792. opts = opts || {};
  8793. if (this._singleCanvas && !this._compositeManually) {
  8794. return this._layers[CANVAS_ZLEVEL].dom;
  8795. }
  8796. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8797. imageLayer.initContext();
  8798. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8799. if (opts.pixelRatio <= this.dpr) {
  8800. this.refresh();
  8801. var width = imageLayer.dom.width;
  8802. var height = imageLayer.dom.height;
  8803. var ctx = imageLayer.ctx;
  8804. this.eachLayer(function (layer) {
  8805. if (layer.__builtin__) {
  8806. ctx.drawImage(layer.dom, 0, 0, width, height);
  8807. }
  8808. else if (layer.renderToCanvas) {
  8809. imageLayer.ctx.save();
  8810. layer.renderToCanvas(imageLayer.ctx);
  8811. imageLayer.ctx.restore();
  8812. }
  8813. });
  8814. }
  8815. else {
  8816. // PENDING, echarts-gl and incremental rendering.
  8817. var scope = {};
  8818. var displayList = this.storage.getDisplayList(true);
  8819. for (var i = 0; i < displayList.length; i++) {
  8820. var el = displayList[i];
  8821. this._doPaintEl(el, imageLayer, true, scope);
  8822. }
  8823. }
  8824. return imageLayer.dom;
  8825. },
  8826. /**
  8827. * 获取绘图区域宽度
  8828. */
  8829. getWidth: function () {
  8830. return this._width;
  8831. },
  8832. /**
  8833. * 获取绘图区域高度
  8834. */
  8835. getHeight: function () {
  8836. return this._height;
  8837. },
  8838. _getSize: function (whIdx) {
  8839. var opts = this._opts;
  8840. var wh = ['width', 'height'][whIdx];
  8841. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8842. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8843. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8844. if (opts[wh] != null && opts[wh] !== 'auto') {
  8845. return parseFloat(opts[wh]);
  8846. }
  8847. var root = this.root;
  8848. // IE8 does not support getComputedStyle, but it use VML.
  8849. var stl = document.defaultView.getComputedStyle(root);
  8850. return (
  8851. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8852. - (parseInt10(stl[plt]) || 0)
  8853. - (parseInt10(stl[prb]) || 0)
  8854. ) | 0;
  8855. },
  8856. pathToImage: function (path, dpr) {
  8857. dpr = dpr || this.dpr;
  8858. var canvas = document.createElement('canvas');
  8859. var ctx = canvas.getContext('2d');
  8860. var rect = path.getBoundingRect();
  8861. var style = path.style;
  8862. var shadowBlurSize = style.shadowBlur * dpr;
  8863. var shadowOffsetX = style.shadowOffsetX * dpr;
  8864. var shadowOffsetY = style.shadowOffsetY * dpr;
  8865. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8866. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8867. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8868. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8869. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8870. var width = rect.width + leftMargin + rightMargin;
  8871. var height = rect.height + topMargin + bottomMargin;
  8872. canvas.width = width * dpr;
  8873. canvas.height = height * dpr;
  8874. ctx.scale(dpr, dpr);
  8875. ctx.clearRect(0, 0, width, height);
  8876. ctx.dpr = dpr;
  8877. var pathTransform = {
  8878. position: path.position,
  8879. rotation: path.rotation,
  8880. scale: path.scale
  8881. };
  8882. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8883. path.rotation = 0;
  8884. path.scale = [1, 1];
  8885. path.updateTransform();
  8886. if (path) {
  8887. path.brush(ctx);
  8888. }
  8889. var ImageShape = ZImage;
  8890. var imgShape = new ImageShape({
  8891. style: {
  8892. x: 0,
  8893. y: 0,
  8894. image: canvas
  8895. }
  8896. });
  8897. if (pathTransform.position != null) {
  8898. imgShape.position = path.position = pathTransform.position;
  8899. }
  8900. if (pathTransform.rotation != null) {
  8901. imgShape.rotation = path.rotation = pathTransform.rotation;
  8902. }
  8903. if (pathTransform.scale != null) {
  8904. imgShape.scale = path.scale = pathTransform.scale;
  8905. }
  8906. return imgShape;
  8907. }
  8908. };
  8909. /**
  8910. * 动画主类, 调度和管理所有动画控制器
  8911. *
  8912. * @module zrender/animation/Animation
  8913. * @author pissang(https://github.com/pissang)
  8914. */
  8915. // TODO Additive animation
  8916. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8917. // https://developer.apple.com/videos/wwdc2014/#236
  8918. /**
  8919. * @typedef {Object} IZRenderStage
  8920. * @property {Function} update
  8921. */
  8922. /**
  8923. * @alias module:zrender/animation/Animation
  8924. * @constructor
  8925. * @param {Object} [options]
  8926. * @param {Function} [options.onframe]
  8927. * @param {IZRenderStage} [options.stage]
  8928. * @example
  8929. * var animation = new Animation();
  8930. * var obj = {
  8931. * x: 100,
  8932. * y: 100
  8933. * };
  8934. * animation.animate(node.position)
  8935. * .when(1000, {
  8936. * x: 500,
  8937. * y: 500
  8938. * })
  8939. * .when(2000, {
  8940. * x: 100,
  8941. * y: 100
  8942. * })
  8943. * .start('spline');
  8944. */
  8945. var Animation = function (options) {
  8946. options = options || {};
  8947. this.stage = options.stage || {};
  8948. this.onframe = options.onframe || function () {};
  8949. // private properties
  8950. this._clips = [];
  8951. this._running = false;
  8952. this._time;
  8953. this._pausedTime;
  8954. this._pauseStart;
  8955. this._paused = false;
  8956. Eventful.call(this);
  8957. };
  8958. Animation.prototype = {
  8959. constructor: Animation,
  8960. /**
  8961. * 添加 clip
  8962. * @param {module:zrender/animation/Clip} clip
  8963. */
  8964. addClip: function (clip) {
  8965. this._clips.push(clip);
  8966. },
  8967. /**
  8968. * 添加 animator
  8969. * @param {module:zrender/animation/Animator} animator
  8970. */
  8971. addAnimator: function (animator) {
  8972. animator.animation = this;
  8973. var clips = animator.getClips();
  8974. for (var i = 0; i < clips.length; i++) {
  8975. this.addClip(clips[i]);
  8976. }
  8977. },
  8978. /**
  8979. * 删除动画片段
  8980. * @param {module:zrender/animation/Clip} clip
  8981. */
  8982. removeClip: function (clip) {
  8983. var idx = indexOf(this._clips, clip);
  8984. if (idx >= 0) {
  8985. this._clips.splice(idx, 1);
  8986. }
  8987. },
  8988. /**
  8989. * 删除动画片段
  8990. * @param {module:zrender/animation/Animator} animator
  8991. */
  8992. removeAnimator: function (animator) {
  8993. var clips = animator.getClips();
  8994. for (var i = 0; i < clips.length; i++) {
  8995. this.removeClip(clips[i]);
  8996. }
  8997. animator.animation = null;
  8998. },
  8999. _update: function () {
  9000. var time = new Date().getTime() - this._pausedTime;
  9001. var delta = time - this._time;
  9002. var clips = this._clips;
  9003. var len = clips.length;
  9004. var deferredEvents = [];
  9005. var deferredClips = [];
  9006. for (var i = 0; i < len; i++) {
  9007. var clip = clips[i];
  9008. var e = clip.step(time, delta);
  9009. // Throw out the events need to be called after
  9010. // stage.update, like destroy
  9011. if (e) {
  9012. deferredEvents.push(e);
  9013. deferredClips.push(clip);
  9014. }
  9015. }
  9016. // Remove the finished clip
  9017. for (var i = 0; i < len;) {
  9018. if (clips[i]._needsRemove) {
  9019. clips[i] = clips[len - 1];
  9020. clips.pop();
  9021. len--;
  9022. }
  9023. else {
  9024. i++;
  9025. }
  9026. }
  9027. len = deferredEvents.length;
  9028. for (var i = 0; i < len; i++) {
  9029. deferredClips[i].fire(deferredEvents[i]);
  9030. }
  9031. this._time = time;
  9032. this.onframe(delta);
  9033. // 'frame' should be triggered before stage, because upper application
  9034. // depends on the sequence (e.g., echarts-stream and finish
  9035. // event judge)
  9036. this.trigger('frame', delta);
  9037. if (this.stage.update) {
  9038. this.stage.update();
  9039. }
  9040. },
  9041. _startLoop: function () {
  9042. var self = this;
  9043. this._running = true;
  9044. function step() {
  9045. if (self._running) {
  9046. requestAnimationFrame(step);
  9047. !self._paused && self._update();
  9048. }
  9049. }
  9050. requestAnimationFrame(step);
  9051. },
  9052. /**
  9053. * Start animation.
  9054. */
  9055. start: function () {
  9056. this._time = new Date().getTime();
  9057. this._pausedTime = 0;
  9058. this._startLoop();
  9059. },
  9060. /**
  9061. * Stop animation.
  9062. */
  9063. stop: function () {
  9064. this._running = false;
  9065. },
  9066. /**
  9067. * Pause animation.
  9068. */
  9069. pause: function () {
  9070. if (!this._paused) {
  9071. this._pauseStart = new Date().getTime();
  9072. this._paused = true;
  9073. }
  9074. },
  9075. /**
  9076. * Resume animation.
  9077. */
  9078. resume: function () {
  9079. if (this._paused) {
  9080. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9081. this._paused = false;
  9082. }
  9083. },
  9084. /**
  9085. * Clear animation.
  9086. */
  9087. clear: function () {
  9088. this._clips = [];
  9089. },
  9090. /**
  9091. * Whether animation finished.
  9092. */
  9093. isFinished: function () {
  9094. return !this._clips.length;
  9095. },
  9096. /**
  9097. * Creat animator for a target, whose props can be animated.
  9098. *
  9099. * @param {Object} target
  9100. * @param {Object} options
  9101. * @param {boolean} [options.loop=false] Whether loop animation.
  9102. * @param {Function} [options.getter=null] Get value from target.
  9103. * @param {Function} [options.setter=null] Set value to target.
  9104. * @return {module:zrender/animation/Animation~Animator}
  9105. */
  9106. // TODO Gap
  9107. animate: function (target, options) {
  9108. options = options || {};
  9109. var animator = new Animator(
  9110. target,
  9111. options.loop,
  9112. options.getter,
  9113. options.setter
  9114. );
  9115. this.addAnimator(animator);
  9116. return animator;
  9117. }
  9118. };
  9119. mixin(Animation, Eventful);
  9120. var TOUCH_CLICK_DELAY = 300;
  9121. var mouseHandlerNames = [
  9122. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9123. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9124. ];
  9125. var touchHandlerNames = [
  9126. 'touchstart', 'touchend', 'touchmove'
  9127. ];
  9128. var pointerEventNames = {
  9129. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9130. };
  9131. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9132. var nm = name.replace('mouse', 'pointer');
  9133. return pointerEventNames[nm] ? nm : name;
  9134. });
  9135. function eventNameFix(name) {
  9136. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9137. }
  9138. // function onMSGestureChange(proxy, event) {
  9139. // if (event.translationX || event.translationY) {
  9140. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9141. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9142. // }
  9143. // if (event.scale !== 1) {
  9144. // event.pinchX = event.offsetX;
  9145. // event.pinchY = event.offsetY;
  9146. // event.pinchScale = event.scale;
  9147. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9148. // }
  9149. // }
  9150. /**
  9151. * Prevent mouse event from being dispatched after Touch Events action
  9152. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9153. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9154. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9155. * Result: Blocking Mouse Events for 700ms.
  9156. */
  9157. function setTouchTimer(instance) {
  9158. instance._touching = true;
  9159. clearTimeout(instance._touchTimer);
  9160. instance._touchTimer = setTimeout(function () {
  9161. instance._touching = false;
  9162. }, 700);
  9163. }
  9164. var domHandlers = {
  9165. /**
  9166. * Mouse move handler
  9167. * @inner
  9168. * @param {Event} event
  9169. */
  9170. mousemove: function (event) {
  9171. event = normalizeEvent(this.dom, event);
  9172. this.trigger('mousemove', event);
  9173. },
  9174. /**
  9175. * Mouse out handler
  9176. * @inner
  9177. * @param {Event} event
  9178. */
  9179. mouseout: function (event) {
  9180. event = normalizeEvent(this.dom, event);
  9181. var element = event.toElement || event.relatedTarget;
  9182. if (element !== this.dom) {
  9183. while (element && element.nodeType !== 9) {
  9184. // 忽略包含在root中的dom引起的mouseOut
  9185. if (element === this.dom) {
  9186. return;
  9187. }
  9188. element = element.parentNode;
  9189. }
  9190. }
  9191. this.trigger('mouseout', event);
  9192. },
  9193. /**
  9194. * Touch开始响应函数
  9195. * @inner
  9196. * @param {Event} event
  9197. */
  9198. touchstart: function (event) {
  9199. // Default mouse behaviour should not be disabled here.
  9200. // For example, page may needs to be slided.
  9201. event = normalizeEvent(this.dom, event);
  9202. // Mark touch, which is useful in distinguish touch and
  9203. // mouse event in upper applicatoin.
  9204. event.zrByTouch = true;
  9205. this._lastTouchMoment = new Date();
  9206. this.handler.processGesture(this, event, 'start');
  9207. // In touch device, trigger `mousemove`(`mouseover`) should
  9208. // be triggered, and must before `mousedown` triggered.
  9209. domHandlers.mousemove.call(this, event);
  9210. domHandlers.mousedown.call(this, event);
  9211. setTouchTimer(this);
  9212. },
  9213. /**
  9214. * Touch移动响应函数
  9215. * @inner
  9216. * @param {Event} event
  9217. */
  9218. touchmove: function (event) {
  9219. event = normalizeEvent(this.dom, event);
  9220. // Mark touch, which is useful in distinguish touch and
  9221. // mouse event in upper applicatoin.
  9222. event.zrByTouch = true;
  9223. this.handler.processGesture(this, event, 'change');
  9224. // Mouse move should always be triggered no matter whether
  9225. // there is gestrue event, because mouse move and pinch may
  9226. // be used at the same time.
  9227. domHandlers.mousemove.call(this, event);
  9228. setTouchTimer(this);
  9229. },
  9230. /**
  9231. * Touch结束响应函数
  9232. * @inner
  9233. * @param {Event} event
  9234. */
  9235. touchend: function (event) {
  9236. event = normalizeEvent(this.dom, event);
  9237. // Mark touch, which is useful in distinguish touch and
  9238. // mouse event in upper applicatoin.
  9239. event.zrByTouch = true;
  9240. this.handler.processGesture(this, event, 'end');
  9241. domHandlers.mouseup.call(this, event);
  9242. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9243. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9244. // we can conveniently implement "hover style" in both PC and touch device just
  9245. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9246. // to remove "hover style" on an element, without any additional code for
  9247. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9248. // style" will remain for user view)
  9249. // click event should always be triggered no matter whether
  9250. // there is gestrue event. System click can not be prevented.
  9251. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9252. domHandlers.click.call(this, event);
  9253. }
  9254. setTouchTimer(this);
  9255. },
  9256. pointerdown: function (event) {
  9257. domHandlers.mousedown.call(this, event);
  9258. // if (useMSGuesture(this, event)) {
  9259. // this._msGesture.addPointer(event.pointerId);
  9260. // }
  9261. },
  9262. pointermove: function (event) {
  9263. // FIXME
  9264. // pointermove is so sensitive that it always triggered when
  9265. // tap(click) on touch screen, which affect some judgement in
  9266. // upper application. So, we dont support mousemove on MS touch
  9267. // device yet.
  9268. if (!isPointerFromTouch(event)) {
  9269. domHandlers.mousemove.call(this, event);
  9270. }
  9271. },
  9272. pointerup: function (event) {
  9273. domHandlers.mouseup.call(this, event);
  9274. },
  9275. pointerout: function (event) {
  9276. // pointerout will be triggered when tap on touch screen
  9277. // (IE11+/Edge on MS Surface) after click event triggered,
  9278. // which is inconsistent with the mousout behavior we defined
  9279. // in touchend. So we unify them.
  9280. // (check domHandlers.touchend for detailed explanation)
  9281. if (!isPointerFromTouch(event)) {
  9282. domHandlers.mouseout.call(this, event);
  9283. }
  9284. }
  9285. };
  9286. function isPointerFromTouch(event) {
  9287. var pointerType = event.pointerType;
  9288. return pointerType === 'pen' || pointerType === 'touch';
  9289. }
  9290. // function useMSGuesture(handlerProxy, event) {
  9291. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9292. // }
  9293. // Common handlers
  9294. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9295. domHandlers[name] = function (event) {
  9296. event = normalizeEvent(this.dom, event);
  9297. this.trigger(name, event);
  9298. };
  9299. });
  9300. /**
  9301. * 为控制类实例初始化dom 事件处理函数
  9302. *
  9303. * @inner
  9304. * @param {module:zrender/Handler} instance 控制类实例
  9305. */
  9306. function initDomHandler(instance) {
  9307. each$1(touchHandlerNames, function (name) {
  9308. instance._handlers[name] = bind(domHandlers[name], instance);
  9309. });
  9310. each$1(pointerHandlerNames, function (name) {
  9311. instance._handlers[name] = bind(domHandlers[name], instance);
  9312. });
  9313. each$1(mouseHandlerNames, function (name) {
  9314. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  9315. });
  9316. function makeMouseHandler(fn, instance) {
  9317. return function () {
  9318. if (instance._touching) {
  9319. return;
  9320. }
  9321. return fn.apply(instance, arguments);
  9322. };
  9323. }
  9324. }
  9325. function HandlerDomProxy(dom) {
  9326. Eventful.call(this);
  9327. this.dom = dom;
  9328. /**
  9329. * @private
  9330. * @type {boolean}
  9331. */
  9332. this._touching = false;
  9333. /**
  9334. * @private
  9335. * @type {number}
  9336. */
  9337. this._touchTimer;
  9338. this._handlers = {};
  9339. initDomHandler(this);
  9340. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9341. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9342. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9343. // at the same time.
  9344. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9345. // screen, which do not occurs in pointer event.
  9346. // So we use pointer event to both detect touch gesture and mouse behavior.
  9347. mountHandlers(pointerHandlerNames, this);
  9348. // FIXME
  9349. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9350. // which does not prevent defuault behavior occasionally (which may cause view port
  9351. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9352. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9353. // touch screen. And we only support click behavior on MS touch screen now.
  9354. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9355. // We dont support touch on IE on win7.
  9356. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9357. // if (typeof MSGesture === 'function') {
  9358. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9359. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9360. // }
  9361. }
  9362. else {
  9363. if (env$1.touchEventsSupported) {
  9364. mountHandlers(touchHandlerNames, this);
  9365. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9366. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9367. }
  9368. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9369. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9370. // mouse event can not be handle in those devices.
  9371. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9372. // mouseevent after touch event triggered, see `setTouchTimer`.
  9373. mountHandlers(mouseHandlerNames, this);
  9374. }
  9375. function mountHandlers(handlerNames, instance) {
  9376. each$1(handlerNames, function (name) {
  9377. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9378. }, instance);
  9379. }
  9380. }
  9381. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9382. handlerDomProxyProto.dispose = function () {
  9383. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9384. for (var i = 0; i < handlerNames.length; i++) {
  9385. var name = handlerNames[i];
  9386. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9387. }
  9388. };
  9389. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9390. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9391. };
  9392. mixin(HandlerDomProxy, Eventful);
  9393. /*!
  9394. * ZRender, a high performance 2d drawing library.
  9395. *
  9396. * Copyright (c) 2013, Baidu Inc.
  9397. * All rights reserved.
  9398. *
  9399. * LICENSE
  9400. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9401. */
  9402. var useVML = !env$1.canvasSupported;
  9403. var painterCtors = {
  9404. canvas: Painter
  9405. };
  9406. var instances$1 = {}; // ZRender实例map索引
  9407. /**
  9408. * @type {string}
  9409. */
  9410. var version$1 = '4.0.7';
  9411. /**
  9412. * Initializing a zrender instance
  9413. * @param {HTMLElement} dom
  9414. * @param {Object} [opts]
  9415. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9416. * @param {number} [opts.devicePixelRatio]
  9417. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9418. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9419. * @return {module:zrender/ZRender}
  9420. */
  9421. function init$1(dom, opts) {
  9422. var zr = new ZRender(guid(), dom, opts);
  9423. instances$1[zr.id] = zr;
  9424. return zr;
  9425. }
  9426. /**
  9427. * Dispose zrender instance
  9428. * @param {module:zrender/ZRender} zr
  9429. */
  9430. function dispose$1(zr) {
  9431. if (zr) {
  9432. zr.dispose();
  9433. }
  9434. else {
  9435. for (var key in instances$1) {
  9436. if (instances$1.hasOwnProperty(key)) {
  9437. instances$1[key].dispose();
  9438. }
  9439. }
  9440. instances$1 = {};
  9441. }
  9442. return this;
  9443. }
  9444. /**
  9445. * Get zrender instance by id
  9446. * @param {string} id zrender instance id
  9447. * @return {module:zrender/ZRender}
  9448. */
  9449. function getInstance(id) {
  9450. return instances$1[id];
  9451. }
  9452. function registerPainter(name, Ctor) {
  9453. painterCtors[name] = Ctor;
  9454. }
  9455. function delInstance(id) {
  9456. delete instances$1[id];
  9457. }
  9458. /**
  9459. * @module zrender/ZRender
  9460. */
  9461. /**
  9462. * @constructor
  9463. * @alias module:zrender/ZRender
  9464. * @param {string} id
  9465. * @param {HTMLElement} dom
  9466. * @param {Object} opts
  9467. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9468. * @param {number} [opts.devicePixelRatio]
  9469. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9470. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9471. */
  9472. var ZRender = function (id, dom, opts) {
  9473. opts = opts || {};
  9474. /**
  9475. * @type {HTMLDomElement}
  9476. */
  9477. this.dom = dom;
  9478. /**
  9479. * @type {string}
  9480. */
  9481. this.id = id;
  9482. var self = this;
  9483. var storage = new Storage();
  9484. var rendererType = opts.renderer;
  9485. // TODO WebGL
  9486. if (useVML) {
  9487. if (!painterCtors.vml) {
  9488. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9489. }
  9490. rendererType = 'vml';
  9491. }
  9492. else if (!rendererType || !painterCtors[rendererType]) {
  9493. rendererType = 'canvas';
  9494. }
  9495. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9496. this.storage = storage;
  9497. this.painter = painter;
  9498. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9499. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9500. /**
  9501. * @type {module:zrender/animation/Animation}
  9502. */
  9503. this.animation = new Animation({
  9504. stage: {
  9505. update: bind(this.flush, this)
  9506. }
  9507. });
  9508. this.animation.start();
  9509. /**
  9510. * @type {boolean}
  9511. * @private
  9512. */
  9513. this._needsRefresh;
  9514. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9515. // FIXME 有点ugly
  9516. var oldDelFromStorage = storage.delFromStorage;
  9517. var oldAddToStorage = storage.addToStorage;
  9518. storage.delFromStorage = function (el) {
  9519. oldDelFromStorage.call(storage, el);
  9520. el && el.removeSelfFromZr(self);
  9521. };
  9522. storage.addToStorage = function (el) {
  9523. oldAddToStorage.call(storage, el);
  9524. el.addSelfToZr(self);
  9525. };
  9526. };
  9527. ZRender.prototype = {
  9528. constructor: ZRender,
  9529. /**
  9530. * 获取实例唯一标识
  9531. * @return {string}
  9532. */
  9533. getId: function () {
  9534. return this.id;
  9535. },
  9536. /**
  9537. * 添加元素
  9538. * @param {module:zrender/Element} el
  9539. */
  9540. add: function (el) {
  9541. this.storage.addRoot(el);
  9542. this._needsRefresh = true;
  9543. },
  9544. /**
  9545. * 删除元素
  9546. * @param {module:zrender/Element} el
  9547. */
  9548. remove: function (el) {
  9549. this.storage.delRoot(el);
  9550. this._needsRefresh = true;
  9551. },
  9552. /**
  9553. * Change configuration of layer
  9554. * @param {string} zLevel
  9555. * @param {Object} config
  9556. * @param {string} [config.clearColor=0] Clear color
  9557. * @param {string} [config.motionBlur=false] If enable motion blur
  9558. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9559. */
  9560. configLayer: function (zLevel, config) {
  9561. if (this.painter.configLayer) {
  9562. this.painter.configLayer(zLevel, config);
  9563. }
  9564. this._needsRefresh = true;
  9565. },
  9566. /**
  9567. * Set background color
  9568. * @param {string} backgroundColor
  9569. */
  9570. setBackgroundColor: function (backgroundColor) {
  9571. if (this.painter.setBackgroundColor) {
  9572. this.painter.setBackgroundColor(backgroundColor);
  9573. }
  9574. this._needsRefresh = true;
  9575. },
  9576. /**
  9577. * Repaint the canvas immediately
  9578. */
  9579. refreshImmediately: function () {
  9580. // var start = new Date();
  9581. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9582. // Or it will cause zrender refreshes again and again.
  9583. this._needsRefresh = false;
  9584. this.painter.refresh();
  9585. /**
  9586. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9587. */
  9588. this._needsRefresh = false;
  9589. // var end = new Date();
  9590. // var log = document.getElementById('log');
  9591. // if (log) {
  9592. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9593. // }
  9594. },
  9595. /**
  9596. * Mark and repaint the canvas in the next frame of browser
  9597. */
  9598. refresh: function () {
  9599. this._needsRefresh = true;
  9600. },
  9601. /**
  9602. * Perform all refresh
  9603. */
  9604. flush: function () {
  9605. var triggerRendered;
  9606. if (this._needsRefresh) {
  9607. triggerRendered = true;
  9608. this.refreshImmediately();
  9609. }
  9610. if (this._needsRefreshHover) {
  9611. triggerRendered = true;
  9612. this.refreshHoverImmediately();
  9613. }
  9614. triggerRendered && this.trigger('rendered');
  9615. },
  9616. /**
  9617. * Add element to hover layer
  9618. * @param {module:zrender/Element} el
  9619. * @param {Object} style
  9620. */
  9621. addHover: function (el, style) {
  9622. if (this.painter.addHover) {
  9623. var elMirror = this.painter.addHover(el, style);
  9624. this.refreshHover();
  9625. return elMirror;
  9626. }
  9627. },
  9628. /**
  9629. * Add element from hover layer
  9630. * @param {module:zrender/Element} el
  9631. */
  9632. removeHover: function (el) {
  9633. if (this.painter.removeHover) {
  9634. this.painter.removeHover(el);
  9635. this.refreshHover();
  9636. }
  9637. },
  9638. /**
  9639. * Clear all hover elements in hover layer
  9640. * @param {module:zrender/Element} el
  9641. */
  9642. clearHover: function () {
  9643. if (this.painter.clearHover) {
  9644. this.painter.clearHover();
  9645. this.refreshHover();
  9646. }
  9647. },
  9648. /**
  9649. * Refresh hover in next frame
  9650. */
  9651. refreshHover: function () {
  9652. this._needsRefreshHover = true;
  9653. },
  9654. /**
  9655. * Refresh hover immediately
  9656. */
  9657. refreshHoverImmediately: function () {
  9658. this._needsRefreshHover = false;
  9659. this.painter.refreshHover && this.painter.refreshHover();
  9660. },
  9661. /**
  9662. * Resize the canvas.
  9663. * Should be invoked when container size is changed
  9664. * @param {Object} [opts]
  9665. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9666. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9667. */
  9668. resize: function (opts) {
  9669. opts = opts || {};
  9670. this.painter.resize(opts.width, opts.height);
  9671. this.handler.resize();
  9672. },
  9673. /**
  9674. * Stop and clear all animation immediately
  9675. */
  9676. clearAnimation: function () {
  9677. this.animation.clear();
  9678. },
  9679. /**
  9680. * Get container width
  9681. */
  9682. getWidth: function () {
  9683. return this.painter.getWidth();
  9684. },
  9685. /**
  9686. * Get container height
  9687. */
  9688. getHeight: function () {
  9689. return this.painter.getHeight();
  9690. },
  9691. /**
  9692. * Export the canvas as Base64 URL
  9693. * @param {string} type
  9694. * @param {string} [backgroundColor='#fff']
  9695. * @return {string} Base64 URL
  9696. */
  9697. // toDataURL: function(type, backgroundColor) {
  9698. // return this.painter.getRenderedCanvas({
  9699. // backgroundColor: backgroundColor
  9700. // }).toDataURL(type);
  9701. // },
  9702. /**
  9703. * Converting a path to image.
  9704. * It has much better performance of drawing image rather than drawing a vector path.
  9705. * @param {module:zrender/graphic/Path} e
  9706. * @param {number} width
  9707. * @param {number} height
  9708. */
  9709. pathToImage: function (e, dpr) {
  9710. return this.painter.pathToImage(e, dpr);
  9711. },
  9712. /**
  9713. * Set default cursor
  9714. * @param {string} [cursorStyle='default'] 例如 crosshair
  9715. */
  9716. setCursorStyle: function (cursorStyle) {
  9717. this.handler.setCursorStyle(cursorStyle);
  9718. },
  9719. /**
  9720. * Find hovered element
  9721. * @param {number} x
  9722. * @param {number} y
  9723. * @return {Object} {target, topTarget}
  9724. */
  9725. findHover: function (x, y) {
  9726. return this.handler.findHover(x, y);
  9727. },
  9728. /**
  9729. * Bind event
  9730. *
  9731. * @param {string} eventName Event name
  9732. * @param {Function} eventHandler Handler function
  9733. * @param {Object} [context] Context object
  9734. */
  9735. on: function (eventName, eventHandler, context) {
  9736. this.handler.on(eventName, eventHandler, context);
  9737. },
  9738. /**
  9739. * Unbind event
  9740. * @param {string} eventName Event name
  9741. * @param {Function} [eventHandler] Handler function
  9742. */
  9743. off: function (eventName, eventHandler) {
  9744. this.handler.off(eventName, eventHandler);
  9745. },
  9746. /**
  9747. * Trigger event manually
  9748. *
  9749. * @param {string} eventName Event name
  9750. * @param {event=} event Event object
  9751. */
  9752. trigger: function (eventName, event) {
  9753. this.handler.trigger(eventName, event);
  9754. },
  9755. /**
  9756. * Clear all objects and the canvas.
  9757. */
  9758. clear: function () {
  9759. this.storage.delRoot();
  9760. this.painter.clear();
  9761. },
  9762. /**
  9763. * Dispose self.
  9764. */
  9765. dispose: function () {
  9766. this.animation.stop();
  9767. this.clear();
  9768. this.storage.dispose();
  9769. this.painter.dispose();
  9770. this.handler.dispose();
  9771. this.animation =
  9772. this.storage =
  9773. this.painter =
  9774. this.handler = null;
  9775. delInstance(this.id);
  9776. }
  9777. };
  9778. var zrender = (Object.freeze || Object)({
  9779. version: version$1,
  9780. init: init$1,
  9781. dispose: dispose$1,
  9782. getInstance: getInstance,
  9783. registerPainter: registerPainter
  9784. });
  9785. /*
  9786. * Licensed to the Apache Software Foundation (ASF) under one
  9787. * or more contributor license agreements. See the NOTICE file
  9788. * distributed with this work for additional information
  9789. * regarding copyright ownership. The ASF licenses this file
  9790. * to you under the Apache License, Version 2.0 (the
  9791. * "License"); you may not use this file except in compliance
  9792. * with the License. You may obtain a copy of the License at
  9793. *
  9794. * http://www.apache.org/licenses/LICENSE-2.0
  9795. *
  9796. * Unless required by applicable law or agreed to in writing,
  9797. * software distributed under the License is distributed on an
  9798. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9799. * KIND, either express or implied. See the License for the
  9800. * specific language governing permissions and limitations
  9801. * under the License.
  9802. */
  9803. var each$2 = each$1;
  9804. var isObject$2 = isObject$1;
  9805. var isArray$1 = isArray;
  9806. /**
  9807. * Make the name displayable. But we should
  9808. * make sure it is not duplicated with user
  9809. * specified name, so use '\0';
  9810. */
  9811. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9812. /**
  9813. * If value is not array, then translate it to array.
  9814. * @param {*} value
  9815. * @return {Array} [value] or value
  9816. */
  9817. function normalizeToArray(value) {
  9818. return value instanceof Array
  9819. ? value
  9820. : value == null
  9821. ? []
  9822. : [value];
  9823. }
  9824. /**
  9825. * Sync default option between normal and emphasis like `position` and `show`
  9826. * In case some one will write code like
  9827. * label: {
  9828. * show: false,
  9829. * position: 'outside',
  9830. * fontSize: 18
  9831. * },
  9832. * emphasis: {
  9833. * label: { show: true }
  9834. * }
  9835. * @param {Object} opt
  9836. * @param {string} key
  9837. * @param {Array.<string>} subOpts
  9838. */
  9839. function defaultEmphasis(opt, key, subOpts) {
  9840. // Caution: performance sensitive.
  9841. if (opt) {
  9842. opt[key] = opt[key] || {};
  9843. opt.emphasis = opt.emphasis || {};
  9844. opt.emphasis[key] = opt.emphasis[key] || {};
  9845. // Default emphasis option from normal
  9846. for (var i = 0, len = subOpts.length; i < len; i++) {
  9847. var subOptName = subOpts[i];
  9848. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9849. && opt[key].hasOwnProperty(subOptName)
  9850. ) {
  9851. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9852. }
  9853. }
  9854. }
  9855. }
  9856. var TEXT_STYLE_OPTIONS = [
  9857. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9858. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9859. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9860. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9861. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9862. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9863. ];
  9864. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9865. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9866. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9867. // // FIXME: deprecated, check and remove it.
  9868. // 'textStyle'
  9869. // ]);
  9870. /**
  9871. * The method do not ensure performance.
  9872. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9873. * This helper method retieves value from data.
  9874. * @param {string|number|Date|Array|Object} dataItem
  9875. * @return {number|string|Date|Array.<number|string|Date>}
  9876. */
  9877. function getDataItemValue(dataItem) {
  9878. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9879. ? dataItem.value : dataItem;
  9880. }
  9881. /**
  9882. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9883. * This helper method determine if dataItem has extra option besides value
  9884. * @param {string|number|Date|Array|Object} dataItem
  9885. */
  9886. function isDataItemOption(dataItem) {
  9887. return isObject$2(dataItem)
  9888. && !(dataItem instanceof Array);
  9889. // // markLine data can be array
  9890. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9891. }
  9892. /**
  9893. * Mapping to exists for merge.
  9894. *
  9895. * @public
  9896. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9897. * @param {Object|Array.<Object>} newCptOptions
  9898. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9899. * index of which is the same as exists.
  9900. */
  9901. function mappingToExists(exists, newCptOptions) {
  9902. // Mapping by the order by original option (but not order of
  9903. // new option) in merge mode. Because we should ensure
  9904. // some specified index (like xAxisIndex) is consistent with
  9905. // original option, which is easy to understand, espatially in
  9906. // media query. And in most case, merge option is used to
  9907. // update partial option but not be expected to change order.
  9908. newCptOptions = (newCptOptions || []).slice();
  9909. var result = map(exists || [], function (obj, index) {
  9910. return {exist: obj};
  9911. });
  9912. // Mapping by id or name if specified.
  9913. each$2(newCptOptions, function (cptOption, index) {
  9914. if (!isObject$2(cptOption)) {
  9915. return;
  9916. }
  9917. // id has highest priority.
  9918. for (var i = 0; i < result.length; i++) {
  9919. if (!result[i].option // Consider name: two map to one.
  9920. && cptOption.id != null
  9921. && result[i].exist.id === cptOption.id + ''
  9922. ) {
  9923. result[i].option = cptOption;
  9924. newCptOptions[index] = null;
  9925. return;
  9926. }
  9927. }
  9928. for (var i = 0; i < result.length; i++) {
  9929. var exist = result[i].exist;
  9930. if (!result[i].option // Consider name: two map to one.
  9931. // Can not match when both ids exist but different.
  9932. && (exist.id == null || cptOption.id == null)
  9933. && cptOption.name != null
  9934. && !isIdInner(cptOption)
  9935. && !isIdInner(exist)
  9936. && exist.name === cptOption.name + ''
  9937. ) {
  9938. result[i].option = cptOption;
  9939. newCptOptions[index] = null;
  9940. return;
  9941. }
  9942. }
  9943. });
  9944. // Otherwise mapping by index.
  9945. each$2(newCptOptions, function (cptOption, index) {
  9946. if (!isObject$2(cptOption)) {
  9947. return;
  9948. }
  9949. var i = 0;
  9950. for (; i < result.length; i++) {
  9951. var exist = result[i].exist;
  9952. if (!result[i].option
  9953. // Existing model that already has id should be able to
  9954. // mapped to (because after mapping performed model may
  9955. // be assigned with a id, whish should not affect next
  9956. // mapping), except those has inner id.
  9957. && !isIdInner(exist)
  9958. // Caution:
  9959. // Do not overwrite id. But name can be overwritten,
  9960. // because axis use name as 'show label text'.
  9961. // 'exist' always has id and name and we dont
  9962. // need to check it.
  9963. && cptOption.id == null
  9964. ) {
  9965. result[i].option = cptOption;
  9966. break;
  9967. }
  9968. }
  9969. if (i >= result.length) {
  9970. result.push({option: cptOption});
  9971. }
  9972. });
  9973. return result;
  9974. }
  9975. /**
  9976. * Make id and name for mapping result (result of mappingToExists)
  9977. * into `keyInfo` field.
  9978. *
  9979. * @public
  9980. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9981. * which order is the same as exists.
  9982. * @return {Array.<Object>} The input.
  9983. */
  9984. function makeIdAndName(mapResult) {
  9985. // We use this id to hash component models and view instances
  9986. // in echarts. id can be specified by user, or auto generated.
  9987. // The id generation rule ensures new view instance are able
  9988. // to mapped to old instance when setOption are called in
  9989. // no-merge mode. So we generate model id by name and plus
  9990. // type in view id.
  9991. // name can be duplicated among components, which is convenient
  9992. // to specify multi components (like series) by one name.
  9993. // Ensure that each id is distinct.
  9994. var idMap = createHashMap();
  9995. each$2(mapResult, function (item, index) {
  9996. var existCpt = item.exist;
  9997. existCpt && idMap.set(existCpt.id, item);
  9998. });
  9999. each$2(mapResult, function (item, index) {
  10000. var opt = item.option;
  10001. assert$1(
  10002. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10003. 'id duplicates: ' + (opt && opt.id)
  10004. );
  10005. opt && opt.id != null && idMap.set(opt.id, item);
  10006. !item.keyInfo && (item.keyInfo = {});
  10007. });
  10008. // Make name and id.
  10009. each$2(mapResult, function (item, index) {
  10010. var existCpt = item.exist;
  10011. var opt = item.option;
  10012. var keyInfo = item.keyInfo;
  10013. if (!isObject$2(opt)) {
  10014. return;
  10015. }
  10016. // name can be overwitten. Consider case: axis.name = '20km'.
  10017. // But id generated by name will not be changed, which affect
  10018. // only in that case: setOption with 'not merge mode' and view
  10019. // instance will be recreated, which can be accepted.
  10020. keyInfo.name = opt.name != null
  10021. ? opt.name + ''
  10022. : existCpt
  10023. ? existCpt.name
  10024. // Avoid diffferent series has the same name,
  10025. // because name may be used like in color pallet.
  10026. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10027. if (existCpt) {
  10028. keyInfo.id = existCpt.id;
  10029. }
  10030. else if (opt.id != null) {
  10031. keyInfo.id = opt.id + '';
  10032. }
  10033. else {
  10034. // Consider this situatoin:
  10035. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10036. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10037. // Series with the same name between optionA and optionB
  10038. // should be mapped.
  10039. var idNum = 0;
  10040. do {
  10041. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10042. }
  10043. while (idMap.get(keyInfo.id));
  10044. }
  10045. idMap.set(keyInfo.id, item);
  10046. });
  10047. }
  10048. function isNameSpecified(componentModel) {
  10049. var name = componentModel.name;
  10050. // Is specified when `indexOf` get -1 or > 0.
  10051. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10052. }
  10053. /**
  10054. * @public
  10055. * @param {Object} cptOption
  10056. * @return {boolean}
  10057. */
  10058. function isIdInner(cptOption) {
  10059. return isObject$2(cptOption)
  10060. && cptOption.id
  10061. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10062. }
  10063. /**
  10064. * A helper for removing duplicate items between batchA and batchB,
  10065. * and in themselves, and categorize by series.
  10066. *
  10067. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10068. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10069. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10070. */
  10071. /**
  10072. * @param {module:echarts/data/List} data
  10073. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10074. * each of which can be Array or primary type.
  10075. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10076. */
  10077. function queryDataIndex(data, payload) {
  10078. if (payload.dataIndexInside != null) {
  10079. return payload.dataIndexInside;
  10080. }
  10081. else if (payload.dataIndex != null) {
  10082. return isArray(payload.dataIndex)
  10083. ? map(payload.dataIndex, function (value) {
  10084. return data.indexOfRawIndex(value);
  10085. })
  10086. : data.indexOfRawIndex(payload.dataIndex);
  10087. }
  10088. else if (payload.name != null) {
  10089. return isArray(payload.name)
  10090. ? map(payload.name, function (value) {
  10091. return data.indexOfName(value);
  10092. })
  10093. : data.indexOfName(payload.name);
  10094. }
  10095. }
  10096. /**
  10097. * Enable property storage to any host object.
  10098. * Notice: Serialization is not supported.
  10099. *
  10100. * For example:
  10101. * var inner = zrUitl.makeInner();
  10102. *
  10103. * function some1(hostObj) {
  10104. * inner(hostObj).someProperty = 1212;
  10105. * ...
  10106. * }
  10107. * function some2() {
  10108. * var fields = inner(this);
  10109. * fields.someProperty1 = 1212;
  10110. * fields.someProperty2 = 'xx';
  10111. * ...
  10112. * }
  10113. *
  10114. * @return {Function}
  10115. */
  10116. function makeInner() {
  10117. // Consider different scope by es module import.
  10118. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10119. return function (hostObj) {
  10120. return hostObj[key] || (hostObj[key] = {});
  10121. };
  10122. }
  10123. var innerUniqueIndex = 0;
  10124. /**
  10125. * @param {module:echarts/model/Global} ecModel
  10126. * @param {string|Object} finder
  10127. * If string, e.g., 'geo', means {geoIndex: 0}.
  10128. * If Object, could contain some of these properties below:
  10129. * {
  10130. * seriesIndex, seriesId, seriesName,
  10131. * geoIndex, geoId, geoName,
  10132. * bmapIndex, bmapId, bmapName,
  10133. * xAxisIndex, xAxisId, xAxisName,
  10134. * yAxisIndex, yAxisId, yAxisName,
  10135. * gridIndex, gridId, gridName,
  10136. * ... (can be extended)
  10137. * }
  10138. * Each properties can be number|string|Array.<number>|Array.<string>
  10139. * For example, a finder could be
  10140. * {
  10141. * seriesIndex: 3,
  10142. * geoId: ['aa', 'cc'],
  10143. * gridName: ['xx', 'rr']
  10144. * }
  10145. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10146. * If nothing or null/undefined specified, return nothing.
  10147. * @param {Object} [opt]
  10148. * @param {string} [opt.defaultMainType]
  10149. * @param {Array.<string>} [opt.includeMainTypes]
  10150. * @return {Object} result like:
  10151. * {
  10152. * seriesModels: [seriesModel1, seriesModel2],
  10153. * seriesModel: seriesModel1, // The first model
  10154. * geoModels: [geoModel1, geoModel2],
  10155. * geoModel: geoModel1, // The first model
  10156. * ...
  10157. * }
  10158. */
  10159. function parseFinder(ecModel, finder, opt) {
  10160. if (isString(finder)) {
  10161. var obj = {};
  10162. obj[finder + 'Index'] = 0;
  10163. finder = obj;
  10164. }
  10165. var defaultMainType = opt && opt.defaultMainType;
  10166. if (defaultMainType
  10167. && !has(finder, defaultMainType + 'Index')
  10168. && !has(finder, defaultMainType + 'Id')
  10169. && !has(finder, defaultMainType + 'Name')
  10170. ) {
  10171. finder[defaultMainType + 'Index'] = 0;
  10172. }
  10173. var result = {};
  10174. each$2(finder, function (value, key) {
  10175. var value = finder[key];
  10176. // Exclude 'dataIndex' and other illgal keys.
  10177. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10178. result[key] = value;
  10179. return;
  10180. }
  10181. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10182. var mainType = parsedKey[1];
  10183. var queryType = (parsedKey[2] || '').toLowerCase();
  10184. if (!mainType
  10185. || !queryType
  10186. || value == null
  10187. || (queryType === 'index' && value === 'none')
  10188. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10189. ) {
  10190. return;
  10191. }
  10192. var queryParam = {mainType: mainType};
  10193. if (queryType !== 'index' || value !== 'all') {
  10194. queryParam[queryType] = value;
  10195. }
  10196. var models = ecModel.queryComponents(queryParam);
  10197. result[mainType + 'Models'] = models;
  10198. result[mainType + 'Model'] = models[0];
  10199. });
  10200. return result;
  10201. }
  10202. function has(obj, prop) {
  10203. return obj && obj.hasOwnProperty(prop);
  10204. }
  10205. function setAttribute(dom, key, value) {
  10206. dom.setAttribute
  10207. ? dom.setAttribute(key, value)
  10208. : (dom[key] = value);
  10209. }
  10210. function getAttribute(dom, key) {
  10211. return dom.getAttribute
  10212. ? dom.getAttribute(key)
  10213. : dom[key];
  10214. }
  10215. function getTooltipRenderMode(renderModeOption) {
  10216. if (renderModeOption === 'auto') {
  10217. // Using html when `document` exists, use richText otherwise
  10218. return env$1.domSupported ? 'html' : 'richText';
  10219. }
  10220. else {
  10221. return renderModeOption || 'html';
  10222. }
  10223. }
  10224. /**
  10225. * Group a list by key.
  10226. *
  10227. * @param {Array} array
  10228. * @param {Function} getKey
  10229. * param {*} Array item
  10230. * return {string} key
  10231. * @return {Object} Result
  10232. * {Array}: keys,
  10233. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10234. */
  10235. /*
  10236. * Licensed to the Apache Software Foundation (ASF) under one
  10237. * or more contributor license agreements. See the NOTICE file
  10238. * distributed with this work for additional information
  10239. * regarding copyright ownership. The ASF licenses this file
  10240. * to you under the Apache License, Version 2.0 (the
  10241. * "License"); you may not use this file except in compliance
  10242. * with the License. You may obtain a copy of the License at
  10243. *
  10244. * http://www.apache.org/licenses/LICENSE-2.0
  10245. *
  10246. * Unless required by applicable law or agreed to in writing,
  10247. * software distributed under the License is distributed on an
  10248. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10249. * KIND, either express or implied. See the License for the
  10250. * specific language governing permissions and limitations
  10251. * under the License.
  10252. */
  10253. var TYPE_DELIMITER = '.';
  10254. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10255. /**
  10256. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10257. * @public
  10258. */
  10259. function parseClassType$1(componentType) {
  10260. var ret = {main: '', sub: ''};
  10261. if (componentType) {
  10262. componentType = componentType.split(TYPE_DELIMITER);
  10263. ret.main = componentType[0] || '';
  10264. ret.sub = componentType[1] || '';
  10265. }
  10266. return ret;
  10267. }
  10268. /**
  10269. * @public
  10270. */
  10271. function checkClassType(componentType) {
  10272. assert$1(
  10273. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10274. 'componentType "' + componentType + '" illegal'
  10275. );
  10276. }
  10277. /**
  10278. * @public
  10279. */
  10280. function enableClassExtend(RootClass, mandatoryMethods) {
  10281. RootClass.$constructor = RootClass;
  10282. RootClass.extend = function (proto) {
  10283. if (__DEV__) {
  10284. each$1(mandatoryMethods, function (method) {
  10285. if (!proto[method]) {
  10286. console.warn(
  10287. 'Method `' + method + '` should be implemented'
  10288. + (proto.type ? ' in ' + proto.type : '') + '.'
  10289. );
  10290. }
  10291. });
  10292. }
  10293. var superClass = this;
  10294. var ExtendedClass = function () {
  10295. if (!proto.$constructor) {
  10296. superClass.apply(this, arguments);
  10297. }
  10298. else {
  10299. proto.$constructor.apply(this, arguments);
  10300. }
  10301. };
  10302. extend(ExtendedClass.prototype, proto);
  10303. ExtendedClass.extend = this.extend;
  10304. ExtendedClass.superCall = superCall;
  10305. ExtendedClass.superApply = superApply;
  10306. inherits(ExtendedClass, this);
  10307. ExtendedClass.superClass = superClass;
  10308. return ExtendedClass;
  10309. };
  10310. }
  10311. var classBase = 0;
  10312. /**
  10313. * Can not use instanceof, consider different scope by
  10314. * cross domain or es module import in ec extensions.
  10315. * Mount a method "isInstance()" to Clz.
  10316. */
  10317. function enableClassCheck(Clz) {
  10318. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10319. Clz.prototype[classAttr] = true;
  10320. if (__DEV__) {
  10321. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10322. }
  10323. Clz.isInstance = function (obj) {
  10324. return !!(obj && obj[classAttr]);
  10325. };
  10326. }
  10327. // superCall should have class info, which can not be fetch from 'this'.
  10328. // Consider this case:
  10329. // class A has method f,
  10330. // class B inherits class A, overrides method f, f call superApply('f'),
  10331. // class C inherits class B, do not overrides method f,
  10332. // then when method of class C is called, dead loop occured.
  10333. function superCall(context, methodName) {
  10334. var args = slice(arguments, 2);
  10335. return this.superClass.prototype[methodName].apply(context, args);
  10336. }
  10337. function superApply(context, methodName, args) {
  10338. return this.superClass.prototype[methodName].apply(context, args);
  10339. }
  10340. /**
  10341. * @param {Object} entity
  10342. * @param {Object} options
  10343. * @param {boolean} [options.registerWhenExtend]
  10344. * @public
  10345. */
  10346. function enableClassManagement(entity, options) {
  10347. options = options || {};
  10348. /**
  10349. * Component model classes
  10350. * key: componentType,
  10351. * value:
  10352. * componentClass, when componentType is 'xxx'
  10353. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10354. * @type {Object}
  10355. */
  10356. var storage = {};
  10357. entity.registerClass = function (Clazz, componentType) {
  10358. if (componentType) {
  10359. checkClassType(componentType);
  10360. componentType = parseClassType$1(componentType);
  10361. if (!componentType.sub) {
  10362. if (__DEV__) {
  10363. if (storage[componentType.main]) {
  10364. console.warn(componentType.main + ' exists.');
  10365. }
  10366. }
  10367. storage[componentType.main] = Clazz;
  10368. }
  10369. else if (componentType.sub !== IS_CONTAINER) {
  10370. var container = makeContainer(componentType);
  10371. container[componentType.sub] = Clazz;
  10372. }
  10373. }
  10374. return Clazz;
  10375. };
  10376. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10377. var Clazz = storage[componentMainType];
  10378. if (Clazz && Clazz[IS_CONTAINER]) {
  10379. Clazz = subType ? Clazz[subType] : null;
  10380. }
  10381. if (throwWhenNotFound && !Clazz) {
  10382. throw new Error(
  10383. !subType
  10384. ? componentMainType + '.' + 'type should be specified.'
  10385. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10386. );
  10387. }
  10388. return Clazz;
  10389. };
  10390. entity.getClassesByMainType = function (componentType) {
  10391. componentType = parseClassType$1(componentType);
  10392. var result = [];
  10393. var obj = storage[componentType.main];
  10394. if (obj && obj[IS_CONTAINER]) {
  10395. each$1(obj, function (o, type) {
  10396. type !== IS_CONTAINER && result.push(o);
  10397. });
  10398. }
  10399. else {
  10400. result.push(obj);
  10401. }
  10402. return result;
  10403. };
  10404. entity.hasClass = function (componentType) {
  10405. // Just consider componentType.main.
  10406. componentType = parseClassType$1(componentType);
  10407. return !!storage[componentType.main];
  10408. };
  10409. /**
  10410. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10411. */
  10412. entity.getAllClassMainTypes = function () {
  10413. var types = [];
  10414. each$1(storage, function (obj, type) {
  10415. types.push(type);
  10416. });
  10417. return types;
  10418. };
  10419. /**
  10420. * If a main type is container and has sub types
  10421. * @param {string} mainType
  10422. * @return {boolean}
  10423. */
  10424. entity.hasSubTypes = function (componentType) {
  10425. componentType = parseClassType$1(componentType);
  10426. var obj = storage[componentType.main];
  10427. return obj && obj[IS_CONTAINER];
  10428. };
  10429. entity.parseClassType = parseClassType$1;
  10430. function makeContainer(componentType) {
  10431. var container = storage[componentType.main];
  10432. if (!container || !container[IS_CONTAINER]) {
  10433. container = storage[componentType.main] = {};
  10434. container[IS_CONTAINER] = true;
  10435. }
  10436. return container;
  10437. }
  10438. if (options.registerWhenExtend) {
  10439. var originalExtend = entity.extend;
  10440. if (originalExtend) {
  10441. entity.extend = function (proto) {
  10442. var ExtendedClass = originalExtend.call(this, proto);
  10443. return entity.registerClass(ExtendedClass, proto.type);
  10444. };
  10445. }
  10446. }
  10447. return entity;
  10448. }
  10449. /**
  10450. * @param {string|Array.<string>} properties
  10451. */
  10452. /*
  10453. * Licensed to the Apache Software Foundation (ASF) under one
  10454. * or more contributor license agreements. See the NOTICE file
  10455. * distributed with this work for additional information
  10456. * regarding copyright ownership. The ASF licenses this file
  10457. * to you under the Apache License, Version 2.0 (the
  10458. * "License"); you may not use this file except in compliance
  10459. * with the License. You may obtain a copy of the License at
  10460. *
  10461. * http://www.apache.org/licenses/LICENSE-2.0
  10462. *
  10463. * Unless required by applicable law or agreed to in writing,
  10464. * software distributed under the License is distributed on an
  10465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10466. * KIND, either express or implied. See the License for the
  10467. * specific language governing permissions and limitations
  10468. * under the License.
  10469. */
  10470. // TODO Parse shadow style
  10471. // TODO Only shallow path support
  10472. var makeStyleMapper = function (properties) {
  10473. // Normalize
  10474. for (var i = 0; i < properties.length; i++) {
  10475. if (!properties[i][1]) {
  10476. properties[i][1] = properties[i][0];
  10477. }
  10478. }
  10479. return function (model, excludes, includes) {
  10480. var style = {};
  10481. for (var i = 0; i < properties.length; i++) {
  10482. var propName = properties[i][1];
  10483. if ((excludes && indexOf(excludes, propName) >= 0)
  10484. || (includes && indexOf(includes, propName) < 0)
  10485. ) {
  10486. continue;
  10487. }
  10488. var val = model.getShallow(propName);
  10489. if (val != null) {
  10490. style[properties[i][0]] = val;
  10491. }
  10492. }
  10493. return style;
  10494. };
  10495. };
  10496. /*
  10497. * Licensed to the Apache Software Foundation (ASF) under one
  10498. * or more contributor license agreements. See the NOTICE file
  10499. * distributed with this work for additional information
  10500. * regarding copyright ownership. The ASF licenses this file
  10501. * to you under the Apache License, Version 2.0 (the
  10502. * "License"); you may not use this file except in compliance
  10503. * with the License. You may obtain a copy of the License at
  10504. *
  10505. * http://www.apache.org/licenses/LICENSE-2.0
  10506. *
  10507. * Unless required by applicable law or agreed to in writing,
  10508. * software distributed under the License is distributed on an
  10509. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10510. * KIND, either express or implied. See the License for the
  10511. * specific language governing permissions and limitations
  10512. * under the License.
  10513. */
  10514. var getLineStyle = makeStyleMapper(
  10515. [
  10516. ['lineWidth', 'width'],
  10517. ['stroke', 'color'],
  10518. ['opacity'],
  10519. ['shadowBlur'],
  10520. ['shadowOffsetX'],
  10521. ['shadowOffsetY'],
  10522. ['shadowColor']
  10523. ]
  10524. );
  10525. var lineStyleMixin = {
  10526. getLineStyle: function (excludes) {
  10527. var style = getLineStyle(this, excludes);
  10528. var lineDash = this.getLineDash(style.lineWidth);
  10529. lineDash && (style.lineDash = lineDash);
  10530. return style;
  10531. },
  10532. getLineDash: function (lineWidth) {
  10533. if (lineWidth == null) {
  10534. lineWidth = 1;
  10535. }
  10536. var lineType = this.get('type');
  10537. var dotSize = Math.max(lineWidth, 2);
  10538. var dashSize = lineWidth * 4;
  10539. return (lineType === 'solid' || lineType == null) ? null
  10540. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10541. }
  10542. };
  10543. /*
  10544. * Licensed to the Apache Software Foundation (ASF) under one
  10545. * or more contributor license agreements. See the NOTICE file
  10546. * distributed with this work for additional information
  10547. * regarding copyright ownership. The ASF licenses this file
  10548. * to you under the Apache License, Version 2.0 (the
  10549. * "License"); you may not use this file except in compliance
  10550. * with the License. You may obtain a copy of the License at
  10551. *
  10552. * http://www.apache.org/licenses/LICENSE-2.0
  10553. *
  10554. * Unless required by applicable law or agreed to in writing,
  10555. * software distributed under the License is distributed on an
  10556. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10557. * KIND, either express or implied. See the License for the
  10558. * specific language governing permissions and limitations
  10559. * under the License.
  10560. */
  10561. var getAreaStyle = makeStyleMapper(
  10562. [
  10563. ['fill', 'color'],
  10564. ['shadowBlur'],
  10565. ['shadowOffsetX'],
  10566. ['shadowOffsetY'],
  10567. ['opacity'],
  10568. ['shadowColor']
  10569. ]
  10570. );
  10571. var areaStyleMixin = {
  10572. getAreaStyle: function (excludes, includes) {
  10573. return getAreaStyle(this, excludes, includes);
  10574. }
  10575. };
  10576. /**
  10577. * 曲线辅助模块
  10578. * @module zrender/core/curve
  10579. * @author pissang(https://www.github.com/pissang)
  10580. */
  10581. var mathPow = Math.pow;
  10582. var mathSqrt$2 = Math.sqrt;
  10583. var EPSILON$1 = 1e-8;
  10584. var EPSILON_NUMERIC = 1e-4;
  10585. var THREE_SQRT = mathSqrt$2(3);
  10586. var ONE_THIRD = 1 / 3;
  10587. // 临时变量
  10588. var _v0 = create();
  10589. var _v1 = create();
  10590. var _v2 = create();
  10591. function isAroundZero(val) {
  10592. return val > -EPSILON$1 && val < EPSILON$1;
  10593. }
  10594. function isNotAroundZero$1(val) {
  10595. return val > EPSILON$1 || val < -EPSILON$1;
  10596. }
  10597. /**
  10598. * 计算三次贝塞尔值
  10599. * @memberOf module:zrender/core/curve
  10600. * @param {number} p0
  10601. * @param {number} p1
  10602. * @param {number} p2
  10603. * @param {number} p3
  10604. * @param {number} t
  10605. * @return {number}
  10606. */
  10607. function cubicAt(p0, p1, p2, p3, t) {
  10608. var onet = 1 - t;
  10609. return onet * onet * (onet * p0 + 3 * t * p1)
  10610. + t * t * (t * p3 + 3 * onet * p2);
  10611. }
  10612. /**
  10613. * 计算三次贝塞尔导数值
  10614. * @memberOf module:zrender/core/curve
  10615. * @param {number} p0
  10616. * @param {number} p1
  10617. * @param {number} p2
  10618. * @param {number} p3
  10619. * @param {number} t
  10620. * @return {number}
  10621. */
  10622. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10623. var onet = 1 - t;
  10624. return 3 * (
  10625. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10626. + (p3 - p2) * t * t
  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} p3
  10636. * @param {number} val
  10637. * @param {Array.<number>} roots
  10638. * @return {number} 有效根数目
  10639. */
  10640. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10641. // Evaluate roots of cubic functions
  10642. var a = p3 + 3 * (p1 - p2) - p0;
  10643. var b = 3 * (p2 - p1 * 2 + p0);
  10644. var c = 3 * (p1 - p0);
  10645. var d = p0 - val;
  10646. var A = b * b - 3 * a * c;
  10647. var B = b * c - 9 * a * d;
  10648. var C = c * c - 3 * b * d;
  10649. var n = 0;
  10650. if (isAroundZero(A) && isAroundZero(B)) {
  10651. if (isAroundZero(b)) {
  10652. roots[0] = 0;
  10653. }
  10654. else {
  10655. var t1 = -c / b; //t1, t2, t3, b is not zero
  10656. if (t1 >= 0 && t1 <= 1) {
  10657. roots[n++] = t1;
  10658. }
  10659. }
  10660. }
  10661. else {
  10662. var disc = B * B - 4 * A * C;
  10663. if (isAroundZero(disc)) {
  10664. var K = B / A;
  10665. var t1 = -b / a + K; // t1, a is not zero
  10666. var t2 = -K / 2; // t2, t3
  10667. if (t1 >= 0 && t1 <= 1) {
  10668. roots[n++] = t1;
  10669. }
  10670. if (t2 >= 0 && t2 <= 1) {
  10671. roots[n++] = t2;
  10672. }
  10673. }
  10674. else if (disc > 0) {
  10675. var discSqrt = mathSqrt$2(disc);
  10676. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10677. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10678. if (Y1 < 0) {
  10679. Y1 = -mathPow(-Y1, ONE_THIRD);
  10680. }
  10681. else {
  10682. Y1 = mathPow(Y1, ONE_THIRD);
  10683. }
  10684. if (Y2 < 0) {
  10685. Y2 = -mathPow(-Y2, ONE_THIRD);
  10686. }
  10687. else {
  10688. Y2 = mathPow(Y2, ONE_THIRD);
  10689. }
  10690. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10691. if (t1 >= 0 && t1 <= 1) {
  10692. roots[n++] = t1;
  10693. }
  10694. }
  10695. else {
  10696. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10697. var theta = Math.acos(T) / 3;
  10698. var ASqrt = mathSqrt$2(A);
  10699. var tmp = Math.cos(theta);
  10700. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10701. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10702. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10703. if (t1 >= 0 && t1 <= 1) {
  10704. roots[n++] = t1;
  10705. }
  10706. if (t2 >= 0 && t2 <= 1) {
  10707. roots[n++] = t2;
  10708. }
  10709. if (t3 >= 0 && t3 <= 1) {
  10710. roots[n++] = t3;
  10711. }
  10712. }
  10713. }
  10714. return n;
  10715. }
  10716. /**
  10717. * 计算三次贝塞尔方程极限值的位置
  10718. * @memberOf module:zrender/core/curve
  10719. * @param {number} p0
  10720. * @param {number} p1
  10721. * @param {number} p2
  10722. * @param {number} p3
  10723. * @param {Array.<number>} extrema
  10724. * @return {number} 有效数目
  10725. */
  10726. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10727. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10728. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10729. var c = 3 * p1 - 3 * p0;
  10730. var n = 0;
  10731. if (isAroundZero(a)) {
  10732. if (isNotAroundZero$1(b)) {
  10733. var t1 = -c / b;
  10734. if (t1 >= 0 && t1 <= 1) {
  10735. extrema[n++] = t1;
  10736. }
  10737. }
  10738. }
  10739. else {
  10740. var disc = b * b - 4 * a * c;
  10741. if (isAroundZero(disc)) {
  10742. extrema[0] = -b / (2 * a);
  10743. }
  10744. else if (disc > 0) {
  10745. var discSqrt = mathSqrt$2(disc);
  10746. var t1 = (-b + discSqrt) / (2 * a);
  10747. var t2 = (-b - discSqrt) / (2 * a);
  10748. if (t1 >= 0 && t1 <= 1) {
  10749. extrema[n++] = t1;
  10750. }
  10751. if (t2 >= 0 && t2 <= 1) {
  10752. extrema[n++] = t2;
  10753. }
  10754. }
  10755. }
  10756. return n;
  10757. }
  10758. /**
  10759. * 细分三次贝塞尔曲线
  10760. * @memberOf module:zrender/core/curve
  10761. * @param {number} p0
  10762. * @param {number} p1
  10763. * @param {number} p2
  10764. * @param {number} p3
  10765. * @param {number} t
  10766. * @param {Array.<number>} out
  10767. */
  10768. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10769. var p01 = (p1 - p0) * t + p0;
  10770. var p12 = (p2 - p1) * t + p1;
  10771. var p23 = (p3 - p2) * t + p2;
  10772. var p012 = (p12 - p01) * t + p01;
  10773. var p123 = (p23 - p12) * t + p12;
  10774. var p0123 = (p123 - p012) * t + p012;
  10775. // Seg0
  10776. out[0] = p0;
  10777. out[1] = p01;
  10778. out[2] = p012;
  10779. out[3] = p0123;
  10780. // Seg1
  10781. out[4] = p0123;
  10782. out[5] = p123;
  10783. out[6] = p23;
  10784. out[7] = p3;
  10785. }
  10786. /**
  10787. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10788. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10789. * @param {number} x0
  10790. * @param {number} y0
  10791. * @param {number} x1
  10792. * @param {number} y1
  10793. * @param {number} x2
  10794. * @param {number} y2
  10795. * @param {number} x3
  10796. * @param {number} y3
  10797. * @param {number} x
  10798. * @param {number} y
  10799. * @param {Array.<number>} [out] 投射点
  10800. * @return {number}
  10801. */
  10802. function cubicProjectPoint(
  10803. x0, y0, x1, y1, x2, y2, x3, y3,
  10804. x, y, out
  10805. ) {
  10806. // http://pomax.github.io/bezierinfo/#projections
  10807. var t;
  10808. var interval = 0.005;
  10809. var d = Infinity;
  10810. var prev;
  10811. var next;
  10812. var d1;
  10813. var d2;
  10814. _v0[0] = x;
  10815. _v0[1] = y;
  10816. // 先粗略估计一下可能的最小距离的 t 值
  10817. // PENDING
  10818. for (var _t = 0; _t < 1; _t += 0.05) {
  10819. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10820. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10821. d1 = distSquare(_v0, _v1);
  10822. if (d1 < d) {
  10823. t = _t;
  10824. d = d1;
  10825. }
  10826. }
  10827. d = Infinity;
  10828. // At most 32 iteration
  10829. for (var i = 0; i < 32; i++) {
  10830. if (interval < EPSILON_NUMERIC) {
  10831. break;
  10832. }
  10833. prev = t - interval;
  10834. next = t + interval;
  10835. // t - interval
  10836. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10837. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10838. d1 = distSquare(_v1, _v0);
  10839. if (prev >= 0 && d1 < d) {
  10840. t = prev;
  10841. d = d1;
  10842. }
  10843. else {
  10844. // t + interval
  10845. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10846. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10847. d2 = distSquare(_v2, _v0);
  10848. if (next <= 1 && d2 < d) {
  10849. t = next;
  10850. d = d2;
  10851. }
  10852. else {
  10853. interval *= 0.5;
  10854. }
  10855. }
  10856. }
  10857. // t
  10858. if (out) {
  10859. out[0] = cubicAt(x0, x1, x2, x3, t);
  10860. out[1] = cubicAt(y0, y1, y2, y3, t);
  10861. }
  10862. // console.log(interval, i);
  10863. return mathSqrt$2(d);
  10864. }
  10865. /**
  10866. * 计算二次方贝塞尔值
  10867. * @param {number} p0
  10868. * @param {number} p1
  10869. * @param {number} p2
  10870. * @param {number} t
  10871. * @return {number}
  10872. */
  10873. function quadraticAt(p0, p1, p2, t) {
  10874. var onet = 1 - t;
  10875. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10876. }
  10877. /**
  10878. * 计算二次方贝塞尔导数值
  10879. * @param {number} p0
  10880. * @param {number} p1
  10881. * @param {number} p2
  10882. * @param {number} t
  10883. * @return {number}
  10884. */
  10885. function quadraticDerivativeAt(p0, p1, p2, t) {
  10886. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10887. }
  10888. /**
  10889. * 计算二次方贝塞尔方程根
  10890. * @param {number} p0
  10891. * @param {number} p1
  10892. * @param {number} p2
  10893. * @param {number} t
  10894. * @param {Array.<number>} roots
  10895. * @return {number} 有效根数目
  10896. */
  10897. function quadraticRootAt(p0, p1, p2, val, roots) {
  10898. var a = p0 - 2 * p1 + p2;
  10899. var b = 2 * (p1 - p0);
  10900. var c = p0 - val;
  10901. var n = 0;
  10902. if (isAroundZero(a)) {
  10903. if (isNotAroundZero$1(b)) {
  10904. var t1 = -c / b;
  10905. if (t1 >= 0 && t1 <= 1) {
  10906. roots[n++] = t1;
  10907. }
  10908. }
  10909. }
  10910. else {
  10911. var disc = b * b - 4 * a * c;
  10912. if (isAroundZero(disc)) {
  10913. var t1 = -b / (2 * a);
  10914. if (t1 >= 0 && t1 <= 1) {
  10915. roots[n++] = t1;
  10916. }
  10917. }
  10918. else if (disc > 0) {
  10919. var discSqrt = mathSqrt$2(disc);
  10920. var t1 = (-b + discSqrt) / (2 * a);
  10921. var t2 = (-b - discSqrt) / (2 * a);
  10922. if (t1 >= 0 && t1 <= 1) {
  10923. roots[n++] = t1;
  10924. }
  10925. if (t2 >= 0 && t2 <= 1) {
  10926. roots[n++] = t2;
  10927. }
  10928. }
  10929. }
  10930. return n;
  10931. }
  10932. /**
  10933. * 计算二次贝塞尔方程极限值
  10934. * @memberOf module:zrender/core/curve
  10935. * @param {number} p0
  10936. * @param {number} p1
  10937. * @param {number} p2
  10938. * @return {number}
  10939. */
  10940. function quadraticExtremum(p0, p1, p2) {
  10941. var divider = p0 + p2 - 2 * p1;
  10942. if (divider === 0) {
  10943. // p1 is center of p0 and p2
  10944. return 0.5;
  10945. }
  10946. else {
  10947. return (p0 - p1) / divider;
  10948. }
  10949. }
  10950. /**
  10951. * 细分二次贝塞尔曲线
  10952. * @memberOf module:zrender/core/curve
  10953. * @param {number} p0
  10954. * @param {number} p1
  10955. * @param {number} p2
  10956. * @param {number} t
  10957. * @param {Array.<number>} out
  10958. */
  10959. function quadraticSubdivide(p0, p1, p2, t, out) {
  10960. var p01 = (p1 - p0) * t + p0;
  10961. var p12 = (p2 - p1) * t + p1;
  10962. var p012 = (p12 - p01) * t + p01;
  10963. // Seg0
  10964. out[0] = p0;
  10965. out[1] = p01;
  10966. out[2] = p012;
  10967. // Seg1
  10968. out[3] = p012;
  10969. out[4] = p12;
  10970. out[5] = p2;
  10971. }
  10972. /**
  10973. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10974. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10975. * @param {number} x0
  10976. * @param {number} y0
  10977. * @param {number} x1
  10978. * @param {number} y1
  10979. * @param {number} x2
  10980. * @param {number} y2
  10981. * @param {number} x
  10982. * @param {number} y
  10983. * @param {Array.<number>} out 投射点
  10984. * @return {number}
  10985. */
  10986. function quadraticProjectPoint(
  10987. x0, y0, x1, y1, x2, y2,
  10988. x, y, out
  10989. ) {
  10990. // http://pomax.github.io/bezierinfo/#projections
  10991. var t;
  10992. var interval = 0.005;
  10993. var d = Infinity;
  10994. _v0[0] = x;
  10995. _v0[1] = y;
  10996. // 先粗略估计一下可能的最小距离的 t 值
  10997. // PENDING
  10998. for (var _t = 0; _t < 1; _t += 0.05) {
  10999. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11000. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11001. var d1 = distSquare(_v0, _v1);
  11002. if (d1 < d) {
  11003. t = _t;
  11004. d = d1;
  11005. }
  11006. }
  11007. d = Infinity;
  11008. // At most 32 iteration
  11009. for (var i = 0; i < 32; i++) {
  11010. if (interval < EPSILON_NUMERIC) {
  11011. break;
  11012. }
  11013. var prev = t - interval;
  11014. var next = t + interval;
  11015. // t - interval
  11016. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11017. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11018. var d1 = distSquare(_v1, _v0);
  11019. if (prev >= 0 && d1 < d) {
  11020. t = prev;
  11021. d = d1;
  11022. }
  11023. else {
  11024. // t + interval
  11025. _v2[0] = quadraticAt(x0, x1, x2, next);
  11026. _v2[1] = quadraticAt(y0, y1, y2, next);
  11027. var d2 = distSquare(_v2, _v0);
  11028. if (next <= 1 && d2 < d) {
  11029. t = next;
  11030. d = d2;
  11031. }
  11032. else {
  11033. interval *= 0.5;
  11034. }
  11035. }
  11036. }
  11037. // t
  11038. if (out) {
  11039. out[0] = quadraticAt(x0, x1, x2, t);
  11040. out[1] = quadraticAt(y0, y1, y2, t);
  11041. }
  11042. // console.log(interval, i);
  11043. return mathSqrt$2(d);
  11044. }
  11045. /**
  11046. * @author Yi Shen(https://github.com/pissang)
  11047. */
  11048. var mathMin$3 = Math.min;
  11049. var mathMax$3 = Math.max;
  11050. var mathSin$2 = Math.sin;
  11051. var mathCos$2 = Math.cos;
  11052. var PI2 = Math.PI * 2;
  11053. var start = create();
  11054. var end = create();
  11055. var extremity = create();
  11056. /**
  11057. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11058. * @module zrender/core/bbox
  11059. * @param {Array<Object>} points 顶点数组
  11060. * @param {number} min
  11061. * @param {number} max
  11062. */
  11063. function fromPoints(points, min$$1, max$$1) {
  11064. if (points.length === 0) {
  11065. return;
  11066. }
  11067. var p = points[0];
  11068. var left = p[0];
  11069. var right = p[0];
  11070. var top = p[1];
  11071. var bottom = p[1];
  11072. var i;
  11073. for (i = 1; i < points.length; i++) {
  11074. p = points[i];
  11075. left = mathMin$3(left, p[0]);
  11076. right = mathMax$3(right, p[0]);
  11077. top = mathMin$3(top, p[1]);
  11078. bottom = mathMax$3(bottom, p[1]);
  11079. }
  11080. min$$1[0] = left;
  11081. min$$1[1] = top;
  11082. max$$1[0] = right;
  11083. max$$1[1] = bottom;
  11084. }
  11085. /**
  11086. * @memberOf module:zrender/core/bbox
  11087. * @param {number} x0
  11088. * @param {number} y0
  11089. * @param {number} x1
  11090. * @param {number} y1
  11091. * @param {Array.<number>} min
  11092. * @param {Array.<number>} max
  11093. */
  11094. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11095. min$$1[0] = mathMin$3(x0, x1);
  11096. min$$1[1] = mathMin$3(y0, y1);
  11097. max$$1[0] = mathMax$3(x0, x1);
  11098. max$$1[1] = mathMax$3(y0, y1);
  11099. }
  11100. var xDim = [];
  11101. var yDim = [];
  11102. /**
  11103. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11104. * @memberOf module:zrender/core/bbox
  11105. * @param {number} x0
  11106. * @param {number} y0
  11107. * @param {number} x1
  11108. * @param {number} y1
  11109. * @param {number} x2
  11110. * @param {number} y2
  11111. * @param {number} x3
  11112. * @param {number} y3
  11113. * @param {Array.<number>} min
  11114. * @param {Array.<number>} max
  11115. */
  11116. function fromCubic(
  11117. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11118. ) {
  11119. var cubicExtrema$$1 = cubicExtrema;
  11120. var cubicAt$$1 = cubicAt;
  11121. var i;
  11122. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11123. min$$1[0] = Infinity;
  11124. min$$1[1] = Infinity;
  11125. max$$1[0] = -Infinity;
  11126. max$$1[1] = -Infinity;
  11127. for (i = 0; i < n; i++) {
  11128. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11129. min$$1[0] = mathMin$3(x, min$$1[0]);
  11130. max$$1[0] = mathMax$3(x, max$$1[0]);
  11131. }
  11132. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11133. for (i = 0; i < n; i++) {
  11134. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11135. min$$1[1] = mathMin$3(y, min$$1[1]);
  11136. max$$1[1] = mathMax$3(y, max$$1[1]);
  11137. }
  11138. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11139. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11140. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11141. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11142. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11143. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11144. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11145. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11146. }
  11147. /**
  11148. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11149. * @memberOf module:zrender/core/bbox
  11150. * @param {number} x0
  11151. * @param {number} y0
  11152. * @param {number} x1
  11153. * @param {number} y1
  11154. * @param {number} x2
  11155. * @param {number} y2
  11156. * @param {Array.<number>} min
  11157. * @param {Array.<number>} max
  11158. */
  11159. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11160. var quadraticExtremum$$1 = quadraticExtremum;
  11161. var quadraticAt$$1 = quadraticAt;
  11162. // Find extremities, where derivative in x dim or y dim is zero
  11163. var tx =
  11164. mathMax$3(
  11165. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11166. );
  11167. var ty =
  11168. mathMax$3(
  11169. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11170. );
  11171. var x = quadraticAt$$1(x0, x1, x2, tx);
  11172. var y = quadraticAt$$1(y0, y1, y2, ty);
  11173. min$$1[0] = mathMin$3(x0, x2, x);
  11174. min$$1[1] = mathMin$3(y0, y2, y);
  11175. max$$1[0] = mathMax$3(x0, x2, x);
  11176. max$$1[1] = mathMax$3(y0, y2, y);
  11177. }
  11178. /**
  11179. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11180. * @method
  11181. * @memberOf module:zrender/core/bbox
  11182. * @param {number} x
  11183. * @param {number} y
  11184. * @param {number} rx
  11185. * @param {number} ry
  11186. * @param {number} startAngle
  11187. * @param {number} endAngle
  11188. * @param {number} anticlockwise
  11189. * @param {Array.<number>} min
  11190. * @param {Array.<number>} max
  11191. */
  11192. function fromArc(
  11193. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11194. ) {
  11195. var vec2Min = min;
  11196. var vec2Max = max;
  11197. var diff = Math.abs(startAngle - endAngle);
  11198. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11199. // Is a circle
  11200. min$$1[0] = x - rx;
  11201. min$$1[1] = y - ry;
  11202. max$$1[0] = x + rx;
  11203. max$$1[1] = y + ry;
  11204. return;
  11205. }
  11206. start[0] = mathCos$2(startAngle) * rx + x;
  11207. start[1] = mathSin$2(startAngle) * ry + y;
  11208. end[0] = mathCos$2(endAngle) * rx + x;
  11209. end[1] = mathSin$2(endAngle) * ry + y;
  11210. vec2Min(min$$1, start, end);
  11211. vec2Max(max$$1, start, end);
  11212. // Thresh to [0, Math.PI * 2]
  11213. startAngle = startAngle % (PI2);
  11214. if (startAngle < 0) {
  11215. startAngle = startAngle + PI2;
  11216. }
  11217. endAngle = endAngle % (PI2);
  11218. if (endAngle < 0) {
  11219. endAngle = endAngle + PI2;
  11220. }
  11221. if (startAngle > endAngle && !anticlockwise) {
  11222. endAngle += PI2;
  11223. }
  11224. else if (startAngle < endAngle && anticlockwise) {
  11225. startAngle += PI2;
  11226. }
  11227. if (anticlockwise) {
  11228. var tmp = endAngle;
  11229. endAngle = startAngle;
  11230. startAngle = tmp;
  11231. }
  11232. // var number = 0;
  11233. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11234. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11235. if (angle > startAngle) {
  11236. extremity[0] = mathCos$2(angle) * rx + x;
  11237. extremity[1] = mathSin$2(angle) * ry + y;
  11238. vec2Min(min$$1, extremity, min$$1);
  11239. vec2Max(max$$1, extremity, max$$1);
  11240. }
  11241. }
  11242. }
  11243. /**
  11244. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11245. * 可以用于 isInsidePath 判断以及获取boundingRect
  11246. *
  11247. * @module zrender/core/PathProxy
  11248. * @author Yi Shen (http://www.github.com/pissang)
  11249. */
  11250. // TODO getTotalLength, getPointAtLength
  11251. var CMD = {
  11252. M: 1,
  11253. L: 2,
  11254. C: 3,
  11255. Q: 4,
  11256. A: 5,
  11257. Z: 6,
  11258. // Rect
  11259. R: 7
  11260. };
  11261. // var CMD_MEM_SIZE = {
  11262. // M: 3,
  11263. // L: 3,
  11264. // C: 7,
  11265. // Q: 5,
  11266. // A: 9,
  11267. // R: 5,
  11268. // Z: 1
  11269. // };
  11270. var min$1 = [];
  11271. var max$1 = [];
  11272. var min2 = [];
  11273. var max2 = [];
  11274. var mathMin$2 = Math.min;
  11275. var mathMax$2 = Math.max;
  11276. var mathCos$1 = Math.cos;
  11277. var mathSin$1 = Math.sin;
  11278. var mathSqrt$1 = Math.sqrt;
  11279. var mathAbs = Math.abs;
  11280. var hasTypedArray = typeof Float32Array !== 'undefined';
  11281. /**
  11282. * @alias module:zrender/core/PathProxy
  11283. * @constructor
  11284. */
  11285. var PathProxy = function (notSaveData) {
  11286. this._saveData = !(notSaveData || false);
  11287. if (this._saveData) {
  11288. /**
  11289. * Path data. Stored as flat array
  11290. * @type {Array.<Object>}
  11291. */
  11292. this.data = [];
  11293. }
  11294. this._ctx = null;
  11295. };
  11296. /**
  11297. * 快速计算Path包围盒(并不是最小包围盒)
  11298. * @return {Object}
  11299. */
  11300. PathProxy.prototype = {
  11301. constructor: PathProxy,
  11302. _xi: 0,
  11303. _yi: 0,
  11304. _x0: 0,
  11305. _y0: 0,
  11306. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11307. _ux: 0,
  11308. _uy: 0,
  11309. _len: 0,
  11310. _lineDash: null,
  11311. _dashOffset: 0,
  11312. _dashIdx: 0,
  11313. _dashSum: 0,
  11314. /**
  11315. * @readOnly
  11316. */
  11317. setScale: function (sx, sy) {
  11318. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  11319. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  11320. },
  11321. getContext: function () {
  11322. return this._ctx;
  11323. },
  11324. /**
  11325. * @param {CanvasRenderingContext2D} ctx
  11326. * @return {module:zrender/core/PathProxy}
  11327. */
  11328. beginPath: function (ctx) {
  11329. this._ctx = ctx;
  11330. ctx && ctx.beginPath();
  11331. ctx && (this.dpr = ctx.dpr);
  11332. // Reset
  11333. if (this._saveData) {
  11334. this._len = 0;
  11335. }
  11336. if (this._lineDash) {
  11337. this._lineDash = null;
  11338. this._dashOffset = 0;
  11339. }
  11340. return this;
  11341. },
  11342. /**
  11343. * @param {number} x
  11344. * @param {number} y
  11345. * @return {module:zrender/core/PathProxy}
  11346. */
  11347. moveTo: function (x, y) {
  11348. this.addData(CMD.M, x, y);
  11349. this._ctx && this._ctx.moveTo(x, y);
  11350. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11351. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11352. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11353. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11354. this._x0 = x;
  11355. this._y0 = y;
  11356. this._xi = x;
  11357. this._yi = y;
  11358. return this;
  11359. },
  11360. /**
  11361. * @param {number} x
  11362. * @param {number} y
  11363. * @return {module:zrender/core/PathProxy}
  11364. */
  11365. lineTo: function (x, y) {
  11366. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11367. || mathAbs(y - this._yi) > this._uy
  11368. // Force draw the first segment
  11369. || this._len < 5;
  11370. this.addData(CMD.L, x, y);
  11371. if (this._ctx && exceedUnit) {
  11372. this._needsDash() ? this._dashedLineTo(x, y)
  11373. : this._ctx.lineTo(x, y);
  11374. }
  11375. if (exceedUnit) {
  11376. this._xi = x;
  11377. this._yi = y;
  11378. }
  11379. return this;
  11380. },
  11381. /**
  11382. * @param {number} x1
  11383. * @param {number} y1
  11384. * @param {number} x2
  11385. * @param {number} y2
  11386. * @param {number} x3
  11387. * @param {number} y3
  11388. * @return {module:zrender/core/PathProxy}
  11389. */
  11390. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11391. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11392. if (this._ctx) {
  11393. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11394. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11395. }
  11396. this._xi = x3;
  11397. this._yi = y3;
  11398. return this;
  11399. },
  11400. /**
  11401. * @param {number} x1
  11402. * @param {number} y1
  11403. * @param {number} x2
  11404. * @param {number} y2
  11405. * @return {module:zrender/core/PathProxy}
  11406. */
  11407. quadraticCurveTo: function (x1, y1, x2, y2) {
  11408. this.addData(CMD.Q, x1, y1, x2, y2);
  11409. if (this._ctx) {
  11410. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11411. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11412. }
  11413. this._xi = x2;
  11414. this._yi = y2;
  11415. return this;
  11416. },
  11417. /**
  11418. * @param {number} cx
  11419. * @param {number} cy
  11420. * @param {number} r
  11421. * @param {number} startAngle
  11422. * @param {number} endAngle
  11423. * @param {boolean} anticlockwise
  11424. * @return {module:zrender/core/PathProxy}
  11425. */
  11426. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11427. this.addData(
  11428. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11429. );
  11430. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11431. this._xi = mathCos$1(endAngle) * r + cx;
  11432. this._yi = mathSin$1(endAngle) * r + cy;
  11433. return this;
  11434. },
  11435. // TODO
  11436. arcTo: function (x1, y1, x2, y2, radius) {
  11437. if (this._ctx) {
  11438. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11439. }
  11440. return this;
  11441. },
  11442. // TODO
  11443. rect: function (x, y, w, h) {
  11444. this._ctx && this._ctx.rect(x, y, w, h);
  11445. this.addData(CMD.R, x, y, w, h);
  11446. return this;
  11447. },
  11448. /**
  11449. * @return {module:zrender/core/PathProxy}
  11450. */
  11451. closePath: function () {
  11452. this.addData(CMD.Z);
  11453. var ctx = this._ctx;
  11454. var x0 = this._x0;
  11455. var y0 = this._y0;
  11456. if (ctx) {
  11457. this._needsDash() && this._dashedLineTo(x0, y0);
  11458. ctx.closePath();
  11459. }
  11460. this._xi = x0;
  11461. this._yi = y0;
  11462. return this;
  11463. },
  11464. /**
  11465. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11466. * stroke 同样
  11467. * @param {CanvasRenderingContext2D} ctx
  11468. * @return {module:zrender/core/PathProxy}
  11469. */
  11470. fill: function (ctx) {
  11471. ctx && ctx.fill();
  11472. this.toStatic();
  11473. },
  11474. /**
  11475. * @param {CanvasRenderingContext2D} ctx
  11476. * @return {module:zrender/core/PathProxy}
  11477. */
  11478. stroke: function (ctx) {
  11479. ctx && ctx.stroke();
  11480. this.toStatic();
  11481. },
  11482. /**
  11483. * 必须在其它绘制命令前调用
  11484. * Must be invoked before all other path drawing methods
  11485. * @return {module:zrender/core/PathProxy}
  11486. */
  11487. setLineDash: function (lineDash) {
  11488. if (lineDash instanceof Array) {
  11489. this._lineDash = lineDash;
  11490. this._dashIdx = 0;
  11491. var lineDashSum = 0;
  11492. for (var i = 0; i < lineDash.length; i++) {
  11493. lineDashSum += lineDash[i];
  11494. }
  11495. this._dashSum = lineDashSum;
  11496. }
  11497. return this;
  11498. },
  11499. /**
  11500. * 必须在其它绘制命令前调用
  11501. * Must be invoked before all other path drawing methods
  11502. * @return {module:zrender/core/PathProxy}
  11503. */
  11504. setLineDashOffset: function (offset) {
  11505. this._dashOffset = offset;
  11506. return this;
  11507. },
  11508. /**
  11509. *
  11510. * @return {boolean}
  11511. */
  11512. len: function () {
  11513. return this._len;
  11514. },
  11515. /**
  11516. * 直接设置 Path 数据
  11517. */
  11518. setData: function (data) {
  11519. var len$$1 = data.length;
  11520. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11521. this.data = new Float32Array(len$$1);
  11522. }
  11523. for (var i = 0; i < len$$1; i++) {
  11524. this.data[i] = data[i];
  11525. }
  11526. this._len = len$$1;
  11527. },
  11528. /**
  11529. * 添加子路径
  11530. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11531. */
  11532. appendPath: function (path) {
  11533. if (!(path instanceof Array)) {
  11534. path = [path];
  11535. }
  11536. var len$$1 = path.length;
  11537. var appendSize = 0;
  11538. var offset = this._len;
  11539. for (var i = 0; i < len$$1; i++) {
  11540. appendSize += path[i].len();
  11541. }
  11542. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11543. this.data = new Float32Array(offset + appendSize);
  11544. }
  11545. for (var i = 0; i < len$$1; i++) {
  11546. var appendPathData = path[i].data;
  11547. for (var k = 0; k < appendPathData.length; k++) {
  11548. this.data[offset++] = appendPathData[k];
  11549. }
  11550. }
  11551. this._len = offset;
  11552. },
  11553. /**
  11554. * 填充 Path 数据。
  11555. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11556. */
  11557. addData: function (cmd) {
  11558. if (!this._saveData) {
  11559. return;
  11560. }
  11561. var data = this.data;
  11562. if (this._len + arguments.length > data.length) {
  11563. // 因为之前的数组已经转换成静态的 Float32Array
  11564. // 所以不够用时需要扩展一个新的动态数组
  11565. this._expandData();
  11566. data = this.data;
  11567. }
  11568. for (var i = 0; i < arguments.length; i++) {
  11569. data[this._len++] = arguments[i];
  11570. }
  11571. this._prevCmd = cmd;
  11572. },
  11573. _expandData: function () {
  11574. // Only if data is Float32Array
  11575. if (!(this.data instanceof Array)) {
  11576. var newData = [];
  11577. for (var i = 0; i < this._len; i++) {
  11578. newData[i] = this.data[i];
  11579. }
  11580. this.data = newData;
  11581. }
  11582. },
  11583. /**
  11584. * If needs js implemented dashed line
  11585. * @return {boolean}
  11586. * @private
  11587. */
  11588. _needsDash: function () {
  11589. return this._lineDash;
  11590. },
  11591. _dashedLineTo: function (x1, y1) {
  11592. var dashSum = this._dashSum;
  11593. var offset = this._dashOffset;
  11594. var lineDash = this._lineDash;
  11595. var ctx = this._ctx;
  11596. var x0 = this._xi;
  11597. var y0 = this._yi;
  11598. var dx = x1 - x0;
  11599. var dy = y1 - y0;
  11600. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11601. var x = x0;
  11602. var y = y0;
  11603. var dash;
  11604. var nDash = lineDash.length;
  11605. var idx;
  11606. dx /= dist$$1;
  11607. dy /= dist$$1;
  11608. if (offset < 0) {
  11609. // Convert to positive offset
  11610. offset = dashSum + offset;
  11611. }
  11612. offset %= dashSum;
  11613. x -= offset * dx;
  11614. y -= offset * dy;
  11615. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11616. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11617. idx = this._dashIdx;
  11618. dash = lineDash[idx];
  11619. x += dx * dash;
  11620. y += dy * dash;
  11621. this._dashIdx = (idx + 1) % nDash;
  11622. // Skip positive offset
  11623. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11624. continue;
  11625. }
  11626. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11627. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11628. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11629. );
  11630. }
  11631. // Offset for next lineTo
  11632. dx = x - x1;
  11633. dy = y - y1;
  11634. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11635. },
  11636. // Not accurate dashed line to
  11637. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11638. var dashSum = this._dashSum;
  11639. var offset = this._dashOffset;
  11640. var lineDash = this._lineDash;
  11641. var ctx = this._ctx;
  11642. var x0 = this._xi;
  11643. var y0 = this._yi;
  11644. var t;
  11645. var dx;
  11646. var dy;
  11647. var cubicAt$$1 = cubicAt;
  11648. var bezierLen = 0;
  11649. var idx = this._dashIdx;
  11650. var nDash = lineDash.length;
  11651. var x;
  11652. var y;
  11653. var tmpLen = 0;
  11654. if (offset < 0) {
  11655. // Convert to positive offset
  11656. offset = dashSum + offset;
  11657. }
  11658. offset %= dashSum;
  11659. // Bezier approx length
  11660. for (t = 0; t < 1; t += 0.1) {
  11661. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11662. - cubicAt$$1(x0, x1, x2, x3, t);
  11663. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11664. - cubicAt$$1(y0, y1, y2, y3, t);
  11665. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11666. }
  11667. // Find idx after add offset
  11668. for (; idx < nDash; idx++) {
  11669. tmpLen += lineDash[idx];
  11670. if (tmpLen > offset) {
  11671. break;
  11672. }
  11673. }
  11674. t = (tmpLen - offset) / bezierLen;
  11675. while (t <= 1) {
  11676. x = cubicAt$$1(x0, x1, x2, x3, t);
  11677. y = cubicAt$$1(y0, y1, y2, y3, t);
  11678. // Use line to approximate dashed bezier
  11679. // Bad result if dash is long
  11680. idx % 2 ? ctx.moveTo(x, y)
  11681. : ctx.lineTo(x, y);
  11682. t += lineDash[idx] / bezierLen;
  11683. idx = (idx + 1) % nDash;
  11684. }
  11685. // Finish the last segment and calculate the new offset
  11686. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11687. dx = x3 - x;
  11688. dy = y3 - y;
  11689. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11690. },
  11691. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11692. // Convert quadratic to cubic using degree elevation
  11693. var x3 = x2;
  11694. var y3 = y2;
  11695. x2 = (x2 + 2 * x1) / 3;
  11696. y2 = (y2 + 2 * y1) / 3;
  11697. x1 = (this._xi + 2 * x1) / 3;
  11698. y1 = (this._yi + 2 * y1) / 3;
  11699. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11700. },
  11701. /**
  11702. * 转成静态的 Float32Array 减少堆内存占用
  11703. * Convert dynamic array to static Float32Array
  11704. */
  11705. toStatic: function () {
  11706. var data = this.data;
  11707. if (data instanceof Array) {
  11708. data.length = this._len;
  11709. if (hasTypedArray) {
  11710. this.data = new Float32Array(data);
  11711. }
  11712. }
  11713. },
  11714. /**
  11715. * @return {module:zrender/core/BoundingRect}
  11716. */
  11717. getBoundingRect: function () {
  11718. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11719. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11720. var data = this.data;
  11721. var xi = 0;
  11722. var yi = 0;
  11723. var x0 = 0;
  11724. var y0 = 0;
  11725. for (var i = 0; i < data.length;) {
  11726. var cmd = data[i++];
  11727. if (i === 1) {
  11728. // 如果第一个命令是 L, C, Q
  11729. // 则 previous point 同绘制命令的第一个 point
  11730. //
  11731. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11732. xi = data[i];
  11733. yi = data[i + 1];
  11734. x0 = xi;
  11735. y0 = yi;
  11736. }
  11737. switch (cmd) {
  11738. case CMD.M:
  11739. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11740. // 在 closePath 的时候使用
  11741. x0 = data[i++];
  11742. y0 = data[i++];
  11743. xi = x0;
  11744. yi = y0;
  11745. min2[0] = x0;
  11746. min2[1] = y0;
  11747. max2[0] = x0;
  11748. max2[1] = y0;
  11749. break;
  11750. case CMD.L:
  11751. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11752. xi = data[i++];
  11753. yi = data[i++];
  11754. break;
  11755. case CMD.C:
  11756. fromCubic(
  11757. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11758. min2, max2
  11759. );
  11760. xi = data[i++];
  11761. yi = data[i++];
  11762. break;
  11763. case CMD.Q:
  11764. fromQuadratic(
  11765. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11766. min2, max2
  11767. );
  11768. xi = data[i++];
  11769. yi = data[i++];
  11770. break;
  11771. case CMD.A:
  11772. // TODO Arc 判断的开销比较大
  11773. var cx = data[i++];
  11774. var cy = data[i++];
  11775. var rx = data[i++];
  11776. var ry = data[i++];
  11777. var startAngle = data[i++];
  11778. var endAngle = data[i++] + startAngle;
  11779. // TODO Arc 旋转
  11780. i += 1;
  11781. var anticlockwise = 1 - data[i++];
  11782. if (i === 1) {
  11783. // 直接使用 arc 命令
  11784. // 第一个命令起点还未定义
  11785. x0 = mathCos$1(startAngle) * rx + cx;
  11786. y0 = mathSin$1(startAngle) * ry + cy;
  11787. }
  11788. fromArc(
  11789. cx, cy, rx, ry, startAngle, endAngle,
  11790. anticlockwise, min2, max2
  11791. );
  11792. xi = mathCos$1(endAngle) * rx + cx;
  11793. yi = mathSin$1(endAngle) * ry + cy;
  11794. break;
  11795. case CMD.R:
  11796. x0 = xi = data[i++];
  11797. y0 = yi = data[i++];
  11798. var width = data[i++];
  11799. var height = data[i++];
  11800. // Use fromLine
  11801. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11802. break;
  11803. case CMD.Z:
  11804. xi = x0;
  11805. yi = y0;
  11806. break;
  11807. }
  11808. // Union
  11809. min(min$1, min$1, min2);
  11810. max(max$1, max$1, max2);
  11811. }
  11812. // No data
  11813. if (i === 0) {
  11814. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11815. }
  11816. return new BoundingRect(
  11817. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11818. );
  11819. },
  11820. /**
  11821. * Rebuild path from current data
  11822. * Rebuild path will not consider javascript implemented line dash.
  11823. * @param {CanvasRenderingContext2D} ctx
  11824. */
  11825. rebuildPath: function (ctx) {
  11826. var d = this.data;
  11827. var x0, y0;
  11828. var xi, yi;
  11829. var x, y;
  11830. var ux = this._ux;
  11831. var uy = this._uy;
  11832. var len$$1 = this._len;
  11833. for (var i = 0; i < len$$1;) {
  11834. var cmd = d[i++];
  11835. if (i === 1) {
  11836. // 如果第一个命令是 L, C, Q
  11837. // 则 previous point 同绘制命令的第一个 point
  11838. //
  11839. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11840. xi = d[i];
  11841. yi = d[i + 1];
  11842. x0 = xi;
  11843. y0 = yi;
  11844. }
  11845. switch (cmd) {
  11846. case CMD.M:
  11847. x0 = xi = d[i++];
  11848. y0 = yi = d[i++];
  11849. ctx.moveTo(xi, yi);
  11850. break;
  11851. case CMD.L:
  11852. x = d[i++];
  11853. y = d[i++];
  11854. // Not draw too small seg between
  11855. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11856. ctx.lineTo(x, y);
  11857. xi = x;
  11858. yi = y;
  11859. }
  11860. break;
  11861. case CMD.C:
  11862. ctx.bezierCurveTo(
  11863. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11864. );
  11865. xi = d[i - 2];
  11866. yi = d[i - 1];
  11867. break;
  11868. case CMD.Q:
  11869. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11870. xi = d[i - 2];
  11871. yi = d[i - 1];
  11872. break;
  11873. case CMD.A:
  11874. var cx = d[i++];
  11875. var cy = d[i++];
  11876. var rx = d[i++];
  11877. var ry = d[i++];
  11878. var theta = d[i++];
  11879. var dTheta = d[i++];
  11880. var psi = d[i++];
  11881. var fs = d[i++];
  11882. var r = (rx > ry) ? rx : ry;
  11883. var scaleX = (rx > ry) ? 1 : rx / ry;
  11884. var scaleY = (rx > ry) ? ry / rx : 1;
  11885. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11886. var endAngle = theta + dTheta;
  11887. if (isEllipse) {
  11888. ctx.translate(cx, cy);
  11889. ctx.rotate(psi);
  11890. ctx.scale(scaleX, scaleY);
  11891. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11892. ctx.scale(1 / scaleX, 1 / scaleY);
  11893. ctx.rotate(-psi);
  11894. ctx.translate(-cx, -cy);
  11895. }
  11896. else {
  11897. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11898. }
  11899. if (i === 1) {
  11900. // 直接使用 arc 命令
  11901. // 第一个命令起点还未定义
  11902. x0 = mathCos$1(theta) * rx + cx;
  11903. y0 = mathSin$1(theta) * ry + cy;
  11904. }
  11905. xi = mathCos$1(endAngle) * rx + cx;
  11906. yi = mathSin$1(endAngle) * ry + cy;
  11907. break;
  11908. case CMD.R:
  11909. x0 = xi = d[i];
  11910. y0 = yi = d[i + 1];
  11911. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11912. break;
  11913. case CMD.Z:
  11914. ctx.closePath();
  11915. xi = x0;
  11916. yi = y0;
  11917. }
  11918. }
  11919. }
  11920. };
  11921. PathProxy.CMD = CMD;
  11922. /**
  11923. * 线段包含判断
  11924. * @param {number} x0
  11925. * @param {number} y0
  11926. * @param {number} x1
  11927. * @param {number} y1
  11928. * @param {number} lineWidth
  11929. * @param {number} x
  11930. * @param {number} y
  11931. * @return {boolean}
  11932. */
  11933. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11934. if (lineWidth === 0) {
  11935. return false;
  11936. }
  11937. var _l = lineWidth;
  11938. var _a = 0;
  11939. var _b = x0;
  11940. // Quick reject
  11941. if (
  11942. (y > y0 + _l && y > y1 + _l)
  11943. || (y < y0 - _l && y < y1 - _l)
  11944. || (x > x0 + _l && x > x1 + _l)
  11945. || (x < x0 - _l && x < x1 - _l)
  11946. ) {
  11947. return false;
  11948. }
  11949. if (x0 !== x1) {
  11950. _a = (y0 - y1) / (x0 - x1);
  11951. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  11952. }
  11953. else {
  11954. return Math.abs(x - x0) <= _l / 2;
  11955. }
  11956. var tmp = _a * x - y + _b;
  11957. var _s = tmp * tmp / (_a * _a + 1);
  11958. return _s <= _l / 2 * _l / 2;
  11959. }
  11960. /**
  11961. * 三次贝塞尔曲线描边包含判断
  11962. * @param {number} x0
  11963. * @param {number} y0
  11964. * @param {number} x1
  11965. * @param {number} y1
  11966. * @param {number} x2
  11967. * @param {number} y2
  11968. * @param {number} x3
  11969. * @param {number} y3
  11970. * @param {number} lineWidth
  11971. * @param {number} x
  11972. * @param {number} y
  11973. * @return {boolean}
  11974. */
  11975. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11976. if (lineWidth === 0) {
  11977. return false;
  11978. }
  11979. var _l = lineWidth;
  11980. // Quick reject
  11981. if (
  11982. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11983. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11984. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11985. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11986. ) {
  11987. return false;
  11988. }
  11989. var d = cubicProjectPoint(
  11990. x0, y0, x1, y1, x2, y2, x3, y3,
  11991. x, y, null
  11992. );
  11993. return d <= _l / 2;
  11994. }
  11995. /**
  11996. * 二次贝塞尔曲线描边包含判断
  11997. * @param {number} x0
  11998. * @param {number} y0
  11999. * @param {number} x1
  12000. * @param {number} y1
  12001. * @param {number} x2
  12002. * @param {number} y2
  12003. * @param {number} lineWidth
  12004. * @param {number} x
  12005. * @param {number} y
  12006. * @return {boolean}
  12007. */
  12008. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12009. if (lineWidth === 0) {
  12010. return false;
  12011. }
  12012. var _l = lineWidth;
  12013. // Quick reject
  12014. if (
  12015. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12016. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12017. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12018. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12019. ) {
  12020. return false;
  12021. }
  12022. var d = quadraticProjectPoint(
  12023. x0, y0, x1, y1, x2, y2,
  12024. x, y, null
  12025. );
  12026. return d <= _l / 2;
  12027. }
  12028. var PI2$3 = Math.PI * 2;
  12029. function normalizeRadian(angle) {
  12030. angle %= PI2$3;
  12031. if (angle < 0) {
  12032. angle += PI2$3;
  12033. }
  12034. return angle;
  12035. }
  12036. var PI2$2 = Math.PI * 2;
  12037. /**
  12038. * 圆弧描边包含判断
  12039. * @param {number} cx
  12040. * @param {number} cy
  12041. * @param {number} r
  12042. * @param {number} startAngle
  12043. * @param {number} endAngle
  12044. * @param {boolean} anticlockwise
  12045. * @param {number} lineWidth
  12046. * @param {number} x
  12047. * @param {number} y
  12048. * @return {Boolean}
  12049. */
  12050. function containStroke$4(
  12051. cx, cy, r, startAngle, endAngle, anticlockwise,
  12052. lineWidth, x, y
  12053. ) {
  12054. if (lineWidth === 0) {
  12055. return false;
  12056. }
  12057. var _l = lineWidth;
  12058. x -= cx;
  12059. y -= cy;
  12060. var d = Math.sqrt(x * x + y * y);
  12061. if ((d - _l > r) || (d + _l < r)) {
  12062. return false;
  12063. }
  12064. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12065. // Is a circle
  12066. return true;
  12067. }
  12068. if (anticlockwise) {
  12069. var tmp = startAngle;
  12070. startAngle = normalizeRadian(endAngle);
  12071. endAngle = normalizeRadian(tmp);
  12072. }
  12073. else {
  12074. startAngle = normalizeRadian(startAngle);
  12075. endAngle = normalizeRadian(endAngle);
  12076. }
  12077. if (startAngle > endAngle) {
  12078. endAngle += PI2$2;
  12079. }
  12080. var angle = Math.atan2(y, x);
  12081. if (angle < 0) {
  12082. angle += PI2$2;
  12083. }
  12084. return (angle >= startAngle && angle <= endAngle)
  12085. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12086. }
  12087. function windingLine(x0, y0, x1, y1, x, y) {
  12088. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12089. return 0;
  12090. }
  12091. // Ignore horizontal line
  12092. if (y1 === y0) {
  12093. return 0;
  12094. }
  12095. var dir = y1 < y0 ? 1 : -1;
  12096. var t = (y - y0) / (y1 - y0);
  12097. // Avoid winding error when intersection point is the connect point of two line of polygon
  12098. if (t === 1 || t === 0) {
  12099. dir = y1 < y0 ? 0.5 : -0.5;
  12100. }
  12101. var x_ = t * (x1 - x0) + x0;
  12102. // If (x, y) on the line, considered as "contain".
  12103. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12104. }
  12105. var CMD$1 = PathProxy.CMD;
  12106. var PI2$1 = Math.PI * 2;
  12107. var EPSILON$2 = 1e-4;
  12108. function isAroundEqual(a, b) {
  12109. return Math.abs(a - b) < EPSILON$2;
  12110. }
  12111. // 临时数组
  12112. var roots = [-1, -1, -1];
  12113. var extrema = [-1, -1];
  12114. function swapExtrema() {
  12115. var tmp = extrema[0];
  12116. extrema[0] = extrema[1];
  12117. extrema[1] = tmp;
  12118. }
  12119. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12120. // Quick reject
  12121. if (
  12122. (y > y0 && y > y1 && y > y2 && y > y3)
  12123. || (y < y0 && y < y1 && y < y2 && y < y3)
  12124. ) {
  12125. return 0;
  12126. }
  12127. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12128. if (nRoots === 0) {
  12129. return 0;
  12130. }
  12131. else {
  12132. var w = 0;
  12133. var nExtrema = -1;
  12134. var y0_;
  12135. var y1_;
  12136. for (var i = 0; i < nRoots; i++) {
  12137. var t = roots[i];
  12138. // Avoid winding error when intersection point is the connect point of two line of polygon
  12139. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12140. var x_ = cubicAt(x0, x1, x2, x3, t);
  12141. if (x_ < x) { // Quick reject
  12142. continue;
  12143. }
  12144. if (nExtrema < 0) {
  12145. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12146. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12147. swapExtrema();
  12148. }
  12149. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12150. if (nExtrema > 1) {
  12151. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12152. }
  12153. }
  12154. if (nExtrema === 2) {
  12155. // 分成三段单调函数
  12156. if (t < extrema[0]) {
  12157. w += y0_ < y0 ? unit : -unit;
  12158. }
  12159. else if (t < extrema[1]) {
  12160. w += y1_ < y0_ ? unit : -unit;
  12161. }
  12162. else {
  12163. w += y3 < y1_ ? unit : -unit;
  12164. }
  12165. }
  12166. else {
  12167. // 分成两段单调函数
  12168. if (t < extrema[0]) {
  12169. w += y0_ < y0 ? unit : -unit;
  12170. }
  12171. else {
  12172. w += y3 < y0_ ? unit : -unit;
  12173. }
  12174. }
  12175. }
  12176. return w;
  12177. }
  12178. }
  12179. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12180. // Quick reject
  12181. if (
  12182. (y > y0 && y > y1 && y > y2)
  12183. || (y < y0 && y < y1 && y < y2)
  12184. ) {
  12185. return 0;
  12186. }
  12187. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12188. if (nRoots === 0) {
  12189. return 0;
  12190. }
  12191. else {
  12192. var t = quadraticExtremum(y0, y1, y2);
  12193. if (t >= 0 && t <= 1) {
  12194. var w = 0;
  12195. var y_ = quadraticAt(y0, y1, y2, t);
  12196. for (var i = 0; i < nRoots; i++) {
  12197. // Remove one endpoint.
  12198. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12199. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12200. if (x_ < x) { // Quick reject
  12201. continue;
  12202. }
  12203. if (roots[i] < t) {
  12204. w += y_ < y0 ? unit : -unit;
  12205. }
  12206. else {
  12207. w += y2 < y_ ? unit : -unit;
  12208. }
  12209. }
  12210. return w;
  12211. }
  12212. else {
  12213. // Remove one endpoint.
  12214. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12215. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12216. if (x_ < x) { // Quick reject
  12217. return 0;
  12218. }
  12219. return y2 < y0 ? unit : -unit;
  12220. }
  12221. }
  12222. }
  12223. // TODO
  12224. // Arc 旋转
  12225. function windingArc(
  12226. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12227. ) {
  12228. y -= cy;
  12229. if (y > r || y < -r) {
  12230. return 0;
  12231. }
  12232. var tmp = Math.sqrt(r * r - y * y);
  12233. roots[0] = -tmp;
  12234. roots[1] = tmp;
  12235. var diff = Math.abs(startAngle - endAngle);
  12236. if (diff < 1e-4) {
  12237. return 0;
  12238. }
  12239. if (diff % PI2$1 < 1e-4) {
  12240. // Is a circle
  12241. startAngle = 0;
  12242. endAngle = PI2$1;
  12243. var dir = anticlockwise ? 1 : -1;
  12244. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12245. return dir;
  12246. }
  12247. else {
  12248. return 0;
  12249. }
  12250. }
  12251. if (anticlockwise) {
  12252. var tmp = startAngle;
  12253. startAngle = normalizeRadian(endAngle);
  12254. endAngle = normalizeRadian(tmp);
  12255. }
  12256. else {
  12257. startAngle = normalizeRadian(startAngle);
  12258. endAngle = normalizeRadian(endAngle);
  12259. }
  12260. if (startAngle > endAngle) {
  12261. endAngle += PI2$1;
  12262. }
  12263. var w = 0;
  12264. for (var i = 0; i < 2; i++) {
  12265. var x_ = roots[i];
  12266. if (x_ + cx > x) {
  12267. var angle = Math.atan2(y, x_);
  12268. var dir = anticlockwise ? 1 : -1;
  12269. if (angle < 0) {
  12270. angle = PI2$1 + angle;
  12271. }
  12272. if (
  12273. (angle >= startAngle && angle <= endAngle)
  12274. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12275. ) {
  12276. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12277. dir = -dir;
  12278. }
  12279. w += dir;
  12280. }
  12281. }
  12282. }
  12283. return w;
  12284. }
  12285. function containPath(data, lineWidth, isStroke, x, y) {
  12286. var w = 0;
  12287. var xi = 0;
  12288. var yi = 0;
  12289. var x0 = 0;
  12290. var y0 = 0;
  12291. for (var i = 0; i < data.length;) {
  12292. var cmd = data[i++];
  12293. // Begin a new subpath
  12294. if (cmd === CMD$1.M && i > 1) {
  12295. // Close previous subpath
  12296. if (!isStroke) {
  12297. w += windingLine(xi, yi, x0, y0, x, y);
  12298. }
  12299. // 如果被任何一个 subpath 包含
  12300. // if (w !== 0) {
  12301. // return true;
  12302. // }
  12303. }
  12304. if (i === 1) {
  12305. // 如果第一个命令是 L, C, Q
  12306. // 则 previous point 同绘制命令的第一个 point
  12307. //
  12308. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12309. xi = data[i];
  12310. yi = data[i + 1];
  12311. x0 = xi;
  12312. y0 = yi;
  12313. }
  12314. switch (cmd) {
  12315. case CMD$1.M:
  12316. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12317. // 在 closePath 的时候使用
  12318. x0 = data[i++];
  12319. y0 = data[i++];
  12320. xi = x0;
  12321. yi = y0;
  12322. break;
  12323. case CMD$1.L:
  12324. if (isStroke) {
  12325. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12326. return true;
  12327. }
  12328. }
  12329. else {
  12330. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12331. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12332. }
  12333. xi = data[i++];
  12334. yi = data[i++];
  12335. break;
  12336. case CMD$1.C:
  12337. if (isStroke) {
  12338. if (containStroke$2(xi, yi,
  12339. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12340. lineWidth, x, y
  12341. )) {
  12342. return true;
  12343. }
  12344. }
  12345. else {
  12346. w += windingCubic(
  12347. xi, yi,
  12348. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12349. x, y
  12350. ) || 0;
  12351. }
  12352. xi = data[i++];
  12353. yi = data[i++];
  12354. break;
  12355. case CMD$1.Q:
  12356. if (isStroke) {
  12357. if (containStroke$3(xi, yi,
  12358. data[i++], data[i++], data[i], data[i + 1],
  12359. lineWidth, x, y
  12360. )) {
  12361. return true;
  12362. }
  12363. }
  12364. else {
  12365. w += windingQuadratic(
  12366. xi, yi,
  12367. data[i++], data[i++], data[i], data[i + 1],
  12368. x, y
  12369. ) || 0;
  12370. }
  12371. xi = data[i++];
  12372. yi = data[i++];
  12373. break;
  12374. case CMD$1.A:
  12375. // TODO Arc 判断的开销比较大
  12376. var cx = data[i++];
  12377. var cy = data[i++];
  12378. var rx = data[i++];
  12379. var ry = data[i++];
  12380. var theta = data[i++];
  12381. var dTheta = data[i++];
  12382. // TODO Arc 旋转
  12383. i += 1;
  12384. var anticlockwise = 1 - data[i++];
  12385. var x1 = Math.cos(theta) * rx + cx;
  12386. var y1 = Math.sin(theta) * ry + cy;
  12387. // 不是直接使用 arc 命令
  12388. if (i > 1) {
  12389. w += windingLine(xi, yi, x1, y1, x, y);
  12390. }
  12391. else {
  12392. // 第一个命令起点还未定义
  12393. x0 = x1;
  12394. y0 = y1;
  12395. }
  12396. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12397. var _x = (x - cx) * ry / rx + cx;
  12398. if (isStroke) {
  12399. if (containStroke$4(
  12400. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12401. lineWidth, _x, y
  12402. )) {
  12403. return true;
  12404. }
  12405. }
  12406. else {
  12407. w += windingArc(
  12408. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12409. _x, y
  12410. );
  12411. }
  12412. xi = Math.cos(theta + dTheta) * rx + cx;
  12413. yi = Math.sin(theta + dTheta) * ry + cy;
  12414. break;
  12415. case CMD$1.R:
  12416. x0 = xi = data[i++];
  12417. y0 = yi = data[i++];
  12418. var width = data[i++];
  12419. var height = data[i++];
  12420. var x1 = x0 + width;
  12421. var y1 = y0 + height;
  12422. if (isStroke) {
  12423. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12424. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12425. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12426. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12427. ) {
  12428. return true;
  12429. }
  12430. }
  12431. else {
  12432. // FIXME Clockwise ?
  12433. w += windingLine(x1, y0, x1, y1, x, y);
  12434. w += windingLine(x0, y1, x0, y0, x, y);
  12435. }
  12436. break;
  12437. case CMD$1.Z:
  12438. if (isStroke) {
  12439. if (containStroke$1(
  12440. xi, yi, x0, y0, lineWidth, x, y
  12441. )) {
  12442. return true;
  12443. }
  12444. }
  12445. else {
  12446. // Close a subpath
  12447. w += windingLine(xi, yi, x0, y0, x, y);
  12448. // 如果被任何一个 subpath 包含
  12449. // FIXME subpaths may overlap
  12450. // if (w !== 0) {
  12451. // return true;
  12452. // }
  12453. }
  12454. xi = x0;
  12455. yi = y0;
  12456. break;
  12457. }
  12458. }
  12459. if (!isStroke && !isAroundEqual(yi, y0)) {
  12460. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12461. }
  12462. return w !== 0;
  12463. }
  12464. function contain(pathData, x, y) {
  12465. return containPath(pathData, 0, false, x, y);
  12466. }
  12467. function containStroke(pathData, lineWidth, x, y) {
  12468. return containPath(pathData, lineWidth, true, x, y);
  12469. }
  12470. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12471. var abs = Math.abs;
  12472. var pathProxyForDraw = new PathProxy(true);
  12473. /**
  12474. * @alias module:zrender/graphic/Path
  12475. * @extends module:zrender/graphic/Displayable
  12476. * @constructor
  12477. * @param {Object} opts
  12478. */
  12479. function Path(opts) {
  12480. Displayable.call(this, opts);
  12481. /**
  12482. * @type {module:zrender/core/PathProxy}
  12483. * @readOnly
  12484. */
  12485. this.path = null;
  12486. }
  12487. Path.prototype = {
  12488. constructor: Path,
  12489. type: 'path',
  12490. __dirtyPath: true,
  12491. strokeContainThreshold: 5,
  12492. /**
  12493. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12494. * @type {boolean}
  12495. */
  12496. subPixelOptimize: false,
  12497. brush: function (ctx, prevEl) {
  12498. var style = this.style;
  12499. var path = this.path || pathProxyForDraw;
  12500. var hasStroke = style.hasStroke();
  12501. var hasFill = style.hasFill();
  12502. var fill = style.fill;
  12503. var stroke = style.stroke;
  12504. var hasFillGradient = hasFill && !!(fill.colorStops);
  12505. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12506. var hasFillPattern = hasFill && !!(fill.image);
  12507. var hasStrokePattern = hasStroke && !!(stroke.image);
  12508. style.bind(ctx, this, prevEl);
  12509. this.setTransform(ctx);
  12510. if (this.__dirty) {
  12511. var rect;
  12512. // Update gradient because bounding rect may changed
  12513. if (hasFillGradient) {
  12514. rect = rect || this.getBoundingRect();
  12515. this._fillGradient = style.getGradient(ctx, fill, rect);
  12516. }
  12517. if (hasStrokeGradient) {
  12518. rect = rect || this.getBoundingRect();
  12519. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12520. }
  12521. }
  12522. // Use the gradient or pattern
  12523. if (hasFillGradient) {
  12524. // PENDING If may have affect the state
  12525. ctx.fillStyle = this._fillGradient;
  12526. }
  12527. else if (hasFillPattern) {
  12528. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12529. }
  12530. if (hasStrokeGradient) {
  12531. ctx.strokeStyle = this._strokeGradient;
  12532. }
  12533. else if (hasStrokePattern) {
  12534. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12535. }
  12536. var lineDash = style.lineDash;
  12537. var lineDashOffset = style.lineDashOffset;
  12538. var ctxLineDash = !!ctx.setLineDash;
  12539. // Update path sx, sy
  12540. var scale = this.getGlobalScale();
  12541. path.setScale(scale[0], scale[1]);
  12542. // Proxy context
  12543. // Rebuild path in following 2 cases
  12544. // 1. Path is dirty
  12545. // 2. Path needs javascript implemented lineDash stroking.
  12546. // In this case, lineDash information will not be saved in PathProxy
  12547. if (this.__dirtyPath
  12548. || (lineDash && !ctxLineDash && hasStroke)
  12549. ) {
  12550. path.beginPath(ctx);
  12551. // Setting line dash before build path
  12552. if (lineDash && !ctxLineDash) {
  12553. path.setLineDash(lineDash);
  12554. path.setLineDashOffset(lineDashOffset);
  12555. }
  12556. this.buildPath(path, this.shape, false);
  12557. // Clear path dirty flag
  12558. if (this.path) {
  12559. this.__dirtyPath = false;
  12560. }
  12561. }
  12562. else {
  12563. // Replay path building
  12564. ctx.beginPath();
  12565. this.path.rebuildPath(ctx);
  12566. }
  12567. if (hasFill) {
  12568. if (style.fillOpacity != null) {
  12569. var originalGlobalAlpha = ctx.globalAlpha;
  12570. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12571. path.fill(ctx);
  12572. ctx.globalAlpha = originalGlobalAlpha;
  12573. }
  12574. else {
  12575. path.fill(ctx);
  12576. }
  12577. }
  12578. if (lineDash && ctxLineDash) {
  12579. ctx.setLineDash(lineDash);
  12580. ctx.lineDashOffset = lineDashOffset;
  12581. }
  12582. if (hasStroke) {
  12583. if (style.strokeOpacity != null) {
  12584. var originalGlobalAlpha = ctx.globalAlpha;
  12585. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12586. path.stroke(ctx);
  12587. ctx.globalAlpha = originalGlobalAlpha;
  12588. }
  12589. else {
  12590. path.stroke(ctx);
  12591. }
  12592. }
  12593. if (lineDash && ctxLineDash) {
  12594. // PENDING
  12595. // Remove lineDash
  12596. ctx.setLineDash([]);
  12597. }
  12598. // Draw rect text
  12599. if (style.text != null) {
  12600. // Only restore transform when needs draw text.
  12601. this.restoreTransform(ctx);
  12602. this.drawRectText(ctx, this.getBoundingRect());
  12603. }
  12604. },
  12605. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12606. // Like in circle
  12607. buildPath: function (ctx, shapeCfg, inBundle) {},
  12608. createPathProxy: function () {
  12609. this.path = new PathProxy();
  12610. },
  12611. getBoundingRect: function () {
  12612. var rect = this._rect;
  12613. var style = this.style;
  12614. var needsUpdateRect = !rect;
  12615. if (needsUpdateRect) {
  12616. var path = this.path;
  12617. if (!path) {
  12618. // Create path on demand.
  12619. path = this.path = new PathProxy();
  12620. }
  12621. if (this.__dirtyPath) {
  12622. path.beginPath();
  12623. this.buildPath(path, this.shape, false);
  12624. }
  12625. rect = path.getBoundingRect();
  12626. }
  12627. this._rect = rect;
  12628. if (style.hasStroke()) {
  12629. // Needs update rect with stroke lineWidth when
  12630. // 1. Element changes scale or lineWidth
  12631. // 2. Shape is changed
  12632. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12633. if (this.__dirty || needsUpdateRect) {
  12634. rectWithStroke.copy(rect);
  12635. // FIXME Must after updateTransform
  12636. var w = style.lineWidth;
  12637. // PENDING, Min line width is needed when line is horizontal or vertical
  12638. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12639. // Only add extra hover lineWidth when there are no fill
  12640. if (!style.hasFill()) {
  12641. w = Math.max(w, this.strokeContainThreshold || 4);
  12642. }
  12643. // Consider line width
  12644. // Line scale can't be 0;
  12645. if (lineScale > 1e-10) {
  12646. rectWithStroke.width += w / lineScale;
  12647. rectWithStroke.height += w / lineScale;
  12648. rectWithStroke.x -= w / lineScale / 2;
  12649. rectWithStroke.y -= w / lineScale / 2;
  12650. }
  12651. }
  12652. // Return rect with stroke
  12653. return rectWithStroke;
  12654. }
  12655. return rect;
  12656. },
  12657. contain: function (x, y) {
  12658. var localPos = this.transformCoordToLocal(x, y);
  12659. var rect = this.getBoundingRect();
  12660. var style = this.style;
  12661. x = localPos[0];
  12662. y = localPos[1];
  12663. if (rect.contain(x, y)) {
  12664. var pathData = this.path.data;
  12665. if (style.hasStroke()) {
  12666. var lineWidth = style.lineWidth;
  12667. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12668. // Line scale can't be 0;
  12669. if (lineScale > 1e-10) {
  12670. // Only add extra hover lineWidth when there are no fill
  12671. if (!style.hasFill()) {
  12672. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12673. }
  12674. if (containStroke(
  12675. pathData, lineWidth / lineScale, x, y
  12676. )) {
  12677. return true;
  12678. }
  12679. }
  12680. }
  12681. if (style.hasFill()) {
  12682. return contain(pathData, x, y);
  12683. }
  12684. }
  12685. return false;
  12686. },
  12687. /**
  12688. * @param {boolean} dirtyPath
  12689. */
  12690. dirty: function (dirtyPath) {
  12691. if (dirtyPath == null) {
  12692. dirtyPath = true;
  12693. }
  12694. // Only mark dirty, not mark clean
  12695. if (dirtyPath) {
  12696. this.__dirtyPath = dirtyPath;
  12697. this._rect = null;
  12698. }
  12699. this.__dirty = this.__dirtyText = true;
  12700. this.__zr && this.__zr.refresh();
  12701. // Used as a clipping path
  12702. if (this.__clipTarget) {
  12703. this.__clipTarget.dirty();
  12704. }
  12705. },
  12706. /**
  12707. * Alias for animate('shape')
  12708. * @param {boolean} loop
  12709. */
  12710. animateShape: function (loop) {
  12711. return this.animate('shape', loop);
  12712. },
  12713. // Overwrite attrKV
  12714. attrKV: function (key, value) {
  12715. // FIXME
  12716. if (key === 'shape') {
  12717. this.setShape(value);
  12718. this.__dirtyPath = true;
  12719. this._rect = null;
  12720. }
  12721. else {
  12722. Displayable.prototype.attrKV.call(this, key, value);
  12723. }
  12724. },
  12725. /**
  12726. * @param {Object|string} key
  12727. * @param {*} value
  12728. */
  12729. setShape: function (key, value) {
  12730. var shape = this.shape;
  12731. // Path from string may not have shape
  12732. if (shape) {
  12733. if (isObject$1(key)) {
  12734. for (var name in key) {
  12735. if (key.hasOwnProperty(name)) {
  12736. shape[name] = key[name];
  12737. }
  12738. }
  12739. }
  12740. else {
  12741. shape[key] = value;
  12742. }
  12743. this.dirty(true);
  12744. }
  12745. return this;
  12746. },
  12747. getLineScale: function () {
  12748. var m = this.transform;
  12749. // Get the line scale.
  12750. // Determinant of `m` means how much the area is enlarged by the
  12751. // transformation. So its square root can be used as a scale factor
  12752. // for width.
  12753. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12754. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12755. : 1;
  12756. }
  12757. };
  12758. /**
  12759. * 扩展一个 Path element, 比如星形,圆等。
  12760. * Extend a path element
  12761. * @param {Object} props
  12762. * @param {string} props.type Path type
  12763. * @param {Function} props.init Initialize
  12764. * @param {Function} props.buildPath Overwrite buildPath method
  12765. * @param {Object} [props.style] Extended default style config
  12766. * @param {Object} [props.shape] Extended default shape config
  12767. */
  12768. Path.extend = function (defaults$$1) {
  12769. var Sub = function (opts) {
  12770. Path.call(this, opts);
  12771. if (defaults$$1.style) {
  12772. // Extend default style
  12773. this.style.extendFrom(defaults$$1.style, false);
  12774. }
  12775. // Extend default shape
  12776. var defaultShape = defaults$$1.shape;
  12777. if (defaultShape) {
  12778. this.shape = this.shape || {};
  12779. var thisShape = this.shape;
  12780. for (var name in defaultShape) {
  12781. if (
  12782. !thisShape.hasOwnProperty(name)
  12783. && defaultShape.hasOwnProperty(name)
  12784. ) {
  12785. thisShape[name] = defaultShape[name];
  12786. }
  12787. }
  12788. }
  12789. defaults$$1.init && defaults$$1.init.call(this, opts);
  12790. };
  12791. inherits(Sub, Path);
  12792. // FIXME 不能 extend position, rotation 等引用对象
  12793. for (var name in defaults$$1) {
  12794. // Extending prototype values and methods
  12795. if (name !== 'style' && name !== 'shape') {
  12796. Sub.prototype[name] = defaults$$1[name];
  12797. }
  12798. }
  12799. return Sub;
  12800. };
  12801. inherits(Path, Displayable);
  12802. var CMD$2 = PathProxy.CMD;
  12803. var points = [[], [], []];
  12804. var mathSqrt$3 = Math.sqrt;
  12805. var mathAtan2 = Math.atan2;
  12806. var transformPath = function (path, m) {
  12807. var data = path.data;
  12808. var cmd;
  12809. var nPoint;
  12810. var i;
  12811. var j;
  12812. var k;
  12813. var p;
  12814. var M = CMD$2.M;
  12815. var C = CMD$2.C;
  12816. var L = CMD$2.L;
  12817. var R = CMD$2.R;
  12818. var A = CMD$2.A;
  12819. var Q = CMD$2.Q;
  12820. for (i = 0, j = 0; i < data.length;) {
  12821. cmd = data[i++];
  12822. j = i;
  12823. nPoint = 0;
  12824. switch (cmd) {
  12825. case M:
  12826. nPoint = 1;
  12827. break;
  12828. case L:
  12829. nPoint = 1;
  12830. break;
  12831. case C:
  12832. nPoint = 3;
  12833. break;
  12834. case Q:
  12835. nPoint = 2;
  12836. break;
  12837. case A:
  12838. var x = m[4];
  12839. var y = m[5];
  12840. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12841. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12842. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12843. // cx
  12844. data[i] *= sx;
  12845. data[i++] += x;
  12846. // cy
  12847. data[i] *= sy;
  12848. data[i++] += y;
  12849. // Scale rx and ry
  12850. // FIXME Assume psi is 0 here
  12851. data[i++] *= sx;
  12852. data[i++] *= sy;
  12853. // Start angle
  12854. data[i++] += angle;
  12855. // end angle
  12856. data[i++] += angle;
  12857. // FIXME psi
  12858. i += 2;
  12859. j = i;
  12860. break;
  12861. case R:
  12862. // x0, y0
  12863. p[0] = data[i++];
  12864. p[1] = data[i++];
  12865. applyTransform(p, p, m);
  12866. data[j++] = p[0];
  12867. data[j++] = p[1];
  12868. // x1, y1
  12869. p[0] += data[i++];
  12870. p[1] += data[i++];
  12871. applyTransform(p, p, m);
  12872. data[j++] = p[0];
  12873. data[j++] = p[1];
  12874. }
  12875. for (k = 0; k < nPoint; k++) {
  12876. var p = points[k];
  12877. p[0] = data[i++];
  12878. p[1] = data[i++];
  12879. applyTransform(p, p, m);
  12880. // Write back
  12881. data[j++] = p[0];
  12882. data[j++] = p[1];
  12883. }
  12884. }
  12885. };
  12886. // command chars
  12887. // var cc = [
  12888. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12889. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12890. // ];
  12891. var mathSqrt = Math.sqrt;
  12892. var mathSin = Math.sin;
  12893. var mathCos = Math.cos;
  12894. var PI = Math.PI;
  12895. var vMag = function (v) {
  12896. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12897. };
  12898. var vRatio = function (u, v) {
  12899. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12900. };
  12901. var vAngle = function (u, v) {
  12902. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12903. * Math.acos(vRatio(u, v));
  12904. };
  12905. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12906. var psi = psiDeg * (PI / 180.0);
  12907. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12908. + mathSin(psi) * (y1 - y2) / 2.0;
  12909. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12910. + mathCos(psi) * (y1 - y2) / 2.0;
  12911. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12912. if (lambda > 1) {
  12913. rx *= mathSqrt(lambda);
  12914. ry *= mathSqrt(lambda);
  12915. }
  12916. var f = (fa === fs ? -1 : 1)
  12917. * mathSqrt((((rx * rx) * (ry * ry))
  12918. - ((rx * rx) * (yp * yp))
  12919. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12920. + (ry * ry) * (xp * xp))
  12921. ) || 0;
  12922. var cxp = f * rx * yp / ry;
  12923. var cyp = f * -ry * xp / rx;
  12924. var cx = (x1 + x2) / 2.0
  12925. + mathCos(psi) * cxp
  12926. - mathSin(psi) * cyp;
  12927. var cy = (y1 + y2) / 2.0
  12928. + mathSin(psi) * cxp
  12929. + mathCos(psi) * cyp;
  12930. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12931. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12932. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12933. var dTheta = vAngle(u, v);
  12934. if (vRatio(u, v) <= -1) {
  12935. dTheta = PI;
  12936. }
  12937. if (vRatio(u, v) >= 1) {
  12938. dTheta = 0;
  12939. }
  12940. if (fs === 0 && dTheta > 0) {
  12941. dTheta = dTheta - 2 * PI;
  12942. }
  12943. if (fs === 1 && dTheta < 0) {
  12944. dTheta = dTheta + 2 * PI;
  12945. }
  12946. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12947. }
  12948. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12949. // Consider case:
  12950. // (1) delimiter can be comma or space, where continuous commas
  12951. // or spaces should be seen as one comma.
  12952. // (2) value can be like:
  12953. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  12954. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  12955. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12956. // var valueSplitReg = /[\s,]+/;
  12957. function createPathProxyFromString(data) {
  12958. if (!data) {
  12959. return new PathProxy();
  12960. }
  12961. // var data = data.replace(/-/g, ' -')
  12962. // .replace(/ /g, ' ')
  12963. // .replace(/ /g, ',')
  12964. // .replace(/,,/g, ',');
  12965. // var n;
  12966. // create pipes so that we can split the data
  12967. // for (n = 0; n < cc.length; n++) {
  12968. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12969. // }
  12970. // data = data.replace(/-/g, ',-');
  12971. // create array
  12972. // var arr = cs.split('|');
  12973. // init context point
  12974. var cpx = 0;
  12975. var cpy = 0;
  12976. var subpathX = cpx;
  12977. var subpathY = cpy;
  12978. var prevCmd;
  12979. var path = new PathProxy();
  12980. var CMD = PathProxy.CMD;
  12981. // commandReg.lastIndex = 0;
  12982. // var cmdResult;
  12983. // while ((cmdResult = commandReg.exec(data)) != null) {
  12984. // var cmdStr = cmdResult[1];
  12985. // var cmdContent = cmdResult[2];
  12986. var cmdList = data.match(commandReg);
  12987. for (var l = 0; l < cmdList.length; l++) {
  12988. var cmdText = cmdList[l];
  12989. var cmdStr = cmdText.charAt(0);
  12990. var cmd;
  12991. // String#split is faster a little bit than String#replace or RegExp#exec.
  12992. // var p = cmdContent.split(valueSplitReg);
  12993. // var pLen = 0;
  12994. // for (var i = 0; i < p.length; i++) {
  12995. // // '' and other invalid str => NaN
  12996. // var val = parseFloat(p[i]);
  12997. // !isNaN(val) && (p[pLen++] = val);
  12998. // }
  12999. var p = cmdText.match(numberReg) || [];
  13000. var pLen = p.length;
  13001. for (var i = 0; i < pLen; i++) {
  13002. p[i] = parseFloat(p[i]);
  13003. }
  13004. var off = 0;
  13005. while (off < pLen) {
  13006. var ctlPtx;
  13007. var ctlPty;
  13008. var rx;
  13009. var ry;
  13010. var psi;
  13011. var fa;
  13012. var fs;
  13013. var x1 = cpx;
  13014. var y1 = cpy;
  13015. // convert l, H, h, V, and v to L
  13016. switch (cmdStr) {
  13017. case 'l':
  13018. cpx += p[off++];
  13019. cpy += p[off++];
  13020. cmd = CMD.L;
  13021. path.addData(cmd, cpx, cpy);
  13022. break;
  13023. case 'L':
  13024. cpx = p[off++];
  13025. cpy = p[off++];
  13026. cmd = CMD.L;
  13027. path.addData(cmd, cpx, cpy);
  13028. break;
  13029. case 'm':
  13030. cpx += p[off++];
  13031. cpy += p[off++];
  13032. cmd = CMD.M;
  13033. path.addData(cmd, cpx, cpy);
  13034. subpathX = cpx;
  13035. subpathY = cpy;
  13036. cmdStr = 'l';
  13037. break;
  13038. case 'M':
  13039. cpx = p[off++];
  13040. cpy = p[off++];
  13041. cmd = CMD.M;
  13042. path.addData(cmd, cpx, cpy);
  13043. subpathX = cpx;
  13044. subpathY = cpy;
  13045. cmdStr = 'L';
  13046. break;
  13047. case 'h':
  13048. cpx += p[off++];
  13049. cmd = CMD.L;
  13050. path.addData(cmd, cpx, cpy);
  13051. break;
  13052. case 'H':
  13053. cpx = p[off++];
  13054. cmd = CMD.L;
  13055. path.addData(cmd, cpx, cpy);
  13056. break;
  13057. case 'v':
  13058. cpy += p[off++];
  13059. cmd = CMD.L;
  13060. path.addData(cmd, cpx, cpy);
  13061. break;
  13062. case 'V':
  13063. cpy = p[off++];
  13064. cmd = CMD.L;
  13065. path.addData(cmd, cpx, cpy);
  13066. break;
  13067. case 'C':
  13068. cmd = CMD.C;
  13069. path.addData(
  13070. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13071. );
  13072. cpx = p[off - 2];
  13073. cpy = p[off - 1];
  13074. break;
  13075. case 'c':
  13076. cmd = CMD.C;
  13077. path.addData(
  13078. cmd,
  13079. p[off++] + cpx, p[off++] + cpy,
  13080. p[off++] + cpx, p[off++] + cpy,
  13081. p[off++] + cpx, p[off++] + cpy
  13082. );
  13083. cpx += p[off - 2];
  13084. cpy += p[off - 1];
  13085. break;
  13086. case 'S':
  13087. ctlPtx = cpx;
  13088. ctlPty = cpy;
  13089. var len = path.len();
  13090. var pathData = path.data;
  13091. if (prevCmd === CMD.C) {
  13092. ctlPtx += cpx - pathData[len - 4];
  13093. ctlPty += cpy - pathData[len - 3];
  13094. }
  13095. cmd = CMD.C;
  13096. x1 = p[off++];
  13097. y1 = p[off++];
  13098. cpx = p[off++];
  13099. cpy = p[off++];
  13100. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13101. break;
  13102. case 's':
  13103. ctlPtx = cpx;
  13104. ctlPty = cpy;
  13105. var len = path.len();
  13106. var pathData = path.data;
  13107. if (prevCmd === CMD.C) {
  13108. ctlPtx += cpx - pathData[len - 4];
  13109. ctlPty += cpy - pathData[len - 3];
  13110. }
  13111. cmd = CMD.C;
  13112. x1 = cpx + p[off++];
  13113. y1 = cpy + p[off++];
  13114. cpx += p[off++];
  13115. cpy += p[off++];
  13116. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13117. break;
  13118. case 'Q':
  13119. x1 = p[off++];
  13120. y1 = p[off++];
  13121. cpx = p[off++];
  13122. cpy = p[off++];
  13123. cmd = CMD.Q;
  13124. path.addData(cmd, x1, y1, cpx, cpy);
  13125. break;
  13126. case 'q':
  13127. x1 = p[off++] + cpx;
  13128. y1 = p[off++] + cpy;
  13129. cpx += p[off++];
  13130. cpy += p[off++];
  13131. cmd = CMD.Q;
  13132. path.addData(cmd, x1, y1, cpx, cpy);
  13133. break;
  13134. case 'T':
  13135. ctlPtx = cpx;
  13136. ctlPty = cpy;
  13137. var len = path.len();
  13138. var pathData = path.data;
  13139. if (prevCmd === CMD.Q) {
  13140. ctlPtx += cpx - pathData[len - 4];
  13141. ctlPty += cpy - pathData[len - 3];
  13142. }
  13143. cpx = p[off++];
  13144. cpy = p[off++];
  13145. cmd = CMD.Q;
  13146. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13147. break;
  13148. case 't':
  13149. ctlPtx = cpx;
  13150. ctlPty = cpy;
  13151. var len = path.len();
  13152. var pathData = path.data;
  13153. if (prevCmd === CMD.Q) {
  13154. ctlPtx += cpx - pathData[len - 4];
  13155. ctlPty += cpy - pathData[len - 3];
  13156. }
  13157. cpx += p[off++];
  13158. cpy += p[off++];
  13159. cmd = CMD.Q;
  13160. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13161. break;
  13162. case 'A':
  13163. rx = p[off++];
  13164. ry = p[off++];
  13165. psi = p[off++];
  13166. fa = p[off++];
  13167. fs = p[off++];
  13168. x1 = cpx, y1 = cpy;
  13169. cpx = p[off++];
  13170. cpy = p[off++];
  13171. cmd = CMD.A;
  13172. processArc(
  13173. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13174. );
  13175. break;
  13176. case 'a':
  13177. rx = p[off++];
  13178. ry = p[off++];
  13179. psi = p[off++];
  13180. fa = p[off++];
  13181. fs = p[off++];
  13182. x1 = cpx, y1 = cpy;
  13183. cpx += p[off++];
  13184. cpy += p[off++];
  13185. cmd = CMD.A;
  13186. processArc(
  13187. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13188. );
  13189. break;
  13190. }
  13191. }
  13192. if (cmdStr === 'z' || cmdStr === 'Z') {
  13193. cmd = CMD.Z;
  13194. path.addData(cmd);
  13195. // z may be in the middle of the path.
  13196. cpx = subpathX;
  13197. cpy = subpathY;
  13198. }
  13199. prevCmd = cmd;
  13200. }
  13201. path.toStatic();
  13202. return path;
  13203. }
  13204. // TODO Optimize double memory cost problem
  13205. function createPathOptions(str, opts) {
  13206. var pathProxy = createPathProxyFromString(str);
  13207. opts = opts || {};
  13208. opts.buildPath = function (path) {
  13209. if (path.setData) {
  13210. path.setData(pathProxy.data);
  13211. // Svg and vml renderer don't have context
  13212. var ctx = path.getContext();
  13213. if (ctx) {
  13214. path.rebuildPath(ctx);
  13215. }
  13216. }
  13217. else {
  13218. var ctx = path;
  13219. pathProxy.rebuildPath(ctx);
  13220. }
  13221. };
  13222. opts.applyTransform = function (m) {
  13223. transformPath(pathProxy, m);
  13224. this.dirty(true);
  13225. };
  13226. return opts;
  13227. }
  13228. /**
  13229. * Create a Path object from path string data
  13230. * http://www.w3.org/TR/SVG/paths.html#PathData
  13231. * @param {Object} opts Other options
  13232. */
  13233. function createFromString(str, opts) {
  13234. return new Path(createPathOptions(str, opts));
  13235. }
  13236. /**
  13237. * Create a Path class from path string data
  13238. * @param {string} str
  13239. * @param {Object} opts Other options
  13240. */
  13241. function extendFromString(str, opts) {
  13242. return Path.extend(createPathOptions(str, opts));
  13243. }
  13244. /**
  13245. * Merge multiple paths
  13246. */
  13247. // TODO Apply transform
  13248. // TODO stroke dash
  13249. // TODO Optimize double memory cost problem
  13250. function mergePath$1(pathEls, opts) {
  13251. var pathList = [];
  13252. var len = pathEls.length;
  13253. for (var i = 0; i < len; i++) {
  13254. var pathEl = pathEls[i];
  13255. if (!pathEl.path) {
  13256. pathEl.createPathProxy();
  13257. }
  13258. if (pathEl.__dirtyPath) {
  13259. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13260. }
  13261. pathList.push(pathEl.path);
  13262. }
  13263. var pathBundle = new Path(opts);
  13264. // Need path proxy.
  13265. pathBundle.createPathProxy();
  13266. pathBundle.buildPath = function (path) {
  13267. path.appendPath(pathList);
  13268. // Svg and vml renderer don't have context
  13269. var ctx = path.getContext();
  13270. if (ctx) {
  13271. path.rebuildPath(ctx);
  13272. }
  13273. };
  13274. return pathBundle;
  13275. }
  13276. /**
  13277. * @alias zrender/graphic/Text
  13278. * @extends module:zrender/graphic/Displayable
  13279. * @constructor
  13280. * @param {Object} opts
  13281. */
  13282. var Text = function (opts) { // jshint ignore:line
  13283. Displayable.call(this, opts);
  13284. };
  13285. Text.prototype = {
  13286. constructor: Text,
  13287. type: 'text',
  13288. brush: function (ctx, prevEl) {
  13289. var style = this.style;
  13290. // Optimize, avoid normalize every time.
  13291. this.__dirty && normalizeTextStyle(style, true);
  13292. // Use props with prefix 'text'.
  13293. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13294. style.shadowOffsetX = style.shadowOffsetY = null;
  13295. var text = style.text;
  13296. // Convert to string
  13297. text != null && (text += '');
  13298. // Do not apply style.bind in Text node. Because the real bind job
  13299. // is in textHelper.renderText, and performance of text render should
  13300. // be considered.
  13301. // style.bind(ctx, this, prevEl);
  13302. if (!needDrawText(text, style)) {
  13303. // The current el.style is not applied
  13304. // and should not be used as cache.
  13305. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13306. return;
  13307. }
  13308. this.setTransform(ctx);
  13309. renderText(this, ctx, text, style, null, prevEl);
  13310. this.restoreTransform(ctx);
  13311. },
  13312. getBoundingRect: function () {
  13313. var style = this.style;
  13314. // Optimize, avoid normalize every time.
  13315. this.__dirty && normalizeTextStyle(style, true);
  13316. if (!this._rect) {
  13317. var text = style.text;
  13318. text != null ? (text += '') : (text = '');
  13319. var rect = getBoundingRect(
  13320. style.text + '',
  13321. style.font,
  13322. style.textAlign,
  13323. style.textVerticalAlign,
  13324. style.textPadding,
  13325. style.textLineHeight,
  13326. style.rich
  13327. );
  13328. rect.x += style.x || 0;
  13329. rect.y += style.y || 0;
  13330. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13331. var w = style.textStrokeWidth;
  13332. rect.x -= w / 2;
  13333. rect.y -= w / 2;
  13334. rect.width += w;
  13335. rect.height += w;
  13336. }
  13337. this._rect = rect;
  13338. }
  13339. return this._rect;
  13340. }
  13341. };
  13342. inherits(Text, Displayable);
  13343. /**
  13344. * 圆形
  13345. * @module zrender/shape/Circle
  13346. */
  13347. var Circle = Path.extend({
  13348. type: 'circle',
  13349. shape: {
  13350. cx: 0,
  13351. cy: 0,
  13352. r: 0
  13353. },
  13354. buildPath: function (ctx, shape, inBundle) {
  13355. // Better stroking in ShapeBundle
  13356. // Always do it may have performence issue ( fill may be 2x more cost)
  13357. if (inBundle) {
  13358. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13359. }
  13360. // else {
  13361. // if (ctx.allocate && !ctx.data.length) {
  13362. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13363. // }
  13364. // }
  13365. // Better stroking in ShapeBundle
  13366. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13367. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13368. }
  13369. });
  13370. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13371. // where exception "unexpected call to method or property access"
  13372. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13373. // whose area size is zero is drawn and ctx.clip() is called and
  13374. // shadowBlur is set. See #4572, #3112, #5777.
  13375. // (e.g.,
  13376. // ctx.moveTo(10, 10);
  13377. // ctx.lineTo(20, 10);
  13378. // ctx.closePath();
  13379. // ctx.clip();
  13380. // ctx.shadowBlur = 10;
  13381. // ...
  13382. // ctx.fill();
  13383. // )
  13384. var shadowTemp = [
  13385. ['shadowBlur', 0],
  13386. ['shadowColor', '#000'],
  13387. ['shadowOffsetX', 0],
  13388. ['shadowOffsetY', 0]
  13389. ];
  13390. var fixClipWithShadow = function (orignalBrush) {
  13391. // version string can be: '11.0'
  13392. return (env$1.browser.ie && env$1.browser.version >= 11)
  13393. ? function () {
  13394. var clipPaths = this.__clipPaths;
  13395. var style = this.style;
  13396. var modified;
  13397. if (clipPaths) {
  13398. for (var i = 0; i < clipPaths.length; i++) {
  13399. var clipPath = clipPaths[i];
  13400. var shape = clipPath && clipPath.shape;
  13401. var type = clipPath && clipPath.type;
  13402. if (shape && (
  13403. (type === 'sector' && shape.startAngle === shape.endAngle)
  13404. || (type === 'rect' && (!shape.width || !shape.height))
  13405. )) {
  13406. for (var j = 0; j < shadowTemp.length; j++) {
  13407. // It is save to put shadowTemp static, because shadowTemp
  13408. // will be all modified each item brush called.
  13409. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13410. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13411. }
  13412. modified = true;
  13413. break;
  13414. }
  13415. }
  13416. }
  13417. orignalBrush.apply(this, arguments);
  13418. if (modified) {
  13419. for (var j = 0; j < shadowTemp.length; j++) {
  13420. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13421. }
  13422. }
  13423. }
  13424. : orignalBrush;
  13425. };
  13426. /**
  13427. * 扇形
  13428. * @module zrender/graphic/shape/Sector
  13429. */
  13430. var Sector = Path.extend({
  13431. type: 'sector',
  13432. shape: {
  13433. cx: 0,
  13434. cy: 0,
  13435. r0: 0,
  13436. r: 0,
  13437. startAngle: 0,
  13438. endAngle: Math.PI * 2,
  13439. clockwise: true
  13440. },
  13441. brush: fixClipWithShadow(Path.prototype.brush),
  13442. buildPath: function (ctx, shape) {
  13443. var x = shape.cx;
  13444. var y = shape.cy;
  13445. var r0 = Math.max(shape.r0 || 0, 0);
  13446. var r = Math.max(shape.r, 0);
  13447. var startAngle = shape.startAngle;
  13448. var endAngle = shape.endAngle;
  13449. var clockwise = shape.clockwise;
  13450. var unitX = Math.cos(startAngle);
  13451. var unitY = Math.sin(startAngle);
  13452. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13453. ctx.lineTo(unitX * r + x, unitY * r + y);
  13454. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13455. ctx.lineTo(
  13456. Math.cos(endAngle) * r0 + x,
  13457. Math.sin(endAngle) * r0 + y
  13458. );
  13459. if (r0 !== 0) {
  13460. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13461. }
  13462. ctx.closePath();
  13463. }
  13464. });
  13465. /**
  13466. * 圆环
  13467. * @module zrender/graphic/shape/Ring
  13468. */
  13469. var Ring = Path.extend({
  13470. type: 'ring',
  13471. shape: {
  13472. cx: 0,
  13473. cy: 0,
  13474. r: 0,
  13475. r0: 0
  13476. },
  13477. buildPath: function (ctx, shape) {
  13478. var x = shape.cx;
  13479. var y = shape.cy;
  13480. var PI2 = Math.PI * 2;
  13481. ctx.moveTo(x + shape.r, y);
  13482. ctx.arc(x, y, shape.r, 0, PI2, false);
  13483. ctx.moveTo(x + shape.r0, y);
  13484. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13485. }
  13486. });
  13487. /**
  13488. * Catmull-Rom spline 插值折线
  13489. * @module zrender/shape/util/smoothSpline
  13490. * @author pissang (https://www.github.com/pissang)
  13491. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13492. * errorrik (errorrik@gmail.com)
  13493. */
  13494. /**
  13495. * @inner
  13496. */
  13497. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13498. var v0 = (p2 - p0) * 0.5;
  13499. var v1 = (p3 - p1) * 0.5;
  13500. return (2 * (p1 - p2) + v0 + v1) * t3
  13501. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13502. + v0 * t + p1;
  13503. }
  13504. /**
  13505. * @alias module:zrender/shape/util/smoothSpline
  13506. * @param {Array} points 线段顶点数组
  13507. * @param {boolean} isLoop
  13508. * @return {Array}
  13509. */
  13510. var smoothSpline = function (points, isLoop) {
  13511. var len$$1 = points.length;
  13512. var ret = [];
  13513. var distance$$1 = 0;
  13514. for (var i = 1; i < len$$1; i++) {
  13515. distance$$1 += distance(points[i - 1], points[i]);
  13516. }
  13517. var segs = distance$$1 / 2;
  13518. segs = segs < len$$1 ? len$$1 : segs;
  13519. for (var i = 0; i < segs; i++) {
  13520. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13521. var idx = Math.floor(pos);
  13522. var w = pos - idx;
  13523. var p0;
  13524. var p1 = points[idx % len$$1];
  13525. var p2;
  13526. var p3;
  13527. if (!isLoop) {
  13528. p0 = points[idx === 0 ? idx : idx - 1];
  13529. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13530. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13531. }
  13532. else {
  13533. p0 = points[(idx - 1 + len$$1) % len$$1];
  13534. p2 = points[(idx + 1) % len$$1];
  13535. p3 = points[(idx + 2) % len$$1];
  13536. }
  13537. var w2 = w * w;
  13538. var w3 = w * w2;
  13539. ret.push([
  13540. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13541. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13542. ]);
  13543. }
  13544. return ret;
  13545. };
  13546. /**
  13547. * 贝塞尔平滑曲线
  13548. * @module zrender/shape/util/smoothBezier
  13549. * @author pissang (https://www.github.com/pissang)
  13550. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13551. * errorrik (errorrik@gmail.com)
  13552. */
  13553. /**
  13554. * 贝塞尔平滑曲线
  13555. * @alias module:zrender/shape/util/smoothBezier
  13556. * @param {Array} points 线段顶点数组
  13557. * @param {number} smooth 平滑等级, 0-1
  13558. * @param {boolean} isLoop
  13559. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13560. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13561. * 整个折线的包围盒做一个并集用来约束控制点。
  13562. * @param {Array} 计算出来的控制点数组
  13563. */
  13564. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13565. var cps = [];
  13566. var v = [];
  13567. var v1 = [];
  13568. var v2 = [];
  13569. var prevPoint;
  13570. var nextPoint;
  13571. var min$$1;
  13572. var max$$1;
  13573. if (constraint) {
  13574. min$$1 = [Infinity, Infinity];
  13575. max$$1 = [-Infinity, -Infinity];
  13576. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13577. min(min$$1, min$$1, points[i]);
  13578. max(max$$1, max$$1, points[i]);
  13579. }
  13580. // 与指定的包围盒做并集
  13581. min(min$$1, min$$1, constraint[0]);
  13582. max(max$$1, max$$1, constraint[1]);
  13583. }
  13584. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13585. var point = points[i];
  13586. if (isLoop) {
  13587. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13588. nextPoint = points[(i + 1) % len$$1];
  13589. }
  13590. else {
  13591. if (i === 0 || i === len$$1 - 1) {
  13592. cps.push(clone$1(points[i]));
  13593. continue;
  13594. }
  13595. else {
  13596. prevPoint = points[i - 1];
  13597. nextPoint = points[i + 1];
  13598. }
  13599. }
  13600. sub(v, nextPoint, prevPoint);
  13601. // use degree to scale the handle length
  13602. scale(v, v, smooth);
  13603. var d0 = distance(point, prevPoint);
  13604. var d1 = distance(point, nextPoint);
  13605. var sum = d0 + d1;
  13606. if (sum !== 0) {
  13607. d0 /= sum;
  13608. d1 /= sum;
  13609. }
  13610. scale(v1, v, -d0);
  13611. scale(v2, v, d1);
  13612. var cp0 = add([], point, v1);
  13613. var cp1 = add([], point, v2);
  13614. if (constraint) {
  13615. max(cp0, cp0, min$$1);
  13616. min(cp0, cp0, max$$1);
  13617. max(cp1, cp1, min$$1);
  13618. min(cp1, cp1, max$$1);
  13619. }
  13620. cps.push(cp0);
  13621. cps.push(cp1);
  13622. }
  13623. if (isLoop) {
  13624. cps.push(cps.shift());
  13625. }
  13626. return cps;
  13627. };
  13628. function buildPath$1(ctx, shape, closePath) {
  13629. var points = shape.points;
  13630. var smooth = shape.smooth;
  13631. if (points && points.length >= 2) {
  13632. if (smooth && smooth !== 'spline') {
  13633. var controlPoints = smoothBezier(
  13634. points, smooth, closePath, shape.smoothConstraint
  13635. );
  13636. ctx.moveTo(points[0][0], points[0][1]);
  13637. var len = points.length;
  13638. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13639. var cp1 = controlPoints[i * 2];
  13640. var cp2 = controlPoints[i * 2 + 1];
  13641. var p = points[(i + 1) % len];
  13642. ctx.bezierCurveTo(
  13643. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13644. );
  13645. }
  13646. }
  13647. else {
  13648. if (smooth === 'spline') {
  13649. points = smoothSpline(points, closePath);
  13650. }
  13651. ctx.moveTo(points[0][0], points[0][1]);
  13652. for (var i = 1, l = points.length; i < l; i++) {
  13653. ctx.lineTo(points[i][0], points[i][1]);
  13654. }
  13655. }
  13656. closePath && ctx.closePath();
  13657. }
  13658. }
  13659. /**
  13660. * 多边形
  13661. * @module zrender/shape/Polygon
  13662. */
  13663. var Polygon = Path.extend({
  13664. type: 'polygon',
  13665. shape: {
  13666. points: null,
  13667. smooth: false,
  13668. smoothConstraint: null
  13669. },
  13670. buildPath: function (ctx, shape) {
  13671. buildPath$1(ctx, shape, true);
  13672. }
  13673. });
  13674. /**
  13675. * @module zrender/graphic/shape/Polyline
  13676. */
  13677. var Polyline = Path.extend({
  13678. type: 'polyline',
  13679. shape: {
  13680. points: null,
  13681. smooth: false,
  13682. smoothConstraint: null
  13683. },
  13684. style: {
  13685. stroke: '#000',
  13686. fill: null
  13687. },
  13688. buildPath: function (ctx, shape) {
  13689. buildPath$1(ctx, shape, false);
  13690. }
  13691. });
  13692. /**
  13693. * Sub-pixel optimize for canvas rendering, prevent from blur
  13694. * when rendering a thin vertical/horizontal line.
  13695. */
  13696. var round$1 = Math.round;
  13697. /**
  13698. * Sub pixel optimize line for canvas
  13699. *
  13700. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13701. * `outputShape` and `inputShape` can be the same object.
  13702. * `outputShape` object can be used repeatly, because all of
  13703. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13704. * @param {Object} [inputShape]
  13705. * @param {number} [inputShape.x1]
  13706. * @param {number} [inputShape.y1]
  13707. * @param {number} [inputShape.x2]
  13708. * @param {number} [inputShape.y2]
  13709. * @param {Object} [style]
  13710. * @param {number} [style.lineWidth]
  13711. */
  13712. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  13713. var lineWidth = style && style.lineWidth;
  13714. if (!inputShape || !lineWidth) {
  13715. return;
  13716. }
  13717. var x1 = inputShape.x1;
  13718. var x2 = inputShape.x2;
  13719. var y1 = inputShape.y1;
  13720. var y2 = inputShape.y2;
  13721. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  13722. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  13723. }
  13724. else {
  13725. outputShape.x1 = x1;
  13726. outputShape.x2 = x2;
  13727. }
  13728. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  13729. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  13730. }
  13731. else {
  13732. outputShape.y1 = y1;
  13733. outputShape.y2 = y2;
  13734. }
  13735. }
  13736. /**
  13737. * Sub pixel optimize rect for canvas
  13738. *
  13739. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13740. * `outputShape` and `inputShape` can be the same object.
  13741. * `outputShape` object can be used repeatly, because all of
  13742. * the `x`, `y`, `width`, `height` will be assigned in this method.
  13743. * @param {Object} [inputShape]
  13744. * @param {number} [inputShape.x]
  13745. * @param {number} [inputShape.y]
  13746. * @param {number} [inputShape.width]
  13747. * @param {number} [inputShape.height]
  13748. * @param {Object} [style]
  13749. * @param {number} [style.lineWidth]
  13750. */
  13751. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  13752. var lineWidth = style && style.lineWidth;
  13753. if (!inputShape || !lineWidth) {
  13754. return;
  13755. }
  13756. var originX = inputShape.x;
  13757. var originY = inputShape.y;
  13758. var originWidth = inputShape.width;
  13759. var originHeight = inputShape.height;
  13760. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  13761. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  13762. outputShape.width = Math.max(
  13763. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  13764. originWidth === 0 ? 0 : 1
  13765. );
  13766. outputShape.height = Math.max(
  13767. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  13768. originHeight === 0 ? 0 : 1
  13769. );
  13770. }
  13771. /**
  13772. * Sub pixel optimize for canvas
  13773. *
  13774. * @param {number} position Coordinate, such as x, y
  13775. * @param {number} lineWidth Should be nonnegative integer.
  13776. * @param {boolean=} positiveOrNegative Default false (negative).
  13777. * @return {number} Optimized position.
  13778. */
  13779. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  13780. // Assure that (position + lineWidth / 2) is near integer edge,
  13781. // otherwise line will be fuzzy in canvas.
  13782. var doubledPosition = round$1(position * 2);
  13783. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  13784. ? doubledPosition / 2
  13785. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13786. }
  13787. /**
  13788. * 矩形
  13789. * @module zrender/graphic/shape/Rect
  13790. */
  13791. // Avoid create repeatly.
  13792. var subPixelOptimizeOutputShape = {};
  13793. var Rect = Path.extend({
  13794. type: 'rect',
  13795. shape: {
  13796. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13797. // r缩写为1 相当于 [1, 1, 1, 1]
  13798. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13799. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13800. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13801. r: 0,
  13802. x: 0,
  13803. y: 0,
  13804. width: 0,
  13805. height: 0
  13806. },
  13807. buildPath: function (ctx, shape) {
  13808. var x;
  13809. var y;
  13810. var width;
  13811. var height;
  13812. if (this.subPixelOptimize) {
  13813. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  13814. x = subPixelOptimizeOutputShape.x;
  13815. y = subPixelOptimizeOutputShape.y;
  13816. width = subPixelOptimizeOutputShape.width;
  13817. height = subPixelOptimizeOutputShape.height;
  13818. subPixelOptimizeOutputShape.r = shape.r;
  13819. shape = subPixelOptimizeOutputShape;
  13820. }
  13821. else {
  13822. x = shape.x;
  13823. y = shape.y;
  13824. width = shape.width;
  13825. height = shape.height;
  13826. }
  13827. if (!shape.r) {
  13828. ctx.rect(x, y, width, height);
  13829. }
  13830. else {
  13831. buildPath(ctx, shape);
  13832. }
  13833. ctx.closePath();
  13834. return;
  13835. }
  13836. });
  13837. /**
  13838. * 直线
  13839. * @module zrender/graphic/shape/Line
  13840. */
  13841. // Avoid create repeatly.
  13842. var subPixelOptimizeOutputShape$1 = {};
  13843. var Line = Path.extend({
  13844. type: 'line',
  13845. shape: {
  13846. // Start point
  13847. x1: 0,
  13848. y1: 0,
  13849. // End point
  13850. x2: 0,
  13851. y2: 0,
  13852. percent: 1
  13853. },
  13854. style: {
  13855. stroke: '#000',
  13856. fill: null
  13857. },
  13858. buildPath: function (ctx, shape) {
  13859. var x1;
  13860. var y1;
  13861. var x2;
  13862. var y2;
  13863. if (this.subPixelOptimize) {
  13864. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  13865. x1 = subPixelOptimizeOutputShape$1.x1;
  13866. y1 = subPixelOptimizeOutputShape$1.y1;
  13867. x2 = subPixelOptimizeOutputShape$1.x2;
  13868. y2 = subPixelOptimizeOutputShape$1.y2;
  13869. }
  13870. else {
  13871. x1 = shape.x1;
  13872. y1 = shape.y1;
  13873. x2 = shape.x2;
  13874. y2 = shape.y2;
  13875. }
  13876. var percent = shape.percent;
  13877. if (percent === 0) {
  13878. return;
  13879. }
  13880. ctx.moveTo(x1, y1);
  13881. if (percent < 1) {
  13882. x2 = x1 * (1 - percent) + x2 * percent;
  13883. y2 = y1 * (1 - percent) + y2 * percent;
  13884. }
  13885. ctx.lineTo(x2, y2);
  13886. },
  13887. /**
  13888. * Get point at percent
  13889. * @param {number} percent
  13890. * @return {Array.<number>}
  13891. */
  13892. pointAt: function (p) {
  13893. var shape = this.shape;
  13894. return [
  13895. shape.x1 * (1 - p) + shape.x2 * p,
  13896. shape.y1 * (1 - p) + shape.y2 * p
  13897. ];
  13898. }
  13899. });
  13900. /**
  13901. * 贝塞尔曲线
  13902. * @module zrender/shape/BezierCurve
  13903. */
  13904. var out = [];
  13905. function someVectorAt(shape, t, isTangent) {
  13906. var cpx2 = shape.cpx2;
  13907. var cpy2 = shape.cpy2;
  13908. if (cpx2 === null || cpy2 === null) {
  13909. return [
  13910. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13911. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13912. ];
  13913. }
  13914. else {
  13915. return [
  13916. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13917. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13918. ];
  13919. }
  13920. }
  13921. var BezierCurve = Path.extend({
  13922. type: 'bezier-curve',
  13923. shape: {
  13924. x1: 0,
  13925. y1: 0,
  13926. x2: 0,
  13927. y2: 0,
  13928. cpx1: 0,
  13929. cpy1: 0,
  13930. // cpx2: 0,
  13931. // cpy2: 0
  13932. // Curve show percent, for animating
  13933. percent: 1
  13934. },
  13935. style: {
  13936. stroke: '#000',
  13937. fill: null
  13938. },
  13939. buildPath: function (ctx, shape) {
  13940. var x1 = shape.x1;
  13941. var y1 = shape.y1;
  13942. var x2 = shape.x2;
  13943. var y2 = shape.y2;
  13944. var cpx1 = shape.cpx1;
  13945. var cpy1 = shape.cpy1;
  13946. var cpx2 = shape.cpx2;
  13947. var cpy2 = shape.cpy2;
  13948. var percent = shape.percent;
  13949. if (percent === 0) {
  13950. return;
  13951. }
  13952. ctx.moveTo(x1, y1);
  13953. if (cpx2 == null || cpy2 == null) {
  13954. if (percent < 1) {
  13955. quadraticSubdivide(
  13956. x1, cpx1, x2, percent, out
  13957. );
  13958. cpx1 = out[1];
  13959. x2 = out[2];
  13960. quadraticSubdivide(
  13961. y1, cpy1, y2, percent, out
  13962. );
  13963. cpy1 = out[1];
  13964. y2 = out[2];
  13965. }
  13966. ctx.quadraticCurveTo(
  13967. cpx1, cpy1,
  13968. x2, y2
  13969. );
  13970. }
  13971. else {
  13972. if (percent < 1) {
  13973. cubicSubdivide(
  13974. x1, cpx1, cpx2, x2, percent, out
  13975. );
  13976. cpx1 = out[1];
  13977. cpx2 = out[2];
  13978. x2 = out[3];
  13979. cubicSubdivide(
  13980. y1, cpy1, cpy2, y2, percent, out
  13981. );
  13982. cpy1 = out[1];
  13983. cpy2 = out[2];
  13984. y2 = out[3];
  13985. }
  13986. ctx.bezierCurveTo(
  13987. cpx1, cpy1,
  13988. cpx2, cpy2,
  13989. x2, y2
  13990. );
  13991. }
  13992. },
  13993. /**
  13994. * Get point at percent
  13995. * @param {number} t
  13996. * @return {Array.<number>}
  13997. */
  13998. pointAt: function (t) {
  13999. return someVectorAt(this.shape, t, false);
  14000. },
  14001. /**
  14002. * Get tangent at percent
  14003. * @param {number} t
  14004. * @return {Array.<number>}
  14005. */
  14006. tangentAt: function (t) {
  14007. var p = someVectorAt(this.shape, t, true);
  14008. return normalize(p, p);
  14009. }
  14010. });
  14011. /**
  14012. * 圆弧
  14013. * @module zrender/graphic/shape/Arc
  14014. */
  14015. var Arc = Path.extend({
  14016. type: 'arc',
  14017. shape: {
  14018. cx: 0,
  14019. cy: 0,
  14020. r: 0,
  14021. startAngle: 0,
  14022. endAngle: Math.PI * 2,
  14023. clockwise: true
  14024. },
  14025. style: {
  14026. stroke: '#000',
  14027. fill: null
  14028. },
  14029. buildPath: function (ctx, shape) {
  14030. var x = shape.cx;
  14031. var y = shape.cy;
  14032. var r = Math.max(shape.r, 0);
  14033. var startAngle = shape.startAngle;
  14034. var endAngle = shape.endAngle;
  14035. var clockwise = shape.clockwise;
  14036. var unitX = Math.cos(startAngle);
  14037. var unitY = Math.sin(startAngle);
  14038. ctx.moveTo(unitX * r + x, unitY * r + y);
  14039. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14040. }
  14041. });
  14042. // CompoundPath to improve performance
  14043. var CompoundPath = Path.extend({
  14044. type: 'compound',
  14045. shape: {
  14046. paths: null
  14047. },
  14048. _updatePathDirty: function () {
  14049. var dirtyPath = this.__dirtyPath;
  14050. var paths = this.shape.paths;
  14051. for (var i = 0; i < paths.length; i++) {
  14052. // Mark as dirty if any subpath is dirty
  14053. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14054. }
  14055. this.__dirtyPath = dirtyPath;
  14056. this.__dirty = this.__dirty || dirtyPath;
  14057. },
  14058. beforeBrush: function () {
  14059. this._updatePathDirty();
  14060. var paths = this.shape.paths || [];
  14061. var scale = this.getGlobalScale();
  14062. // Update path scale
  14063. for (var i = 0; i < paths.length; i++) {
  14064. if (!paths[i].path) {
  14065. paths[i].createPathProxy();
  14066. }
  14067. paths[i].path.setScale(scale[0], scale[1]);
  14068. }
  14069. },
  14070. buildPath: function (ctx, shape) {
  14071. var paths = shape.paths || [];
  14072. for (var i = 0; i < paths.length; i++) {
  14073. paths[i].buildPath(ctx, paths[i].shape, true);
  14074. }
  14075. },
  14076. afterBrush: function () {
  14077. var paths = this.shape.paths || [];
  14078. for (var i = 0; i < paths.length; i++) {
  14079. paths[i].__dirtyPath = false;
  14080. }
  14081. },
  14082. getBoundingRect: function () {
  14083. this._updatePathDirty();
  14084. return Path.prototype.getBoundingRect.call(this);
  14085. }
  14086. });
  14087. /**
  14088. * @param {Array.<Object>} colorStops
  14089. */
  14090. var Gradient = function (colorStops) {
  14091. this.colorStops = colorStops || [];
  14092. };
  14093. Gradient.prototype = {
  14094. constructor: Gradient,
  14095. addColorStop: function (offset, color) {
  14096. this.colorStops.push({
  14097. offset: offset,
  14098. color: color
  14099. });
  14100. }
  14101. };
  14102. /**
  14103. * x, y, x2, y2 are all percent from 0 to 1
  14104. * @param {number} [x=0]
  14105. * @param {number} [y=0]
  14106. * @param {number} [x2=1]
  14107. * @param {number} [y2=0]
  14108. * @param {Array.<Object>} colorStops
  14109. * @param {boolean} [globalCoord=false]
  14110. */
  14111. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14112. // Should do nothing more in this constructor. Because gradient can be
  14113. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14114. // this constructor will not be called.
  14115. this.x = x == null ? 0 : x;
  14116. this.y = y == null ? 0 : y;
  14117. this.x2 = x2 == null ? 1 : x2;
  14118. this.y2 = y2 == null ? 0 : y2;
  14119. // Can be cloned
  14120. this.type = 'linear';
  14121. // If use global coord
  14122. this.global = globalCoord || false;
  14123. Gradient.call(this, colorStops);
  14124. };
  14125. LinearGradient.prototype = {
  14126. constructor: LinearGradient
  14127. };
  14128. inherits(LinearGradient, Gradient);
  14129. /**
  14130. * x, y, r are all percent from 0 to 1
  14131. * @param {number} [x=0.5]
  14132. * @param {number} [y=0.5]
  14133. * @param {number} [r=0.5]
  14134. * @param {Array.<Object>} [colorStops]
  14135. * @param {boolean} [globalCoord=false]
  14136. */
  14137. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14138. // Should do nothing more in this constructor. Because gradient can be
  14139. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14140. // this constructor will not be called.
  14141. this.x = x == null ? 0.5 : x;
  14142. this.y = y == null ? 0.5 : y;
  14143. this.r = r == null ? 0.5 : r;
  14144. // Can be cloned
  14145. this.type = 'radial';
  14146. // If use global coord
  14147. this.global = globalCoord || false;
  14148. Gradient.call(this, colorStops);
  14149. };
  14150. RadialGradient.prototype = {
  14151. constructor: RadialGradient
  14152. };
  14153. inherits(RadialGradient, Gradient);
  14154. /**
  14155. * Displayable for incremental rendering. It will be rendered in a separate layer
  14156. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14157. * addDisplayables will render the added displayables incremetally.
  14158. *
  14159. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14160. */
  14161. // TODO Style override ?
  14162. function IncrementalDisplayble(opts) {
  14163. Displayable.call(this, opts);
  14164. this._displayables = [];
  14165. this._temporaryDisplayables = [];
  14166. this._cursor = 0;
  14167. this.notClear = true;
  14168. }
  14169. IncrementalDisplayble.prototype.incremental = true;
  14170. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14171. this._displayables = [];
  14172. this._temporaryDisplayables = [];
  14173. this._cursor = 0;
  14174. this.dirty();
  14175. this.notClear = false;
  14176. };
  14177. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14178. if (notPersistent) {
  14179. this._temporaryDisplayables.push(displayable);
  14180. }
  14181. else {
  14182. this._displayables.push(displayable);
  14183. }
  14184. this.dirty();
  14185. };
  14186. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14187. notPersistent = notPersistent || false;
  14188. for (var i = 0; i < displayables.length; i++) {
  14189. this.addDisplayable(displayables[i], notPersistent);
  14190. }
  14191. };
  14192. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14193. for (var i = this._cursor; i < this._displayables.length; i++) {
  14194. cb && cb(this._displayables[i]);
  14195. }
  14196. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14197. cb && cb(this._temporaryDisplayables[i]);
  14198. }
  14199. };
  14200. IncrementalDisplayble.prototype.update = function () {
  14201. this.updateTransform();
  14202. for (var i = this._cursor; i < this._displayables.length; i++) {
  14203. var displayable = this._displayables[i];
  14204. // PENDING
  14205. displayable.parent = this;
  14206. displayable.update();
  14207. displayable.parent = null;
  14208. }
  14209. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14210. var displayable = this._temporaryDisplayables[i];
  14211. // PENDING
  14212. displayable.parent = this;
  14213. displayable.update();
  14214. displayable.parent = null;
  14215. }
  14216. };
  14217. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14218. // Render persistant displayables.
  14219. for (var i = this._cursor; i < this._displayables.length; i++) {
  14220. var displayable = this._displayables[i];
  14221. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14222. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14223. displayable.afterBrush && displayable.afterBrush(ctx);
  14224. }
  14225. this._cursor = i;
  14226. // Render temporary displayables.
  14227. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14228. var displayable = this._temporaryDisplayables[i];
  14229. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14230. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14231. displayable.afterBrush && displayable.afterBrush(ctx);
  14232. }
  14233. this._temporaryDisplayables = [];
  14234. this.notClear = true;
  14235. };
  14236. var m = [];
  14237. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14238. if (!this._rect) {
  14239. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14240. for (var i = 0; i < this._displayables.length; i++) {
  14241. var displayable = this._displayables[i];
  14242. var childRect = displayable.getBoundingRect().clone();
  14243. if (displayable.needLocalTransform()) {
  14244. childRect.applyTransform(displayable.getLocalTransform(m));
  14245. }
  14246. rect.union(childRect);
  14247. }
  14248. this._rect = rect;
  14249. }
  14250. return this._rect;
  14251. };
  14252. IncrementalDisplayble.prototype.contain = function (x, y) {
  14253. var localPos = this.transformCoordToLocal(x, y);
  14254. var rect = this.getBoundingRect();
  14255. if (rect.contain(localPos[0], localPos[1])) {
  14256. for (var i = 0; i < this._displayables.length; i++) {
  14257. var displayable = this._displayables[i];
  14258. if (displayable.contain(x, y)) {
  14259. return true;
  14260. }
  14261. }
  14262. }
  14263. return false;
  14264. };
  14265. inherits(IncrementalDisplayble, Displayable);
  14266. /*
  14267. * Licensed to the Apache Software Foundation (ASF) under one
  14268. * or more contributor license agreements. See the NOTICE file
  14269. * distributed with this work for additional information
  14270. * regarding copyright ownership. The ASF licenses this file
  14271. * to you under the Apache License, Version 2.0 (the
  14272. * "License"); you may not use this file except in compliance
  14273. * with the License. You may obtain a copy of the License at
  14274. *
  14275. * http://www.apache.org/licenses/LICENSE-2.0
  14276. *
  14277. * Unless required by applicable law or agreed to in writing,
  14278. * software distributed under the License is distributed on an
  14279. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14280. * KIND, either express or implied. See the License for the
  14281. * specific language governing permissions and limitations
  14282. * under the License.
  14283. */
  14284. var round = Math.round;
  14285. var mathMax$1 = Math.max;
  14286. var mathMin$1 = Math.min;
  14287. var EMPTY_OBJ = {};
  14288. var Z2_EMPHASIS_LIFT = 1;
  14289. /**
  14290. * Extend shape with parameters
  14291. */
  14292. function extendShape(opts) {
  14293. return Path.extend(opts);
  14294. }
  14295. /**
  14296. * Extend path
  14297. */
  14298. function extendPath(pathData, opts) {
  14299. return extendFromString(pathData, opts);
  14300. }
  14301. /**
  14302. * Create a path element from path data string
  14303. * @param {string} pathData
  14304. * @param {Object} opts
  14305. * @param {module:zrender/core/BoundingRect} rect
  14306. * @param {string} [layout=cover] 'center' or 'cover'
  14307. */
  14308. function makePath(pathData, opts, rect, layout) {
  14309. var path = createFromString(pathData, opts);
  14310. if (rect) {
  14311. if (layout === 'center') {
  14312. rect = centerGraphic(rect, path.getBoundingRect());
  14313. }
  14314. resizePath(path, rect);
  14315. }
  14316. return path;
  14317. }
  14318. /**
  14319. * Create a image element from image url
  14320. * @param {string} imageUrl image url
  14321. * @param {Object} opts options
  14322. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14323. * @param {string} [layout=cover] 'center' or 'cover'
  14324. */
  14325. function makeImage(imageUrl, rect, layout) {
  14326. var path = new ZImage({
  14327. style: {
  14328. image: imageUrl,
  14329. x: rect.x,
  14330. y: rect.y,
  14331. width: rect.width,
  14332. height: rect.height
  14333. },
  14334. onload: function (img) {
  14335. if (layout === 'center') {
  14336. var boundingRect = {
  14337. width: img.width,
  14338. height: img.height
  14339. };
  14340. path.setStyle(centerGraphic(rect, boundingRect));
  14341. }
  14342. }
  14343. });
  14344. return path;
  14345. }
  14346. /**
  14347. * Get position of centered element in bounding box.
  14348. *
  14349. * @param {Object} rect element local bounding box
  14350. * @param {Object} boundingRect constraint bounding box
  14351. * @return {Object} element position containing x, y, width, and height
  14352. */
  14353. function centerGraphic(rect, boundingRect) {
  14354. // Set rect to center, keep width / height ratio.
  14355. var aspect = boundingRect.width / boundingRect.height;
  14356. var width = rect.height * aspect;
  14357. var height;
  14358. if (width <= rect.width) {
  14359. height = rect.height;
  14360. }
  14361. else {
  14362. width = rect.width;
  14363. height = width / aspect;
  14364. }
  14365. var cx = rect.x + rect.width / 2;
  14366. var cy = rect.y + rect.height / 2;
  14367. return {
  14368. x: cx - width / 2,
  14369. y: cy - height / 2,
  14370. width: width,
  14371. height: height
  14372. };
  14373. }
  14374. var mergePath = mergePath$1;
  14375. /**
  14376. * Resize a path to fit the rect
  14377. * @param {module:zrender/graphic/Path} path
  14378. * @param {Object} rect
  14379. */
  14380. function resizePath(path, rect) {
  14381. if (!path.applyTransform) {
  14382. return;
  14383. }
  14384. var pathRect = path.getBoundingRect();
  14385. var m = pathRect.calculateTransform(rect);
  14386. path.applyTransform(m);
  14387. }
  14388. /**
  14389. * Sub pixel optimize line for canvas
  14390. *
  14391. * @param {Object} param
  14392. * @param {Object} [param.shape]
  14393. * @param {number} [param.shape.x1]
  14394. * @param {number} [param.shape.y1]
  14395. * @param {number} [param.shape.x2]
  14396. * @param {number} [param.shape.y2]
  14397. * @param {Object} [param.style]
  14398. * @param {number} [param.style.lineWidth]
  14399. * @return {Object} Modified param
  14400. */
  14401. function subPixelOptimizeLine(param) {
  14402. var shape = param.shape;
  14403. var lineWidth = param.style.lineWidth;
  14404. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  14405. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  14406. }
  14407. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  14408. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  14409. }
  14410. return param;
  14411. }
  14412. /**
  14413. * Sub pixel optimize rect for canvas
  14414. *
  14415. * @param {Object} param
  14416. * @param {Object} [param.shape]
  14417. * @param {number} [param.shape.x]
  14418. * @param {number} [param.shape.y]
  14419. * @param {number} [param.shape.width]
  14420. * @param {number} [param.shape.height]
  14421. * @param {Object} [param.style]
  14422. * @param {number} [param.style.lineWidth]
  14423. * @return {Object} Modified param
  14424. */
  14425. function subPixelOptimizeRect(param) {
  14426. var shape = param.shape;
  14427. var lineWidth = param.style.lineWidth;
  14428. var originX = shape.x;
  14429. var originY = shape.y;
  14430. var originWidth = shape.width;
  14431. var originHeight = shape.height;
  14432. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  14433. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  14434. shape.width = Math.max(
  14435. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  14436. originWidth === 0 ? 0 : 1
  14437. );
  14438. shape.height = Math.max(
  14439. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  14440. originHeight === 0 ? 0 : 1
  14441. );
  14442. return param;
  14443. }
  14444. /**
  14445. * Sub pixel optimize for canvas
  14446. *
  14447. * @param {number} position Coordinate, such as x, y
  14448. * @param {number} lineWidth Should be nonnegative integer.
  14449. * @param {boolean=} positiveOrNegative Default false (negative).
  14450. * @return {number} Optimized position.
  14451. */
  14452. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  14453. // Assure that (position + lineWidth / 2) is near integer edge,
  14454. // otherwise line will be fuzzy in canvas.
  14455. var doubledPosition = round(position * 2);
  14456. return (doubledPosition + round(lineWidth)) % 2 === 0
  14457. ? doubledPosition / 2
  14458. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14459. }
  14460. function hasFillOrStroke(fillOrStroke) {
  14461. return fillOrStroke != null && fillOrStroke !== 'none';
  14462. }
  14463. // Most lifted color are duplicated.
  14464. var liftedColorMap = createHashMap();
  14465. var liftedColorCount = 0;
  14466. function liftColor(color) {
  14467. if (typeof color !== 'string') {
  14468. return color;
  14469. }
  14470. var liftedColor = liftedColorMap.get(color);
  14471. if (!liftedColor) {
  14472. liftedColor = lift(color, -0.1);
  14473. if (liftedColorCount < 10000) {
  14474. liftedColorMap.set(color, liftedColor);
  14475. liftedColorCount++;
  14476. }
  14477. }
  14478. return liftedColor;
  14479. }
  14480. function cacheElementStl(el) {
  14481. if (!el.__hoverStlDirty) {
  14482. return;
  14483. }
  14484. el.__hoverStlDirty = false;
  14485. var hoverStyle = el.__hoverStl;
  14486. if (!hoverStyle) {
  14487. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  14488. return;
  14489. }
  14490. var normalStyle = el.__cachedNormalStl = {};
  14491. el.__cachedNormalZ2 = el.z2;
  14492. var elStyle = el.style;
  14493. for (var name in hoverStyle) {
  14494. // See comment in `doSingleEnterHover`.
  14495. if (hoverStyle[name] != null) {
  14496. normalStyle[name] = elStyle[name];
  14497. }
  14498. }
  14499. // Always cache fill and stroke to normalStyle for lifting color.
  14500. normalStyle.fill = elStyle.fill;
  14501. normalStyle.stroke = elStyle.stroke;
  14502. }
  14503. function doSingleEnterHover(el) {
  14504. var hoverStl = el.__hoverStl;
  14505. if (!hoverStl || el.__highlighted) {
  14506. return;
  14507. }
  14508. var useHoverLayer = el.useHoverLayer;
  14509. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14510. var zr = el.__zr;
  14511. if (!zr && useHoverLayer) {
  14512. return;
  14513. }
  14514. var elTarget = el;
  14515. var targetStyle = el.style;
  14516. if (useHoverLayer) {
  14517. elTarget = zr.addHover(el);
  14518. targetStyle = elTarget.style;
  14519. }
  14520. rollbackDefaultTextStyle(targetStyle);
  14521. if (!useHoverLayer) {
  14522. cacheElementStl(elTarget);
  14523. }
  14524. // styles can be:
  14525. // {
  14526. // label: {
  14527. // show: false,
  14528. // position: 'outside',
  14529. // fontSize: 18
  14530. // },
  14531. // emphasis: {
  14532. // label: {
  14533. // show: true
  14534. // }
  14535. // }
  14536. // },
  14537. // where properties of `emphasis` may not appear in `normal`. We previously use
  14538. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14539. // But consider rich text and setOption in merge mode, it is impossible to cover
  14540. // all properties in merge. So we use merge mode when setting style here, where
  14541. // only properties that is not `null/undefined` can be set. The disadventage:
  14542. // null/undefined can not be used to remove style any more in `emphasis`.
  14543. targetStyle.extendFrom(hoverStl);
  14544. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14545. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14546. applyDefaultTextStyle(targetStyle);
  14547. if (!useHoverLayer) {
  14548. el.dirty(false);
  14549. el.z2 += Z2_EMPHASIS_LIFT;
  14550. }
  14551. }
  14552. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14553. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14554. targetStyle[prop] = liftColor(targetStyle[prop]);
  14555. }
  14556. }
  14557. function doSingleLeaveHover(el) {
  14558. var highlighted = el.__highlighted;
  14559. if (!highlighted) {
  14560. return;
  14561. }
  14562. el.__highlighted = false;
  14563. if (highlighted === 'layer') {
  14564. el.__zr && el.__zr.removeHover(el);
  14565. }
  14566. else if (highlighted) {
  14567. var style = el.style;
  14568. var normalStl = el.__cachedNormalStl;
  14569. if (normalStl) {
  14570. rollbackDefaultTextStyle(style);
  14571. // Consider null/undefined value, should use
  14572. // `setStyle` but not `extendFrom(stl, true)`.
  14573. el.setStyle(normalStl);
  14574. applyDefaultTextStyle(style);
  14575. }
  14576. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  14577. // when `el` is on emphasis state. So here by comparing with 1, we try
  14578. // hard to make the bug case rare.
  14579. var normalZ2 = el.__cachedNormalZ2;
  14580. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  14581. el.z2 = normalZ2;
  14582. }
  14583. }
  14584. }
  14585. function traverseCall(el, method) {
  14586. el.isGroup
  14587. ? el.traverse(function (child) {
  14588. !child.isGroup && method(child);
  14589. })
  14590. : method(el);
  14591. }
  14592. /**
  14593. * Set hover style (namely "emphasis style") of element, based on the current
  14594. * style of the given `el`.
  14595. * This method should be called after all of the normal styles have been adopted
  14596. * to the `el`. See the reason on `setHoverStyle`.
  14597. *
  14598. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14599. * @param {Object|boolean} [hoverStl] The specified hover style.
  14600. * If set as `false`, disable the hover style.
  14601. * Similarly, The `el.hoverStyle` can alse be set
  14602. * as `false` to disable the hover style.
  14603. * Otherwise, use the default hover style if not provided.
  14604. * @param {Object} [opt]
  14605. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`
  14606. */
  14607. function setElementHoverStyle(el, hoverStl) {
  14608. // For performance consideration, it might be better to make the "hover style" only the
  14609. // difference properties from the "normal style", but not a entire copy of all styles.
  14610. hoverStl = el.__hoverStl = hoverStl !== false && (hoverStl || {});
  14611. el.__hoverStlDirty = true;
  14612. // FIXME
  14613. // It is not completely right to save "normal"/"emphasis" flag on elements.
  14614. // It probably should be saved on `data` of series. Consider the cases:
  14615. // (1) A highlighted elements are moved out of the view port and re-enter
  14616. // again by dataZoom.
  14617. // (2) call `setOption` and replace elements totally when they are highlighted.
  14618. if (el.__highlighted) {
  14619. // Consider the case:
  14620. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  14621. // should be adapted to the `el`. Notice here new "normal styles" should have
  14622. // been set outside and the cached "normal style" is out of date.
  14623. el.__cachedNormalStl = null;
  14624. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  14625. // of this method. In most cases, `z2` is not set and hover style should be able
  14626. // to rollback. Of course, that would bring bug, but only in a rare case, see
  14627. // `doSingleLeaveHover` for details.
  14628. doSingleLeaveHover(el);
  14629. doSingleEnterHover(el);
  14630. }
  14631. }
  14632. /**
  14633. * Emphasis (called by API) has higher priority than `mouseover`.
  14634. * When element has been called to be entered emphasis, mouse over
  14635. * should not trigger the highlight effect (for example, animation
  14636. * scale) again, and `mouseout` should not downplay the highlight
  14637. * effect. So the listener of `mouseover` and `mouseout` should
  14638. * check `isInEmphasis`.
  14639. *
  14640. * @param {module:zrender/Element} el
  14641. * @return {boolean}
  14642. */
  14643. function isInEmphasis(el) {
  14644. return el && el.__isEmphasisEntered;
  14645. }
  14646. function onElementMouseOver(e) {
  14647. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14648. return;
  14649. }
  14650. // Only if element is not in emphasis status
  14651. !this.__isEmphasisEntered && traverseCall(this, doSingleEnterHover);
  14652. }
  14653. function onElementMouseOut(e) {
  14654. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14655. return;
  14656. }
  14657. // Only if element is not in emphasis status
  14658. !this.__isEmphasisEntered && traverseCall(this, doSingleLeaveHover);
  14659. }
  14660. function enterEmphasis() {
  14661. this.__isEmphasisEntered = true;
  14662. traverseCall(this, doSingleEnterHover);
  14663. }
  14664. function leaveEmphasis() {
  14665. this.__isEmphasisEntered = false;
  14666. traverseCall(this, doSingleLeaveHover);
  14667. }
  14668. /**
  14669. * Set hover style (namely "emphasis style") of element,
  14670. * based on the current style of the given `el`.
  14671. *
  14672. * (1)
  14673. * **CONSTRAINTS** for this method:
  14674. * <A> This method MUST be called after all of the normal styles having been adopted
  14675. * to the `el`.
  14676. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  14677. * "normal style" having been set to the el.
  14678. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  14679. * a default hover style).
  14680. *
  14681. * The reason: this method treat the current style of the `el` as the "normal style"
  14682. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  14683. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  14684. * logic, where the el should shift from the original emphasis style to the new
  14685. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  14686. *
  14687. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  14688. * not found a better solution yet to fit the backward compatibility, performance and
  14689. * the current programming style.
  14690. *
  14691. * (2)
  14692. * Call the method for a "root" element once. Do not call it for each descendants.
  14693. * If the descendants elemenets of a group has itself hover style different from the
  14694. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  14695. * not call this method for them.
  14696. *
  14697. * @param {module:zrender/Element} el
  14698. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  14699. * @param {Object} [opt]
  14700. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`.
  14701. */
  14702. function setHoverStyle(el, hoverStyle, opt) {
  14703. el.isGroup
  14704. ? el.traverse(function (child) {
  14705. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14706. // Often used when item group has a label element and it's hoverStyle is different
  14707. !child.isGroup && setElementHoverStyle(child, child.hoverStyle || hoverStyle);
  14708. })
  14709. : setElementHoverStyle(el, el.hoverStyle || hoverStyle);
  14710. setAsHoverStyleTrigger(el, opt);
  14711. }
  14712. /**
  14713. * @param {Object|boolean} [opt] If `false`, means disable trigger.
  14714. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14715. * In touch device, mouseover event will be trigger on touchstart event
  14716. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14717. * conveniently use hoverStyle when tap on touch screen without additional
  14718. * code for compatibility.
  14719. * But if the chart/component has select feature, which usually also use
  14720. * hoverStyle, there might be conflict between 'select-highlight' and
  14721. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14722. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14723. * on touch device.
  14724. */
  14725. function setAsHoverStyleTrigger(el, opt) {
  14726. var disable = opt === false;
  14727. el.__hoverSilentOnTouch = opt != null && opt.hoverSilentOnTouch;
  14728. // Simple optimize, since this method might be
  14729. // called for each elements of a group in some cases.
  14730. if (!disable || el.__hoverStyleTrigger) {
  14731. var method = disable ? 'off' : 'on';
  14732. // Duplicated function will be auto-ignored, see Eventful.js.
  14733. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  14734. // Emphasis, normal can be triggered manually
  14735. el[method]('emphasis', enterEmphasis)[method]('normal', leaveEmphasis);
  14736. el.__hoverStyleTrigger = !disable;
  14737. }
  14738. }
  14739. /**
  14740. * See more info in `setTextStyleCommon`.
  14741. * @param {Object|module:zrender/graphic/Style} normalStyle
  14742. * @param {Object} emphasisStyle
  14743. * @param {module:echarts/model/Model} normalModel
  14744. * @param {module:echarts/model/Model} emphasisModel
  14745. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14746. * @param {string|Function} [opt.defaultText]
  14747. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14748. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14749. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14750. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14751. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14752. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14753. * @param {Object} [normalSpecified]
  14754. * @param {Object} [emphasisSpecified]
  14755. */
  14756. function setLabelStyle(
  14757. normalStyle, emphasisStyle,
  14758. normalModel, emphasisModel,
  14759. opt,
  14760. normalSpecified, emphasisSpecified
  14761. ) {
  14762. opt = opt || EMPTY_OBJ;
  14763. var labelFetcher = opt.labelFetcher;
  14764. var labelDataIndex = opt.labelDataIndex;
  14765. var labelDimIndex = opt.labelDimIndex;
  14766. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14767. // is not supported util someone requests.
  14768. var showNormal = normalModel.getShallow('show');
  14769. var showEmphasis = emphasisModel.getShallow('show');
  14770. // Consider performance, only fetch label when necessary.
  14771. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14772. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14773. var baseText;
  14774. if (showNormal || showEmphasis) {
  14775. if (labelFetcher) {
  14776. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14777. }
  14778. if (baseText == null) {
  14779. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14780. }
  14781. }
  14782. var normalStyleText = showNormal ? baseText : null;
  14783. var emphasisStyleText = showEmphasis
  14784. ? retrieve2(
  14785. labelFetcher
  14786. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14787. : null,
  14788. baseText
  14789. )
  14790. : null;
  14791. // Optimize: If style.text is null, text will not be drawn.
  14792. if (normalStyleText != null || emphasisStyleText != null) {
  14793. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14794. // values have to be set on `normalStyle`.
  14795. // If we set default values on `emphasisStyle`, consider case:
  14796. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14797. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14798. // Then the 'red' will not work on emphasis.
  14799. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14800. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14801. }
  14802. normalStyle.text = normalStyleText;
  14803. emphasisStyle.text = emphasisStyleText;
  14804. }
  14805. /**
  14806. * Set basic textStyle properties.
  14807. * See more info in `setTextStyleCommon`.
  14808. * @param {Object|module:zrender/graphic/Style} textStyle
  14809. * @param {module:echarts/model/Model} model
  14810. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14811. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14812. * @param {boolean} [isEmphasis]
  14813. */
  14814. function setTextStyle(
  14815. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14816. ) {
  14817. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14818. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14819. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14820. return textStyle;
  14821. }
  14822. /**
  14823. * Set text option in the style.
  14824. * See more info in `setTextStyleCommon`.
  14825. * @deprecated
  14826. * @param {Object} textStyle
  14827. * @param {module:echarts/model/Model} labelModel
  14828. * @param {string|boolean} defaultColor Default text color.
  14829. * If set as false, it will be processed as a emphasis style.
  14830. */
  14831. function setText(textStyle, labelModel, defaultColor) {
  14832. var opt = {isRectText: true};
  14833. var isEmphasis;
  14834. if (defaultColor === false) {
  14835. isEmphasis = true;
  14836. }
  14837. else {
  14838. // Support setting color as 'auto' to get visual color.
  14839. opt.autoColor = defaultColor;
  14840. }
  14841. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14842. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14843. }
  14844. /**
  14845. * The uniform entry of set text style, that is, retrieve style definitions
  14846. * from `model` and set to `textStyle` object.
  14847. *
  14848. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14849. * properties will be set. (Consider the states of normal and emphasis and
  14850. * default value can be adopted, merge would make the logic too complicated
  14851. * to manage.)
  14852. *
  14853. * The `textStyle` object can either be a plain object or an instance of
  14854. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  14855. * After this mothod called, the `textStyle` object can then be used in
  14856. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  14857. *
  14858. * Default value will be adopted and `insideRollbackOpt` will be created.
  14859. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  14860. *
  14861. * opt: {
  14862. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14863. * isRectText: boolean,
  14864. * autoColor: string, specify a color when color is 'auto',
  14865. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14866. * If autoColor specified, it is used as default textFill.
  14867. * useInsideStyle:
  14868. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14869. * if `textFill` is not specified.
  14870. * `false`: Do not use inside style.
  14871. * `null/undefined`: use inside style if `isRectText` is true and
  14872. * `textFill` is not specified and textPosition contains `'inside'`.
  14873. * forceRich: boolean
  14874. * }
  14875. */
  14876. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14877. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14878. opt = opt || EMPTY_OBJ;
  14879. if (opt.isRectText) {
  14880. var textPosition = textStyleModel.getShallow('position')
  14881. || (isEmphasis ? null : 'inside');
  14882. // 'outside' is not a valid zr textPostion value, but used
  14883. // in bar series, and magric type should be considered.
  14884. textPosition === 'outside' && (textPosition = 'top');
  14885. textStyle.textPosition = textPosition;
  14886. textStyle.textOffset = textStyleModel.getShallow('offset');
  14887. var labelRotate = textStyleModel.getShallow('rotate');
  14888. labelRotate != null && (labelRotate *= Math.PI / 180);
  14889. textStyle.textRotation = labelRotate;
  14890. textStyle.textDistance = retrieve2(
  14891. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14892. );
  14893. }
  14894. var ecModel = textStyleModel.ecModel;
  14895. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14896. // Consider case:
  14897. // {
  14898. // data: [{
  14899. // value: 12,
  14900. // label: {
  14901. // rich: {
  14902. // // no 'a' here but using parent 'a'.
  14903. // }
  14904. // }
  14905. // }],
  14906. // rich: {
  14907. // a: { ... }
  14908. // }
  14909. // }
  14910. var richItemNames = getRichItemNames(textStyleModel);
  14911. var richResult;
  14912. if (richItemNames) {
  14913. richResult = {};
  14914. for (var name in richItemNames) {
  14915. if (richItemNames.hasOwnProperty(name)) {
  14916. // Cascade is supported in rich.
  14917. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14918. // In rich, never `disableBox`.
  14919. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14920. }
  14921. }
  14922. }
  14923. textStyle.rich = richResult;
  14924. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14925. if (opt.forceRich && !opt.textStyle) {
  14926. opt.textStyle = {};
  14927. }
  14928. return textStyle;
  14929. }
  14930. // Consider case:
  14931. // {
  14932. // data: [{
  14933. // value: 12,
  14934. // label: {
  14935. // rich: {
  14936. // // no 'a' here but using parent 'a'.
  14937. // }
  14938. // }
  14939. // }],
  14940. // rich: {
  14941. // a: { ... }
  14942. // }
  14943. // }
  14944. function getRichItemNames(textStyleModel) {
  14945. // Use object to remove duplicated names.
  14946. var richItemNameMap;
  14947. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14948. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14949. if (rich) {
  14950. richItemNameMap = richItemNameMap || {};
  14951. for (var name in rich) {
  14952. if (rich.hasOwnProperty(name)) {
  14953. richItemNameMap[name] = 1;
  14954. }
  14955. }
  14956. }
  14957. textStyleModel = textStyleModel.parentModel;
  14958. }
  14959. return richItemNameMap;
  14960. }
  14961. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14962. // In merge mode, default value should not be given.
  14963. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14964. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14965. || globalTextStyle.color;
  14966. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14967. || globalTextStyle.textBorderColor;
  14968. textStyle.textStrokeWidth = retrieve2(
  14969. textStyleModel.getShallow('textBorderWidth'),
  14970. globalTextStyle.textBorderWidth
  14971. );
  14972. // Save original textPosition, because style.textPosition will be repalced by
  14973. // real location (like [10, 30]) in zrender.
  14974. textStyle.insideRawTextPosition = textStyle.textPosition;
  14975. if (!isEmphasis) {
  14976. if (isBlock) {
  14977. textStyle.insideRollbackOpt = opt;
  14978. applyDefaultTextStyle(textStyle);
  14979. }
  14980. // Set default finally.
  14981. if (textStyle.textFill == null) {
  14982. textStyle.textFill = opt.autoColor;
  14983. }
  14984. }
  14985. // Do not use `getFont` here, because merge should be supported, where
  14986. // part of these properties may be changed in emphasis style, and the
  14987. // others should remain their original value got from normal style.
  14988. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14989. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14990. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14991. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14992. textStyle.textAlign = textStyleModel.getShallow('align');
  14993. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14994. || textStyleModel.getShallow('baseline');
  14995. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14996. textStyle.textWidth = textStyleModel.getShallow('width');
  14997. textStyle.textHeight = textStyleModel.getShallow('height');
  14998. textStyle.textTag = textStyleModel.getShallow('tag');
  14999. if (!isBlock || !opt.disableBox) {
  15000. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15001. textStyle.textPadding = textStyleModel.getShallow('padding');
  15002. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15003. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15004. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15005. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15006. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15007. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15008. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15009. }
  15010. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15011. || globalTextStyle.textShadowColor;
  15012. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15013. || globalTextStyle.textShadowBlur;
  15014. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15015. || globalTextStyle.textShadowOffsetX;
  15016. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15017. || globalTextStyle.textShadowOffsetY;
  15018. }
  15019. function getAutoColor(color, opt) {
  15020. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15021. }
  15022. /**
  15023. * Give some default value to the input `textStyle` object, based on the current settings
  15024. * in this `textStyle` object.
  15025. *
  15026. * The Scenario:
  15027. * when text position is `inside` and `textFill` is not specified, we show
  15028. * text border by default for better view. But it should be considered that text position
  15029. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15030. * restore the style.
  15031. *
  15032. * Usage (& NOTICE):
  15033. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15034. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15035. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15036. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15037. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15038. */
  15039. function applyDefaultTextStyle(textStyle) {
  15040. var opt = textStyle.insideRollbackOpt;
  15041. // Only `insideRollbackOpt` created (in `setTextStyleCommon`),
  15042. // applyDefaultTextStyle works.
  15043. if (!opt || textStyle.textFill != null) {
  15044. return;
  15045. }
  15046. var useInsideStyle = opt.useInsideStyle;
  15047. var textPosition = textStyle.insideRawTextPosition;
  15048. var insideRollback;
  15049. var autoColor = opt.autoColor;
  15050. if (useInsideStyle !== false
  15051. && (useInsideStyle === true
  15052. || (opt.isRectText
  15053. && textPosition
  15054. // textPosition can be [10, 30]
  15055. && typeof textPosition === 'string'
  15056. && textPosition.indexOf('inside') >= 0
  15057. )
  15058. )
  15059. ) {
  15060. insideRollback = {
  15061. textFill: null,
  15062. textStroke: textStyle.textStroke,
  15063. textStrokeWidth: textStyle.textStrokeWidth
  15064. };
  15065. textStyle.textFill = '#fff';
  15066. // Consider text with #fff overflow its container.
  15067. if (textStyle.textStroke == null) {
  15068. textStyle.textStroke = autoColor;
  15069. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15070. }
  15071. }
  15072. else if (autoColor != null) {
  15073. insideRollback = {textFill: null};
  15074. textStyle.textFill = autoColor;
  15075. }
  15076. // Always set `insideRollback`, for clearing previous.
  15077. if (insideRollback) {
  15078. textStyle.insideRollback = insideRollback;
  15079. }
  15080. }
  15081. /**
  15082. * Consider the case: in a scatter,
  15083. * label: {
  15084. * normal: {position: 'inside'},
  15085. * emphasis: {position: 'top'}
  15086. * }
  15087. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15088. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15089. * should be retured to 'autoColor', but not keep '#fff'.
  15090. */
  15091. function rollbackDefaultTextStyle(style) {
  15092. var insideRollback = style.insideRollback;
  15093. if (insideRollback) {
  15094. style.textFill = insideRollback.textFill;
  15095. style.textStroke = insideRollback.textStroke;
  15096. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15097. style.insideRollback = null;
  15098. }
  15099. }
  15100. function getFont(opt, ecModel) {
  15101. // ecModel or default text style model.
  15102. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  15103. return trim([
  15104. // FIXME in node-canvas fontWeight is before fontStyle
  15105. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15106. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15107. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15108. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15109. ].join(' '));
  15110. }
  15111. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15112. if (typeof dataIndex === 'function') {
  15113. cb = dataIndex;
  15114. dataIndex = null;
  15115. }
  15116. // Do not check 'animation' property directly here. Consider this case:
  15117. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15118. // but its parent model (`seriesModel`) does.
  15119. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15120. if (animationEnabled) {
  15121. var postfix = isUpdate ? 'Update' : '';
  15122. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15123. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15124. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15125. if (typeof animationDelay === 'function') {
  15126. animationDelay = animationDelay(
  15127. dataIndex,
  15128. animatableModel.getAnimationDelayParams
  15129. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15130. : null
  15131. );
  15132. }
  15133. if (typeof duration === 'function') {
  15134. duration = duration(dataIndex);
  15135. }
  15136. duration > 0
  15137. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15138. : (el.stopAnimation(), el.attr(props), cb && cb());
  15139. }
  15140. else {
  15141. el.stopAnimation();
  15142. el.attr(props);
  15143. cb && cb();
  15144. }
  15145. }
  15146. /**
  15147. * Update graphic element properties with or without animation according to the
  15148. * configuration in series.
  15149. *
  15150. * Caution: this method will stop previous animation.
  15151. * So if do not use this method to one element twice before
  15152. * animation starts, unless you know what you are doing.
  15153. *
  15154. * @param {module:zrender/Element} el
  15155. * @param {Object} props
  15156. * @param {module:echarts/model/Model} [animatableModel]
  15157. * @param {number} [dataIndex]
  15158. * @param {Function} [cb]
  15159. * @example
  15160. * graphic.updateProps(el, {
  15161. * position: [100, 100]
  15162. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15163. * // Or
  15164. * graphic.updateProps(el, {
  15165. * position: [100, 100]
  15166. * }, seriesModel, function () { console.log('Animation done!'); });
  15167. */
  15168. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15169. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15170. }
  15171. /**
  15172. * Init graphic element properties with or without animation according to the
  15173. * configuration in series.
  15174. *
  15175. * Caution: this method will stop previous animation.
  15176. * So if do not use this method to one element twice before
  15177. * animation starts, unless you know what you are doing.
  15178. *
  15179. * @param {module:zrender/Element} el
  15180. * @param {Object} props
  15181. * @param {module:echarts/model/Model} [animatableModel]
  15182. * @param {number} [dataIndex]
  15183. * @param {Function} cb
  15184. */
  15185. function initProps(el, props, animatableModel, dataIndex, cb) {
  15186. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15187. }
  15188. /**
  15189. * Get transform matrix of target (param target),
  15190. * in coordinate of its ancestor (param ancestor)
  15191. *
  15192. * @param {module:zrender/mixin/Transformable} target
  15193. * @param {module:zrender/mixin/Transformable} [ancestor]
  15194. */
  15195. function getTransform(target, ancestor) {
  15196. var mat = identity([]);
  15197. while (target && target !== ancestor) {
  15198. mul$1(mat, target.getLocalTransform(), mat);
  15199. target = target.parent;
  15200. }
  15201. return mat;
  15202. }
  15203. /**
  15204. * Apply transform to an vertex.
  15205. * @param {Array.<number>} target [x, y]
  15206. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15207. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15208. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15209. * @param {boolean=} invert Whether use invert matrix.
  15210. * @return {Array.<number>} [x, y]
  15211. */
  15212. function applyTransform$1(target, transform, invert$$1) {
  15213. if (transform && !isArrayLike(transform)) {
  15214. transform = Transformable.getLocalTransform(transform);
  15215. }
  15216. if (invert$$1) {
  15217. transform = invert([], transform);
  15218. }
  15219. return applyTransform([], target, transform);
  15220. }
  15221. /**
  15222. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15223. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15224. * @param {boolean=} invert Whether use invert matrix.
  15225. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15226. */
  15227. function transformDirection(direction, transform, invert$$1) {
  15228. // Pick a base, ensure that transform result will not be (0, 0).
  15229. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  15230. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  15231. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  15232. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  15233. var vertex = [
  15234. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  15235. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  15236. ];
  15237. vertex = applyTransform$1(vertex, transform, invert$$1);
  15238. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  15239. ? (vertex[0] > 0 ? 'right' : 'left')
  15240. : (vertex[1] > 0 ? 'bottom' : 'top');
  15241. }
  15242. /**
  15243. * Apply group transition animation from g1 to g2.
  15244. * If no animatableModel, no animation.
  15245. */
  15246. function groupTransition(g1, g2, animatableModel, cb) {
  15247. if (!g1 || !g2) {
  15248. return;
  15249. }
  15250. function getElMap(g) {
  15251. var elMap = {};
  15252. g.traverse(function (el) {
  15253. if (!el.isGroup && el.anid) {
  15254. elMap[el.anid] = el;
  15255. }
  15256. });
  15257. return elMap;
  15258. }
  15259. function getAnimatableProps(el) {
  15260. var obj = {
  15261. position: clone$1(el.position),
  15262. rotation: el.rotation
  15263. };
  15264. if (el.shape) {
  15265. obj.shape = extend({}, el.shape);
  15266. }
  15267. return obj;
  15268. }
  15269. var elMap1 = getElMap(g1);
  15270. g2.traverse(function (el) {
  15271. if (!el.isGroup && el.anid) {
  15272. var oldEl = elMap1[el.anid];
  15273. if (oldEl) {
  15274. var newProp = getAnimatableProps(el);
  15275. el.attr(getAnimatableProps(oldEl));
  15276. updateProps(el, newProp, animatableModel, el.dataIndex);
  15277. }
  15278. // else {
  15279. // if (el.previousProps) {
  15280. // graphic.updateProps
  15281. // }
  15282. // }
  15283. }
  15284. });
  15285. }
  15286. /**
  15287. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15288. * @param {Object} rect {x, y, width, height}
  15289. * @return {Array.<Array.<number>>} A new clipped points.
  15290. */
  15291. function clipPointsByRect(points, rect) {
  15292. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  15293. // and when element have border.
  15294. return map(points, function (point) {
  15295. var x = point[0];
  15296. x = mathMax$1(x, rect.x);
  15297. x = mathMin$1(x, rect.x + rect.width);
  15298. var y = point[1];
  15299. y = mathMax$1(y, rect.y);
  15300. y = mathMin$1(y, rect.y + rect.height);
  15301. return [x, y];
  15302. });
  15303. }
  15304. /**
  15305. * @param {Object} targetRect {x, y, width, height}
  15306. * @param {Object} rect {x, y, width, height}
  15307. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  15308. */
  15309. function clipRectByRect(targetRect, rect) {
  15310. var x = mathMax$1(targetRect.x, rect.x);
  15311. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  15312. var y = mathMax$1(targetRect.y, rect.y);
  15313. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  15314. // If the total rect is cliped, nothing, including the border,
  15315. // should be painted. So return undefined.
  15316. if (x2 >= x && y2 >= y) {
  15317. return {
  15318. x: x,
  15319. y: y,
  15320. width: x2 - x,
  15321. height: y2 - y
  15322. };
  15323. }
  15324. }
  15325. /**
  15326. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  15327. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  15328. * @param {Object} [rect] {x, y, width, height}
  15329. * @return {module:zrender/Element} Icon path or image element.
  15330. */
  15331. function createIcon(iconStr, opt, rect) {
  15332. opt = extend({rectHover: true}, opt);
  15333. var style = opt.style = {strokeNoScale: true};
  15334. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  15335. if (iconStr) {
  15336. return iconStr.indexOf('image://') === 0
  15337. ? (
  15338. style.image = iconStr.slice(8),
  15339. defaults(style, rect),
  15340. new ZImage(opt)
  15341. )
  15342. : (
  15343. makePath(
  15344. iconStr.replace('path://', ''),
  15345. opt,
  15346. rect,
  15347. 'center'
  15348. )
  15349. );
  15350. }
  15351. }
  15352. var graphic = (Object.freeze || Object)({
  15353. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  15354. extendShape: extendShape,
  15355. extendPath: extendPath,
  15356. makePath: makePath,
  15357. makeImage: makeImage,
  15358. mergePath: mergePath,
  15359. resizePath: resizePath,
  15360. subPixelOptimizeLine: subPixelOptimizeLine,
  15361. subPixelOptimizeRect: subPixelOptimizeRect,
  15362. subPixelOptimize: subPixelOptimize,
  15363. setElementHoverStyle: setElementHoverStyle,
  15364. isInEmphasis: isInEmphasis,
  15365. setHoverStyle: setHoverStyle,
  15366. setAsHoverStyleTrigger: setAsHoverStyleTrigger,
  15367. setLabelStyle: setLabelStyle,
  15368. setTextStyle: setTextStyle,
  15369. setText: setText,
  15370. getFont: getFont,
  15371. updateProps: updateProps,
  15372. initProps: initProps,
  15373. getTransform: getTransform,
  15374. applyTransform: applyTransform$1,
  15375. transformDirection: transformDirection,
  15376. groupTransition: groupTransition,
  15377. clipPointsByRect: clipPointsByRect,
  15378. clipRectByRect: clipRectByRect,
  15379. createIcon: createIcon,
  15380. Group: Group,
  15381. Image: ZImage,
  15382. Text: Text,
  15383. Circle: Circle,
  15384. Sector: Sector,
  15385. Ring: Ring,
  15386. Polygon: Polygon,
  15387. Polyline: Polyline,
  15388. Rect: Rect,
  15389. Line: Line,
  15390. BezierCurve: BezierCurve,
  15391. Arc: Arc,
  15392. IncrementalDisplayable: IncrementalDisplayble,
  15393. CompoundPath: CompoundPath,
  15394. LinearGradient: LinearGradient,
  15395. RadialGradient: RadialGradient,
  15396. BoundingRect: BoundingRect
  15397. });
  15398. /*
  15399. * Licensed to the Apache Software Foundation (ASF) under one
  15400. * or more contributor license agreements. See the NOTICE file
  15401. * distributed with this work for additional information
  15402. * regarding copyright ownership. The ASF licenses this file
  15403. * to you under the Apache License, Version 2.0 (the
  15404. * "License"); you may not use this file except in compliance
  15405. * with the License. You may obtain a copy of the License at
  15406. *
  15407. * http://www.apache.org/licenses/LICENSE-2.0
  15408. *
  15409. * Unless required by applicable law or agreed to in writing,
  15410. * software distributed under the License is distributed on an
  15411. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15412. * KIND, either express or implied. See the License for the
  15413. * specific language governing permissions and limitations
  15414. * under the License.
  15415. */
  15416. var PATH_COLOR = ['textStyle', 'color'];
  15417. var textStyleMixin = {
  15418. /**
  15419. * Get color property or get color from option.textStyle.color
  15420. * @param {boolean} [isEmphasis]
  15421. * @return {string}
  15422. */
  15423. getTextColor: function (isEmphasis) {
  15424. var ecModel = this.ecModel;
  15425. return this.getShallow('color')
  15426. || (
  15427. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  15428. );
  15429. },
  15430. /**
  15431. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15432. * @return {string}
  15433. */
  15434. getFont: function () {
  15435. return getFont({
  15436. fontStyle: this.getShallow('fontStyle'),
  15437. fontWeight: this.getShallow('fontWeight'),
  15438. fontSize: this.getShallow('fontSize'),
  15439. fontFamily: this.getShallow('fontFamily')
  15440. }, this.ecModel);
  15441. },
  15442. getTextRect: function (text) {
  15443. return getBoundingRect(
  15444. text,
  15445. this.getFont(),
  15446. this.getShallow('align'),
  15447. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  15448. this.getShallow('padding'),
  15449. this.getShallow('lineHeight'),
  15450. this.getShallow('rich'),
  15451. this.getShallow('truncateText')
  15452. );
  15453. }
  15454. };
  15455. /*
  15456. * Licensed to the Apache Software Foundation (ASF) under one
  15457. * or more contributor license agreements. See the NOTICE file
  15458. * distributed with this work for additional information
  15459. * regarding copyright ownership. The ASF licenses this file
  15460. * to you under the Apache License, Version 2.0 (the
  15461. * "License"); you may not use this file except in compliance
  15462. * with the License. You may obtain a copy of the License at
  15463. *
  15464. * http://www.apache.org/licenses/LICENSE-2.0
  15465. *
  15466. * Unless required by applicable law or agreed to in writing,
  15467. * software distributed under the License is distributed on an
  15468. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15469. * KIND, either express or implied. See the License for the
  15470. * specific language governing permissions and limitations
  15471. * under the License.
  15472. */
  15473. var getItemStyle = makeStyleMapper(
  15474. [
  15475. ['fill', 'color'],
  15476. ['stroke', 'borderColor'],
  15477. ['lineWidth', 'borderWidth'],
  15478. ['opacity'],
  15479. ['shadowBlur'],
  15480. ['shadowOffsetX'],
  15481. ['shadowOffsetY'],
  15482. ['shadowColor'],
  15483. ['textPosition'],
  15484. ['textAlign']
  15485. ]
  15486. );
  15487. var itemStyleMixin = {
  15488. getItemStyle: function (excludes, includes) {
  15489. var style = getItemStyle(this, excludes, includes);
  15490. var lineDash = this.getBorderLineDash();
  15491. lineDash && (style.lineDash = lineDash);
  15492. return style;
  15493. },
  15494. getBorderLineDash: function () {
  15495. var lineType = this.get('borderType');
  15496. return (lineType === 'solid' || lineType == null) ? null
  15497. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  15498. }
  15499. };
  15500. /*
  15501. * Licensed to the Apache Software Foundation (ASF) under one
  15502. * or more contributor license agreements. See the NOTICE file
  15503. * distributed with this work for additional information
  15504. * regarding copyright ownership. The ASF licenses this file
  15505. * to you under the Apache License, Version 2.0 (the
  15506. * "License"); you may not use this file except in compliance
  15507. * with the License. You may obtain a copy of the License at
  15508. *
  15509. * http://www.apache.org/licenses/LICENSE-2.0
  15510. *
  15511. * Unless required by applicable law or agreed to in writing,
  15512. * software distributed under the License is distributed on an
  15513. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15514. * KIND, either express or implied. See the License for the
  15515. * specific language governing permissions and limitations
  15516. * under the License.
  15517. */
  15518. /**
  15519. * @module echarts/model/Model
  15520. */
  15521. var mixin$1 = mixin;
  15522. var inner = makeInner();
  15523. /**
  15524. * @alias module:echarts/model/Model
  15525. * @constructor
  15526. * @param {Object} [option]
  15527. * @param {module:echarts/model/Model} [parentModel]
  15528. * @param {module:echarts/model/Global} [ecModel]
  15529. */
  15530. function Model(option, parentModel, ecModel) {
  15531. /**
  15532. * @type {module:echarts/model/Model}
  15533. * @readOnly
  15534. */
  15535. this.parentModel = parentModel;
  15536. /**
  15537. * @type {module:echarts/model/Global}
  15538. * @readOnly
  15539. */
  15540. this.ecModel = ecModel;
  15541. /**
  15542. * @type {Object}
  15543. * @protected
  15544. */
  15545. this.option = option;
  15546. // Simple optimization
  15547. // if (this.init) {
  15548. // if (arguments.length <= 4) {
  15549. // this.init(option, parentModel, ecModel, extraOpt);
  15550. // }
  15551. // else {
  15552. // this.init.apply(this, arguments);
  15553. // }
  15554. // }
  15555. }
  15556. Model.prototype = {
  15557. constructor: Model,
  15558. /**
  15559. * Model 的初始化函数
  15560. * @param {Object} option
  15561. */
  15562. init: null,
  15563. /**
  15564. * 从新的 Option merge
  15565. */
  15566. mergeOption: function (option) {
  15567. merge(this.option, option, true);
  15568. },
  15569. /**
  15570. * @param {string|Array.<string>} path
  15571. * @param {boolean} [ignoreParent=false]
  15572. * @return {*}
  15573. */
  15574. get: function (path, ignoreParent) {
  15575. if (path == null) {
  15576. return this.option;
  15577. }
  15578. return doGet(
  15579. this.option,
  15580. this.parsePath(path),
  15581. !ignoreParent && getParent(this, path)
  15582. );
  15583. },
  15584. /**
  15585. * @param {string} key
  15586. * @param {boolean} [ignoreParent=false]
  15587. * @return {*}
  15588. */
  15589. getShallow: function (key, ignoreParent) {
  15590. var option = this.option;
  15591. var val = option == null ? option : option[key];
  15592. var parentModel = !ignoreParent && getParent(this, key);
  15593. if (val == null && parentModel) {
  15594. val = parentModel.getShallow(key);
  15595. }
  15596. return val;
  15597. },
  15598. /**
  15599. * @param {string|Array.<string>} [path]
  15600. * @param {module:echarts/model/Model} [parentModel]
  15601. * @return {module:echarts/model/Model}
  15602. */
  15603. getModel: function (path, parentModel) {
  15604. var obj = path == null
  15605. ? this.option
  15606. : doGet(this.option, path = this.parsePath(path));
  15607. var thisParentModel;
  15608. parentModel = parentModel || (
  15609. (thisParentModel = getParent(this, path))
  15610. && thisParentModel.getModel(path)
  15611. );
  15612. return new Model(obj, parentModel, this.ecModel);
  15613. },
  15614. /**
  15615. * If model has option
  15616. */
  15617. isEmpty: function () {
  15618. return this.option == null;
  15619. },
  15620. restoreData: function () {},
  15621. // Pending
  15622. clone: function () {
  15623. var Ctor = this.constructor;
  15624. return new Ctor(clone(this.option));
  15625. },
  15626. setReadOnly: function (properties) {
  15627. // clazzUtil.setReadOnly(this, properties);
  15628. },
  15629. // If path is null/undefined, return null/undefined.
  15630. parsePath: function (path) {
  15631. if (typeof path === 'string') {
  15632. path = path.split('.');
  15633. }
  15634. return path;
  15635. },
  15636. /**
  15637. * @param {Function} getParentMethod
  15638. * param {Array.<string>|string} path
  15639. * return {module:echarts/model/Model}
  15640. */
  15641. customizeGetParent: function (getParentMethod) {
  15642. inner(this).getParent = getParentMethod;
  15643. },
  15644. isAnimationEnabled: function () {
  15645. if (!env$1.node) {
  15646. if (this.option.animation != null) {
  15647. return !!this.option.animation;
  15648. }
  15649. else if (this.parentModel) {
  15650. return this.parentModel.isAnimationEnabled();
  15651. }
  15652. }
  15653. }
  15654. };
  15655. function doGet(obj, pathArr, parentModel) {
  15656. for (var i = 0; i < pathArr.length; i++) {
  15657. // Ignore empty
  15658. if (!pathArr[i]) {
  15659. continue;
  15660. }
  15661. // obj could be number/string/... (like 0)
  15662. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  15663. if (obj == null) {
  15664. break;
  15665. }
  15666. }
  15667. if (obj == null && parentModel) {
  15668. obj = parentModel.get(pathArr);
  15669. }
  15670. return obj;
  15671. }
  15672. // `path` can be null/undefined
  15673. function getParent(model, path) {
  15674. var getParentMethod = inner(model).getParent;
  15675. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15676. }
  15677. // Enable Model.extend.
  15678. enableClassExtend(Model);
  15679. enableClassCheck(Model);
  15680. mixin$1(Model, lineStyleMixin);
  15681. mixin$1(Model, areaStyleMixin);
  15682. mixin$1(Model, textStyleMixin);
  15683. mixin$1(Model, itemStyleMixin);
  15684. /*
  15685. * Licensed to the Apache Software Foundation (ASF) under one
  15686. * or more contributor license agreements. See the NOTICE file
  15687. * distributed with this work for additional information
  15688. * regarding copyright ownership. The ASF licenses this file
  15689. * to you under the Apache License, Version 2.0 (the
  15690. * "License"); you may not use this file except in compliance
  15691. * with the License. You may obtain a copy of the License at
  15692. *
  15693. * http://www.apache.org/licenses/LICENSE-2.0
  15694. *
  15695. * Unless required by applicable law or agreed to in writing,
  15696. * software distributed under the License is distributed on an
  15697. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15698. * KIND, either express or implied. See the License for the
  15699. * specific language governing permissions and limitations
  15700. * under the License.
  15701. */
  15702. var base = 0;
  15703. /**
  15704. * @public
  15705. * @param {string} type
  15706. * @return {string}
  15707. */
  15708. function getUID(type) {
  15709. // Considering the case of crossing js context,
  15710. // use Math.random to make id as unique as possible.
  15711. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  15712. }
  15713. /**
  15714. * @inner
  15715. */
  15716. function enableSubTypeDefaulter(entity) {
  15717. var subTypeDefaulters = {};
  15718. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15719. componentType = parseClassType$1(componentType);
  15720. subTypeDefaulters[componentType.main] = defaulter;
  15721. };
  15722. entity.determineSubType = function (componentType, option) {
  15723. var type = option.type;
  15724. if (!type) {
  15725. var componentTypeMain = parseClassType$1(componentType).main;
  15726. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15727. type = subTypeDefaulters[componentTypeMain](option);
  15728. }
  15729. }
  15730. return type;
  15731. };
  15732. return entity;
  15733. }
  15734. /**
  15735. * Topological travel on Activity Network (Activity On Vertices).
  15736. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15737. *
  15738. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15739. *
  15740. * If there is circle dependencey, Error will be thrown.
  15741. *
  15742. */
  15743. function enableTopologicalTravel(entity, dependencyGetter) {
  15744. /**
  15745. * @public
  15746. * @param {Array.<string>} targetNameList Target Component type list.
  15747. * Can be ['aa', 'bb', 'aa.xx']
  15748. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15749. * @param {Function} callback Params: componentType, dependencies.
  15750. * @param {Object} context Scope of callback.
  15751. */
  15752. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15753. if (!targetNameList.length) {
  15754. return;
  15755. }
  15756. var result = makeDepndencyGraph(fullNameList);
  15757. var graph = result.graph;
  15758. var stack = result.noEntryList;
  15759. var targetNameSet = {};
  15760. each$1(targetNameList, function (name) {
  15761. targetNameSet[name] = true;
  15762. });
  15763. while (stack.length) {
  15764. var currComponentType = stack.pop();
  15765. var currVertex = graph[currComponentType];
  15766. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15767. if (isInTargetNameSet) {
  15768. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15769. delete targetNameSet[currComponentType];
  15770. }
  15771. each$1(
  15772. currVertex.successor,
  15773. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15774. );
  15775. }
  15776. each$1(targetNameSet, function () {
  15777. throw new Error('Circle dependency may exists');
  15778. });
  15779. function removeEdge(succComponentType) {
  15780. graph[succComponentType].entryCount--;
  15781. if (graph[succComponentType].entryCount === 0) {
  15782. stack.push(succComponentType);
  15783. }
  15784. }
  15785. // Consider this case: legend depends on series, and we call
  15786. // chart.setOption({series: [...]}), where only series is in option.
  15787. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15788. // not be called, but only sereis.mergeOption is called. Thus legend
  15789. // have no chance to update its local record about series (like which
  15790. // name of series is available in legend).
  15791. function removeEdgeAndAdd(succComponentType) {
  15792. targetNameSet[succComponentType] = true;
  15793. removeEdge(succComponentType);
  15794. }
  15795. };
  15796. /**
  15797. * DepndencyGraph: {Object}
  15798. * key: conponentType,
  15799. * value: {
  15800. * successor: [conponentTypes...],
  15801. * originalDeps: [conponentTypes...],
  15802. * entryCount: {number}
  15803. * }
  15804. */
  15805. function makeDepndencyGraph(fullNameList) {
  15806. var graph = {};
  15807. var noEntryList = [];
  15808. each$1(fullNameList, function (name) {
  15809. var thisItem = createDependencyGraphItem(graph, name);
  15810. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15811. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15812. thisItem.entryCount = availableDeps.length;
  15813. if (thisItem.entryCount === 0) {
  15814. noEntryList.push(name);
  15815. }
  15816. each$1(availableDeps, function (dependentName) {
  15817. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15818. thisItem.predecessor.push(dependentName);
  15819. }
  15820. var thatItem = createDependencyGraphItem(graph, dependentName);
  15821. if (indexOf(thatItem.successor, dependentName) < 0) {
  15822. thatItem.successor.push(name);
  15823. }
  15824. });
  15825. });
  15826. return {graph: graph, noEntryList: noEntryList};
  15827. }
  15828. function createDependencyGraphItem(graph, name) {
  15829. if (!graph[name]) {
  15830. graph[name] = {predecessor: [], successor: []};
  15831. }
  15832. return graph[name];
  15833. }
  15834. function getAvailableDependencies(originalDeps, fullNameList) {
  15835. var availableDeps = [];
  15836. each$1(originalDeps, function (dep) {
  15837. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15838. });
  15839. return availableDeps;
  15840. }
  15841. }
  15842. /*
  15843. * Licensed to the Apache Software Foundation (ASF) under one
  15844. * or more contributor license agreements. See the NOTICE file
  15845. * distributed with this work for additional information
  15846. * regarding copyright ownership. The ASF licenses this file
  15847. * to you under the Apache License, Version 2.0 (the
  15848. * "License"); you may not use this file except in compliance
  15849. * with the License. You may obtain a copy of the License at
  15850. *
  15851. * http://www.apache.org/licenses/LICENSE-2.0
  15852. *
  15853. * Unless required by applicable law or agreed to in writing,
  15854. * software distributed under the License is distributed on an
  15855. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15856. * KIND, either express or implied. See the License for the
  15857. * specific language governing permissions and limitations
  15858. * under the License.
  15859. */
  15860. /*
  15861. * A third-party license is embeded for some of the code in this file:
  15862. * The method "quantile" was copied from "d3.js".
  15863. * (See more details in the comment of the method below.)
  15864. * The use of the source code of this file is also subject to the terms
  15865. * and consitions of the license of "d3.js" (BSD-3Clause, see
  15866. * </licenses/LICENSE-d3>).
  15867. */
  15868. var RADIAN_EPSILON = 1e-4;
  15869. function _trim(str) {
  15870. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15871. }
  15872. /**
  15873. * Linear mapping a value from domain to range
  15874. * @memberOf module:echarts/util/number
  15875. * @param {(number|Array.<number>)} val
  15876. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15877. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15878. * @param {boolean} clamp
  15879. * @return {(number|Array.<number>}
  15880. */
  15881. function linearMap(val, domain, range, clamp) {
  15882. var subDomain = domain[1] - domain[0];
  15883. var subRange = range[1] - range[0];
  15884. if (subDomain === 0) {
  15885. return subRange === 0
  15886. ? range[0]
  15887. : (range[0] + range[1]) / 2;
  15888. }
  15889. // Avoid accuracy problem in edge, such as
  15890. // 146.39 - 62.83 === 83.55999999999999.
  15891. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15892. // It is a little verbose for efficiency considering this method
  15893. // is a hotspot.
  15894. if (clamp) {
  15895. if (subDomain > 0) {
  15896. if (val <= domain[0]) {
  15897. return range[0];
  15898. }
  15899. else if (val >= domain[1]) {
  15900. return range[1];
  15901. }
  15902. }
  15903. else {
  15904. if (val >= domain[0]) {
  15905. return range[0];
  15906. }
  15907. else if (val <= domain[1]) {
  15908. return range[1];
  15909. }
  15910. }
  15911. }
  15912. else {
  15913. if (val === domain[0]) {
  15914. return range[0];
  15915. }
  15916. if (val === domain[1]) {
  15917. return range[1];
  15918. }
  15919. }
  15920. return (val - domain[0]) / subDomain * subRange + range[0];
  15921. }
  15922. /**
  15923. * Convert a percent string to absolute number.
  15924. * Returns NaN if percent is not a valid string or number
  15925. * @memberOf module:echarts/util/number
  15926. * @param {string|number} percent
  15927. * @param {number} all
  15928. * @return {number}
  15929. */
  15930. function parsePercent$1(percent, all) {
  15931. switch (percent) {
  15932. case 'center':
  15933. case 'middle':
  15934. percent = '50%';
  15935. break;
  15936. case 'left':
  15937. case 'top':
  15938. percent = '0%';
  15939. break;
  15940. case 'right':
  15941. case 'bottom':
  15942. percent = '100%';
  15943. break;
  15944. }
  15945. if (typeof percent === 'string') {
  15946. if (_trim(percent).match(/%$/)) {
  15947. return parseFloat(percent) / 100 * all;
  15948. }
  15949. return parseFloat(percent);
  15950. }
  15951. return percent == null ? NaN : +percent;
  15952. }
  15953. /**
  15954. * (1) Fix rounding error of float numbers.
  15955. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15956. *
  15957. * @param {number} x
  15958. * @param {number} [precision]
  15959. * @param {boolean} [returnStr]
  15960. * @return {number|string}
  15961. */
  15962. function round$2(x, precision, returnStr) {
  15963. if (precision == null) {
  15964. precision = 10;
  15965. }
  15966. // Avoid range error
  15967. precision = Math.min(Math.max(0, precision), 20);
  15968. x = (+x).toFixed(precision);
  15969. return returnStr ? x : +x;
  15970. }
  15971. function asc(arr) {
  15972. arr.sort(function (a, b) {
  15973. return a - b;
  15974. });
  15975. return arr;
  15976. }
  15977. /**
  15978. * Get precision
  15979. * @param {number} val
  15980. */
  15981. function getPrecision(val) {
  15982. val = +val;
  15983. if (isNaN(val)) {
  15984. return 0;
  15985. }
  15986. // It is much faster than methods converting number to string as follows
  15987. // var tmp = val.toString();
  15988. // return tmp.length - 1 - tmp.indexOf('.');
  15989. // especially when precision is low
  15990. var e = 1;
  15991. var count = 0;
  15992. while (Math.round(val * e) / e !== val) {
  15993. e *= 10;
  15994. count++;
  15995. }
  15996. return count;
  15997. }
  15998. /**
  15999. * @param {string|number} val
  16000. * @return {number}
  16001. */
  16002. function getPrecisionSafe(val) {
  16003. var str = val.toString();
  16004. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16005. var eIndex = str.indexOf('e');
  16006. if (eIndex > 0) {
  16007. var precision = +str.slice(eIndex + 1);
  16008. return precision < 0 ? -precision : 0;
  16009. }
  16010. else {
  16011. var dotIndex = str.indexOf('.');
  16012. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16013. }
  16014. }
  16015. /**
  16016. * Minimal dicernible data precisioin according to a single pixel.
  16017. *
  16018. * @param {Array.<number>} dataExtent
  16019. * @param {Array.<number>} pixelExtent
  16020. * @return {number} precision
  16021. */
  16022. function getPixelPrecision(dataExtent, pixelExtent) {
  16023. var log = Math.log;
  16024. var LN10 = Math.LN10;
  16025. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16026. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16027. // toFixed() digits argument must be between 0 and 20.
  16028. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16029. return !isFinite(precision) ? 20 : precision;
  16030. }
  16031. /**
  16032. * Get a data of given precision, assuring the sum of percentages
  16033. * in valueList is 1.
  16034. * The largest remainer method is used.
  16035. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16036. *
  16037. * @param {Array.<number>} valueList a list of all data
  16038. * @param {number} idx index of the data to be processed in valueList
  16039. * @param {number} precision integer number showing digits of precision
  16040. * @return {number} percent ranging from 0 to 100
  16041. */
  16042. function getPercentWithPrecision(valueList, idx, precision) {
  16043. if (!valueList[idx]) {
  16044. return 0;
  16045. }
  16046. var sum = reduce(valueList, function (acc, val) {
  16047. return acc + (isNaN(val) ? 0 : val);
  16048. }, 0);
  16049. if (sum === 0) {
  16050. return 0;
  16051. }
  16052. var digits = Math.pow(10, precision);
  16053. var votesPerQuota = map(valueList, function (val) {
  16054. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16055. });
  16056. var targetSeats = digits * 100;
  16057. var seats = map(votesPerQuota, function (votes) {
  16058. // Assign automatic seats.
  16059. return Math.floor(votes);
  16060. });
  16061. var currentSum = reduce(seats, function (acc, val) {
  16062. return acc + val;
  16063. }, 0);
  16064. var remainder = map(votesPerQuota, function (votes, idx) {
  16065. return votes - seats[idx];
  16066. });
  16067. // Has remainding votes.
  16068. while (currentSum < targetSeats) {
  16069. // Find next largest remainder.
  16070. var max = Number.NEGATIVE_INFINITY;
  16071. var maxId = null;
  16072. for (var i = 0, len = remainder.length; i < len; ++i) {
  16073. if (remainder[i] > max) {
  16074. max = remainder[i];
  16075. maxId = i;
  16076. }
  16077. }
  16078. // Add a vote to max remainder.
  16079. ++seats[maxId];
  16080. remainder[maxId] = 0;
  16081. ++currentSum;
  16082. }
  16083. return seats[idx] / digits;
  16084. }
  16085. // Number.MAX_SAFE_INTEGER, ie do not support.
  16086. var MAX_SAFE_INTEGER = 9007199254740991;
  16087. /**
  16088. * To 0 - 2 * PI, considering negative radian.
  16089. * @param {number} radian
  16090. * @return {number}
  16091. */
  16092. function remRadian(radian) {
  16093. var pi2 = Math.PI * 2;
  16094. return (radian % pi2 + pi2) % pi2;
  16095. }
  16096. /**
  16097. * @param {type} radian
  16098. * @return {boolean}
  16099. */
  16100. function isRadianAroundZero(val) {
  16101. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16102. }
  16103. /* eslint-disable */
  16104. 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
  16105. /* eslint-enable */
  16106. /**
  16107. * @param {string|Date|number} value These values can be accepted:
  16108. * + An instance of Date, represent a time in its own time zone.
  16109. * + Or string in a subset of ISO 8601, only including:
  16110. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16111. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16112. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16113. * all of which will be treated as local time if time zone is not specified
  16114. * (see <https://momentjs.com/>).
  16115. * + Or other string format, including (all of which will be treated as loacal time):
  16116. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16117. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16118. * + a timestamp, which represent a time in UTC.
  16119. * @return {Date} date
  16120. */
  16121. function parseDate(value) {
  16122. if (value instanceof Date) {
  16123. return value;
  16124. }
  16125. else if (typeof value === 'string') {
  16126. // Different browsers parse date in different way, so we parse it manually.
  16127. // Some other issues:
  16128. // new Date('1970-01-01') is UTC,
  16129. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  16130. // See issue #3623
  16131. var match = TIME_REG.exec(value);
  16132. if (!match) {
  16133. // return Invalid Date.
  16134. return new Date(NaN);
  16135. }
  16136. // Use local time when no timezone offset specifed.
  16137. if (!match[8]) {
  16138. // match[n] can only be string or undefined.
  16139. // But take care of '12' + 1 => '121'.
  16140. return new Date(
  16141. +match[1],
  16142. +(match[2] || 1) - 1,
  16143. +match[3] || 1,
  16144. +match[4] || 0,
  16145. +(match[5] || 0),
  16146. +match[6] || 0,
  16147. +match[7] || 0
  16148. );
  16149. }
  16150. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  16151. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  16152. // For example, system timezone is set as "Time Zone: America/Toronto",
  16153. // then these code will get different result:
  16154. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  16155. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  16156. // So we should not use `new Date`, but use `Date.UTC`.
  16157. else {
  16158. var hour = +match[4] || 0;
  16159. if (match[8].toUpperCase() !== 'Z') {
  16160. hour -= match[8].slice(0, 3);
  16161. }
  16162. return new Date(Date.UTC(
  16163. +match[1],
  16164. +(match[2] || 1) - 1,
  16165. +match[3] || 1,
  16166. hour,
  16167. +(match[5] || 0),
  16168. +match[6] || 0,
  16169. +match[7] || 0
  16170. ));
  16171. }
  16172. }
  16173. else if (value == null) {
  16174. return new Date(NaN);
  16175. }
  16176. return new Date(Math.round(value));
  16177. }
  16178. /**
  16179. * Quantity of a number. e.g. 0.1, 1, 10, 100
  16180. *
  16181. * @param {number} val
  16182. * @return {number}
  16183. */
  16184. function quantity(val) {
  16185. return Math.pow(10, quantityExponent(val));
  16186. }
  16187. function quantityExponent(val) {
  16188. return Math.floor(Math.log(val) / Math.LN10);
  16189. }
  16190. /**
  16191. * find a “nice” number approximately equal to x. Round the number if round = true,
  16192. * take ceiling if round = false. The primary observation is that the “nicest”
  16193. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  16194. *
  16195. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  16196. *
  16197. * @param {number} val Non-negative value.
  16198. * @param {boolean} round
  16199. * @return {number}
  16200. */
  16201. function nice(val, round) {
  16202. var exponent = quantityExponent(val);
  16203. var exp10 = Math.pow(10, exponent);
  16204. var f = val / exp10; // 1 <= f < 10
  16205. var nf;
  16206. if (round) {
  16207. if (f < 1.5) {
  16208. nf = 1;
  16209. }
  16210. else if (f < 2.5) {
  16211. nf = 2;
  16212. }
  16213. else if (f < 4) {
  16214. nf = 3;
  16215. }
  16216. else if (f < 7) {
  16217. nf = 5;
  16218. }
  16219. else {
  16220. nf = 10;
  16221. }
  16222. }
  16223. else {
  16224. if (f < 1) {
  16225. nf = 1;
  16226. }
  16227. else if (f < 2) {
  16228. nf = 2;
  16229. }
  16230. else if (f < 3) {
  16231. nf = 3;
  16232. }
  16233. else if (f < 5) {
  16234. nf = 5;
  16235. }
  16236. else {
  16237. nf = 10;
  16238. }
  16239. }
  16240. val = nf * exp10;
  16241. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  16242. // 20 is the uppper bound of toFixed.
  16243. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  16244. }
  16245. /**
  16246. * This code was copied from "d3.js"
  16247. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  16248. * See the license statement at the head of this file.
  16249. * @param {Array.<number>} ascArr
  16250. */
  16251. function quantile(ascArr, p) {
  16252. var H = (ascArr.length - 1) * p + 1;
  16253. var h = Math.floor(H);
  16254. var v = +ascArr[h - 1];
  16255. var e = H - h;
  16256. return e ? v + e * (ascArr[h] - v) : v;
  16257. }
  16258. /**
  16259. * Order intervals asc, and split them when overlap.
  16260. * expect(numberUtil.reformIntervals([
  16261. * {interval: [18, 62], close: [1, 1]},
  16262. * {interval: [-Infinity, -70], close: [0, 0]},
  16263. * {interval: [-70, -26], close: [1, 1]},
  16264. * {interval: [-26, 18], close: [1, 1]},
  16265. * {interval: [62, 150], close: [1, 1]},
  16266. * {interval: [106, 150], close: [1, 1]},
  16267. * {interval: [150, Infinity], close: [0, 0]}
  16268. * ])).toEqual([
  16269. * {interval: [-Infinity, -70], close: [0, 0]},
  16270. * {interval: [-70, -26], close: [1, 1]},
  16271. * {interval: [-26, 18], close: [0, 1]},
  16272. * {interval: [18, 62], close: [0, 1]},
  16273. * {interval: [62, 150], close: [0, 1]},
  16274. * {interval: [150, Infinity], close: [0, 0]}
  16275. * ]);
  16276. * @param {Array.<Object>} list, where `close` mean open or close
  16277. * of the interval, and Infinity can be used.
  16278. * @return {Array.<Object>} The origin list, which has been reformed.
  16279. */
  16280. function reformIntervals(list) {
  16281. list.sort(function (a, b) {
  16282. return littleThan(a, b, 0) ? -1 : 1;
  16283. });
  16284. var curr = -Infinity;
  16285. var currClose = 1;
  16286. for (var i = 0; i < list.length;) {
  16287. var interval = list[i].interval;
  16288. var close = list[i].close;
  16289. for (var lg = 0; lg < 2; lg++) {
  16290. if (interval[lg] <= curr) {
  16291. interval[lg] = curr;
  16292. close[lg] = !lg ? 1 - currClose : 1;
  16293. }
  16294. curr = interval[lg];
  16295. currClose = close[lg];
  16296. }
  16297. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  16298. list.splice(i, 1);
  16299. }
  16300. else {
  16301. i++;
  16302. }
  16303. }
  16304. return list;
  16305. function littleThan(a, b, lg) {
  16306. return a.interval[lg] < b.interval[lg]
  16307. || (
  16308. a.interval[lg] === b.interval[lg]
  16309. && (
  16310. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  16311. || (!lg && littleThan(a, b, 1))
  16312. )
  16313. );
  16314. }
  16315. }
  16316. /**
  16317. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  16318. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  16319. * subtraction forces infinities to NaN
  16320. *
  16321. * @param {*} v
  16322. * @return {boolean}
  16323. */
  16324. function isNumeric(v) {
  16325. return v - parseFloat(v) >= 0;
  16326. }
  16327. var number = (Object.freeze || Object)({
  16328. linearMap: linearMap,
  16329. parsePercent: parsePercent$1,
  16330. round: round$2,
  16331. asc: asc,
  16332. getPrecision: getPrecision,
  16333. getPrecisionSafe: getPrecisionSafe,
  16334. getPixelPrecision: getPixelPrecision,
  16335. getPercentWithPrecision: getPercentWithPrecision,
  16336. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  16337. remRadian: remRadian,
  16338. isRadianAroundZero: isRadianAroundZero,
  16339. parseDate: parseDate,
  16340. quantity: quantity,
  16341. nice: nice,
  16342. quantile: quantile,
  16343. reformIntervals: reformIntervals,
  16344. isNumeric: isNumeric
  16345. });
  16346. /*
  16347. * Licensed to the Apache Software Foundation (ASF) under one
  16348. * or more contributor license agreements. See the NOTICE file
  16349. * distributed with this work for additional information
  16350. * regarding copyright ownership. The ASF licenses this file
  16351. * to you under the Apache License, Version 2.0 (the
  16352. * "License"); you may not use this file except in compliance
  16353. * with the License. You may obtain a copy of the License at
  16354. *
  16355. * http://www.apache.org/licenses/LICENSE-2.0
  16356. *
  16357. * Unless required by applicable law or agreed to in writing,
  16358. * software distributed under the License is distributed on an
  16359. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16360. * KIND, either express or implied. See the License for the
  16361. * specific language governing permissions and limitations
  16362. * under the License.
  16363. */
  16364. // import Text from 'zrender/src/graphic/Text';
  16365. /**
  16366. * 每三位默认加,格式化
  16367. * @param {string|number} x
  16368. * @return {string}
  16369. */
  16370. function addCommas(x) {
  16371. if (isNaN(x)) {
  16372. return '-';
  16373. }
  16374. x = (x + '').split('.');
  16375. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  16376. + (x.length > 1 ? ('.' + x[1]) : '');
  16377. }
  16378. /**
  16379. * @param {string} str
  16380. * @param {boolean} [upperCaseFirst=false]
  16381. * @return {string} str
  16382. */
  16383. function toCamelCase(str, upperCaseFirst) {
  16384. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16385. return group1.toUpperCase();
  16386. });
  16387. if (upperCaseFirst && str) {
  16388. str = str.charAt(0).toUpperCase() + str.slice(1);
  16389. }
  16390. return str;
  16391. }
  16392. var normalizeCssArray$1 = normalizeCssArray;
  16393. var replaceReg = /([&<>"'])/g;
  16394. var replaceMap = {
  16395. '&': '&amp;',
  16396. '<': '&lt;',
  16397. '>': '&gt;',
  16398. '"': '&quot;',
  16399. '\'': '&#39;'
  16400. };
  16401. function encodeHTML(source) {
  16402. return source == null
  16403. ? ''
  16404. : (source + '').replace(replaceReg, function (str, c) {
  16405. return replaceMap[c];
  16406. });
  16407. }
  16408. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16409. var wrapVar = function (varName, seriesIdx) {
  16410. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16411. };
  16412. /**
  16413. * Template formatter
  16414. * @param {string} tpl
  16415. * @param {Array.<Object>|Object} paramsList
  16416. * @param {boolean} [encode=false]
  16417. * @return {string}
  16418. */
  16419. function formatTpl(tpl, paramsList, encode) {
  16420. if (!isArray(paramsList)) {
  16421. paramsList = [paramsList];
  16422. }
  16423. var seriesLen = paramsList.length;
  16424. if (!seriesLen) {
  16425. return '';
  16426. }
  16427. var $vars = paramsList[0].$vars || [];
  16428. for (var i = 0; i < $vars.length; i++) {
  16429. var alias = TPL_VAR_ALIAS[i];
  16430. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16431. }
  16432. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16433. for (var k = 0; k < $vars.length; k++) {
  16434. var val = paramsList[seriesIdx][$vars[k]];
  16435. tpl = tpl.replace(
  16436. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  16437. encode ? encodeHTML(val) : val
  16438. );
  16439. }
  16440. }
  16441. return tpl;
  16442. }
  16443. /**
  16444. * simple Template formatter
  16445. *
  16446. * @param {string} tpl
  16447. * @param {Object} param
  16448. * @param {boolean} [encode=false]
  16449. * @return {string}
  16450. */
  16451. function formatTplSimple(tpl, param, encode) {
  16452. each$1(param, function (value, key) {
  16453. tpl = tpl.replace(
  16454. '{' + key + '}',
  16455. encode ? encodeHTML(value) : value
  16456. );
  16457. });
  16458. return tpl;
  16459. }
  16460. /**
  16461. * @param {Object|string} [opt] If string, means color.
  16462. * @param {string} [opt.color]
  16463. * @param {string} [opt.extraCssText]
  16464. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16465. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16466. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16467. * @return {string}
  16468. */
  16469. function getTooltipMarker(opt, extraCssText) {
  16470. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  16471. var color = opt.color;
  16472. var type = opt.type;
  16473. var extraCssText = opt.extraCssText;
  16474. var renderMode = opt.renderMode || 'html';
  16475. var markerId = opt.markerId || 'X';
  16476. if (!color) {
  16477. return '';
  16478. }
  16479. if (renderMode === 'html') {
  16480. return type === 'subItem'
  16481. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  16482. + 'border-radius:4px;width:4px;height:4px;background-color:'
  16483. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  16484. : '<span style="display:inline-block;margin-right:5px;'
  16485. + 'border-radius:10px;width:10px;height:10px;background-color:'
  16486. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16487. }
  16488. else {
  16489. // Space for rich element marker
  16490. return {
  16491. renderMode: renderMode,
  16492. content: '{marker' + markerId + '|} ',
  16493. style: {
  16494. color: color
  16495. }
  16496. };
  16497. }
  16498. }
  16499. function pad(str, len) {
  16500. str += '';
  16501. return '0000'.substr(0, len - str.length) + str;
  16502. }
  16503. /**
  16504. * ISO Date format
  16505. * @param {string} tpl
  16506. * @param {number} value
  16507. * @param {boolean} [isUTC=false] Default in local time.
  16508. * see `module:echarts/scale/Time`
  16509. * and `module:echarts/util/number#parseDate`.
  16510. * @inner
  16511. */
  16512. function formatTime(tpl, value, isUTC) {
  16513. if (tpl === 'week'
  16514. || tpl === 'month'
  16515. || tpl === 'quarter'
  16516. || tpl === 'half-year'
  16517. || tpl === 'year'
  16518. ) {
  16519. tpl = 'MM-dd\nyyyy';
  16520. }
  16521. var date = parseDate(value);
  16522. var utc = isUTC ? 'UTC' : '';
  16523. var y = date['get' + utc + 'FullYear']();
  16524. var M = date['get' + utc + 'Month']() + 1;
  16525. var d = date['get' + utc + 'Date']();
  16526. var h = date['get' + utc + 'Hours']();
  16527. var m = date['get' + utc + 'Minutes']();
  16528. var s = date['get' + utc + 'Seconds']();
  16529. var S = date['get' + utc + 'Milliseconds']();
  16530. tpl = tpl.replace('MM', pad(M, 2))
  16531. .replace('M', M)
  16532. .replace('yyyy', y)
  16533. .replace('yy', y % 100)
  16534. .replace('dd', pad(d, 2))
  16535. .replace('d', d)
  16536. .replace('hh', pad(h, 2))
  16537. .replace('h', h)
  16538. .replace('mm', pad(m, 2))
  16539. .replace('m', m)
  16540. .replace('ss', pad(s, 2))
  16541. .replace('s', s)
  16542. .replace('SSS', pad(S, 3));
  16543. return tpl;
  16544. }
  16545. /**
  16546. * Capital first
  16547. * @param {string} str
  16548. * @return {string}
  16549. */
  16550. function capitalFirst(str) {
  16551. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16552. }
  16553. var truncateText$1 = truncateText;
  16554. /**
  16555. * @public
  16556. * @param {Object} opt
  16557. * @param {string} opt.text
  16558. * @param {string} opt.font
  16559. * @param {string} [opt.textAlign='left']
  16560. * @param {string} [opt.textVerticalAlign='top']
  16561. * @param {Array.<number>} [opt.textPadding]
  16562. * @param {number} [opt.textLineHeight]
  16563. * @param {Object} [opt.rich]
  16564. * @param {Object} [opt.truncate]
  16565. * @return {Object} {x, y, width, height, lineHeight}
  16566. */
  16567. function getTextBoundingRect(opt) {
  16568. return getBoundingRect(
  16569. opt.text,
  16570. opt.font,
  16571. opt.textAlign,
  16572. opt.textVerticalAlign,
  16573. opt.textPadding,
  16574. opt.textLineHeight,
  16575. opt.rich,
  16576. opt.truncate
  16577. );
  16578. }
  16579. /**
  16580. * @deprecated
  16581. * the `textLineHeight` was added later.
  16582. * For backward compatiblility, put it as the last parameter.
  16583. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  16584. */
  16585. function getTextRect(
  16586. text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight
  16587. ) {
  16588. return getBoundingRect(
  16589. text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate
  16590. );
  16591. }
  16592. var format = (Object.freeze || Object)({
  16593. addCommas: addCommas,
  16594. toCamelCase: toCamelCase,
  16595. normalizeCssArray: normalizeCssArray$1,
  16596. encodeHTML: encodeHTML,
  16597. formatTpl: formatTpl,
  16598. formatTplSimple: formatTplSimple,
  16599. getTooltipMarker: getTooltipMarker,
  16600. formatTime: formatTime,
  16601. capitalFirst: capitalFirst,
  16602. truncateText: truncateText$1,
  16603. getTextBoundingRect: getTextBoundingRect,
  16604. getTextRect: getTextRect
  16605. });
  16606. /*
  16607. * Licensed to the Apache Software Foundation (ASF) under one
  16608. * or more contributor license agreements. See the NOTICE file
  16609. * distributed with this work for additional information
  16610. * regarding copyright ownership. The ASF licenses this file
  16611. * to you under the Apache License, Version 2.0 (the
  16612. * "License"); you may not use this file except in compliance
  16613. * with the License. You may obtain a copy of the License at
  16614. *
  16615. * http://www.apache.org/licenses/LICENSE-2.0
  16616. *
  16617. * Unless required by applicable law or agreed to in writing,
  16618. * software distributed under the License is distributed on an
  16619. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16620. * KIND, either express or implied. See the License for the
  16621. * specific language governing permissions and limitations
  16622. * under the License.
  16623. */
  16624. // Layout helpers for each component positioning
  16625. var each$3 = each$1;
  16626. /**
  16627. * @public
  16628. */
  16629. var LOCATION_PARAMS = [
  16630. 'left', 'right', 'top', 'bottom', 'width', 'height'
  16631. ];
  16632. /**
  16633. * @public
  16634. */
  16635. var HV_NAMES = [
  16636. ['width', 'left', 'right'],
  16637. ['height', 'top', 'bottom']
  16638. ];
  16639. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16640. var x = 0;
  16641. var y = 0;
  16642. if (maxWidth == null) {
  16643. maxWidth = Infinity;
  16644. }
  16645. if (maxHeight == null) {
  16646. maxHeight = Infinity;
  16647. }
  16648. var currentLineMaxSize = 0;
  16649. group.eachChild(function (child, idx) {
  16650. var position = child.position;
  16651. var rect = child.getBoundingRect();
  16652. var nextChild = group.childAt(idx + 1);
  16653. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16654. var nextX;
  16655. var nextY;
  16656. if (orient === 'horizontal') {
  16657. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  16658. nextX = x + moveX;
  16659. // Wrap when width exceeds maxWidth or meet a `newline` group
  16660. // FIXME compare before adding gap?
  16661. if (nextX > maxWidth || child.newline) {
  16662. x = 0;
  16663. nextX = moveX;
  16664. y += currentLineMaxSize + gap;
  16665. currentLineMaxSize = rect.height;
  16666. }
  16667. else {
  16668. // FIXME: consider rect.y is not `0`?
  16669. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16670. }
  16671. }
  16672. else {
  16673. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  16674. nextY = y + moveY;
  16675. // Wrap when width exceeds maxHeight or meet a `newline` group
  16676. if (nextY > maxHeight || child.newline) {
  16677. x += currentLineMaxSize + gap;
  16678. y = 0;
  16679. nextY = moveY;
  16680. currentLineMaxSize = rect.width;
  16681. }
  16682. else {
  16683. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16684. }
  16685. }
  16686. if (child.newline) {
  16687. return;
  16688. }
  16689. position[0] = x;
  16690. position[1] = y;
  16691. orient === 'horizontal'
  16692. ? (x = nextX + gap)
  16693. : (y = nextY + gap);
  16694. });
  16695. }
  16696. /**
  16697. * VBox or HBox layouting
  16698. * @param {string} orient
  16699. * @param {module:zrender/container/Group} group
  16700. * @param {number} gap
  16701. * @param {number} [width=Infinity]
  16702. * @param {number} [height=Infinity]
  16703. */
  16704. var box = boxLayout;
  16705. /**
  16706. * VBox layouting
  16707. * @param {module:zrender/container/Group} group
  16708. * @param {number} gap
  16709. * @param {number} [width=Infinity]
  16710. * @param {number} [height=Infinity]
  16711. */
  16712. var vbox = curry(boxLayout, 'vertical');
  16713. /**
  16714. * HBox layouting
  16715. * @param {module:zrender/container/Group} group
  16716. * @param {number} gap
  16717. * @param {number} [width=Infinity]
  16718. * @param {number} [height=Infinity]
  16719. */
  16720. var hbox = curry(boxLayout, 'horizontal');
  16721. /**
  16722. * If x or x2 is not specified or 'center' 'left' 'right',
  16723. * the width would be as long as possible.
  16724. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16725. * the height would be as long as possible.
  16726. *
  16727. * @param {Object} positionInfo
  16728. * @param {number|string} [positionInfo.x]
  16729. * @param {number|string} [positionInfo.y]
  16730. * @param {number|string} [positionInfo.x2]
  16731. * @param {number|string} [positionInfo.y2]
  16732. * @param {Object} containerRect {width, height}
  16733. * @param {string|number} margin
  16734. * @return {Object} {width, height}
  16735. */
  16736. /**
  16737. * Parse position info.
  16738. *
  16739. * @param {Object} positionInfo
  16740. * @param {number|string} [positionInfo.left]
  16741. * @param {number|string} [positionInfo.top]
  16742. * @param {number|string} [positionInfo.right]
  16743. * @param {number|string} [positionInfo.bottom]
  16744. * @param {number|string} [positionInfo.width]
  16745. * @param {number|string} [positionInfo.height]
  16746. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16747. * @param {Object} containerRect
  16748. * @param {string|number} [margin]
  16749. *
  16750. * @return {module:zrender/core/BoundingRect}
  16751. */
  16752. function getLayoutRect(
  16753. positionInfo, containerRect, margin
  16754. ) {
  16755. margin = normalizeCssArray$1(margin || 0);
  16756. var containerWidth = containerRect.width;
  16757. var containerHeight = containerRect.height;
  16758. var left = parsePercent$1(positionInfo.left, containerWidth);
  16759. var top = parsePercent$1(positionInfo.top, containerHeight);
  16760. var right = parsePercent$1(positionInfo.right, containerWidth);
  16761. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16762. var width = parsePercent$1(positionInfo.width, containerWidth);
  16763. var height = parsePercent$1(positionInfo.height, containerHeight);
  16764. var verticalMargin = margin[2] + margin[0];
  16765. var horizontalMargin = margin[1] + margin[3];
  16766. var aspect = positionInfo.aspect;
  16767. // If width is not specified, calculate width from left and right
  16768. if (isNaN(width)) {
  16769. width = containerWidth - right - horizontalMargin - left;
  16770. }
  16771. if (isNaN(height)) {
  16772. height = containerHeight - bottom - verticalMargin - top;
  16773. }
  16774. if (aspect != null) {
  16775. // If width and height are not given
  16776. // 1. Graph should not exceeds the container
  16777. // 2. Aspect must be keeped
  16778. // 3. Graph should take the space as more as possible
  16779. // FIXME
  16780. // Margin is not considered, because there is no case that both
  16781. // using margin and aspect so far.
  16782. if (isNaN(width) && isNaN(height)) {
  16783. if (aspect > containerWidth / containerHeight) {
  16784. width = containerWidth * 0.8;
  16785. }
  16786. else {
  16787. height = containerHeight * 0.8;
  16788. }
  16789. }
  16790. // Calculate width or height with given aspect
  16791. if (isNaN(width)) {
  16792. width = aspect * height;
  16793. }
  16794. if (isNaN(height)) {
  16795. height = width / aspect;
  16796. }
  16797. }
  16798. // If left is not specified, calculate left from right and width
  16799. if (isNaN(left)) {
  16800. left = containerWidth - right - width - horizontalMargin;
  16801. }
  16802. if (isNaN(top)) {
  16803. top = containerHeight - bottom - height - verticalMargin;
  16804. }
  16805. // Align left and top
  16806. switch (positionInfo.left || positionInfo.right) {
  16807. case 'center':
  16808. left = containerWidth / 2 - width / 2 - margin[3];
  16809. break;
  16810. case 'right':
  16811. left = containerWidth - width - horizontalMargin;
  16812. break;
  16813. }
  16814. switch (positionInfo.top || positionInfo.bottom) {
  16815. case 'middle':
  16816. case 'center':
  16817. top = containerHeight / 2 - height / 2 - margin[0];
  16818. break;
  16819. case 'bottom':
  16820. top = containerHeight - height - verticalMargin;
  16821. break;
  16822. }
  16823. // If something is wrong and left, top, width, height are calculated as NaN
  16824. left = left || 0;
  16825. top = top || 0;
  16826. if (isNaN(width)) {
  16827. // Width may be NaN if only one value is given except width
  16828. width = containerWidth - horizontalMargin - left - (right || 0);
  16829. }
  16830. if (isNaN(height)) {
  16831. // Height may be NaN if only one value is given except height
  16832. height = containerHeight - verticalMargin - top - (bottom || 0);
  16833. }
  16834. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16835. rect.margin = margin;
  16836. return rect;
  16837. }
  16838. /**
  16839. * Position a zr element in viewport
  16840. * Group position is specified by either
  16841. * {left, top}, {right, bottom}
  16842. * If all properties exists, right and bottom will be igonred.
  16843. *
  16844. * Logic:
  16845. * 1. Scale (against origin point in parent coord)
  16846. * 2. Rotate (against origin point in parent coord)
  16847. * 3. Traslate (with el.position by this method)
  16848. * So this method only fixes the last step 'Traslate', which does not affect
  16849. * scaling and rotating.
  16850. *
  16851. * If be called repeatly with the same input el, the same result will be gotten.
  16852. *
  16853. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16854. * @param {Object} positionInfo
  16855. * @param {number|string} [positionInfo.left]
  16856. * @param {number|string} [positionInfo.top]
  16857. * @param {number|string} [positionInfo.right]
  16858. * @param {number|string} [positionInfo.bottom]
  16859. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16860. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16861. * @param {Object} containerRect
  16862. * @param {string|number} margin
  16863. * @param {Object} [opt]
  16864. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16865. * @param {Array.<number>} [opt.boundingMode='all']
  16866. * Specify how to calculate boundingRect when locating.
  16867. * 'all': Position the boundingRect that is transformed and uioned
  16868. * both itself and its descendants.
  16869. * This mode simplies confine the elements in the bounding
  16870. * of their container (e.g., using 'right: 0').
  16871. * 'raw': Position the boundingRect that is not transformed and only itself.
  16872. * This mode is useful when you want a element can overflow its
  16873. * container. (Consider a rotated circle needs to be located in a corner.)
  16874. * In this mode positionInfo.width/height can only be number.
  16875. */
  16876. function positionElement(el, positionInfo, containerRect, margin, opt) {
  16877. var h = !opt || !opt.hv || opt.hv[0];
  16878. var v = !opt || !opt.hv || opt.hv[1];
  16879. var boundingMode = opt && opt.boundingMode || 'all';
  16880. if (!h && !v) {
  16881. return;
  16882. }
  16883. var rect;
  16884. if (boundingMode === 'raw') {
  16885. rect = el.type === 'group'
  16886. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  16887. : el.getBoundingRect();
  16888. }
  16889. else {
  16890. rect = el.getBoundingRect();
  16891. if (el.needLocalTransform()) {
  16892. var transform = el.getLocalTransform();
  16893. // Notice: raw rect may be inner object of el,
  16894. // which should not be modified.
  16895. rect = rect.clone();
  16896. rect.applyTransform(transform);
  16897. }
  16898. }
  16899. // The real width and height can not be specified but calculated by the given el.
  16900. positionInfo = getLayoutRect(
  16901. defaults(
  16902. {width: rect.width, height: rect.height},
  16903. positionInfo
  16904. ),
  16905. containerRect,
  16906. margin
  16907. );
  16908. // Because 'tranlate' is the last step in transform
  16909. // (see zrender/core/Transformable#getLocalTransform),
  16910. // we can just only modify el.position to get final result.
  16911. var elPos = el.position;
  16912. var dx = h ? positionInfo.x - rect.x : 0;
  16913. var dy = v ? positionInfo.y - rect.y : 0;
  16914. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  16915. }
  16916. /**
  16917. * @param {Object} option Contains some of the properties in HV_NAMES.
  16918. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16919. */
  16920. /**
  16921. * Consider Case:
  16922. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16923. * through setOption or media query, using normal zrUtil.merge will cause
  16924. * {right: 0} does not take effect.
  16925. *
  16926. * @example
  16927. * ComponentModel.extend({
  16928. * init: function () {
  16929. * ...
  16930. * var inputPositionParams = layout.getLayoutParams(option);
  16931. * this.mergeOption(inputPositionParams);
  16932. * },
  16933. * mergeOption: function (newOption) {
  16934. * newOption && zrUtil.merge(thisOption, newOption, true);
  16935. * layout.mergeLayoutParam(thisOption, newOption);
  16936. * }
  16937. * });
  16938. *
  16939. * @param {Object} targetOption
  16940. * @param {Object} newOption
  16941. * @param {Object|string} [opt]
  16942. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16943. * that width (or height) should not be calculated by left and right (or top and bottom).
  16944. */
  16945. function mergeLayoutParam(targetOption, newOption, opt) {
  16946. !isObject$1(opt) && (opt = {});
  16947. var ignoreSize = opt.ignoreSize;
  16948. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16949. var hResult = merge$$1(HV_NAMES[0], 0);
  16950. var vResult = merge$$1(HV_NAMES[1], 1);
  16951. copy(HV_NAMES[0], targetOption, hResult);
  16952. copy(HV_NAMES[1], targetOption, vResult);
  16953. function merge$$1(names, hvIdx) {
  16954. var newParams = {};
  16955. var newValueCount = 0;
  16956. var merged = {};
  16957. var mergedValueCount = 0;
  16958. var enoughParamNumber = 2;
  16959. each$3(names, function (name) {
  16960. merged[name] = targetOption[name];
  16961. });
  16962. each$3(names, function (name) {
  16963. // Consider case: newOption.width is null, which is
  16964. // set by user for removing width setting.
  16965. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16966. hasValue(newParams, name) && newValueCount++;
  16967. hasValue(merged, name) && mergedValueCount++;
  16968. });
  16969. if (ignoreSize[hvIdx]) {
  16970. // Only one of left/right is premitted to exist.
  16971. if (hasValue(newOption, names[1])) {
  16972. merged[names[2]] = null;
  16973. }
  16974. else if (hasValue(newOption, names[2])) {
  16975. merged[names[1]] = null;
  16976. }
  16977. return merged;
  16978. }
  16979. // Case: newOption: {width: ..., right: ...},
  16980. // or targetOption: {right: ...} and newOption: {width: ...},
  16981. // There is no conflict when merged only has params count
  16982. // little than enoughParamNumber.
  16983. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16984. return merged;
  16985. }
  16986. // Case: newOption: {width: ..., right: ...},
  16987. // Than we can make sure user only want those two, and ignore
  16988. // all origin params in targetOption.
  16989. else if (newValueCount >= enoughParamNumber) {
  16990. return newParams;
  16991. }
  16992. else {
  16993. // Chose another param from targetOption by priority.
  16994. for (var i = 0; i < names.length; i++) {
  16995. var name = names[i];
  16996. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16997. newParams[name] = targetOption[name];
  16998. break;
  16999. }
  17000. }
  17001. return newParams;
  17002. }
  17003. }
  17004. function hasProp(obj, name) {
  17005. return obj.hasOwnProperty(name);
  17006. }
  17007. function hasValue(obj, name) {
  17008. return obj[name] != null && obj[name] !== 'auto';
  17009. }
  17010. function copy(names, target, source) {
  17011. each$3(names, function (name) {
  17012. target[name] = source[name];
  17013. });
  17014. }
  17015. }
  17016. /**
  17017. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17018. * @param {Object} source
  17019. * @return {Object} Result contains those props.
  17020. */
  17021. function getLayoutParams(source) {
  17022. return copyLayoutParams({}, source);
  17023. }
  17024. /**
  17025. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17026. * @param {Object} source
  17027. * @return {Object} Result contains those props.
  17028. */
  17029. function copyLayoutParams(target, source) {
  17030. source && target && each$3(LOCATION_PARAMS, function (name) {
  17031. source.hasOwnProperty(name) && (target[name] = source[name]);
  17032. });
  17033. return target;
  17034. }
  17035. /*
  17036. * Licensed to the Apache Software Foundation (ASF) under one
  17037. * or more contributor license agreements. See the NOTICE file
  17038. * distributed with this work for additional information
  17039. * regarding copyright ownership. The ASF licenses this file
  17040. * to you under the Apache License, Version 2.0 (the
  17041. * "License"); you may not use this file except in compliance
  17042. * with the License. You may obtain a copy of the License at
  17043. *
  17044. * http://www.apache.org/licenses/LICENSE-2.0
  17045. *
  17046. * Unless required by applicable law or agreed to in writing,
  17047. * software distributed under the License is distributed on an
  17048. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17049. * KIND, either express or implied. See the License for the
  17050. * specific language governing permissions and limitations
  17051. * under the License.
  17052. */
  17053. var boxLayoutMixin = {
  17054. getBoxLayoutParams: function () {
  17055. return {
  17056. left: this.get('left'),
  17057. top: this.get('top'),
  17058. right: this.get('right'),
  17059. bottom: this.get('bottom'),
  17060. width: this.get('width'),
  17061. height: this.get('height')
  17062. };
  17063. }
  17064. };
  17065. /*
  17066. * Licensed to the Apache Software Foundation (ASF) under one
  17067. * or more contributor license agreements. See the NOTICE file
  17068. * distributed with this work for additional information
  17069. * regarding copyright ownership. The ASF licenses this file
  17070. * to you under the Apache License, Version 2.0 (the
  17071. * "License"); you may not use this file except in compliance
  17072. * with the License. You may obtain a copy of the License at
  17073. *
  17074. * http://www.apache.org/licenses/LICENSE-2.0
  17075. *
  17076. * Unless required by applicable law or agreed to in writing,
  17077. * software distributed under the License is distributed on an
  17078. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17079. * KIND, either express or implied. See the License for the
  17080. * specific language governing permissions and limitations
  17081. * under the License.
  17082. */
  17083. /**
  17084. * Component model
  17085. *
  17086. * @module echarts/model/Component
  17087. */
  17088. var inner$1 = makeInner();
  17089. /**
  17090. * @alias module:echarts/model/Component
  17091. * @constructor
  17092. * @param {Object} option
  17093. * @param {module:echarts/model/Model} parentModel
  17094. * @param {module:echarts/model/Model} ecModel
  17095. */
  17096. var ComponentModel = Model.extend({
  17097. type: 'component',
  17098. /**
  17099. * @readOnly
  17100. * @type {string}
  17101. */
  17102. id: '',
  17103. /**
  17104. * Because simplified concept is probably better, series.name (or component.name)
  17105. * has been having too many resposibilities:
  17106. * (1) Generating id (which requires name in option should not be modified).
  17107. * (2) As an index to mapping series when merging option or calling API (a name
  17108. * can refer to more then one components, which is convinient is some case).
  17109. * (3) Display.
  17110. * @readOnly
  17111. */
  17112. name: '',
  17113. /**
  17114. * @readOnly
  17115. * @type {string}
  17116. */
  17117. mainType: '',
  17118. /**
  17119. * @readOnly
  17120. * @type {string}
  17121. */
  17122. subType: '',
  17123. /**
  17124. * @readOnly
  17125. * @type {number}
  17126. */
  17127. componentIndex: 0,
  17128. /**
  17129. * @type {Object}
  17130. * @protected
  17131. */
  17132. defaultOption: null,
  17133. /**
  17134. * @type {module:echarts/model/Global}
  17135. * @readOnly
  17136. */
  17137. ecModel: null,
  17138. /**
  17139. * key: componentType
  17140. * value: Component model list, can not be null.
  17141. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17142. * @readOnly
  17143. */
  17144. dependentModels: [],
  17145. /**
  17146. * @type {string}
  17147. * @readOnly
  17148. */
  17149. uid: null,
  17150. /**
  17151. * Support merge layout params.
  17152. * Only support 'box' now (left/right/top/bottom/width/height).
  17153. * @type {string|Object} Object can be {ignoreSize: true}
  17154. * @readOnly
  17155. */
  17156. layoutMode: null,
  17157. $constructor: function (option, parentModel, ecModel, extraOpt) {
  17158. Model.call(this, option, parentModel, ecModel, extraOpt);
  17159. this.uid = getUID('ec_cpt_model');
  17160. },
  17161. init: function (option, parentModel, ecModel, extraOpt) {
  17162. this.mergeDefaultAndTheme(option, ecModel);
  17163. },
  17164. mergeDefaultAndTheme: function (option, ecModel) {
  17165. var layoutMode = this.layoutMode;
  17166. var inputPositionParams = layoutMode
  17167. ? getLayoutParams(option) : {};
  17168. var themeModel = ecModel.getTheme();
  17169. merge(option, themeModel.get(this.mainType));
  17170. merge(option, this.getDefaultOption());
  17171. if (layoutMode) {
  17172. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17173. }
  17174. },
  17175. mergeOption: function (option, extraOpt) {
  17176. merge(this.option, option, true);
  17177. var layoutMode = this.layoutMode;
  17178. if (layoutMode) {
  17179. mergeLayoutParam(this.option, option, layoutMode);
  17180. }
  17181. },
  17182. // Hooker after init or mergeOption
  17183. optionUpdated: function (newCptOption, isInit) {},
  17184. getDefaultOption: function () {
  17185. var fields = inner$1(this);
  17186. if (!fields.defaultOption) {
  17187. var optList = [];
  17188. var Class = this.constructor;
  17189. while (Class) {
  17190. var opt = Class.prototype.defaultOption;
  17191. opt && optList.push(opt);
  17192. Class = Class.superClass;
  17193. }
  17194. var defaultOption = {};
  17195. for (var i = optList.length - 1; i >= 0; i--) {
  17196. defaultOption = merge(defaultOption, optList[i], true);
  17197. }
  17198. fields.defaultOption = defaultOption;
  17199. }
  17200. return fields.defaultOption;
  17201. },
  17202. getReferringComponents: function (mainType) {
  17203. return this.ecModel.queryComponents({
  17204. mainType: mainType,
  17205. index: this.get(mainType + 'Index', true),
  17206. id: this.get(mainType + 'Id', true)
  17207. });
  17208. }
  17209. });
  17210. // Reset ComponentModel.extend, add preConstruct.
  17211. // clazzUtil.enableClassExtend(
  17212. // ComponentModel,
  17213. // function (option, parentModel, ecModel, extraOpt) {
  17214. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  17215. // zrUtil.extend(this, extraOpt);
  17216. // this.uid = componentUtil.getUID('componentModel');
  17217. // // this.setReadOnly([
  17218. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  17219. // // 'dependentModels', 'componentIndex'
  17220. // // ]);
  17221. // }
  17222. // );
  17223. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17224. enableClassManagement(
  17225. ComponentModel, {registerWhenExtend: true}
  17226. );
  17227. enableSubTypeDefaulter(ComponentModel);
  17228. // Add capability of ComponentModel.topologicalTravel.
  17229. enableTopologicalTravel(ComponentModel, getDependencies);
  17230. function getDependencies(componentType) {
  17231. var deps = [];
  17232. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  17233. deps = deps.concat(Clazz.prototype.dependencies || []);
  17234. });
  17235. // Ensure main type.
  17236. deps = map(deps, function (type) {
  17237. return parseClassType$1(type).main;
  17238. });
  17239. // Hack dataset for convenience.
  17240. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  17241. deps.unshift('dataset');
  17242. }
  17243. return deps;
  17244. }
  17245. mixin(ComponentModel, boxLayoutMixin);
  17246. /*
  17247. * Licensed to the Apache Software Foundation (ASF) under one
  17248. * or more contributor license agreements. See the NOTICE file
  17249. * distributed with this work for additional information
  17250. * regarding copyright ownership. The ASF licenses this file
  17251. * to you under the Apache License, Version 2.0 (the
  17252. * "License"); you may not use this file except in compliance
  17253. * with the License. You may obtain a copy of the License at
  17254. *
  17255. * http://www.apache.org/licenses/LICENSE-2.0
  17256. *
  17257. * Unless required by applicable law or agreed to in writing,
  17258. * software distributed under the License is distributed on an
  17259. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17260. * KIND, either express or implied. See the License for the
  17261. * specific language governing permissions and limitations
  17262. * under the License.
  17263. */
  17264. var platform = '';
  17265. // Navigator not exists in node
  17266. if (typeof navigator !== 'undefined') {
  17267. platform = navigator.platform || '';
  17268. }
  17269. var globalDefault = {
  17270. // backgroundColor: 'rgba(0,0,0,0)',
  17271. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  17272. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  17273. // Light colors:
  17274. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  17275. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  17276. // Dark colors:
  17277. color: [
  17278. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  17279. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  17280. ],
  17281. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  17282. // If xAxis and yAxis declared, grid is created by default.
  17283. // grid: {},
  17284. textStyle: {
  17285. // color: '#000',
  17286. // decoration: 'none',
  17287. // PENDING
  17288. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  17289. // fontFamily: 'Arial, Verdana, sans-serif',
  17290. fontSize: 12,
  17291. fontStyle: 'normal',
  17292. fontWeight: 'normal'
  17293. },
  17294. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  17295. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  17296. // Default is source-over
  17297. blendMode: null,
  17298. animation: 'auto',
  17299. animationDuration: 1000,
  17300. animationDurationUpdate: 300,
  17301. animationEasing: 'exponentialOut',
  17302. animationEasingUpdate: 'cubicOut',
  17303. animationThreshold: 2000,
  17304. // Configuration for progressive/incremental rendering
  17305. progressiveThreshold: 3000,
  17306. progressive: 400,
  17307. // Threshold of if use single hover layer to optimize.
  17308. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  17309. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  17310. // which is unexpected.
  17311. // see example <echarts/test/heatmap-large.html>.
  17312. hoverLayerThreshold: 3000,
  17313. // See: module:echarts/scale/Time
  17314. useUTC: false
  17315. };
  17316. /*
  17317. * Licensed to the Apache Software Foundation (ASF) under one
  17318. * or more contributor license agreements. See the NOTICE file
  17319. * distributed with this work for additional information
  17320. * regarding copyright ownership. The ASF licenses this file
  17321. * to you under the Apache License, Version 2.0 (the
  17322. * "License"); you may not use this file except in compliance
  17323. * with the License. You may obtain a copy of the License at
  17324. *
  17325. * http://www.apache.org/licenses/LICENSE-2.0
  17326. *
  17327. * Unless required by applicable law or agreed to in writing,
  17328. * software distributed under the License is distributed on an
  17329. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17330. * KIND, either express or implied. See the License for the
  17331. * specific language governing permissions and limitations
  17332. * under the License.
  17333. */
  17334. var inner$2 = makeInner();
  17335. function getNearestColorPalette(colors, requestColorNum) {
  17336. var paletteNum = colors.length;
  17337. // TODO colors must be in order
  17338. for (var i = 0; i < paletteNum; i++) {
  17339. if (colors[i].length > requestColorNum) {
  17340. return colors[i];
  17341. }
  17342. }
  17343. return colors[paletteNum - 1];
  17344. }
  17345. var colorPaletteMixin = {
  17346. clearColorPalette: function () {
  17347. inner$2(this).colorIdx = 0;
  17348. inner$2(this).colorNameMap = {};
  17349. },
  17350. /**
  17351. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  17352. * twise with the same parameters will get different result.
  17353. * @param {Object} [scope=this]
  17354. * @param {Object} [requestColorNum]
  17355. * @return {string} color string.
  17356. */
  17357. getColorFromPalette: function (name, scope, requestColorNum) {
  17358. scope = scope || this;
  17359. var scopeFields = inner$2(scope);
  17360. var colorIdx = scopeFields.colorIdx || 0;
  17361. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  17362. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17363. if (colorNameMap.hasOwnProperty(name)) {
  17364. return colorNameMap[name];
  17365. }
  17366. var defaultColorPalette = normalizeToArray(this.get('color', true));
  17367. var layeredColorPalette = this.get('colorLayer', true);
  17368. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  17369. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  17370. // In case can't find in layered color palette.
  17371. colorPalette = colorPalette || defaultColorPalette;
  17372. if (!colorPalette || !colorPalette.length) {
  17373. return;
  17374. }
  17375. var color = colorPalette[colorIdx];
  17376. if (name) {
  17377. colorNameMap[name] = color;
  17378. }
  17379. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  17380. return color;
  17381. }
  17382. };
  17383. /*
  17384. * Licensed to the Apache Software Foundation (ASF) under one
  17385. * or more contributor license agreements. See the NOTICE file
  17386. * distributed with this work for additional information
  17387. * regarding copyright ownership. The ASF licenses this file
  17388. * to you under the Apache License, Version 2.0 (the
  17389. * "License"); you may not use this file except in compliance
  17390. * with the License. You may obtain a copy of the License at
  17391. *
  17392. * http://www.apache.org/licenses/LICENSE-2.0
  17393. *
  17394. * Unless required by applicable law or agreed to in writing,
  17395. * software distributed under the License is distributed on an
  17396. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17397. * KIND, either express or implied. See the License for the
  17398. * specific language governing permissions and limitations
  17399. * under the License.
  17400. */
  17401. /**
  17402. * Helper for model references.
  17403. * There are many manners to refer axis/coordSys.
  17404. */
  17405. // TODO
  17406. // merge relevant logic to this file?
  17407. // check: "modelHelper" of tooltip and "BrushTargetManager".
  17408. /**
  17409. * @return {Object} For example:
  17410. * {
  17411. * coordSysName: 'cartesian2d',
  17412. * coordSysDims: ['x', 'y', ...],
  17413. * axisMap: HashMap({
  17414. * x: xAxisModel,
  17415. * y: yAxisModel
  17416. * }),
  17417. * categoryAxisMap: HashMap({
  17418. * x: xAxisModel,
  17419. * y: undefined
  17420. * }),
  17421. * // It also indicate that whether there is category axis.
  17422. * firstCategoryDimIndex: 1,
  17423. * // To replace user specified encode.
  17424. * }
  17425. */
  17426. function getCoordSysDefineBySeries(seriesModel) {
  17427. var coordSysName = seriesModel.get('coordinateSystem');
  17428. var result = {
  17429. coordSysName: coordSysName,
  17430. coordSysDims: [],
  17431. axisMap: createHashMap(),
  17432. categoryAxisMap: createHashMap()
  17433. };
  17434. var fetch = fetchers[coordSysName];
  17435. if (fetch) {
  17436. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  17437. return result;
  17438. }
  17439. }
  17440. var fetchers = {
  17441. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  17442. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  17443. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  17444. if (__DEV__) {
  17445. if (!xAxisModel) {
  17446. throw new Error('xAxis "' + retrieve(
  17447. seriesModel.get('xAxisIndex'),
  17448. seriesModel.get('xAxisId'),
  17449. 0
  17450. ) + '" not found');
  17451. }
  17452. if (!yAxisModel) {
  17453. throw new Error('yAxis "' + retrieve(
  17454. seriesModel.get('xAxisIndex'),
  17455. seriesModel.get('yAxisId'),
  17456. 0
  17457. ) + '" not found');
  17458. }
  17459. }
  17460. result.coordSysDims = ['x', 'y'];
  17461. axisMap.set('x', xAxisModel);
  17462. axisMap.set('y', yAxisModel);
  17463. if (isCategory(xAxisModel)) {
  17464. categoryAxisMap.set('x', xAxisModel);
  17465. result.firstCategoryDimIndex = 0;
  17466. }
  17467. if (isCategory(yAxisModel)) {
  17468. categoryAxisMap.set('y', yAxisModel);
  17469. result.firstCategoryDimIndex = 1;
  17470. }
  17471. },
  17472. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  17473. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  17474. if (__DEV__) {
  17475. if (!singleAxisModel) {
  17476. throw new Error('singleAxis should be specified.');
  17477. }
  17478. }
  17479. result.coordSysDims = ['single'];
  17480. axisMap.set('single', singleAxisModel);
  17481. if (isCategory(singleAxisModel)) {
  17482. categoryAxisMap.set('single', singleAxisModel);
  17483. result.firstCategoryDimIndex = 0;
  17484. }
  17485. },
  17486. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  17487. var polarModel = seriesModel.getReferringComponents('polar')[0];
  17488. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  17489. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  17490. if (__DEV__) {
  17491. if (!angleAxisModel) {
  17492. throw new Error('angleAxis option not found');
  17493. }
  17494. if (!radiusAxisModel) {
  17495. throw new Error('radiusAxis option not found');
  17496. }
  17497. }
  17498. result.coordSysDims = ['radius', 'angle'];
  17499. axisMap.set('radius', radiusAxisModel);
  17500. axisMap.set('angle', angleAxisModel);
  17501. if (isCategory(radiusAxisModel)) {
  17502. categoryAxisMap.set('radius', radiusAxisModel);
  17503. result.firstCategoryDimIndex = 0;
  17504. }
  17505. if (isCategory(angleAxisModel)) {
  17506. categoryAxisMap.set('angle', angleAxisModel);
  17507. result.firstCategoryDimIndex = 1;
  17508. }
  17509. },
  17510. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  17511. result.coordSysDims = ['lng', 'lat'];
  17512. },
  17513. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  17514. var ecModel = seriesModel.ecModel;
  17515. var parallelModel = ecModel.getComponent(
  17516. 'parallel', seriesModel.get('parallelIndex')
  17517. );
  17518. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  17519. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  17520. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  17521. var axisDim = coordSysDims[index];
  17522. axisMap.set(axisDim, axisModel);
  17523. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  17524. categoryAxisMap.set(axisDim, axisModel);
  17525. result.firstCategoryDimIndex = index;
  17526. }
  17527. });
  17528. }
  17529. };
  17530. function isCategory(axisModel) {
  17531. return axisModel.get('type') === 'category';
  17532. }
  17533. /*
  17534. * Licensed to the Apache Software Foundation (ASF) under one
  17535. * or more contributor license agreements. See the NOTICE file
  17536. * distributed with this work for additional information
  17537. * regarding copyright ownership. The ASF licenses this file
  17538. * to you under the Apache License, Version 2.0 (the
  17539. * "License"); you may not use this file except in compliance
  17540. * with the License. You may obtain a copy of the License at
  17541. *
  17542. * http://www.apache.org/licenses/LICENSE-2.0
  17543. *
  17544. * Unless required by applicable law or agreed to in writing,
  17545. * software distributed under the License is distributed on an
  17546. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17547. * KIND, either express or implied. See the License for the
  17548. * specific language governing permissions and limitations
  17549. * under the License.
  17550. */
  17551. // Avoid typo.
  17552. var SOURCE_FORMAT_ORIGINAL = 'original';
  17553. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17554. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17555. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17556. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17557. // ??? CHANGE A NAME
  17558. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17559. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17560. var SERIES_LAYOUT_BY_ROW = 'row';
  17561. /*
  17562. * Licensed to the Apache Software Foundation (ASF) under one
  17563. * or more contributor license agreements. See the NOTICE file
  17564. * distributed with this work for additional information
  17565. * regarding copyright ownership. The ASF licenses this file
  17566. * to you under the Apache License, Version 2.0 (the
  17567. * "License"); you may not use this file except in compliance
  17568. * with the License. You may obtain a copy of the License at
  17569. *
  17570. * http://www.apache.org/licenses/LICENSE-2.0
  17571. *
  17572. * Unless required by applicable law or agreed to in writing,
  17573. * software distributed under the License is distributed on an
  17574. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17575. * KIND, either express or implied. See the License for the
  17576. * specific language governing permissions and limitations
  17577. * under the License.
  17578. */
  17579. /**
  17580. * [sourceFormat]
  17581. *
  17582. * + "original":
  17583. * This format is only used in series.data, where
  17584. * itemStyle can be specified in data item.
  17585. *
  17586. * + "arrayRows":
  17587. * [
  17588. * ['product', 'score', 'amount'],
  17589. * ['Matcha Latte', 89.3, 95.8],
  17590. * ['Milk Tea', 92.1, 89.4],
  17591. * ['Cheese Cocoa', 94.4, 91.2],
  17592. * ['Walnut Brownie', 85.4, 76.9]
  17593. * ]
  17594. *
  17595. * + "objectRows":
  17596. * [
  17597. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  17598. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  17599. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  17600. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  17601. * ]
  17602. *
  17603. * + "keyedColumns":
  17604. * {
  17605. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  17606. * 'count': [823, 235, 1042, 988],
  17607. * 'score': [95.8, 81.4, 91.2, 76.9]
  17608. * }
  17609. *
  17610. * + "typedArray"
  17611. *
  17612. * + "unknown"
  17613. */
  17614. /**
  17615. * @constructor
  17616. * @param {Object} fields
  17617. * @param {string} fields.sourceFormat
  17618. * @param {Array|Object} fields.fromDataset
  17619. * @param {Array|Object} [fields.data]
  17620. * @param {string} [seriesLayoutBy='column']
  17621. * @param {Array.<Object|string>} [dimensionsDefine]
  17622. * @param {Objet|HashMap} [encodeDefine]
  17623. * @param {number} [startIndex=0]
  17624. * @param {number} [dimensionsDetectCount]
  17625. */
  17626. function Source(fields) {
  17627. /**
  17628. * @type {boolean}
  17629. */
  17630. this.fromDataset = fields.fromDataset;
  17631. /**
  17632. * Not null/undefined.
  17633. * @type {Array|Object}
  17634. */
  17635. this.data = fields.data || (
  17636. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  17637. );
  17638. /**
  17639. * See also "detectSourceFormat".
  17640. * Not null/undefined.
  17641. * @type {string}
  17642. */
  17643. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17644. /**
  17645. * 'row' or 'column'
  17646. * Not null/undefined.
  17647. * @type {string} seriesLayoutBy
  17648. */
  17649. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17650. /**
  17651. * dimensions definition in option.
  17652. * can be null/undefined.
  17653. * @type {Array.<Object|string>}
  17654. */
  17655. this.dimensionsDefine = fields.dimensionsDefine;
  17656. /**
  17657. * encode definition in option.
  17658. * can be null/undefined.
  17659. * @type {Objet|HashMap}
  17660. */
  17661. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17662. /**
  17663. * Not null/undefined, uint.
  17664. * @type {number}
  17665. */
  17666. this.startIndex = fields.startIndex || 0;
  17667. /**
  17668. * Can be null/undefined (when unknown), uint.
  17669. * @type {number}
  17670. */
  17671. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17672. }
  17673. /**
  17674. * Wrap original series data for some compatibility cases.
  17675. */
  17676. Source.seriesDataToSource = function (data) {
  17677. return new Source({
  17678. data: data,
  17679. sourceFormat: isTypedArray(data)
  17680. ? SOURCE_FORMAT_TYPED_ARRAY
  17681. : SOURCE_FORMAT_ORIGINAL,
  17682. fromDataset: false
  17683. });
  17684. };
  17685. enableClassCheck(Source);
  17686. /*
  17687. * Licensed to the Apache Software Foundation (ASF) under one
  17688. * or more contributor license agreements. See the NOTICE file
  17689. * distributed with this work for additional information
  17690. * regarding copyright ownership. The ASF licenses this file
  17691. * to you under the Apache License, Version 2.0 (the
  17692. * "License"); you may not use this file except in compliance
  17693. * with the License. You may obtain a copy of the License at
  17694. *
  17695. * http://www.apache.org/licenses/LICENSE-2.0
  17696. *
  17697. * Unless required by applicable law or agreed to in writing,
  17698. * software distributed under the License is distributed on an
  17699. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17700. * KIND, either express or implied. See the License for the
  17701. * specific language governing permissions and limitations
  17702. * under the License.
  17703. */
  17704. var inner$3 = makeInner();
  17705. /**
  17706. * @see {module:echarts/data/Source}
  17707. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17708. * @return {string} sourceFormat
  17709. */
  17710. function detectSourceFormat(datasetModel) {
  17711. var data = datasetModel.option.source;
  17712. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17713. if (isTypedArray(data)) {
  17714. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17715. }
  17716. else if (isArray(data)) {
  17717. // FIXME Whether tolerate null in top level array?
  17718. if (data.length === 0) {
  17719. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17720. }
  17721. for (var i = 0, len = data.length; i < len; i++) {
  17722. var item = data[i];
  17723. if (item == null) {
  17724. continue;
  17725. }
  17726. else if (isArray(item)) {
  17727. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17728. break;
  17729. }
  17730. else if (isObject$1(item)) {
  17731. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17732. break;
  17733. }
  17734. }
  17735. }
  17736. else if (isObject$1(data)) {
  17737. for (var key in data) {
  17738. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17739. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17740. break;
  17741. }
  17742. }
  17743. }
  17744. else if (data != null) {
  17745. throw new Error('Invalid data');
  17746. }
  17747. inner$3(datasetModel).sourceFormat = sourceFormat;
  17748. }
  17749. /**
  17750. * [Scenarios]:
  17751. * (1) Provide source data directly:
  17752. * series: {
  17753. * encode: {...},
  17754. * dimensions: [...]
  17755. * seriesLayoutBy: 'row',
  17756. * data: [[...]]
  17757. * }
  17758. * (2) Refer to datasetModel.
  17759. * series: [{
  17760. * encode: {...}
  17761. * // Ignore datasetIndex means `datasetIndex: 0`
  17762. * // and the dimensions defination in dataset is used
  17763. * }, {
  17764. * encode: {...},
  17765. * seriesLayoutBy: 'column',
  17766. * datasetIndex: 1
  17767. * }]
  17768. *
  17769. * Get data from series itself or datset.
  17770. * @return {module:echarts/data/Source} source
  17771. */
  17772. function getSource(seriesModel) {
  17773. return inner$3(seriesModel).source;
  17774. }
  17775. /**
  17776. * MUST be called before mergeOption of all series.
  17777. * @param {module:echarts/model/Global} ecModel
  17778. */
  17779. function resetSourceDefaulter(ecModel) {
  17780. // `datasetMap` is used to make default encode.
  17781. inner$3(ecModel).datasetMap = createHashMap();
  17782. }
  17783. /**
  17784. * [Caution]:
  17785. * MUST be called after series option merged and
  17786. * before "series.getInitailData()" called.
  17787. *
  17788. * [The rule of making default encode]:
  17789. * Category axis (if exists) alway map to the first dimension.
  17790. * Each other axis occupies a subsequent dimension.
  17791. *
  17792. * [Why make default encode]:
  17793. * Simplify the typing of encode in option, avoiding the case like that:
  17794. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17795. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17796. *
  17797. * @param {module:echarts/model/Series} seriesModel
  17798. */
  17799. function prepareSource(seriesModel) {
  17800. var seriesOption = seriesModel.option;
  17801. var data = seriesOption.data;
  17802. var sourceFormat = isTypedArray(data)
  17803. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17804. var fromDataset = false;
  17805. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17806. var sourceHeader = seriesOption.sourceHeader;
  17807. var dimensionsDefine = seriesOption.dimensions;
  17808. var datasetModel = getDatasetModel(seriesModel);
  17809. if (datasetModel) {
  17810. var datasetOption = datasetModel.option;
  17811. data = datasetOption.source;
  17812. sourceFormat = inner$3(datasetModel).sourceFormat;
  17813. fromDataset = true;
  17814. // These settings from series has higher priority.
  17815. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17816. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17817. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17818. }
  17819. var completeResult = completeBySourceData(
  17820. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17821. );
  17822. // Note: dataset option does not have `encode`.
  17823. var encodeDefine = seriesOption.encode;
  17824. if (!encodeDefine && datasetModel) {
  17825. encodeDefine = makeDefaultEncode(
  17826. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17827. );
  17828. }
  17829. inner$3(seriesModel).source = new Source({
  17830. data: data,
  17831. fromDataset: fromDataset,
  17832. seriesLayoutBy: seriesLayoutBy,
  17833. sourceFormat: sourceFormat,
  17834. dimensionsDefine: completeResult.dimensionsDefine,
  17835. startIndex: completeResult.startIndex,
  17836. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17837. encodeDefine: encodeDefine
  17838. });
  17839. }
  17840. // return {startIndex, dimensionsDefine, dimensionsCount}
  17841. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17842. if (!data) {
  17843. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17844. }
  17845. var dimensionsDetectCount;
  17846. var startIndex;
  17847. var findPotentialName;
  17848. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17849. // Rule: Most of the first line are string: it is header.
  17850. // Caution: consider a line with 5 string and 1 number,
  17851. // it still can not be sure it is a head, because the
  17852. // 5 string may be 5 values of category columns.
  17853. if (sourceHeader === 'auto' || sourceHeader == null) {
  17854. arrayRowsTravelFirst(function (val) {
  17855. // '-' is regarded as null/undefined.
  17856. if (val != null && val !== '-') {
  17857. if (isString(val)) {
  17858. startIndex == null && (startIndex = 1);
  17859. }
  17860. else {
  17861. startIndex = 0;
  17862. }
  17863. }
  17864. // 10 is an experience number, avoid long loop.
  17865. }, seriesLayoutBy, data, 10);
  17866. }
  17867. else {
  17868. startIndex = sourceHeader ? 1 : 0;
  17869. }
  17870. if (!dimensionsDefine && startIndex === 1) {
  17871. dimensionsDefine = [];
  17872. arrayRowsTravelFirst(function (val, index) {
  17873. dimensionsDefine[index] = val != null ? val : '';
  17874. }, seriesLayoutBy, data);
  17875. }
  17876. dimensionsDetectCount = dimensionsDefine
  17877. ? dimensionsDefine.length
  17878. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17879. ? data.length
  17880. : data[0]
  17881. ? data[0].length
  17882. : null;
  17883. }
  17884. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17885. if (!dimensionsDefine) {
  17886. dimensionsDefine = objectRowsCollectDimensions(data);
  17887. findPotentialName = true;
  17888. }
  17889. }
  17890. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17891. if (!dimensionsDefine) {
  17892. dimensionsDefine = [];
  17893. findPotentialName = true;
  17894. each$1(data, function (colArr, key) {
  17895. dimensionsDefine.push(key);
  17896. });
  17897. }
  17898. }
  17899. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17900. var value0 = getDataItemValue(data[0]);
  17901. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17902. }
  17903. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17904. if (__DEV__) {
  17905. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  17906. }
  17907. }
  17908. var potentialNameDimIndex;
  17909. if (findPotentialName) {
  17910. each$1(dimensionsDefine, function (dim, idx) {
  17911. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17912. potentialNameDimIndex = idx;
  17913. }
  17914. });
  17915. }
  17916. return {
  17917. startIndex: startIndex,
  17918. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17919. dimensionsDetectCount: dimensionsDetectCount,
  17920. potentialNameDimIndex: potentialNameDimIndex
  17921. // TODO: potentialIdDimIdx
  17922. };
  17923. }
  17924. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17925. // which is reasonable. But dimension name is duplicated.
  17926. // Returns undefined or an array contains only object without null/undefiend or string.
  17927. function normalizeDimensionsDefine(dimensionsDefine) {
  17928. if (!dimensionsDefine) {
  17929. // The meaning of null/undefined is different from empty array.
  17930. return;
  17931. }
  17932. var nameMap = createHashMap();
  17933. return map(dimensionsDefine, function (item, index) {
  17934. item = extend({}, isObject$1(item) ? item : {name: item});
  17935. // User can set null in dimensions.
  17936. // We dont auto specify name, othewise a given name may
  17937. // cause it be refered unexpectedly.
  17938. if (item.name == null) {
  17939. return item;
  17940. }
  17941. // Also consider number form like 2012.
  17942. item.name += '';
  17943. // User may also specify displayName.
  17944. // displayName will always exists except user not
  17945. // specified or dim name is not specified or detected.
  17946. // (A auto generated dim name will not be used as
  17947. // displayName).
  17948. if (item.displayName == null) {
  17949. item.displayName = item.name;
  17950. }
  17951. var exist = nameMap.get(item.name);
  17952. if (!exist) {
  17953. nameMap.set(item.name, {count: 1});
  17954. }
  17955. else {
  17956. item.name += '-' + exist.count++;
  17957. }
  17958. return item;
  17959. });
  17960. }
  17961. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  17962. maxLoop == null && (maxLoop = Infinity);
  17963. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17964. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17965. cb(data[i] ? data[i][0] : null, i);
  17966. }
  17967. }
  17968. else {
  17969. var value0 = data[0] || [];
  17970. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  17971. cb(value0[i], i);
  17972. }
  17973. }
  17974. }
  17975. function objectRowsCollectDimensions(data) {
  17976. var firstIndex = 0;
  17977. var obj;
  17978. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  17979. if (obj) {
  17980. var dimensions = [];
  17981. each$1(obj, function (value, key) {
  17982. dimensions.push(key);
  17983. });
  17984. return dimensions;
  17985. }
  17986. }
  17987. // ??? TODO merge to completedimensions, where also has
  17988. // default encode making logic. And the default rule
  17989. // should depends on series? consider 'map'.
  17990. function makeDefaultEncode(
  17991. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17992. ) {
  17993. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  17994. var encode = {};
  17995. // var encodeTooltip = [];
  17996. // var encodeLabel = [];
  17997. var encodeItemName = [];
  17998. var encodeSeriesName = [];
  17999. var seriesType = seriesModel.subType;
  18000. // ??? TODO refactor: provide by series itself.
  18001. // Consider the case: 'map' series is based on geo coordSys,
  18002. // 'graph', 'heatmap' can be based on cartesian. But can not
  18003. // give default rule simply here.
  18004. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  18005. var cSeriesMap = createHashMap([
  18006. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  18007. ]);
  18008. // Usually in this case series will use the first data
  18009. // dimension as the "value" dimension, or other default
  18010. // processes respectively.
  18011. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  18012. var ecModel = seriesModel.ecModel;
  18013. var datasetMap = inner$3(ecModel).datasetMap;
  18014. var key = datasetModel.uid + '_' + seriesLayoutBy;
  18015. var datasetRecord = datasetMap.get(key)
  18016. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  18017. // TODO
  18018. // Auto detect first time axis and do arrangement.
  18019. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  18020. // In value way.
  18021. if (coordSysDefine.firstCategoryDimIndex == null) {
  18022. var dataDim = datasetRecord.valueWayDim++;
  18023. encode[coordDim] = dataDim;
  18024. // ??? TODO give a better default series name rule?
  18025. // especially when encode x y specified.
  18026. // consider: when mutiple series share one dimension
  18027. // category axis, series name should better use
  18028. // the other dimsion name. On the other hand, use
  18029. // both dimensions name.
  18030. encodeSeriesName.push(dataDim);
  18031. // encodeTooltip.push(dataDim);
  18032. // encodeLabel.push(dataDim);
  18033. }
  18034. // In category way, category axis.
  18035. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  18036. encode[coordDim] = 0;
  18037. encodeItemName.push(0);
  18038. }
  18039. // In category way, non-category axis.
  18040. else {
  18041. var dataDim = datasetRecord.categoryWayDim++;
  18042. encode[coordDim] = dataDim;
  18043. // encodeTooltip.push(dataDim);
  18044. // encodeLabel.push(dataDim);
  18045. encodeSeriesName.push(dataDim);
  18046. }
  18047. });
  18048. }
  18049. // Do not make a complex rule! Hard to code maintain and not necessary.
  18050. // ??? TODO refactor: provide by series itself.
  18051. // [{name: ..., value: ...}, ...] like:
  18052. else if (nSeriesMap.get(seriesType) != null) {
  18053. // Find the first not ordinal. (5 is an experience value)
  18054. var firstNotOrdinal;
  18055. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  18056. if (!doGuessOrdinal(
  18057. data, sourceFormat, seriesLayoutBy,
  18058. completeResult.dimensionsDefine, completeResult.startIndex, i
  18059. )) {
  18060. firstNotOrdinal = i;
  18061. }
  18062. }
  18063. if (firstNotOrdinal != null) {
  18064. encode.value = firstNotOrdinal;
  18065. var nameDimIndex = completeResult.potentialNameDimIndex
  18066. || Math.max(firstNotOrdinal - 1, 0);
  18067. // By default, label use itemName in charts.
  18068. // So we dont set encodeLabel here.
  18069. encodeSeriesName.push(nameDimIndex);
  18070. encodeItemName.push(nameDimIndex);
  18071. // encodeTooltip.push(firstNotOrdinal);
  18072. }
  18073. }
  18074. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  18075. // encodeLabel.length && (encode.label = encodeLabel);
  18076. encodeItemName.length && (encode.itemName = encodeItemName);
  18077. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18078. return encode;
  18079. }
  18080. /**
  18081. * If return null/undefined, indicate that should not use datasetModel.
  18082. */
  18083. function getDatasetModel(seriesModel) {
  18084. var option = seriesModel.option;
  18085. // Caution: consider the scenario:
  18086. // A dataset is declared and a series is not expected to use the dataset,
  18087. // and at the beginning `setOption({series: { noData })` (just prepare other
  18088. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18089. // the user should set an empty array to avoid that dataset is used by default.
  18090. var thisData = option.data;
  18091. if (!thisData) {
  18092. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18093. }
  18094. }
  18095. /**
  18096. * The rule should not be complex, otherwise user might not
  18097. * be able to known where the data is wrong.
  18098. * The code is ugly, but how to make it neat?
  18099. *
  18100. * @param {module:echars/data/Source} source
  18101. * @param {number} dimIndex
  18102. * @return {boolean} Whether ordinal.
  18103. */
  18104. function guessOrdinal(source, dimIndex) {
  18105. return doGuessOrdinal(
  18106. source.data,
  18107. source.sourceFormat,
  18108. source.seriesLayoutBy,
  18109. source.dimensionsDefine,
  18110. source.startIndex,
  18111. dimIndex
  18112. );
  18113. }
  18114. // dimIndex may be overflow source data.
  18115. function doGuessOrdinal(
  18116. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18117. ) {
  18118. var result;
  18119. // Experience value.
  18120. var maxLoop = 5;
  18121. if (isTypedArray(data)) {
  18122. return false;
  18123. }
  18124. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18125. // always exists in source.
  18126. var dimName;
  18127. if (dimensionsDefine) {
  18128. dimName = dimensionsDefine[dimIndex];
  18129. dimName = isObject$1(dimName) ? dimName.name : dimName;
  18130. }
  18131. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18132. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18133. var sample = data[dimIndex];
  18134. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18135. if ((result = detectValue(sample[startIndex + i])) != null) {
  18136. return result;
  18137. }
  18138. }
  18139. }
  18140. else {
  18141. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18142. var row = data[startIndex + i];
  18143. if (row && (result = detectValue(row[dimIndex])) != null) {
  18144. return result;
  18145. }
  18146. }
  18147. }
  18148. }
  18149. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18150. if (!dimName) {
  18151. return;
  18152. }
  18153. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18154. var item = data[i];
  18155. if (item && (result = detectValue(item[dimName])) != null) {
  18156. return result;
  18157. }
  18158. }
  18159. }
  18160. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18161. if (!dimName) {
  18162. return;
  18163. }
  18164. var sample = data[dimName];
  18165. if (!sample || isTypedArray(sample)) {
  18166. return false;
  18167. }
  18168. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18169. if ((result = detectValue(sample[i])) != null) {
  18170. return result;
  18171. }
  18172. }
  18173. }
  18174. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18175. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18176. var item = data[i];
  18177. var val = getDataItemValue(item);
  18178. if (!isArray(val)) {
  18179. return false;
  18180. }
  18181. if ((result = detectValue(val[dimIndex])) != null) {
  18182. return result;
  18183. }
  18184. }
  18185. }
  18186. function detectValue(val) {
  18187. // Consider usage convenience, '1', '2' will be treated as "number".
  18188. // `isFinit('')` get `true`.
  18189. if (val != null && isFinite(val) && val !== '') {
  18190. return false;
  18191. }
  18192. else if (isString(val) && val !== '-') {
  18193. return true;
  18194. }
  18195. }
  18196. return false;
  18197. }
  18198. /*
  18199. * Licensed to the Apache Software Foundation (ASF) under one
  18200. * or more contributor license agreements. See the NOTICE file
  18201. * distributed with this work for additional information
  18202. * regarding copyright ownership. The ASF licenses this file
  18203. * to you under the Apache License, Version 2.0 (the
  18204. * "License"); you may not use this file except in compliance
  18205. * with the License. You may obtain a copy of the License at
  18206. *
  18207. * http://www.apache.org/licenses/LICENSE-2.0
  18208. *
  18209. * Unless required by applicable law or agreed to in writing,
  18210. * software distributed under the License is distributed on an
  18211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18212. * KIND, either express or implied. See the License for the
  18213. * specific language governing permissions and limitations
  18214. * under the License.
  18215. */
  18216. /**
  18217. * ECharts global model
  18218. *
  18219. * @module {echarts/model/Global}
  18220. */
  18221. /**
  18222. * Caution: If the mechanism should be changed some day, these cases
  18223. * should be considered:
  18224. *
  18225. * (1) In `merge option` mode, if using the same option to call `setOption`
  18226. * many times, the result should be the same (try our best to ensure that).
  18227. * (2) In `merge option` mode, if a component has no id/name specified, it
  18228. * will be merged by index, and the result sequence of the components is
  18229. * consistent to the original sequence.
  18230. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  18231. * `mergeOption` in module:echarts/model/OptionManager.
  18232. */
  18233. var OPTION_INNER_KEY = '\0_ec_inner';
  18234. /**
  18235. * @alias module:echarts/model/Global
  18236. *
  18237. * @param {Object} option
  18238. * @param {module:echarts/model/Model} parentModel
  18239. * @param {Object} theme
  18240. */
  18241. var GlobalModel = Model.extend({
  18242. init: function (option, parentModel, theme, optionManager) {
  18243. theme = theme || {};
  18244. this.option = null; // Mark as not initialized.
  18245. /**
  18246. * @type {module:echarts/model/Model}
  18247. * @private
  18248. */
  18249. this._theme = new Model(theme);
  18250. /**
  18251. * @type {module:echarts/model/OptionManager}
  18252. */
  18253. this._optionManager = optionManager;
  18254. },
  18255. setOption: function (option, optionPreprocessorFuncs) {
  18256. assert$1(
  18257. !(OPTION_INNER_KEY in option),
  18258. 'please use chart.getOption()'
  18259. );
  18260. this._optionManager.setOption(option, optionPreprocessorFuncs);
  18261. this.resetOption(null);
  18262. },
  18263. /**
  18264. * @param {string} type null/undefined: reset all.
  18265. * 'recreate': force recreate all.
  18266. * 'timeline': only reset timeline option
  18267. * 'media': only reset media query option
  18268. * @return {boolean} Whether option changed.
  18269. */
  18270. resetOption: function (type) {
  18271. var optionChanged = false;
  18272. var optionManager = this._optionManager;
  18273. if (!type || type === 'recreate') {
  18274. var baseOption = optionManager.mountOption(type === 'recreate');
  18275. if (!this.option || type === 'recreate') {
  18276. initBase.call(this, baseOption);
  18277. }
  18278. else {
  18279. this.restoreData();
  18280. this.mergeOption(baseOption);
  18281. }
  18282. optionChanged = true;
  18283. }
  18284. if (type === 'timeline' || type === 'media') {
  18285. this.restoreData();
  18286. }
  18287. if (!type || type === 'recreate' || type === 'timeline') {
  18288. var timelineOption = optionManager.getTimelineOption(this);
  18289. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  18290. }
  18291. if (!type || type === 'recreate' || type === 'media') {
  18292. var mediaOptions = optionManager.getMediaOption(this, this._api);
  18293. if (mediaOptions.length) {
  18294. each$1(mediaOptions, function (mediaOption) {
  18295. this.mergeOption(mediaOption, optionChanged = true);
  18296. }, this);
  18297. }
  18298. }
  18299. return optionChanged;
  18300. },
  18301. /**
  18302. * @protected
  18303. */
  18304. mergeOption: function (newOption) {
  18305. var option = this.option;
  18306. var componentsMap = this._componentsMap;
  18307. var newCptTypes = [];
  18308. resetSourceDefaulter(this);
  18309. // If no component class, merge directly.
  18310. // For example: color, animaiton options, etc.
  18311. each$1(newOption, function (componentOption, mainType) {
  18312. if (componentOption == null) {
  18313. return;
  18314. }
  18315. if (!ComponentModel.hasClass(mainType)) {
  18316. // globalSettingTask.dirty();
  18317. option[mainType] = option[mainType] == null
  18318. ? clone(componentOption)
  18319. : merge(option[mainType], componentOption, true);
  18320. }
  18321. else if (mainType) {
  18322. newCptTypes.push(mainType);
  18323. }
  18324. });
  18325. ComponentModel.topologicalTravel(
  18326. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  18327. );
  18328. function visitComponent(mainType, dependencies) {
  18329. var newCptOptionList = normalizeToArray(newOption[mainType]);
  18330. var mapResult = mappingToExists(
  18331. componentsMap.get(mainType), newCptOptionList
  18332. );
  18333. makeIdAndName(mapResult);
  18334. // Set mainType and complete subType.
  18335. each$1(mapResult, function (item, index) {
  18336. var opt = item.option;
  18337. if (isObject$1(opt)) {
  18338. item.keyInfo.mainType = mainType;
  18339. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  18340. }
  18341. });
  18342. var dependentModels = getComponentsByTypes(
  18343. componentsMap, dependencies
  18344. );
  18345. option[mainType] = [];
  18346. componentsMap.set(mainType, []);
  18347. each$1(mapResult, function (resultItem, index) {
  18348. var componentModel = resultItem.exist;
  18349. var newCptOption = resultItem.option;
  18350. assert$1(
  18351. isObject$1(newCptOption) || componentModel,
  18352. 'Empty component definition'
  18353. );
  18354. // Consider where is no new option and should be merged using {},
  18355. // see removeEdgeAndAdd in topologicalTravel and
  18356. // ComponentModel.getAllClassMainTypes.
  18357. if (!newCptOption) {
  18358. componentModel.mergeOption({}, this);
  18359. componentModel.optionUpdated({}, false);
  18360. }
  18361. else {
  18362. var ComponentModelClass = ComponentModel.getClass(
  18363. mainType, resultItem.keyInfo.subType, true
  18364. );
  18365. if (componentModel && componentModel instanceof ComponentModelClass) {
  18366. componentModel.name = resultItem.keyInfo.name;
  18367. // componentModel.settingTask && componentModel.settingTask.dirty();
  18368. componentModel.mergeOption(newCptOption, this);
  18369. componentModel.optionUpdated(newCptOption, false);
  18370. }
  18371. else {
  18372. // PENDING Global as parent ?
  18373. var extraOpt = extend(
  18374. {
  18375. dependentModels: dependentModels,
  18376. componentIndex: index
  18377. },
  18378. resultItem.keyInfo
  18379. );
  18380. componentModel = new ComponentModelClass(
  18381. newCptOption, this, this, extraOpt
  18382. );
  18383. extend(componentModel, extraOpt);
  18384. componentModel.init(newCptOption, this, this, extraOpt);
  18385. // Call optionUpdated after init.
  18386. // newCptOption has been used as componentModel.option
  18387. // and may be merged with theme and default, so pass null
  18388. // to avoid confusion.
  18389. componentModel.optionUpdated(null, true);
  18390. }
  18391. }
  18392. componentsMap.get(mainType)[index] = componentModel;
  18393. option[mainType][index] = componentModel.option;
  18394. }, this);
  18395. // Backup series for filtering.
  18396. if (mainType === 'series') {
  18397. createSeriesIndices(this, componentsMap.get('series'));
  18398. }
  18399. }
  18400. this._seriesIndicesMap = createHashMap(
  18401. this._seriesIndices = this._seriesIndices || []
  18402. );
  18403. },
  18404. /**
  18405. * Get option for output (cloned option and inner info removed)
  18406. * @public
  18407. * @return {Object}
  18408. */
  18409. getOption: function () {
  18410. var option = clone(this.option);
  18411. each$1(option, function (opts, mainType) {
  18412. if (ComponentModel.hasClass(mainType)) {
  18413. var opts = normalizeToArray(opts);
  18414. for (var i = opts.length - 1; i >= 0; i--) {
  18415. // Remove options with inner id.
  18416. if (isIdInner(opts[i])) {
  18417. opts.splice(i, 1);
  18418. }
  18419. }
  18420. option[mainType] = opts;
  18421. }
  18422. });
  18423. delete option[OPTION_INNER_KEY];
  18424. return option;
  18425. },
  18426. /**
  18427. * @return {module:echarts/model/Model}
  18428. */
  18429. getTheme: function () {
  18430. return this._theme;
  18431. },
  18432. /**
  18433. * @param {string} mainType
  18434. * @param {number} [idx=0]
  18435. * @return {module:echarts/model/Component}
  18436. */
  18437. getComponent: function (mainType, idx) {
  18438. var list = this._componentsMap.get(mainType);
  18439. if (list) {
  18440. return list[idx || 0];
  18441. }
  18442. },
  18443. /**
  18444. * If none of index and id and name used, return all components with mainType.
  18445. * @param {Object} condition
  18446. * @param {string} condition.mainType
  18447. * @param {string} [condition.subType] If ignore, only query by mainType
  18448. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  18449. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  18450. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  18451. * @return {Array.<module:echarts/model/Component>}
  18452. */
  18453. queryComponents: function (condition) {
  18454. var mainType = condition.mainType;
  18455. if (!mainType) {
  18456. return [];
  18457. }
  18458. var index = condition.index;
  18459. var id = condition.id;
  18460. var name = condition.name;
  18461. var cpts = this._componentsMap.get(mainType);
  18462. if (!cpts || !cpts.length) {
  18463. return [];
  18464. }
  18465. var result;
  18466. if (index != null) {
  18467. if (!isArray(index)) {
  18468. index = [index];
  18469. }
  18470. result = filter(map(index, function (idx) {
  18471. return cpts[idx];
  18472. }), function (val) {
  18473. return !!val;
  18474. });
  18475. }
  18476. else if (id != null) {
  18477. var isIdArray = isArray(id);
  18478. result = filter(cpts, function (cpt) {
  18479. return (isIdArray && indexOf(id, cpt.id) >= 0)
  18480. || (!isIdArray && cpt.id === id);
  18481. });
  18482. }
  18483. else if (name != null) {
  18484. var isNameArray = isArray(name);
  18485. result = filter(cpts, function (cpt) {
  18486. return (isNameArray && indexOf(name, cpt.name) >= 0)
  18487. || (!isNameArray && cpt.name === name);
  18488. });
  18489. }
  18490. else {
  18491. // Return all components with mainType
  18492. result = cpts.slice();
  18493. }
  18494. return filterBySubType(result, condition);
  18495. },
  18496. /**
  18497. * The interface is different from queryComponents,
  18498. * which is convenient for inner usage.
  18499. *
  18500. * @usage
  18501. * var result = findComponents(
  18502. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  18503. * );
  18504. * var result = findComponents(
  18505. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  18506. * );
  18507. * var result = findComponents(
  18508. * {mainType: 'series'},
  18509. * function (model, index) {...}
  18510. * );
  18511. * // result like [component0, componnet1, ...]
  18512. *
  18513. * @param {Object} condition
  18514. * @param {string} condition.mainType Mandatory.
  18515. * @param {string} [condition.subType] Optional.
  18516. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  18517. * where xxx is mainType.
  18518. * If query attribute is null/undefined or has no index/id/name,
  18519. * do not filtering by query conditions, which is convenient for
  18520. * no-payload situations or when target of action is global.
  18521. * @param {Function} [condition.filter] parameter: component, return boolean.
  18522. * @return {Array.<module:echarts/model/Component>}
  18523. */
  18524. findComponents: function (condition) {
  18525. var query = condition.query;
  18526. var mainType = condition.mainType;
  18527. var queryCond = getQueryCond(query);
  18528. var result = queryCond
  18529. ? this.queryComponents(queryCond)
  18530. : this._componentsMap.get(mainType);
  18531. return doFilter(filterBySubType(result, condition));
  18532. function getQueryCond(q) {
  18533. var indexAttr = mainType + 'Index';
  18534. var idAttr = mainType + 'Id';
  18535. var nameAttr = mainType + 'Name';
  18536. return q && (
  18537. q[indexAttr] != null
  18538. || q[idAttr] != null
  18539. || q[nameAttr] != null
  18540. )
  18541. ? {
  18542. mainType: mainType,
  18543. // subType will be filtered finally.
  18544. index: q[indexAttr],
  18545. id: q[idAttr],
  18546. name: q[nameAttr]
  18547. }
  18548. : null;
  18549. }
  18550. function doFilter(res) {
  18551. return condition.filter
  18552. ? filter(res, condition.filter)
  18553. : res;
  18554. }
  18555. },
  18556. /**
  18557. * @usage
  18558. * eachComponent('legend', function (legendModel, index) {
  18559. * ...
  18560. * });
  18561. * eachComponent(function (componentType, model, index) {
  18562. * // componentType does not include subType
  18563. * // (componentType is 'xxx' but not 'xxx.aa')
  18564. * });
  18565. * eachComponent(
  18566. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  18567. * function (model, index) {...}
  18568. * );
  18569. * eachComponent(
  18570. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  18571. * function (model, index) {...}
  18572. * );
  18573. *
  18574. * @param {string|Object=} mainType When mainType is object, the definition
  18575. * is the same as the method 'findComponents'.
  18576. * @param {Function} cb
  18577. * @param {*} context
  18578. */
  18579. eachComponent: function (mainType, cb, context) {
  18580. var componentsMap = this._componentsMap;
  18581. if (typeof mainType === 'function') {
  18582. context = cb;
  18583. cb = mainType;
  18584. componentsMap.each(function (components, componentType) {
  18585. each$1(components, function (component, index) {
  18586. cb.call(context, componentType, component, index);
  18587. });
  18588. });
  18589. }
  18590. else if (isString(mainType)) {
  18591. each$1(componentsMap.get(mainType), cb, context);
  18592. }
  18593. else if (isObject$1(mainType)) {
  18594. var queryResult = this.findComponents(mainType);
  18595. each$1(queryResult, cb, context);
  18596. }
  18597. },
  18598. /**
  18599. * @param {string} name
  18600. * @return {Array.<module:echarts/model/Series>}
  18601. */
  18602. getSeriesByName: function (name) {
  18603. var series = this._componentsMap.get('series');
  18604. return filter(series, function (oneSeries) {
  18605. return oneSeries.name === name;
  18606. });
  18607. },
  18608. /**
  18609. * @param {number} seriesIndex
  18610. * @return {module:echarts/model/Series}
  18611. */
  18612. getSeriesByIndex: function (seriesIndex) {
  18613. return this._componentsMap.get('series')[seriesIndex];
  18614. },
  18615. /**
  18616. * Get series list before filtered by type.
  18617. * FIXME: rename to getRawSeriesByType?
  18618. *
  18619. * @param {string} subType
  18620. * @return {Array.<module:echarts/model/Series>}
  18621. */
  18622. getSeriesByType: function (subType) {
  18623. var series = this._componentsMap.get('series');
  18624. return filter(series, function (oneSeries) {
  18625. return oneSeries.subType === subType;
  18626. });
  18627. },
  18628. /**
  18629. * @return {Array.<module:echarts/model/Series>}
  18630. */
  18631. getSeries: function () {
  18632. return this._componentsMap.get('series').slice();
  18633. },
  18634. /**
  18635. * @return {number}
  18636. */
  18637. getSeriesCount: function () {
  18638. return this._componentsMap.get('series').length;
  18639. },
  18640. /**
  18641. * After filtering, series may be different
  18642. * frome raw series.
  18643. *
  18644. * @param {Function} cb
  18645. * @param {*} context
  18646. */
  18647. eachSeries: function (cb, context) {
  18648. assertSeriesInitialized(this);
  18649. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18650. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18651. cb.call(context, series, rawSeriesIndex);
  18652. }, this);
  18653. },
  18654. /**
  18655. * Iterate raw series before filtered.
  18656. *
  18657. * @param {Function} cb
  18658. * @param {*} context
  18659. */
  18660. eachRawSeries: function (cb, context) {
  18661. each$1(this._componentsMap.get('series'), cb, context);
  18662. },
  18663. /**
  18664. * After filtering, series may be different.
  18665. * frome raw series.
  18666. *
  18667. * @parma {string} subType
  18668. * @param {Function} cb
  18669. * @param {*} context
  18670. */
  18671. eachSeriesByType: function (subType, cb, context) {
  18672. assertSeriesInitialized(this);
  18673. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18674. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18675. if (series.subType === subType) {
  18676. cb.call(context, series, rawSeriesIndex);
  18677. }
  18678. }, this);
  18679. },
  18680. /**
  18681. * Iterate raw series before filtered of given type.
  18682. *
  18683. * @parma {string} subType
  18684. * @param {Function} cb
  18685. * @param {*} context
  18686. */
  18687. eachRawSeriesByType: function (subType, cb, context) {
  18688. return each$1(this.getSeriesByType(subType), cb, context);
  18689. },
  18690. /**
  18691. * @param {module:echarts/model/Series} seriesModel
  18692. */
  18693. isSeriesFiltered: function (seriesModel) {
  18694. assertSeriesInitialized(this);
  18695. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18696. },
  18697. /**
  18698. * @return {Array.<number>}
  18699. */
  18700. getCurrentSeriesIndices: function () {
  18701. return (this._seriesIndices || []).slice();
  18702. },
  18703. /**
  18704. * @param {Function} cb
  18705. * @param {*} context
  18706. */
  18707. filterSeries: function (cb, context) {
  18708. assertSeriesInitialized(this);
  18709. var filteredSeries = filter(
  18710. this._componentsMap.get('series'), cb, context
  18711. );
  18712. createSeriesIndices(this, filteredSeries);
  18713. },
  18714. restoreData: function (payload) {
  18715. var componentsMap = this._componentsMap;
  18716. createSeriesIndices(this, componentsMap.get('series'));
  18717. var componentTypes = [];
  18718. componentsMap.each(function (components, componentType) {
  18719. componentTypes.push(componentType);
  18720. });
  18721. ComponentModel.topologicalTravel(
  18722. componentTypes,
  18723. ComponentModel.getAllClassMainTypes(),
  18724. function (componentType, dependencies) {
  18725. each$1(componentsMap.get(componentType), function (component) {
  18726. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18727. && component.restoreData();
  18728. });
  18729. }
  18730. );
  18731. }
  18732. });
  18733. function isNotTargetSeries(seriesModel, payload) {
  18734. if (payload) {
  18735. var index = payload.seiresIndex;
  18736. var id = payload.seriesId;
  18737. var name = payload.seriesName;
  18738. return (index != null && seriesModel.componentIndex !== index)
  18739. || (id != null && seriesModel.id !== id)
  18740. || (name != null && seriesModel.name !== name);
  18741. }
  18742. }
  18743. /**
  18744. * @inner
  18745. */
  18746. function mergeTheme(option, theme) {
  18747. // PENDING
  18748. // NOT use `colorLayer` in theme if option has `color`
  18749. var notMergeColorLayer = option.color && !option.colorLayer;
  18750. each$1(theme, function (themeItem, name) {
  18751. if (name === 'colorLayer' && notMergeColorLayer) {
  18752. return;
  18753. }
  18754. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18755. if (!ComponentModel.hasClass(name)) {
  18756. if (typeof themeItem === 'object') {
  18757. option[name] = !option[name]
  18758. ? clone(themeItem)
  18759. : merge(option[name], themeItem, false);
  18760. }
  18761. else {
  18762. if (option[name] == null) {
  18763. option[name] = themeItem;
  18764. }
  18765. }
  18766. }
  18767. });
  18768. }
  18769. function initBase(baseOption) {
  18770. baseOption = baseOption;
  18771. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18772. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18773. this.option = {};
  18774. this.option[OPTION_INNER_KEY] = 1;
  18775. /**
  18776. * Init with series: [], in case of calling findSeries method
  18777. * before series initialized.
  18778. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18779. * @private
  18780. */
  18781. this._componentsMap = createHashMap({series: []});
  18782. /**
  18783. * Mapping between filtered series list and raw series list.
  18784. * key: filtered series indices, value: raw series indices.
  18785. * @type {Array.<nubmer>}
  18786. * @private
  18787. */
  18788. this._seriesIndices;
  18789. this._seriesIndicesMap;
  18790. mergeTheme(baseOption, this._theme.option);
  18791. // TODO Needs clone when merging to the unexisted property
  18792. merge(baseOption, globalDefault, false);
  18793. this.mergeOption(baseOption);
  18794. }
  18795. /**
  18796. * @inner
  18797. * @param {Array.<string>|string} types model types
  18798. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18799. */
  18800. function getComponentsByTypes(componentsMap, types) {
  18801. if (!isArray(types)) {
  18802. types = types ? [types] : [];
  18803. }
  18804. var ret = {};
  18805. each$1(types, function (type) {
  18806. ret[type] = (componentsMap.get(type) || []).slice();
  18807. });
  18808. return ret;
  18809. }
  18810. /**
  18811. * @inner
  18812. */
  18813. function determineSubType(mainType, newCptOption, existComponent) {
  18814. var subType = newCptOption.type
  18815. ? newCptOption.type
  18816. : existComponent
  18817. ? existComponent.subType
  18818. // Use determineSubType only when there is no existComponent.
  18819. : ComponentModel.determineSubType(mainType, newCptOption);
  18820. // tooltip, markline, markpoint may always has no subType
  18821. return subType;
  18822. }
  18823. /**
  18824. * @inner
  18825. */
  18826. function createSeriesIndices(ecModel, seriesModels) {
  18827. ecModel._seriesIndicesMap = createHashMap(
  18828. ecModel._seriesIndices = map(seriesModels, function (series) {
  18829. return series.componentIndex;
  18830. }) || []
  18831. );
  18832. }
  18833. /**
  18834. * @inner
  18835. */
  18836. function filterBySubType(components, condition) {
  18837. // Using hasOwnProperty for restrict. Consider
  18838. // subType is undefined in user payload.
  18839. return condition.hasOwnProperty('subType')
  18840. ? filter(components, function (cpt) {
  18841. return cpt.subType === condition.subType;
  18842. })
  18843. : components;
  18844. }
  18845. /**
  18846. * @inner
  18847. */
  18848. function assertSeriesInitialized(ecModel) {
  18849. // Components that use _seriesIndices should depends on series component,
  18850. // which make sure that their initialization is after series.
  18851. if (__DEV__) {
  18852. if (!ecModel._seriesIndices) {
  18853. throw new Error('Option should contains series.');
  18854. }
  18855. }
  18856. }
  18857. mixin(GlobalModel, colorPaletteMixin);
  18858. /*
  18859. * Licensed to the Apache Software Foundation (ASF) under one
  18860. * or more contributor license agreements. See the NOTICE file
  18861. * distributed with this work for additional information
  18862. * regarding copyright ownership. The ASF licenses this file
  18863. * to you under the Apache License, Version 2.0 (the
  18864. * "License"); you may not use this file except in compliance
  18865. * with the License. You may obtain a copy of the License at
  18866. *
  18867. * http://www.apache.org/licenses/LICENSE-2.0
  18868. *
  18869. * Unless required by applicable law or agreed to in writing,
  18870. * software distributed under the License is distributed on an
  18871. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18872. * KIND, either express or implied. See the License for the
  18873. * specific language governing permissions and limitations
  18874. * under the License.
  18875. */
  18876. var echartsAPIList = [
  18877. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  18878. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  18879. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  18880. ];
  18881. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18882. function ExtensionAPI(chartInstance) {
  18883. each$1(echartsAPIList, function (name) {
  18884. this[name] = bind(chartInstance[name], chartInstance);
  18885. }, this);
  18886. }
  18887. /*
  18888. * Licensed to the Apache Software Foundation (ASF) under one
  18889. * or more contributor license agreements. See the NOTICE file
  18890. * distributed with this work for additional information
  18891. * regarding copyright ownership. The ASF licenses this file
  18892. * to you under the Apache License, Version 2.0 (the
  18893. * "License"); you may not use this file except in compliance
  18894. * with the License. You may obtain a copy of the License at
  18895. *
  18896. * http://www.apache.org/licenses/LICENSE-2.0
  18897. *
  18898. * Unless required by applicable law or agreed to in writing,
  18899. * software distributed under the License is distributed on an
  18900. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18901. * KIND, either express or implied. See the License for the
  18902. * specific language governing permissions and limitations
  18903. * under the License.
  18904. */
  18905. var coordinateSystemCreators = {};
  18906. function CoordinateSystemManager() {
  18907. this._coordinateSystems = [];
  18908. }
  18909. CoordinateSystemManager.prototype = {
  18910. constructor: CoordinateSystemManager,
  18911. create: function (ecModel, api) {
  18912. var coordinateSystems = [];
  18913. each$1(coordinateSystemCreators, function (creater, type) {
  18914. var list = creater.create(ecModel, api);
  18915. coordinateSystems = coordinateSystems.concat(list || []);
  18916. });
  18917. this._coordinateSystems = coordinateSystems;
  18918. },
  18919. update: function (ecModel, api) {
  18920. each$1(this._coordinateSystems, function (coordSys) {
  18921. coordSys.update && coordSys.update(ecModel, api);
  18922. });
  18923. },
  18924. getCoordinateSystems: function () {
  18925. return this._coordinateSystems.slice();
  18926. }
  18927. };
  18928. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18929. coordinateSystemCreators[type] = coordinateSystemCreator;
  18930. };
  18931. CoordinateSystemManager.get = function (type) {
  18932. return coordinateSystemCreators[type];
  18933. };
  18934. /*
  18935. * Licensed to the Apache Software Foundation (ASF) under one
  18936. * or more contributor license agreements. See the NOTICE file
  18937. * distributed with this work for additional information
  18938. * regarding copyright ownership. The ASF licenses this file
  18939. * to you under the Apache License, Version 2.0 (the
  18940. * "License"); you may not use this file except in compliance
  18941. * with the License. You may obtain a copy of the License at
  18942. *
  18943. * http://www.apache.org/licenses/LICENSE-2.0
  18944. *
  18945. * Unless required by applicable law or agreed to in writing,
  18946. * software distributed under the License is distributed on an
  18947. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18948. * KIND, either express or implied. See the License for the
  18949. * specific language governing permissions and limitations
  18950. * under the License.
  18951. */
  18952. /**
  18953. * ECharts option manager
  18954. *
  18955. * @module {echarts/model/OptionManager}
  18956. */
  18957. var each$4 = each$1;
  18958. var clone$3 = clone;
  18959. var map$1 = map;
  18960. var merge$1 = merge;
  18961. var QUERY_REG = /^(min|max)?(.+)$/;
  18962. /**
  18963. * TERM EXPLANATIONS:
  18964. *
  18965. * [option]:
  18966. *
  18967. * An object that contains definitions of components. For example:
  18968. * var option = {
  18969. * title: {...},
  18970. * legend: {...},
  18971. * visualMap: {...},
  18972. * series: [
  18973. * {data: [...]},
  18974. * {data: [...]},
  18975. * ...
  18976. * ]
  18977. * };
  18978. *
  18979. * [rawOption]:
  18980. *
  18981. * An object input to echarts.setOption. 'rawOption' may be an
  18982. * 'option', or may be an object contains multi-options. For example:
  18983. * var option = {
  18984. * baseOption: {
  18985. * title: {...},
  18986. * legend: {...},
  18987. * series: [
  18988. * {data: [...]},
  18989. * {data: [...]},
  18990. * ...
  18991. * ]
  18992. * },
  18993. * timeline: {...},
  18994. * options: [
  18995. * {title: {...}, series: {data: [...]}},
  18996. * {title: {...}, series: {data: [...]}},
  18997. * ...
  18998. * ],
  18999. * media: [
  19000. * {
  19001. * query: {maxWidth: 320},
  19002. * option: {series: {x: 20}, visualMap: {show: false}}
  19003. * },
  19004. * {
  19005. * query: {minWidth: 320, maxWidth: 720},
  19006. * option: {series: {x: 500}, visualMap: {show: true}}
  19007. * },
  19008. * {
  19009. * option: {series: {x: 1200}, visualMap: {show: true}}
  19010. * }
  19011. * ]
  19012. * };
  19013. *
  19014. * @alias module:echarts/model/OptionManager
  19015. * @param {module:echarts/ExtensionAPI} api
  19016. */
  19017. function OptionManager(api) {
  19018. /**
  19019. * @private
  19020. * @type {module:echarts/ExtensionAPI}
  19021. */
  19022. this._api = api;
  19023. /**
  19024. * @private
  19025. * @type {Array.<number>}
  19026. */
  19027. this._timelineOptions = [];
  19028. /**
  19029. * @private
  19030. * @type {Array.<Object>}
  19031. */
  19032. this._mediaList = [];
  19033. /**
  19034. * @private
  19035. * @type {Object}
  19036. */
  19037. this._mediaDefault;
  19038. /**
  19039. * -1, means default.
  19040. * empty means no media.
  19041. * @private
  19042. * @type {Array.<number>}
  19043. */
  19044. this._currentMediaIndices = [];
  19045. /**
  19046. * @private
  19047. * @type {Object}
  19048. */
  19049. this._optionBackup;
  19050. /**
  19051. * @private
  19052. * @type {Object}
  19053. */
  19054. this._newBaseOption;
  19055. }
  19056. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19057. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19058. // rawOption cloned and backuped when timeline changed, which does no
  19059. // good to performance. What's more, that both timeline and setOption
  19060. // method supply 'notMerge' brings complex and some problems.
  19061. // Consider this case:
  19062. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19063. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19064. OptionManager.prototype = {
  19065. constructor: OptionManager,
  19066. /**
  19067. * @public
  19068. * @param {Object} rawOption Raw option.
  19069. * @param {module:echarts/model/Global} ecModel
  19070. * @param {Array.<Function>} optionPreprocessorFuncs
  19071. * @return {Object} Init option
  19072. */
  19073. setOption: function (rawOption, optionPreprocessorFuncs) {
  19074. if (rawOption) {
  19075. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19076. each$1(normalizeToArray(rawOption.series), function (series) {
  19077. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19078. });
  19079. }
  19080. // Caution: some series modify option data, if do not clone,
  19081. // it should ensure that the repeat modify correctly
  19082. // (create a new object when modify itself).
  19083. rawOption = clone$3(rawOption, true);
  19084. // FIXME
  19085. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19086. var oldOptionBackup = this._optionBackup;
  19087. var newParsedOption = parseRawOption.call(
  19088. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19089. );
  19090. this._newBaseOption = newParsedOption.baseOption;
  19091. // For setOption at second time (using merge mode);
  19092. if (oldOptionBackup) {
  19093. // Only baseOption can be merged.
  19094. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19095. // For simplicity, timeline options and media options do not support merge,
  19096. // that is, if you `setOption` twice and both has timeline options, the latter
  19097. // timeline opitons will not be merged to the formers, but just substitude them.
  19098. if (newParsedOption.timelineOptions.length) {
  19099. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19100. }
  19101. if (newParsedOption.mediaList.length) {
  19102. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19103. }
  19104. if (newParsedOption.mediaDefault) {
  19105. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19106. }
  19107. }
  19108. else {
  19109. this._optionBackup = newParsedOption;
  19110. }
  19111. },
  19112. /**
  19113. * @param {boolean} isRecreate
  19114. * @return {Object}
  19115. */
  19116. mountOption: function (isRecreate) {
  19117. var optionBackup = this._optionBackup;
  19118. // TODO
  19119. // 如果没有reset功能则不clone。
  19120. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19121. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19122. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19123. this._currentMediaIndices = [];
  19124. return clone$3(isRecreate
  19125. // this._optionBackup.baseOption, which is created at the first `setOption`
  19126. // called, and is merged into every new option by inner method `mergeOption`
  19127. // each time `setOption` called, can be only used in `isRecreate`, because
  19128. // its reliability is under suspicion. In other cases option merge is
  19129. // performed by `model.mergeOption`.
  19130. ? optionBackup.baseOption : this._newBaseOption
  19131. );
  19132. },
  19133. /**
  19134. * @param {module:echarts/model/Global} ecModel
  19135. * @return {Object}
  19136. */
  19137. getTimelineOption: function (ecModel) {
  19138. var option;
  19139. var timelineOptions = this._timelineOptions;
  19140. if (timelineOptions.length) {
  19141. // getTimelineOption can only be called after ecModel inited,
  19142. // so we can get currentIndex from timelineModel.
  19143. var timelineModel = ecModel.getComponent('timeline');
  19144. if (timelineModel) {
  19145. option = clone$3(
  19146. timelineOptions[timelineModel.getCurrentIndex()],
  19147. true
  19148. );
  19149. }
  19150. }
  19151. return option;
  19152. },
  19153. /**
  19154. * @param {module:echarts/model/Global} ecModel
  19155. * @return {Array.<Object>}
  19156. */
  19157. getMediaOption: function (ecModel) {
  19158. var ecWidth = this._api.getWidth();
  19159. var ecHeight = this._api.getHeight();
  19160. var mediaList = this._mediaList;
  19161. var mediaDefault = this._mediaDefault;
  19162. var indices = [];
  19163. var result = [];
  19164. // No media defined.
  19165. if (!mediaList.length && !mediaDefault) {
  19166. return result;
  19167. }
  19168. // Multi media may be applied, the latter defined media has higher priority.
  19169. for (var i = 0, len = mediaList.length; i < len; i++) {
  19170. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19171. indices.push(i);
  19172. }
  19173. }
  19174. // FIXME
  19175. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  19176. if (!indices.length && mediaDefault) {
  19177. indices = [-1];
  19178. }
  19179. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19180. result = map$1(indices, function (index) {
  19181. return clone$3(
  19182. index === -1 ? mediaDefault.option : mediaList[index].option
  19183. );
  19184. });
  19185. }
  19186. // Otherwise return nothing.
  19187. this._currentMediaIndices = indices;
  19188. return result;
  19189. }
  19190. };
  19191. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  19192. var timelineOptions = [];
  19193. var mediaList = [];
  19194. var mediaDefault;
  19195. var baseOption;
  19196. // Compatible with ec2.
  19197. var timelineOpt = rawOption.timeline;
  19198. if (rawOption.baseOption) {
  19199. baseOption = rawOption.baseOption;
  19200. }
  19201. // For timeline
  19202. if (timelineOpt || rawOption.options) {
  19203. baseOption = baseOption || {};
  19204. timelineOptions = (rawOption.options || []).slice();
  19205. }
  19206. // For media query
  19207. if (rawOption.media) {
  19208. baseOption = baseOption || {};
  19209. var media = rawOption.media;
  19210. each$4(media, function (singleMedia) {
  19211. if (singleMedia && singleMedia.option) {
  19212. if (singleMedia.query) {
  19213. mediaList.push(singleMedia);
  19214. }
  19215. else if (!mediaDefault) {
  19216. // Use the first media default.
  19217. mediaDefault = singleMedia;
  19218. }
  19219. }
  19220. });
  19221. }
  19222. // For normal option
  19223. if (!baseOption) {
  19224. baseOption = rawOption;
  19225. }
  19226. // Set timelineOpt to baseOption in ec3,
  19227. // which is convenient for merge option.
  19228. if (!baseOption.timeline) {
  19229. baseOption.timeline = timelineOpt;
  19230. }
  19231. // Preprocess.
  19232. each$4([baseOption].concat(timelineOptions)
  19233. .concat(map(mediaList, function (media) {
  19234. return media.option;
  19235. })),
  19236. function (option) {
  19237. each$4(optionPreprocessorFuncs, function (preProcess) {
  19238. preProcess(option, isNew);
  19239. });
  19240. }
  19241. );
  19242. return {
  19243. baseOption: baseOption,
  19244. timelineOptions: timelineOptions,
  19245. mediaDefault: mediaDefault,
  19246. mediaList: mediaList
  19247. };
  19248. }
  19249. /**
  19250. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  19251. * Support: width, height, aspectRatio
  19252. * Can use max or min as prefix.
  19253. */
  19254. function applyMediaQuery(query, ecWidth, ecHeight) {
  19255. var realMap = {
  19256. width: ecWidth,
  19257. height: ecHeight,
  19258. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  19259. };
  19260. var applicatable = true;
  19261. each$1(query, function (value, attr) {
  19262. var matched = attr.match(QUERY_REG);
  19263. if (!matched || !matched[1] || !matched[2]) {
  19264. return;
  19265. }
  19266. var operator = matched[1];
  19267. var realAttr = matched[2].toLowerCase();
  19268. if (!compare(realMap[realAttr], value, operator)) {
  19269. applicatable = false;
  19270. }
  19271. });
  19272. return applicatable;
  19273. }
  19274. function compare(real, expect, operator) {
  19275. if (operator === 'min') {
  19276. return real >= expect;
  19277. }
  19278. else if (operator === 'max') {
  19279. return real <= expect;
  19280. }
  19281. else { // Equals
  19282. return real === expect;
  19283. }
  19284. }
  19285. function indicesEquals(indices1, indices2) {
  19286. // indices is always order by asc and has only finite number.
  19287. return indices1.join(',') === indices2.join(',');
  19288. }
  19289. /**
  19290. * Consider case:
  19291. * `chart.setOption(opt1);`
  19292. * Then user do some interaction like dataZoom, dataView changing.
  19293. * `chart.setOption(opt2);`
  19294. * Then user press 'reset button' in toolbox.
  19295. *
  19296. * After doing that all of the interaction effects should be reset, the
  19297. * chart should be the same as the result of invoke
  19298. * `chart.setOption(opt1); chart.setOption(opt2);`.
  19299. *
  19300. * Although it is not able ensure that
  19301. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  19302. * `chart.setOption(merge(opt1, opt2));` exactly,
  19303. * this might be the only simple way to implement that feature.
  19304. *
  19305. * MEMO: We've considered some other approaches:
  19306. * 1. Each model handle its self restoration but not uniform treatment.
  19307. * (Too complex in logic and error-prone)
  19308. * 2. Use a shadow ecModel. (Performace expensive)
  19309. */
  19310. function mergeOption(oldOption, newOption) {
  19311. newOption = newOption || {};
  19312. each$4(newOption, function (newCptOpt, mainType) {
  19313. if (newCptOpt == null) {
  19314. return;
  19315. }
  19316. var oldCptOpt = oldOption[mainType];
  19317. if (!ComponentModel.hasClass(mainType)) {
  19318. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  19319. }
  19320. else {
  19321. newCptOpt = normalizeToArray(newCptOpt);
  19322. oldCptOpt = normalizeToArray(oldCptOpt);
  19323. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  19324. oldOption[mainType] = map$1(mapResult, function (item) {
  19325. return (item.option && item.exist)
  19326. ? merge$1(item.exist, item.option, true)
  19327. : (item.exist || item.option);
  19328. });
  19329. }
  19330. });
  19331. }
  19332. /*
  19333. * Licensed to the Apache Software Foundation (ASF) under one
  19334. * or more contributor license agreements. See the NOTICE file
  19335. * distributed with this work for additional information
  19336. * regarding copyright ownership. The ASF licenses this file
  19337. * to you under the Apache License, Version 2.0 (the
  19338. * "License"); you may not use this file except in compliance
  19339. * with the License. You may obtain a copy of the License at
  19340. *
  19341. * http://www.apache.org/licenses/LICENSE-2.0
  19342. *
  19343. * Unless required by applicable law or agreed to in writing,
  19344. * software distributed under the License is distributed on an
  19345. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19346. * KIND, either express or implied. See the License for the
  19347. * specific language governing permissions and limitations
  19348. * under the License.
  19349. */
  19350. var each$5 = each$1;
  19351. var isObject$3 = isObject$1;
  19352. var POSSIBLE_STYLES = [
  19353. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  19354. 'chordStyle', 'label', 'labelLine'
  19355. ];
  19356. function compatEC2ItemStyle(opt) {
  19357. var itemStyleOpt = opt && opt.itemStyle;
  19358. if (!itemStyleOpt) {
  19359. return;
  19360. }
  19361. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  19362. var styleName = POSSIBLE_STYLES[i];
  19363. var normalItemStyleOpt = itemStyleOpt.normal;
  19364. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  19365. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  19366. opt[styleName] = opt[styleName] || {};
  19367. if (!opt[styleName].normal) {
  19368. opt[styleName].normal = normalItemStyleOpt[styleName];
  19369. }
  19370. else {
  19371. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  19372. }
  19373. normalItemStyleOpt[styleName] = null;
  19374. }
  19375. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  19376. opt[styleName] = opt[styleName] || {};
  19377. if (!opt[styleName].emphasis) {
  19378. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  19379. }
  19380. else {
  19381. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  19382. }
  19383. emphasisItemStyleOpt[styleName] = null;
  19384. }
  19385. }
  19386. }
  19387. function convertNormalEmphasis(opt, optType, useExtend) {
  19388. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  19389. var normalOpt = opt[optType].normal;
  19390. var emphasisOpt = opt[optType].emphasis;
  19391. if (normalOpt) {
  19392. // Timeline controlStyle has other properties besides normal and emphasis
  19393. if (useExtend) {
  19394. opt[optType].normal = opt[optType].emphasis = null;
  19395. defaults(opt[optType], normalOpt);
  19396. }
  19397. else {
  19398. opt[optType] = normalOpt;
  19399. }
  19400. }
  19401. if (emphasisOpt) {
  19402. opt.emphasis = opt.emphasis || {};
  19403. opt.emphasis[optType] = emphasisOpt;
  19404. }
  19405. }
  19406. }
  19407. function removeEC3NormalStatus(opt) {
  19408. convertNormalEmphasis(opt, 'itemStyle');
  19409. convertNormalEmphasis(opt, 'lineStyle');
  19410. convertNormalEmphasis(opt, 'areaStyle');
  19411. convertNormalEmphasis(opt, 'label');
  19412. convertNormalEmphasis(opt, 'labelLine');
  19413. // treemap
  19414. convertNormalEmphasis(opt, 'upperLabel');
  19415. // graph
  19416. convertNormalEmphasis(opt, 'edgeLabel');
  19417. }
  19418. function compatTextStyle(opt, propName) {
  19419. // Check whether is not object (string\null\undefined ...)
  19420. var labelOptSingle = isObject$3(opt) && opt[propName];
  19421. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  19422. if (textStyle) {
  19423. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  19424. var propName = TEXT_STYLE_OPTIONS[i];
  19425. if (textStyle.hasOwnProperty(propName)) {
  19426. labelOptSingle[propName] = textStyle[propName];
  19427. }
  19428. }
  19429. }
  19430. }
  19431. function compatEC3CommonStyles(opt) {
  19432. if (opt) {
  19433. removeEC3NormalStatus(opt);
  19434. compatTextStyle(opt, 'label');
  19435. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  19436. }
  19437. }
  19438. function processSeries(seriesOpt) {
  19439. if (!isObject$3(seriesOpt)) {
  19440. return;
  19441. }
  19442. compatEC2ItemStyle(seriesOpt);
  19443. removeEC3NormalStatus(seriesOpt);
  19444. compatTextStyle(seriesOpt, 'label');
  19445. // treemap
  19446. compatTextStyle(seriesOpt, 'upperLabel');
  19447. // graph
  19448. compatTextStyle(seriesOpt, 'edgeLabel');
  19449. if (seriesOpt.emphasis) {
  19450. compatTextStyle(seriesOpt.emphasis, 'label');
  19451. // treemap
  19452. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  19453. // graph
  19454. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  19455. }
  19456. var markPoint = seriesOpt.markPoint;
  19457. if (markPoint) {
  19458. compatEC2ItemStyle(markPoint);
  19459. compatEC3CommonStyles(markPoint);
  19460. }
  19461. var markLine = seriesOpt.markLine;
  19462. if (markLine) {
  19463. compatEC2ItemStyle(markLine);
  19464. compatEC3CommonStyles(markLine);
  19465. }
  19466. var markArea = seriesOpt.markArea;
  19467. if (markArea) {
  19468. compatEC3CommonStyles(markArea);
  19469. }
  19470. var data = seriesOpt.data;
  19471. // Break with ec3: if `setOption` again, there may be no `type` in option,
  19472. // then the backward compat based on option type will not be performed.
  19473. if (seriesOpt.type === 'graph') {
  19474. data = data || seriesOpt.nodes;
  19475. var edgeData = seriesOpt.links || seriesOpt.edges;
  19476. if (edgeData && !isTypedArray(edgeData)) {
  19477. for (var i = 0; i < edgeData.length; i++) {
  19478. compatEC3CommonStyles(edgeData[i]);
  19479. }
  19480. }
  19481. each$1(seriesOpt.categories, function (opt) {
  19482. removeEC3NormalStatus(opt);
  19483. });
  19484. }
  19485. if (data && !isTypedArray(data)) {
  19486. for (var i = 0; i < data.length; i++) {
  19487. compatEC3CommonStyles(data[i]);
  19488. }
  19489. }
  19490. // mark point data
  19491. var markPoint = seriesOpt.markPoint;
  19492. if (markPoint && markPoint.data) {
  19493. var mpData = markPoint.data;
  19494. for (var i = 0; i < mpData.length; i++) {
  19495. compatEC3CommonStyles(mpData[i]);
  19496. }
  19497. }
  19498. // mark line data
  19499. var markLine = seriesOpt.markLine;
  19500. if (markLine && markLine.data) {
  19501. var mlData = markLine.data;
  19502. for (var i = 0; i < mlData.length; i++) {
  19503. if (isArray(mlData[i])) {
  19504. compatEC3CommonStyles(mlData[i][0]);
  19505. compatEC3CommonStyles(mlData[i][1]);
  19506. }
  19507. else {
  19508. compatEC3CommonStyles(mlData[i]);
  19509. }
  19510. }
  19511. }
  19512. // Series
  19513. if (seriesOpt.type === 'gauge') {
  19514. compatTextStyle(seriesOpt, 'axisLabel');
  19515. compatTextStyle(seriesOpt, 'title');
  19516. compatTextStyle(seriesOpt, 'detail');
  19517. }
  19518. else if (seriesOpt.type === 'treemap') {
  19519. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  19520. each$1(seriesOpt.levels, function (opt) {
  19521. removeEC3NormalStatus(opt);
  19522. });
  19523. }
  19524. else if (seriesOpt.type === 'tree') {
  19525. removeEC3NormalStatus(seriesOpt.leaves);
  19526. }
  19527. // sunburst starts from ec4, so it does not need to compat levels.
  19528. }
  19529. function toArr(o) {
  19530. return isArray(o) ? o : o ? [o] : [];
  19531. }
  19532. function toObj(o) {
  19533. return (isArray(o) ? o[0] : o) || {};
  19534. }
  19535. var compatStyle = function (option, isTheme) {
  19536. each$5(toArr(option.series), function (seriesOpt) {
  19537. isObject$3(seriesOpt) && processSeries(seriesOpt);
  19538. });
  19539. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  19540. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  19541. each$5(
  19542. axes,
  19543. function (axisName) {
  19544. each$5(toArr(option[axisName]), function (axisOpt) {
  19545. if (axisOpt) {
  19546. compatTextStyle(axisOpt, 'axisLabel');
  19547. compatTextStyle(axisOpt.axisPointer, 'label');
  19548. }
  19549. });
  19550. }
  19551. );
  19552. each$5(toArr(option.parallel), function (parallelOpt) {
  19553. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  19554. compatTextStyle(parallelAxisDefault, 'axisLabel');
  19555. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  19556. });
  19557. each$5(toArr(option.calendar), function (calendarOpt) {
  19558. convertNormalEmphasis(calendarOpt, 'itemStyle');
  19559. compatTextStyle(calendarOpt, 'dayLabel');
  19560. compatTextStyle(calendarOpt, 'monthLabel');
  19561. compatTextStyle(calendarOpt, 'yearLabel');
  19562. });
  19563. // radar.name.textStyle
  19564. each$5(toArr(option.radar), function (radarOpt) {
  19565. compatTextStyle(radarOpt, 'name');
  19566. });
  19567. each$5(toArr(option.geo), function (geoOpt) {
  19568. if (isObject$3(geoOpt)) {
  19569. compatEC3CommonStyles(geoOpt);
  19570. each$5(toArr(geoOpt.regions), function (regionObj) {
  19571. compatEC3CommonStyles(regionObj);
  19572. });
  19573. }
  19574. });
  19575. each$5(toArr(option.timeline), function (timelineOpt) {
  19576. compatEC3CommonStyles(timelineOpt);
  19577. convertNormalEmphasis(timelineOpt, 'label');
  19578. convertNormalEmphasis(timelineOpt, 'itemStyle');
  19579. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  19580. var data = timelineOpt.data;
  19581. isArray(data) && each$1(data, function (item) {
  19582. if (isObject$1(item)) {
  19583. convertNormalEmphasis(item, 'label');
  19584. convertNormalEmphasis(item, 'itemStyle');
  19585. }
  19586. });
  19587. });
  19588. each$5(toArr(option.toolbox), function (toolboxOpt) {
  19589. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  19590. each$5(toolboxOpt.feature, function (featureOpt) {
  19591. convertNormalEmphasis(featureOpt, 'iconStyle');
  19592. });
  19593. });
  19594. compatTextStyle(toObj(option.axisPointer), 'label');
  19595. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  19596. };
  19597. /*
  19598. * Licensed to the Apache Software Foundation (ASF) under one
  19599. * or more contributor license agreements. See the NOTICE file
  19600. * distributed with this work for additional information
  19601. * regarding copyright ownership. The ASF licenses this file
  19602. * to you under the Apache License, Version 2.0 (the
  19603. * "License"); you may not use this file except in compliance
  19604. * with the License. You may obtain a copy of the License at
  19605. *
  19606. * http://www.apache.org/licenses/LICENSE-2.0
  19607. *
  19608. * Unless required by applicable law or agreed to in writing,
  19609. * software distributed under the License is distributed on an
  19610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19611. * KIND, either express or implied. See the License for the
  19612. * specific language governing permissions and limitations
  19613. * under the License.
  19614. */
  19615. // Compatitable with 2.0
  19616. function get(opt, path) {
  19617. path = path.split(',');
  19618. var obj = opt;
  19619. for (var i = 0; i < path.length; i++) {
  19620. obj = obj && obj[path[i]];
  19621. if (obj == null) {
  19622. break;
  19623. }
  19624. }
  19625. return obj;
  19626. }
  19627. function set$1(opt, path, val, overwrite) {
  19628. path = path.split(',');
  19629. var obj = opt;
  19630. var key;
  19631. for (var i = 0; i < path.length - 1; i++) {
  19632. key = path[i];
  19633. if (obj[key] == null) {
  19634. obj[key] = {};
  19635. }
  19636. obj = obj[key];
  19637. }
  19638. if (overwrite || obj[path[i]] == null) {
  19639. obj[path[i]] = val;
  19640. }
  19641. }
  19642. function compatLayoutProperties(option) {
  19643. each$1(LAYOUT_PROPERTIES, function (prop) {
  19644. if (prop[0] in option && !(prop[1] in option)) {
  19645. option[prop[1]] = option[prop[0]];
  19646. }
  19647. });
  19648. }
  19649. var LAYOUT_PROPERTIES = [
  19650. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  19651. ];
  19652. var COMPATITABLE_COMPONENTS = [
  19653. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  19654. ];
  19655. var backwardCompat = function (option, isTheme) {
  19656. compatStyle(option, isTheme);
  19657. // Make sure series array for model initialization.
  19658. option.series = normalizeToArray(option.series);
  19659. each$1(option.series, function (seriesOpt) {
  19660. if (!isObject$1(seriesOpt)) {
  19661. return;
  19662. }
  19663. var seriesType = seriesOpt.type;
  19664. if (seriesType === 'pie' || seriesType === 'gauge') {
  19665. if (seriesOpt.clockWise != null) {
  19666. seriesOpt.clockwise = seriesOpt.clockWise;
  19667. }
  19668. }
  19669. if (seriesType === 'gauge') {
  19670. var pointerColor = get(seriesOpt, 'pointer.color');
  19671. pointerColor != null
  19672. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  19673. }
  19674. compatLayoutProperties(seriesOpt);
  19675. });
  19676. // dataRange has changed to visualMap
  19677. if (option.dataRange) {
  19678. option.visualMap = option.dataRange;
  19679. }
  19680. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19681. var options = option[componentName];
  19682. if (options) {
  19683. if (!isArray(options)) {
  19684. options = [options];
  19685. }
  19686. each$1(options, function (option) {
  19687. compatLayoutProperties(option);
  19688. });
  19689. }
  19690. });
  19691. };
  19692. /*
  19693. * Licensed to the Apache Software Foundation (ASF) under one
  19694. * or more contributor license agreements. See the NOTICE file
  19695. * distributed with this work for additional information
  19696. * regarding copyright ownership. The ASF licenses this file
  19697. * to you under the Apache License, Version 2.0 (the
  19698. * "License"); you may not use this file except in compliance
  19699. * with the License. You may obtain a copy of the License at
  19700. *
  19701. * http://www.apache.org/licenses/LICENSE-2.0
  19702. *
  19703. * Unless required by applicable law or agreed to in writing,
  19704. * software distributed under the License is distributed on an
  19705. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19706. * KIND, either express or implied. See the License for the
  19707. * specific language governing permissions and limitations
  19708. * under the License.
  19709. */
  19710. // (1) [Caution]: the logic is correct based on the premises:
  19711. // data processing stage is blocked in stream.
  19712. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19713. // (2) Only register once when import repeatly.
  19714. // Should be executed before after series filtered and before stack calculation.
  19715. var dataStack = function (ecModel) {
  19716. var stackInfoMap = createHashMap();
  19717. ecModel.eachSeries(function (seriesModel) {
  19718. var stack = seriesModel.get('stack');
  19719. // Compatibal: when `stack` is set as '', do not stack.
  19720. if (stack) {
  19721. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19722. var data = seriesModel.getData();
  19723. var stackInfo = {
  19724. // Used for calculate axis extent automatically.
  19725. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19726. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19727. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19728. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19729. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19730. data: data,
  19731. seriesModel: seriesModel
  19732. };
  19733. // If stacked on axis that do not support data stack.
  19734. if (!stackInfo.stackedDimension
  19735. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19736. ) {
  19737. return;
  19738. }
  19739. stackInfoList.length && data.setCalculationInfo(
  19740. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19741. );
  19742. stackInfoList.push(stackInfo);
  19743. }
  19744. });
  19745. stackInfoMap.each(calculateStack);
  19746. };
  19747. function calculateStack(stackInfoList) {
  19748. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19749. var resultVal = [];
  19750. var resultNaN = [NaN, NaN];
  19751. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19752. var targetData = targetStackInfo.data;
  19753. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19754. // Should not write on raw data, because stack series model list changes
  19755. // depending on legend selection.
  19756. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19757. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19758. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19759. // should also be NaN, to draw a appropriate belt area.
  19760. if (isNaN(sum)) {
  19761. return resultNaN;
  19762. }
  19763. var byValue;
  19764. var stackedDataRawIndex;
  19765. if (isStackedByIndex) {
  19766. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19767. }
  19768. else {
  19769. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19770. }
  19771. // If stackOver is NaN, chart view will render point on value start.
  19772. var stackedOver = NaN;
  19773. for (var j = idxInStack - 1; j >= 0; j--) {
  19774. var stackInfo = stackInfoList[j];
  19775. // Has been optimized by inverted indices on `stackedByDimension`.
  19776. if (!isStackedByIndex) {
  19777. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19778. }
  19779. if (stackedDataRawIndex >= 0) {
  19780. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19781. // Considering positive stack, negative stack and empty data
  19782. if ((sum >= 0 && val > 0) // Positive stack
  19783. || (sum <= 0 && val < 0) // Negative stack
  19784. ) {
  19785. sum += val;
  19786. stackedOver = val;
  19787. break;
  19788. }
  19789. }
  19790. }
  19791. resultVal[0] = sum;
  19792. resultVal[1] = stackedOver;
  19793. return resultVal;
  19794. });
  19795. targetData.hostModel.setData(newData);
  19796. // Update for consequent calculation
  19797. targetStackInfo.data = newData;
  19798. });
  19799. }
  19800. /*
  19801. * Licensed to the Apache Software Foundation (ASF) under one
  19802. * or more contributor license agreements. See the NOTICE file
  19803. * distributed with this work for additional information
  19804. * regarding copyright ownership. The ASF licenses this file
  19805. * to you under the Apache License, Version 2.0 (the
  19806. * "License"); you may not use this file except in compliance
  19807. * with the License. You may obtain a copy of the License at
  19808. *
  19809. * http://www.apache.org/licenses/LICENSE-2.0
  19810. *
  19811. * Unless required by applicable law or agreed to in writing,
  19812. * software distributed under the License is distributed on an
  19813. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19814. * KIND, either express or implied. See the License for the
  19815. * specific language governing permissions and limitations
  19816. * under the License.
  19817. */
  19818. // TODO
  19819. // ??? refactor? check the outer usage of data provider.
  19820. // merge with defaultDimValueGetter?
  19821. /**
  19822. * If normal array used, mutable chunk size is supported.
  19823. * If typed array used, chunk size must be fixed.
  19824. */
  19825. function DefaultDataProvider(source, dimSize) {
  19826. if (!Source.isInstance(source)) {
  19827. source = Source.seriesDataToSource(source);
  19828. }
  19829. this._source = source;
  19830. var data = this._data = source.data;
  19831. var sourceFormat = source.sourceFormat;
  19832. // Typed array. TODO IE10+?
  19833. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19834. if (__DEV__) {
  19835. if (dimSize == null) {
  19836. throw new Error('Typed array data must specify dimension size');
  19837. }
  19838. }
  19839. this._offset = 0;
  19840. this._dimSize = dimSize;
  19841. this._data = data;
  19842. }
  19843. var methods = providerMethods[
  19844. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  19845. ? sourceFormat + '_' + source.seriesLayoutBy
  19846. : sourceFormat
  19847. ];
  19848. if (__DEV__) {
  19849. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19850. }
  19851. extend(this, methods);
  19852. }
  19853. var providerProto = DefaultDataProvider.prototype;
  19854. // If data is pure without style configuration
  19855. providerProto.pure = false;
  19856. // If data is persistent and will not be released after use.
  19857. providerProto.persistent = true;
  19858. // ???! FIXME legacy data provider do not has method getSource
  19859. providerProto.getSource = function () {
  19860. return this._source;
  19861. };
  19862. var providerMethods = {
  19863. 'arrayRows_column': {
  19864. pure: true,
  19865. count: function () {
  19866. return Math.max(0, this._data.length - this._source.startIndex);
  19867. },
  19868. getItem: function (idx) {
  19869. return this._data[idx + this._source.startIndex];
  19870. },
  19871. appendData: appendDataSimply
  19872. },
  19873. 'arrayRows_row': {
  19874. pure: true,
  19875. count: function () {
  19876. var row = this._data[0];
  19877. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19878. },
  19879. getItem: function (idx) {
  19880. idx += this._source.startIndex;
  19881. var item = [];
  19882. var data = this._data;
  19883. for (var i = 0; i < data.length; i++) {
  19884. var row = data[i];
  19885. item.push(row ? row[idx] : null);
  19886. }
  19887. return item;
  19888. },
  19889. appendData: function () {
  19890. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19891. }
  19892. },
  19893. 'objectRows': {
  19894. pure: true,
  19895. count: countSimply,
  19896. getItem: getItemSimply,
  19897. appendData: appendDataSimply
  19898. },
  19899. 'keyedColumns': {
  19900. pure: true,
  19901. count: function () {
  19902. var dimName = this._source.dimensionsDefine[0].name;
  19903. var col = this._data[dimName];
  19904. return col ? col.length : 0;
  19905. },
  19906. getItem: function (idx) {
  19907. var item = [];
  19908. var dims = this._source.dimensionsDefine;
  19909. for (var i = 0; i < dims.length; i++) {
  19910. var col = this._data[dims[i].name];
  19911. item.push(col ? col[idx] : null);
  19912. }
  19913. return item;
  19914. },
  19915. appendData: function (newData) {
  19916. var data = this._data;
  19917. each$1(newData, function (newCol, key) {
  19918. var oldCol = data[key] || (data[key] = []);
  19919. for (var i = 0; i < (newCol || []).length; i++) {
  19920. oldCol.push(newCol[i]);
  19921. }
  19922. });
  19923. }
  19924. },
  19925. 'original': {
  19926. count: countSimply,
  19927. getItem: getItemSimply,
  19928. appendData: appendDataSimply
  19929. },
  19930. 'typedArray': {
  19931. persistent: false,
  19932. pure: true,
  19933. count: function () {
  19934. return this._data ? (this._data.length / this._dimSize) : 0;
  19935. },
  19936. getItem: function (idx, out) {
  19937. idx = idx - this._offset;
  19938. out = out || [];
  19939. var offset = this._dimSize * idx;
  19940. for (var i = 0; i < this._dimSize; i++) {
  19941. out[i] = this._data[offset + i];
  19942. }
  19943. return out;
  19944. },
  19945. appendData: function (newData) {
  19946. if (__DEV__) {
  19947. assert$1(
  19948. isTypedArray(newData),
  19949. 'Added data must be TypedArray if data in initialization is TypedArray'
  19950. );
  19951. }
  19952. this._data = newData;
  19953. },
  19954. // Clean self if data is already used.
  19955. clean: function () {
  19956. // PENDING
  19957. this._offset += this.count();
  19958. this._data = null;
  19959. }
  19960. }
  19961. };
  19962. function countSimply() {
  19963. return this._data.length;
  19964. }
  19965. function getItemSimply(idx) {
  19966. return this._data[idx];
  19967. }
  19968. function appendDataSimply(newData) {
  19969. for (var i = 0; i < newData.length; i++) {
  19970. this._data.push(newData[i]);
  19971. }
  19972. }
  19973. var rawValueGetters = {
  19974. arrayRows: getRawValueSimply,
  19975. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  19976. return dimIndex != null ? dataItem[dimName] : dataItem;
  19977. },
  19978. keyedColumns: getRawValueSimply,
  19979. original: function (dataItem, dataIndex, dimIndex, dimName) {
  19980. // FIXME
  19981. // In some case (markpoint in geo (geo-map.html)), dataItem
  19982. // is {coord: [...]}
  19983. var value = getDataItemValue(dataItem);
  19984. return (dimIndex == null || !(value instanceof Array))
  19985. ? value
  19986. : value[dimIndex];
  19987. },
  19988. typedArray: getRawValueSimply
  19989. };
  19990. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  19991. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  19992. }
  19993. var defaultDimValueGetters = {
  19994. arrayRows: getDimValueSimply,
  19995. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  19996. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  19997. },
  19998. keyedColumns: getDimValueSimply,
  19999. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20000. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20001. // If dataItem is an plain object with no value field, the var `value`
  20002. // will be assigned with the object, but it will be tread correctly
  20003. // in the `convertDataValue`.
  20004. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20005. // If any dataItem is like { value: 10 }
  20006. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20007. this.hasItemOption = true;
  20008. }
  20009. return converDataValue(
  20010. (value instanceof Array)
  20011. ? value[dimIndex]
  20012. // If value is a single number or something else not array.
  20013. : value,
  20014. this._dimensionInfos[dimName]
  20015. );
  20016. },
  20017. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20018. return dataItem[dimIndex];
  20019. }
  20020. };
  20021. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20022. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20023. }
  20024. /**
  20025. * This helper method convert value in data.
  20026. * @param {string|number|Date} value
  20027. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20028. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20029. */
  20030. function converDataValue(value, dimInfo) {
  20031. // Performance sensitive.
  20032. var dimType = dimInfo && dimInfo.type;
  20033. if (dimType === 'ordinal') {
  20034. // If given value is a category string
  20035. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20036. return ordinalMeta
  20037. ? ordinalMeta.parseAndCollect(value)
  20038. : value;
  20039. }
  20040. if (dimType === 'time'
  20041. // spead up when using timestamp
  20042. && typeof value !== 'number'
  20043. && value != null
  20044. && value !== '-'
  20045. ) {
  20046. value = +parseDate(value);
  20047. }
  20048. // dimType defaults 'number'.
  20049. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20050. // parse to NaN.
  20051. return (value == null || value === '')
  20052. ? NaN
  20053. // If string (like '-'), using '+' parse to NaN
  20054. // If object, also parse to NaN
  20055. : +value;
  20056. }
  20057. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20058. // Consider persistent.
  20059. // Caution: why use raw value to display on label or tooltip?
  20060. // A reason is to avoid format. For example time value we do not know
  20061. // how to format is expected. More over, if stack is used, calculated
  20062. // value may be 0.91000000001, which have brings trouble to display.
  20063. // TODO: consider how to treat null/undefined/NaN when display?
  20064. /**
  20065. * @param {module:echarts/data/List} data
  20066. * @param {number} dataIndex
  20067. * @param {string|number} [dim] dimName or dimIndex
  20068. * @return {Array.<number>|string|number} can be null/undefined.
  20069. */
  20070. function retrieveRawValue(data, dataIndex, dim) {
  20071. if (!data) {
  20072. return;
  20073. }
  20074. // Consider data may be not persistent.
  20075. var dataItem = data.getRawDataItem(dataIndex);
  20076. if (dataItem == null) {
  20077. return;
  20078. }
  20079. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20080. var dimName;
  20081. var dimIndex;
  20082. var dimInfo = data.getDimensionInfo(dim);
  20083. if (dimInfo) {
  20084. dimName = dimInfo.name;
  20085. dimIndex = dimInfo.index;
  20086. }
  20087. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20088. }
  20089. /**
  20090. * Compatible with some cases (in pie, map) like:
  20091. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20092. * where only sourceFormat is 'original' and 'objectRows' supported.
  20093. *
  20094. * ??? TODO
  20095. * Supported detail options in data item when using 'arrayRows'.
  20096. *
  20097. * @param {module:echarts/data/List} data
  20098. * @param {number} dataIndex
  20099. * @param {string} attr like 'selected'
  20100. */
  20101. function retrieveRawAttr(data, dataIndex, attr) {
  20102. if (!data) {
  20103. return;
  20104. }
  20105. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20106. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20107. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20108. ) {
  20109. return;
  20110. }
  20111. var dataItem = data.getRawDataItem(dataIndex);
  20112. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20113. dataItem = null;
  20114. }
  20115. if (dataItem) {
  20116. return dataItem[attr];
  20117. }
  20118. }
  20119. /*
  20120. * Licensed to the Apache Software Foundation (ASF) under one
  20121. * or more contributor license agreements. See the NOTICE file
  20122. * distributed with this work for additional information
  20123. * regarding copyright ownership. The ASF licenses this file
  20124. * to you under the Apache License, Version 2.0 (the
  20125. * "License"); you may not use this file except in compliance
  20126. * with the License. You may obtain a copy of the License at
  20127. *
  20128. * http://www.apache.org/licenses/LICENSE-2.0
  20129. *
  20130. * Unless required by applicable law or agreed to in writing,
  20131. * software distributed under the License is distributed on an
  20132. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20133. * KIND, either express or implied. See the License for the
  20134. * specific language governing permissions and limitations
  20135. * under the License.
  20136. */
  20137. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20138. // PENDING A little ugly
  20139. var dataFormatMixin = {
  20140. /**
  20141. * Get params for formatter
  20142. * @param {number} dataIndex
  20143. * @param {string} [dataType]
  20144. * @return {Object}
  20145. */
  20146. getDataParams: function (dataIndex, dataType) {
  20147. var data = this.getData(dataType);
  20148. var rawValue = this.getRawValue(dataIndex, dataType);
  20149. var rawDataIndex = data.getRawIndex(dataIndex);
  20150. var name = data.getName(dataIndex);
  20151. var itemOpt = data.getRawDataItem(dataIndex);
  20152. var color = data.getItemVisual(dataIndex, 'color');
  20153. var tooltipModel = this.ecModel.getComponent('tooltip');
  20154. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20155. var renderMode = getTooltipRenderMode(renderModeOption);
  20156. var mainType = this.mainType;
  20157. var isSeries = mainType === 'series';
  20158. return {
  20159. componentType: mainType,
  20160. componentSubType: this.subType,
  20161. componentIndex: this.componentIndex,
  20162. seriesType: isSeries ? this.subType : null,
  20163. seriesIndex: this.seriesIndex,
  20164. seriesId: isSeries ? this.id : null,
  20165. seriesName: isSeries ? this.name : null,
  20166. name: name,
  20167. dataIndex: rawDataIndex,
  20168. data: itemOpt,
  20169. dataType: dataType,
  20170. value: rawValue,
  20171. color: color,
  20172. marker: getTooltipMarker({
  20173. color: color,
  20174. renderMode: renderMode
  20175. }),
  20176. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20177. $vars: ['seriesName', 'name', 'value']
  20178. };
  20179. },
  20180. /**
  20181. * Format label
  20182. * @param {number} dataIndex
  20183. * @param {string} [status='normal'] 'normal' or 'emphasis'
  20184. * @param {string} [dataType]
  20185. * @param {number} [dimIndex]
  20186. * @param {string} [labelProp='label']
  20187. * @return {string} If not formatter, return null/undefined
  20188. */
  20189. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  20190. status = status || 'normal';
  20191. var data = this.getData(dataType);
  20192. var itemModel = data.getItemModel(dataIndex);
  20193. var params = this.getDataParams(dataIndex, dataType);
  20194. if (dimIndex != null && (params.value instanceof Array)) {
  20195. params.value = params.value[dimIndex];
  20196. }
  20197. var formatter = itemModel.get(
  20198. status === 'normal'
  20199. ? [labelProp || 'label', 'formatter']
  20200. : [status, labelProp || 'label', 'formatter']
  20201. );
  20202. if (typeof formatter === 'function') {
  20203. params.status = status;
  20204. return formatter(params);
  20205. }
  20206. else if (typeof formatter === 'string') {
  20207. var str = formatTpl(formatter, params);
  20208. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20209. // Do not support '}' in dim name util have to.
  20210. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  20211. var len = dim.length;
  20212. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  20213. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  20214. }
  20215. return retrieveRawValue(data, dataIndex, dim);
  20216. });
  20217. }
  20218. },
  20219. /**
  20220. * Get raw value in option
  20221. * @param {number} idx
  20222. * @param {string} [dataType]
  20223. * @return {Array|number|string}
  20224. */
  20225. getRawValue: function (idx, dataType) {
  20226. return retrieveRawValue(this.getData(dataType), idx);
  20227. },
  20228. /**
  20229. * Should be implemented.
  20230. * @param {number} dataIndex
  20231. * @param {boolean} [multipleSeries=false]
  20232. * @param {number} [dataType]
  20233. * @return {string} tooltip string
  20234. */
  20235. formatTooltip: function () {
  20236. // Empty function
  20237. }
  20238. };
  20239. /*
  20240. * Licensed to the Apache Software Foundation (ASF) under one
  20241. * or more contributor license agreements. See the NOTICE file
  20242. * distributed with this work for additional information
  20243. * regarding copyright ownership. The ASF licenses this file
  20244. * to you under the Apache License, Version 2.0 (the
  20245. * "License"); you may not use this file except in compliance
  20246. * with the License. You may obtain a copy of the License at
  20247. *
  20248. * http://www.apache.org/licenses/LICENSE-2.0
  20249. *
  20250. * Unless required by applicable law or agreed to in writing,
  20251. * software distributed under the License is distributed on an
  20252. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20253. * KIND, either express or implied. See the License for the
  20254. * specific language governing permissions and limitations
  20255. * under the License.
  20256. */
  20257. /**
  20258. * @param {Object} define
  20259. * @return See the return of `createTask`.
  20260. */
  20261. function createTask(define) {
  20262. return new Task(define);
  20263. }
  20264. /**
  20265. * @constructor
  20266. * @param {Object} define
  20267. * @param {Function} define.reset Custom reset
  20268. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  20269. * @param {Function} [define.count] count is used to determin data task.
  20270. * @param {Function} [define.onDirty] count is used to determin data task.
  20271. */
  20272. function Task(define) {
  20273. define = define || {};
  20274. this._reset = define.reset;
  20275. this._plan = define.plan;
  20276. this._count = define.count;
  20277. this._onDirty = define.onDirty;
  20278. this._dirty = true;
  20279. // Context must be specified implicitly, to
  20280. // avoid miss update context when model changed.
  20281. this.context;
  20282. }
  20283. var taskProto = Task.prototype;
  20284. /**
  20285. * @param {Object} performArgs
  20286. * @param {number} [performArgs.step] Specified step.
  20287. * @param {number} [performArgs.skip] Skip customer perform call.
  20288. * @param {number} [performArgs.modBy] Sampling window size.
  20289. * @param {number} [performArgs.modDataCount] Sampling count.
  20290. */
  20291. taskProto.perform = function (performArgs) {
  20292. var upTask = this._upstream;
  20293. var skip = performArgs && performArgs.skip;
  20294. // TODO some refactor.
  20295. // Pull data. Must pull data each time, because context.data
  20296. // may be updated by Series.setData.
  20297. if (this._dirty && upTask) {
  20298. var context = this.context;
  20299. context.data = context.outputData = upTask.context.outputData;
  20300. }
  20301. if (this.__pipeline) {
  20302. this.__pipeline.currentTask = this;
  20303. }
  20304. var planResult;
  20305. if (this._plan && !skip) {
  20306. planResult = this._plan(this.context);
  20307. }
  20308. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  20309. // elements uniformed distributed when progress, especially when moving or zooming.
  20310. var lastModBy = normalizeModBy(this._modBy);
  20311. var lastModDataCount = this._modDataCount || 0;
  20312. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  20313. var modDataCount = performArgs && performArgs.modDataCount || 0;
  20314. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  20315. planResult = 'reset';
  20316. }
  20317. function normalizeModBy(val) {
  20318. !(val >= 1) && (val = 1); // jshint ignore:line
  20319. return val;
  20320. }
  20321. var forceFirstProgress;
  20322. if (this._dirty || planResult === 'reset') {
  20323. this._dirty = false;
  20324. forceFirstProgress = reset(this, skip);
  20325. }
  20326. this._modBy = modBy;
  20327. this._modDataCount = modDataCount;
  20328. var step = performArgs && performArgs.step;
  20329. if (upTask) {
  20330. if (__DEV__) {
  20331. assert$1(upTask._outputDueEnd != null);
  20332. }
  20333. this._dueEnd = upTask._outputDueEnd;
  20334. }
  20335. // DataTask or overallTask
  20336. else {
  20337. if (__DEV__) {
  20338. assert$1(!this._progress || this._count);
  20339. }
  20340. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  20341. }
  20342. // Note: Stubs, that its host overall task let it has progress, has progress.
  20343. // If no progress, pass index from upstream to downstream each time plan called.
  20344. if (this._progress) {
  20345. var start = this._dueIndex;
  20346. var end = Math.min(
  20347. step != null ? this._dueIndex + step : Infinity,
  20348. this._dueEnd
  20349. );
  20350. if (!skip && (forceFirstProgress || start < end)) {
  20351. var progress = this._progress;
  20352. if (isArray(progress)) {
  20353. for (var i = 0; i < progress.length; i++) {
  20354. doProgress(this, progress[i], start, end, modBy, modDataCount);
  20355. }
  20356. }
  20357. else {
  20358. doProgress(this, progress, start, end, modBy, modDataCount);
  20359. }
  20360. }
  20361. this._dueIndex = end;
  20362. // If no `outputDueEnd`, assume that output data and
  20363. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  20364. var outputDueEnd = this._settedOutputEnd != null
  20365. ? this._settedOutputEnd : end;
  20366. if (__DEV__) {
  20367. // ??? Can not rollback.
  20368. assert$1(outputDueEnd >= this._outputDueEnd);
  20369. }
  20370. this._outputDueEnd = outputDueEnd;
  20371. }
  20372. else {
  20373. // (1) Some overall task has no progress.
  20374. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  20375. // This should always be performed so it can be passed to downstream.
  20376. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  20377. ? this._settedOutputEnd : this._dueEnd;
  20378. }
  20379. return this.unfinished();
  20380. };
  20381. var iterator = (function () {
  20382. var end;
  20383. var current;
  20384. var modBy;
  20385. var modDataCount;
  20386. var winCount;
  20387. var it = {
  20388. reset: function (s, e, sStep, sCount) {
  20389. current = s;
  20390. end = e;
  20391. modBy = sStep;
  20392. modDataCount = sCount;
  20393. winCount = Math.ceil(modDataCount / modBy);
  20394. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  20395. }
  20396. };
  20397. return it;
  20398. function sequentialNext() {
  20399. return current < end ? current++ : null;
  20400. }
  20401. function modNext() {
  20402. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  20403. var result = current >= end
  20404. ? null
  20405. : dataIndex < modDataCount
  20406. ? dataIndex
  20407. // If modDataCount is smaller than data.count() (consider `appendData` case),
  20408. // Use normal linear rendering mode.
  20409. : current;
  20410. current++;
  20411. return result;
  20412. }
  20413. })();
  20414. taskProto.dirty = function () {
  20415. this._dirty = true;
  20416. this._onDirty && this._onDirty(this.context);
  20417. };
  20418. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  20419. iterator.reset(start, end, modBy, modDataCount);
  20420. taskIns._callingProgress = progress;
  20421. taskIns._callingProgress({
  20422. start: start, end: end, count: end - start, next: iterator.next
  20423. }, taskIns.context);
  20424. }
  20425. function reset(taskIns, skip) {
  20426. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  20427. taskIns._settedOutputEnd = null;
  20428. var progress;
  20429. var forceFirstProgress;
  20430. if (!skip && taskIns._reset) {
  20431. progress = taskIns._reset(taskIns.context);
  20432. if (progress && progress.progress) {
  20433. forceFirstProgress = progress.forceFirstProgress;
  20434. progress = progress.progress;
  20435. }
  20436. // To simplify no progress checking, array must has item.
  20437. if (isArray(progress) && !progress.length) {
  20438. progress = null;
  20439. }
  20440. }
  20441. taskIns._progress = progress;
  20442. taskIns._modBy = taskIns._modDataCount = null;
  20443. var downstream = taskIns._downstream;
  20444. downstream && downstream.dirty();
  20445. return forceFirstProgress;
  20446. }
  20447. /**
  20448. * @return {boolean}
  20449. */
  20450. taskProto.unfinished = function () {
  20451. return this._progress && this._dueIndex < this._dueEnd;
  20452. };
  20453. /**
  20454. * @param {Object} downTask The downstream task.
  20455. * @return {Object} The downstream task.
  20456. */
  20457. taskProto.pipe = function (downTask) {
  20458. if (__DEV__) {
  20459. assert$1(downTask && !downTask._disposed && downTask !== this);
  20460. }
  20461. // If already downstream, do not dirty downTask.
  20462. if (this._downstream !== downTask || this._dirty) {
  20463. this._downstream = downTask;
  20464. downTask._upstream = this;
  20465. downTask.dirty();
  20466. }
  20467. };
  20468. taskProto.dispose = function () {
  20469. if (this._disposed) {
  20470. return;
  20471. }
  20472. this._upstream && (this._upstream._downstream = null);
  20473. this._downstream && (this._downstream._upstream = null);
  20474. this._dirty = false;
  20475. this._disposed = true;
  20476. };
  20477. taskProto.getUpstream = function () {
  20478. return this._upstream;
  20479. };
  20480. taskProto.getDownstream = function () {
  20481. return this._downstream;
  20482. };
  20483. taskProto.setOutputEnd = function (end) {
  20484. // This only happend in dataTask, dataZoom, map, currently.
  20485. // where dataZoom do not set end each time, but only set
  20486. // when reset. So we should record the setted end, in case
  20487. // that the stub of dataZoom perform again and earse the
  20488. // setted end by upstream.
  20489. this._outputDueEnd = this._settedOutputEnd = end;
  20490. };
  20491. ///////////////////////////////////////////////////////////
  20492. // For stream debug (Should be commented out after used!)
  20493. // Usage: printTask(this, 'begin');
  20494. // Usage: printTask(this, null, {someExtraProp});
  20495. // function printTask(task, prefix, extra) {
  20496. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  20497. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  20498. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  20499. // var props = [];
  20500. // if (task.__pipeline) {
  20501. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  20502. // props.push({text: 'idx', value: val});
  20503. // } else {
  20504. // var stubCount = 0;
  20505. // task.agentStubMap.each(() => stubCount++);
  20506. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  20507. // }
  20508. // props.push({text: 'uid', value: task.uidDebug});
  20509. // if (task.__pipeline) {
  20510. // props.push({text: 'pid', value: task.__pipeline.id});
  20511. // task.agent && props.push(
  20512. // {text: 'stubFor', value: task.agent.uidDebug}
  20513. // );
  20514. // }
  20515. // props.push(
  20516. // {text: 'dirty', value: task._dirty},
  20517. // {text: 'dueIndex', value: task._dueIndex},
  20518. // {text: 'dueEnd', value: task._dueEnd},
  20519. // {text: 'outputDueEnd', value: task._outputDueEnd}
  20520. // );
  20521. // if (extra) {
  20522. // Object.keys(extra).forEach(key => {
  20523. // props.push({text: key, value: extra[key]});
  20524. // });
  20525. // }
  20526. // var args = ['color: blue'];
  20527. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  20528. // args.push('color: black', 'color: red'),
  20529. // `${item.text}: %c${item.value}`
  20530. // )).join('%c, ');
  20531. // console.log.apply(console, [msg].concat(args));
  20532. // // console.log(this);
  20533. // }
  20534. /*
  20535. * Licensed to the Apache Software Foundation (ASF) under one
  20536. * or more contributor license agreements. See the NOTICE file
  20537. * distributed with this work for additional information
  20538. * regarding copyright ownership. The ASF licenses this file
  20539. * to you under the Apache License, Version 2.0 (the
  20540. * "License"); you may not use this file except in compliance
  20541. * with the License. You may obtain a copy of the License at
  20542. *
  20543. * http://www.apache.org/licenses/LICENSE-2.0
  20544. *
  20545. * Unless required by applicable law or agreed to in writing,
  20546. * software distributed under the License is distributed on an
  20547. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20548. * KIND, either express or implied. See the License for the
  20549. * specific language governing permissions and limitations
  20550. * under the License.
  20551. */
  20552. var inner$4 = makeInner();
  20553. var SeriesModel = ComponentModel.extend({
  20554. type: 'series.__base__',
  20555. /**
  20556. * @readOnly
  20557. */
  20558. seriesIndex: 0,
  20559. // coodinateSystem will be injected in the echarts/CoordinateSystem
  20560. coordinateSystem: null,
  20561. /**
  20562. * @type {Object}
  20563. * @protected
  20564. */
  20565. defaultOption: null,
  20566. /**
  20567. * Data provided for legend
  20568. * @type {Function}
  20569. */
  20570. // PENDING
  20571. legendDataProvider: null,
  20572. /**
  20573. * Access path of color for visual
  20574. */
  20575. visualColorAccessPath: 'itemStyle.color',
  20576. /**
  20577. * Support merge layout params.
  20578. * Only support 'box' now (left/right/top/bottom/width/height).
  20579. * @type {string|Object} Object can be {ignoreSize: true}
  20580. * @readOnly
  20581. */
  20582. layoutMode: null,
  20583. init: function (option, parentModel, ecModel, extraOpt) {
  20584. /**
  20585. * @type {number}
  20586. * @readOnly
  20587. */
  20588. this.seriesIndex = this.componentIndex;
  20589. this.dataTask = createTask({
  20590. count: dataTaskCount,
  20591. reset: dataTaskReset
  20592. });
  20593. this.dataTask.context = {model: this};
  20594. this.mergeDefaultAndTheme(option, ecModel);
  20595. prepareSource(this);
  20596. var data = this.getInitialData(option, ecModel);
  20597. wrapData(data, this);
  20598. this.dataTask.context.data = data;
  20599. if (__DEV__) {
  20600. assert$1(data, 'getInitialData returned invalid data.');
  20601. }
  20602. /**
  20603. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  20604. * @private
  20605. */
  20606. inner$4(this).dataBeforeProcessed = data;
  20607. // If we reverse the order (make data firstly, and then make
  20608. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20609. // cause data.graph.data !== data when using
  20610. // module:echarts/data/Graph or module:echarts/data/Tree.
  20611. // See module:echarts/data/helper/linkList
  20612. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20613. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20614. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20615. // Call `seriesModel.getRawData()` instead.
  20616. // this.restoreData();
  20617. autoSeriesName(this);
  20618. },
  20619. /**
  20620. * Util for merge default and theme to option
  20621. * @param {Object} option
  20622. * @param {module:echarts/model/Global} ecModel
  20623. */
  20624. mergeDefaultAndTheme: function (option, ecModel) {
  20625. var layoutMode = this.layoutMode;
  20626. var inputPositionParams = layoutMode
  20627. ? getLayoutParams(option) : {};
  20628. // Backward compat: using subType on theme.
  20629. // But if name duplicate between series subType
  20630. // (for example: parallel) add component mainType,
  20631. // add suffix 'Series'.
  20632. var themeSubType = this.subType;
  20633. if (ComponentModel.hasClass(themeSubType)) {
  20634. themeSubType += 'Series';
  20635. }
  20636. merge(
  20637. option,
  20638. ecModel.getTheme().get(this.subType)
  20639. );
  20640. merge(option, this.getDefaultOption());
  20641. // Default label emphasis `show`
  20642. defaultEmphasis(option, 'label', ['show']);
  20643. this.fillDataTextStyle(option.data);
  20644. if (layoutMode) {
  20645. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20646. }
  20647. },
  20648. mergeOption: function (newSeriesOption, ecModel) {
  20649. // this.settingTask.dirty();
  20650. newSeriesOption = merge(this.option, newSeriesOption, true);
  20651. this.fillDataTextStyle(newSeriesOption.data);
  20652. var layoutMode = this.layoutMode;
  20653. if (layoutMode) {
  20654. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20655. }
  20656. prepareSource(this);
  20657. var data = this.getInitialData(newSeriesOption, ecModel);
  20658. wrapData(data, this);
  20659. this.dataTask.dirty();
  20660. this.dataTask.context.data = data;
  20661. inner$4(this).dataBeforeProcessed = data;
  20662. autoSeriesName(this);
  20663. },
  20664. fillDataTextStyle: function (data) {
  20665. // Default data label emphasis `show`
  20666. // FIXME Tree structure data ?
  20667. // FIXME Performance ?
  20668. if (data && !isTypedArray(data)) {
  20669. var props = ['show'];
  20670. for (var i = 0; i < data.length; i++) {
  20671. if (data[i] && data[i].label) {
  20672. defaultEmphasis(data[i], 'label', props);
  20673. }
  20674. }
  20675. }
  20676. },
  20677. /**
  20678. * Init a data structure from data related option in series
  20679. * Must be overwritten
  20680. */
  20681. getInitialData: function () {},
  20682. /**
  20683. * Append data to list
  20684. * @param {Object} params
  20685. * @param {Array|TypedArray} params.data
  20686. */
  20687. appendData: function (params) {
  20688. // FIXME ???
  20689. // (1) If data from dataset, forbidden append.
  20690. // (2) support append data of dataset.
  20691. var data = this.getRawData();
  20692. data.appendData(params.data);
  20693. },
  20694. /**
  20695. * Consider some method like `filter`, `map` need make new data,
  20696. * We should make sure that `seriesModel.getData()` get correct
  20697. * data in the stream procedure. So we fetch data from upstream
  20698. * each time `task.perform` called.
  20699. * @param {string} [dataType]
  20700. * @return {module:echarts/data/List}
  20701. */
  20702. getData: function (dataType) {
  20703. var task = getCurrentTask(this);
  20704. if (task) {
  20705. var data = task.context.data;
  20706. return dataType == null ? data : data.getLinkedData(dataType);
  20707. }
  20708. else {
  20709. // When series is not alive (that may happen when click toolbox
  20710. // restore or setOption with not merge mode), series data may
  20711. // be still need to judge animation or something when graphic
  20712. // elements want to know whether fade out.
  20713. return inner$4(this).data;
  20714. }
  20715. },
  20716. /**
  20717. * @param {module:echarts/data/List} data
  20718. */
  20719. setData: function (data) {
  20720. var task = getCurrentTask(this);
  20721. if (task) {
  20722. var context = task.context;
  20723. // Consider case: filter, data sample.
  20724. if (context.data !== data && task.modifyOutputEnd) {
  20725. task.setOutputEnd(data.count());
  20726. }
  20727. context.outputData = data;
  20728. // Caution: setData should update context.data,
  20729. // Because getData may be called multiply in a
  20730. // single stage and expect to get the data just
  20731. // set. (For example, AxisProxy, x y both call
  20732. // getData and setDate sequentially).
  20733. // So the context.data should be fetched from
  20734. // upstream each time when a stage starts to be
  20735. // performed.
  20736. if (task !== this.dataTask) {
  20737. context.data = data;
  20738. }
  20739. }
  20740. inner$4(this).data = data;
  20741. },
  20742. /**
  20743. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20744. * @return {module:echarts/data/Source} source
  20745. */
  20746. getSource: function () {
  20747. return getSource(this);
  20748. },
  20749. /**
  20750. * Get data before processed
  20751. * @return {module:echarts/data/List}
  20752. */
  20753. getRawData: function () {
  20754. return inner$4(this).dataBeforeProcessed;
  20755. },
  20756. /**
  20757. * Get base axis if has coordinate system and has axis.
  20758. * By default use coordSys.getBaseAxis();
  20759. * Can be overrided for some chart.
  20760. * @return {type} description
  20761. */
  20762. getBaseAxis: function () {
  20763. var coordSys = this.coordinateSystem;
  20764. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20765. },
  20766. // FIXME
  20767. /**
  20768. * Default tooltip formatter
  20769. *
  20770. * @param {number} dataIndex
  20771. * @param {boolean} [multipleSeries=false]
  20772. * @param {number} [dataType]
  20773. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  20774. * 'html' is used for rendering tooltip in extra DOM form, and the result
  20775. * string is used as DOM HTML content.
  20776. * 'richText' is used for rendering tooltip in rich text form, for those where
  20777. * DOM operation is not supported.
  20778. * @return {Object} formatted tooltip with `html` and `markers`
  20779. */
  20780. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  20781. var series = this;
  20782. renderMode = renderMode || 'html';
  20783. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  20784. var isRichText = renderMode === 'richText';
  20785. var markers = {};
  20786. var markerId = 0;
  20787. function formatArrayValue(value) {
  20788. // ??? TODO refactor these logic.
  20789. // check: category-no-encode-has-axis-data in dataset.html
  20790. var vertially = reduce(value, function (vertially, val, idx) {
  20791. var dimItem = data.getDimensionInfo(idx);
  20792. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20793. }, 0);
  20794. var result = [];
  20795. tooltipDims.length
  20796. ? each$1(tooltipDims, function (dim) {
  20797. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20798. })
  20799. // By default, all dims is used on tooltip.
  20800. : each$1(value, setEachItem);
  20801. function setEachItem(val, dim) {
  20802. var dimInfo = data.getDimensionInfo(dim);
  20803. // If `dimInfo.tooltip` is not set, show tooltip.
  20804. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20805. return;
  20806. }
  20807. var dimType = dimInfo.type;
  20808. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  20809. var dimHead = getTooltipMarker({
  20810. color: color,
  20811. type: 'subItem',
  20812. renderMode: renderMode,
  20813. markerId: markName
  20814. });
  20815. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  20816. var valStr = (vertially
  20817. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  20818. : ''
  20819. )
  20820. // FIXME should not format time for raw data?
  20821. + encodeHTML(dimType === 'ordinal'
  20822. ? val + ''
  20823. : dimType === 'time'
  20824. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  20825. : addCommas(val)
  20826. );
  20827. valStr && result.push(valStr);
  20828. if (isRichText) {
  20829. markers[markName] = color;
  20830. ++markerId;
  20831. }
  20832. }
  20833. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  20834. var content = newLine + result.join(newLine || ', ');
  20835. return {
  20836. renderMode: renderMode,
  20837. content: content,
  20838. style: markers
  20839. };
  20840. }
  20841. function formatSingleValue(val) {
  20842. // return encodeHTML(addCommas(val));
  20843. return {
  20844. renderMode: renderMode,
  20845. content: encodeHTML(addCommas(val)),
  20846. style: markers
  20847. };
  20848. }
  20849. var data = this.getData();
  20850. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  20851. var tooltipDimLen = tooltipDims.length;
  20852. var value = this.getRawValue(dataIndex);
  20853. var isValueArr = isArray(value);
  20854. var color = data.getItemVisual(dataIndex, 'color');
  20855. if (isObject$1(color) && color.colorStops) {
  20856. color = (color.colorStops[0] || {}).color;
  20857. }
  20858. color = color || 'transparent';
  20859. // Complicated rule for pretty tooltip.
  20860. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  20861. ? formatArrayValue(value)
  20862. : tooltipDimLen
  20863. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  20864. : formatSingleValue(isValueArr ? value[0] : value);
  20865. var content = formattedValue.content;
  20866. var markName = series.seriesIndex + 'at' + markerId;
  20867. var colorEl = getTooltipMarker({
  20868. color: color,
  20869. type: 'item',
  20870. renderMode: renderMode,
  20871. markerId: markName
  20872. });
  20873. markers[markName] = color;
  20874. ++markerId;
  20875. var name = data.getName(dataIndex);
  20876. var seriesName = this.name;
  20877. if (!isNameSpecified(this)) {
  20878. seriesName = '';
  20879. }
  20880. seriesName = seriesName
  20881. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  20882. : '';
  20883. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  20884. var html = !multipleSeries
  20885. ? seriesName + colorStr
  20886. + (name
  20887. ? encodeHTML(name) + ': ' + content
  20888. : content
  20889. )
  20890. : colorStr + seriesName + content;
  20891. return {
  20892. html: html,
  20893. markers: markers
  20894. };
  20895. },
  20896. /**
  20897. * @return {boolean}
  20898. */
  20899. isAnimationEnabled: function () {
  20900. if (env$1.node) {
  20901. return false;
  20902. }
  20903. var animationEnabled = this.getShallow('animation');
  20904. if (animationEnabled) {
  20905. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20906. animationEnabled = false;
  20907. }
  20908. }
  20909. return animationEnabled;
  20910. },
  20911. restoreData: function () {
  20912. this.dataTask.dirty();
  20913. },
  20914. getColorFromPalette: function (name, scope, requestColorNum) {
  20915. var ecModel = this.ecModel;
  20916. // PENDING
  20917. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  20918. if (!color) {
  20919. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20920. }
  20921. return color;
  20922. },
  20923. /**
  20924. * Use `data.mapDimension(coordDim, true)` instead.
  20925. * @deprecated
  20926. */
  20927. coordDimToDataDim: function (coordDim) {
  20928. return this.getRawData().mapDimension(coordDim, true);
  20929. },
  20930. /**
  20931. * Get progressive rendering count each step
  20932. * @return {number}
  20933. */
  20934. getProgressive: function () {
  20935. return this.get('progressive');
  20936. },
  20937. /**
  20938. * Get progressive rendering count each step
  20939. * @return {number}
  20940. */
  20941. getProgressiveThreshold: function () {
  20942. return this.get('progressiveThreshold');
  20943. },
  20944. /**
  20945. * Get data indices for show tooltip content. See tooltip.
  20946. * @abstract
  20947. * @param {Array.<string>|string} dim
  20948. * @param {Array.<number>} value
  20949. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  20950. * @return {Object} {dataIndices, nestestValue}.
  20951. */
  20952. getAxisTooltipData: null,
  20953. /**
  20954. * See tooltip.
  20955. * @abstract
  20956. * @param {number} dataIndex
  20957. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  20958. */
  20959. getTooltipPosition: null,
  20960. /**
  20961. * @see {module:echarts/stream/Scheduler}
  20962. */
  20963. pipeTask: null,
  20964. /**
  20965. * Convinient for override in extended class.
  20966. * @protected
  20967. * @type {Function}
  20968. */
  20969. preventIncremental: null,
  20970. /**
  20971. * @public
  20972. * @readOnly
  20973. * @type {Object}
  20974. */
  20975. pipelineContext: null
  20976. });
  20977. mixin(SeriesModel, dataFormatMixin);
  20978. mixin(SeriesModel, colorPaletteMixin);
  20979. /**
  20980. * MUST be called after `prepareSource` called
  20981. * Here we need to make auto series, especially for auto legend. But we
  20982. * do not modify series.name in option to avoid side effects.
  20983. */
  20984. function autoSeriesName(seriesModel) {
  20985. // User specified name has higher priority, otherwise it may cause
  20986. // series can not be queried unexpectedly.
  20987. var name = seriesModel.name;
  20988. if (!isNameSpecified(seriesModel)) {
  20989. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20990. }
  20991. }
  20992. function getSeriesAutoName(seriesModel) {
  20993. var data = seriesModel.getRawData();
  20994. var dataDims = data.mapDimension('seriesName', true);
  20995. var nameArr = [];
  20996. each$1(dataDims, function (dataDim) {
  20997. var dimInfo = data.getDimensionInfo(dataDim);
  20998. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20999. });
  21000. return nameArr.join(' ');
  21001. }
  21002. function dataTaskCount(context) {
  21003. return context.model.getRawData().count();
  21004. }
  21005. function dataTaskReset(context) {
  21006. var seriesModel = context.model;
  21007. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21008. return dataTaskProgress;
  21009. }
  21010. function dataTaskProgress(param, context) {
  21011. // Avoid repead cloneShallow when data just created in reset.
  21012. if (param.end > context.outputData.count()) {
  21013. context.model.getRawData().cloneShallow(context.outputData);
  21014. }
  21015. }
  21016. // TODO refactor
  21017. function wrapData(data, seriesModel) {
  21018. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21019. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21020. });
  21021. }
  21022. function onDataSelfChange(seriesModel) {
  21023. var task = getCurrentTask(seriesModel);
  21024. if (task) {
  21025. // Consider case: filter, selectRange
  21026. task.setOutputEnd(this.count());
  21027. }
  21028. }
  21029. function getCurrentTask(seriesModel) {
  21030. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21031. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21032. if (pipeline) {
  21033. // When pipline finished, the currrentTask keep the last
  21034. // task (renderTask).
  21035. var task = pipeline.currentTask;
  21036. if (task) {
  21037. var agentStubMap = task.agentStubMap;
  21038. if (agentStubMap) {
  21039. task = agentStubMap.get(seriesModel.uid);
  21040. }
  21041. }
  21042. return task;
  21043. }
  21044. }
  21045. /*
  21046. * Licensed to the Apache Software Foundation (ASF) under one
  21047. * or more contributor license agreements. See the NOTICE file
  21048. * distributed with this work for additional information
  21049. * regarding copyright ownership. The ASF licenses this file
  21050. * to you under the Apache License, Version 2.0 (the
  21051. * "License"); you may not use this file except in compliance
  21052. * with the License. You may obtain a copy of the License at
  21053. *
  21054. * http://www.apache.org/licenses/LICENSE-2.0
  21055. *
  21056. * Unless required by applicable law or agreed to in writing,
  21057. * software distributed under the License is distributed on an
  21058. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21059. * KIND, either express or implied. See the License for the
  21060. * specific language governing permissions and limitations
  21061. * under the License.
  21062. */
  21063. var Component$1 = function () {
  21064. /**
  21065. * @type {module:zrender/container/Group}
  21066. * @readOnly
  21067. */
  21068. this.group = new Group();
  21069. /**
  21070. * @type {string}
  21071. * @readOnly
  21072. */
  21073. this.uid = getUID('viewComponent');
  21074. };
  21075. Component$1.prototype = {
  21076. constructor: Component$1,
  21077. init: function (ecModel, api) {},
  21078. render: function (componentModel, ecModel, api, payload) {},
  21079. dispose: function () {},
  21080. /**
  21081. * @param {string} eventType
  21082. * @param {Object} query
  21083. * @param {module:zrender/Element} targetEl
  21084. * @param {Object} packedEvent
  21085. * @return {boolen} Pass only when return `true`.
  21086. */
  21087. filterForExposedEvent: null
  21088. };
  21089. var componentProto = Component$1.prototype;
  21090. componentProto.updateView
  21091. = componentProto.updateLayout
  21092. = componentProto.updateVisual
  21093. = function (seriesModel, ecModel, api, payload) {
  21094. // Do nothing;
  21095. };
  21096. // Enable Component.extend.
  21097. enableClassExtend(Component$1);
  21098. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21099. enableClassManagement(Component$1, {registerWhenExtend: true});
  21100. /*
  21101. * Licensed to the Apache Software Foundation (ASF) under one
  21102. * or more contributor license agreements. See the NOTICE file
  21103. * distributed with this work for additional information
  21104. * regarding copyright ownership. The ASF licenses this file
  21105. * to you under the Apache License, Version 2.0 (the
  21106. * "License"); you may not use this file except in compliance
  21107. * with the License. You may obtain a copy of the License at
  21108. *
  21109. * http://www.apache.org/licenses/LICENSE-2.0
  21110. *
  21111. * Unless required by applicable law or agreed to in writing,
  21112. * software distributed under the License is distributed on an
  21113. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21114. * KIND, either express or implied. See the License for the
  21115. * specific language governing permissions and limitations
  21116. * under the License.
  21117. */
  21118. /**
  21119. * @return {string} If large mode changed, return string 'reset';
  21120. */
  21121. var createRenderPlanner = function () {
  21122. var inner = makeInner();
  21123. return function (seriesModel) {
  21124. var fields = inner(seriesModel);
  21125. var pipelineContext = seriesModel.pipelineContext;
  21126. var originalLarge = fields.large;
  21127. var originalProgressive = fields.progressiveRender;
  21128. var large = fields.large = pipelineContext.large;
  21129. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  21130. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21131. };
  21132. };
  21133. /*
  21134. * Licensed to the Apache Software Foundation (ASF) under one
  21135. * or more contributor license agreements. See the NOTICE file
  21136. * distributed with this work for additional information
  21137. * regarding copyright ownership. The ASF licenses this file
  21138. * to you under the Apache License, Version 2.0 (the
  21139. * "License"); you may not use this file except in compliance
  21140. * with the License. You may obtain a copy of the License at
  21141. *
  21142. * http://www.apache.org/licenses/LICENSE-2.0
  21143. *
  21144. * Unless required by applicable law or agreed to in writing,
  21145. * software distributed under the License is distributed on an
  21146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21147. * KIND, either express or implied. See the License for the
  21148. * specific language governing permissions and limitations
  21149. * under the License.
  21150. */
  21151. var inner$5 = makeInner();
  21152. var renderPlanner = createRenderPlanner();
  21153. function Chart() {
  21154. /**
  21155. * @type {module:zrender/container/Group}
  21156. * @readOnly
  21157. */
  21158. this.group = new Group();
  21159. /**
  21160. * @type {string}
  21161. * @readOnly
  21162. */
  21163. this.uid = getUID('viewChart');
  21164. this.renderTask = createTask({
  21165. plan: renderTaskPlan,
  21166. reset: renderTaskReset
  21167. });
  21168. this.renderTask.context = {view: this};
  21169. }
  21170. Chart.prototype = {
  21171. type: 'chart',
  21172. /**
  21173. * Init the chart.
  21174. * @param {module:echarts/model/Global} ecModel
  21175. * @param {module:echarts/ExtensionAPI} api
  21176. */
  21177. init: function (ecModel, api) {},
  21178. /**
  21179. * Render the chart.
  21180. * @param {module:echarts/model/Series} seriesModel
  21181. * @param {module:echarts/model/Global} ecModel
  21182. * @param {module:echarts/ExtensionAPI} api
  21183. * @param {Object} payload
  21184. */
  21185. render: function (seriesModel, ecModel, api, payload) {},
  21186. /**
  21187. * Highlight series or specified data item.
  21188. * @param {module:echarts/model/Series} seriesModel
  21189. * @param {module:echarts/model/Global} ecModel
  21190. * @param {module:echarts/ExtensionAPI} api
  21191. * @param {Object} payload
  21192. */
  21193. highlight: function (seriesModel, ecModel, api, payload) {
  21194. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  21195. },
  21196. /**
  21197. * Downplay series or specified data item.
  21198. * @param {module:echarts/model/Series} seriesModel
  21199. * @param {module:echarts/model/Global} ecModel
  21200. * @param {module:echarts/ExtensionAPI} api
  21201. * @param {Object} payload
  21202. */
  21203. downplay: function (seriesModel, ecModel, api, payload) {
  21204. toggleHighlight(seriesModel.getData(), payload, 'normal');
  21205. },
  21206. /**
  21207. * Remove self.
  21208. * @param {module:echarts/model/Global} ecModel
  21209. * @param {module:echarts/ExtensionAPI} api
  21210. */
  21211. remove: function (ecModel, api) {
  21212. this.group.removeAll();
  21213. },
  21214. /**
  21215. * Dispose self.
  21216. * @param {module:echarts/model/Global} ecModel
  21217. * @param {module:echarts/ExtensionAPI} api
  21218. */
  21219. dispose: function () {},
  21220. /**
  21221. * Rendering preparation in progressive mode.
  21222. * @param {module:echarts/model/Series} seriesModel
  21223. * @param {module:echarts/model/Global} ecModel
  21224. * @param {module:echarts/ExtensionAPI} api
  21225. * @param {Object} payload
  21226. */
  21227. incrementalPrepareRender: null,
  21228. /**
  21229. * Render in progressive mode.
  21230. * @param {Object} params See taskParams in `stream/task.js`
  21231. * @param {module:echarts/model/Series} seriesModel
  21232. * @param {module:echarts/model/Global} ecModel
  21233. * @param {module:echarts/ExtensionAPI} api
  21234. * @param {Object} payload
  21235. */
  21236. incrementalRender: null,
  21237. /**
  21238. * Update transform directly.
  21239. * @param {module:echarts/model/Series} seriesModel
  21240. * @param {module:echarts/model/Global} ecModel
  21241. * @param {module:echarts/ExtensionAPI} api
  21242. * @param {Object} payload
  21243. * @return {Object} {update: true}
  21244. */
  21245. updateTransform: null,
  21246. /**
  21247. * The view contains the given point.
  21248. * @interface
  21249. * @param {Array.<number>} point
  21250. * @return {boolean}
  21251. */
  21252. // containPoint: function () {}
  21253. /**
  21254. * @param {string} eventType
  21255. * @param {Object} query
  21256. * @param {module:zrender/Element} targetEl
  21257. * @param {Object} packedEvent
  21258. * @return {boolen} Pass only when return `true`.
  21259. */
  21260. filterForExposedEvent: null
  21261. };
  21262. var chartProto = Chart.prototype;
  21263. chartProto.updateView
  21264. = chartProto.updateLayout
  21265. = chartProto.updateVisual
  21266. = function (seriesModel, ecModel, api, payload) {
  21267. this.render(seriesModel, ecModel, api, payload);
  21268. };
  21269. /**
  21270. * Set state of single element
  21271. * @param {module:zrender/Element} el
  21272. * @param {string} state
  21273. */
  21274. function elSetState(el, state) {
  21275. if (el) {
  21276. el.trigger(state);
  21277. if (el.type === 'group') {
  21278. for (var i = 0; i < el.childCount(); i++) {
  21279. elSetState(el.childAt(i), state);
  21280. }
  21281. }
  21282. }
  21283. }
  21284. /**
  21285. * @param {module:echarts/data/List} data
  21286. * @param {Object} payload
  21287. * @param {string} state 'normal'|'emphasis'
  21288. */
  21289. function toggleHighlight(data, payload, state) {
  21290. var dataIndex = queryDataIndex(data, payload);
  21291. if (dataIndex != null) {
  21292. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  21293. elSetState(data.getItemGraphicEl(dataIdx), state);
  21294. });
  21295. }
  21296. else {
  21297. data.eachItemGraphicEl(function (el) {
  21298. elSetState(el, state);
  21299. });
  21300. }
  21301. }
  21302. // Enable Chart.extend.
  21303. enableClassExtend(Chart, ['dispose']);
  21304. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21305. enableClassManagement(Chart, {registerWhenExtend: true});
  21306. Chart.markUpdateMethod = function (payload, methodName) {
  21307. inner$5(payload).updateMethod = methodName;
  21308. };
  21309. function renderTaskPlan(context) {
  21310. return renderPlanner(context.model);
  21311. }
  21312. function renderTaskReset(context) {
  21313. var seriesModel = context.model;
  21314. var ecModel = context.ecModel;
  21315. var api = context.api;
  21316. var payload = context.payload;
  21317. // ???! remove updateView updateVisual
  21318. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  21319. var view = context.view;
  21320. var updateMethod = payload && inner$5(payload).updateMethod;
  21321. var methodName = progressiveRender
  21322. ? 'incrementalPrepareRender'
  21323. : (updateMethod && view[updateMethod])
  21324. ? updateMethod
  21325. // `appendData` is also supported when data amount
  21326. // is less than progressive threshold.
  21327. : 'render';
  21328. if (methodName !== 'render') {
  21329. view[methodName](seriesModel, ecModel, api, payload);
  21330. }
  21331. return progressMethodMap[methodName];
  21332. }
  21333. var progressMethodMap = {
  21334. incrementalPrepareRender: {
  21335. progress: function (params, context) {
  21336. context.view.incrementalRender(
  21337. params, context.model, context.ecModel, context.api, context.payload
  21338. );
  21339. }
  21340. },
  21341. render: {
  21342. // Put view.render in `progress` to support appendData. But in this case
  21343. // view.render should not be called in reset, otherwise it will be called
  21344. // twise. Use `forceFirstProgress` to make sure that view.render is called
  21345. // in any cases.
  21346. forceFirstProgress: true,
  21347. progress: function (params, context) {
  21348. context.view.render(
  21349. context.model, context.ecModel, context.api, context.payload
  21350. );
  21351. }
  21352. }
  21353. };
  21354. /*
  21355. * Licensed to the Apache Software Foundation (ASF) under one
  21356. * or more contributor license agreements. See the NOTICE file
  21357. * distributed with this work for additional information
  21358. * regarding copyright ownership. The ASF licenses this file
  21359. * to you under the Apache License, Version 2.0 (the
  21360. * "License"); you may not use this file except in compliance
  21361. * with the License. You may obtain a copy of the License at
  21362. *
  21363. * http://www.apache.org/licenses/LICENSE-2.0
  21364. *
  21365. * Unless required by applicable law or agreed to in writing,
  21366. * software distributed under the License is distributed on an
  21367. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21368. * KIND, either express or implied. See the License for the
  21369. * specific language governing permissions and limitations
  21370. * under the License.
  21371. */
  21372. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  21373. var RATE = '\0__throttleRate';
  21374. var THROTTLE_TYPE = '\0__throttleType';
  21375. /**
  21376. * @public
  21377. * @param {(Function)} fn
  21378. * @param {number} [delay=0] Unit: ms.
  21379. * @param {boolean} [debounce=false]
  21380. * true: If call interval less than `delay`, only the last call works.
  21381. * false: If call interval less than `delay, call works on fixed rate.
  21382. * @return {(Function)} throttled fn.
  21383. */
  21384. function throttle(fn, delay, debounce) {
  21385. var currCall;
  21386. var lastCall = 0;
  21387. var lastExec = 0;
  21388. var timer = null;
  21389. var diff;
  21390. var scope;
  21391. var args;
  21392. var debounceNextCall;
  21393. delay = delay || 0;
  21394. function exec() {
  21395. lastExec = (new Date()).getTime();
  21396. timer = null;
  21397. fn.apply(scope, args || []);
  21398. }
  21399. var cb = function () {
  21400. currCall = (new Date()).getTime();
  21401. scope = this;
  21402. args = arguments;
  21403. var thisDelay = debounceNextCall || delay;
  21404. var thisDebounce = debounceNextCall || debounce;
  21405. debounceNextCall = null;
  21406. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  21407. clearTimeout(timer);
  21408. // Here we should make sure that: the `exec` SHOULD NOT be called later
  21409. // than a new call of `cb`, that is, preserving the command order. Consider
  21410. // calculating "scale rate" when roaming as an example. When a call of `cb`
  21411. // happens, either the `exec` is called dierectly, or the call is delayed.
  21412. // But the delayed call should never be later than next call of `cb`. Under
  21413. // this assurance, we can simply update view state each time `dispatchAction`
  21414. // triggered by user roaming, but not need to add extra code to avoid the
  21415. // state being "rolled-back".
  21416. if (thisDebounce) {
  21417. timer = setTimeout(exec, thisDelay);
  21418. }
  21419. else {
  21420. if (diff >= 0) {
  21421. exec();
  21422. }
  21423. else {
  21424. timer = setTimeout(exec, -diff);
  21425. }
  21426. }
  21427. lastCall = currCall;
  21428. };
  21429. /**
  21430. * Clear throttle.
  21431. * @public
  21432. */
  21433. cb.clear = function () {
  21434. if (timer) {
  21435. clearTimeout(timer);
  21436. timer = null;
  21437. }
  21438. };
  21439. /**
  21440. * Enable debounce once.
  21441. */
  21442. cb.debounceNextCall = function (debounceDelay) {
  21443. debounceNextCall = debounceDelay;
  21444. };
  21445. return cb;
  21446. }
  21447. /**
  21448. * Create throttle method or update throttle rate.
  21449. *
  21450. * @example
  21451. * ComponentView.prototype.render = function () {
  21452. * ...
  21453. * throttle.createOrUpdate(
  21454. * this,
  21455. * '_dispatchAction',
  21456. * this.model.get('throttle'),
  21457. * 'fixRate'
  21458. * );
  21459. * };
  21460. * ComponentView.prototype.remove = function () {
  21461. * throttle.clear(this, '_dispatchAction');
  21462. * };
  21463. * ComponentView.prototype.dispose = function () {
  21464. * throttle.clear(this, '_dispatchAction');
  21465. * };
  21466. *
  21467. * @public
  21468. * @param {Object} obj
  21469. * @param {string} fnAttr
  21470. * @param {number} [rate]
  21471. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  21472. * @return {Function} throttled function.
  21473. */
  21474. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  21475. var fn = obj[fnAttr];
  21476. if (!fn) {
  21477. return;
  21478. }
  21479. var originFn = fn[ORIGIN_METHOD] || fn;
  21480. var lastThrottleType = fn[THROTTLE_TYPE];
  21481. var lastRate = fn[RATE];
  21482. if (lastRate !== rate || lastThrottleType !== throttleType) {
  21483. if (rate == null || !throttleType) {
  21484. return (obj[fnAttr] = originFn);
  21485. }
  21486. fn = obj[fnAttr] = throttle(
  21487. originFn, rate, throttleType === 'debounce'
  21488. );
  21489. fn[ORIGIN_METHOD] = originFn;
  21490. fn[THROTTLE_TYPE] = throttleType;
  21491. fn[RATE] = rate;
  21492. }
  21493. return fn;
  21494. }
  21495. /**
  21496. * Clear throttle. Example see throttle.createOrUpdate.
  21497. *
  21498. * @public
  21499. * @param {Object} obj
  21500. * @param {string} fnAttr
  21501. */
  21502. function clear(obj, fnAttr) {
  21503. var fn = obj[fnAttr];
  21504. if (fn && fn[ORIGIN_METHOD]) {
  21505. obj[fnAttr] = fn[ORIGIN_METHOD];
  21506. }
  21507. }
  21508. /*
  21509. * Licensed to the Apache Software Foundation (ASF) under one
  21510. * or more contributor license agreements. See the NOTICE file
  21511. * distributed with this work for additional information
  21512. * regarding copyright ownership. The ASF licenses this file
  21513. * to you under the Apache License, Version 2.0 (the
  21514. * "License"); you may not use this file except in compliance
  21515. * with the License. You may obtain a copy of the License at
  21516. *
  21517. * http://www.apache.org/licenses/LICENSE-2.0
  21518. *
  21519. * Unless required by applicable law or agreed to in writing,
  21520. * software distributed under the License is distributed on an
  21521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21522. * KIND, either express or implied. See the License for the
  21523. * specific language governing permissions and limitations
  21524. * under the License.
  21525. */
  21526. var seriesColor = {
  21527. createOnAllSeries: true,
  21528. performRawSeries: true,
  21529. reset: function (seriesModel, ecModel) {
  21530. var data = seriesModel.getData();
  21531. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  21532. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  21533. || seriesModel.getColorFromPalette(
  21534. // TODO series count changed.
  21535. seriesModel.name, null, ecModel.getSeriesCount()
  21536. ); // Default color
  21537. // FIXME Set color function or use the platte color
  21538. data.setVisual('color', color);
  21539. // Only visible series has each data be visual encoded
  21540. if (!ecModel.isSeriesFiltered(seriesModel)) {
  21541. if (typeof color === 'function' && !(color instanceof Gradient)) {
  21542. data.each(function (idx) {
  21543. data.setItemVisual(
  21544. idx, 'color', color(seriesModel.getDataParams(idx))
  21545. );
  21546. });
  21547. }
  21548. // itemStyle in each data item
  21549. var dataEach = function (data, idx) {
  21550. var itemModel = data.getItemModel(idx);
  21551. var color = itemModel.get(colorAccessPath, true);
  21552. if (color != null) {
  21553. data.setItemVisual(idx, 'color', color);
  21554. }
  21555. };
  21556. return { dataEach: data.hasItemOption ? dataEach : null };
  21557. }
  21558. }
  21559. };
  21560. /*
  21561. * Licensed to the Apache Software Foundation (ASF) under one
  21562. * or more contributor license agreements. See the NOTICE file
  21563. * distributed with this work for additional information
  21564. * regarding copyright ownership. The ASF licenses this file
  21565. * to you under the Apache License, Version 2.0 (the
  21566. * "License"); you may not use this file except in compliance
  21567. * with the License. You may obtain a copy of the License at
  21568. *
  21569. * http://www.apache.org/licenses/LICENSE-2.0
  21570. *
  21571. * Unless required by applicable law or agreed to in writing,
  21572. * software distributed under the License is distributed on an
  21573. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21574. * KIND, either express or implied. See the License for the
  21575. * specific language governing permissions and limitations
  21576. * under the License.
  21577. */
  21578. var lang = {
  21579. toolbox: {
  21580. brush: {
  21581. title: {
  21582. rect: '矩形选择',
  21583. polygon: '圈选',
  21584. lineX: '横向选择',
  21585. lineY: '纵向选择',
  21586. keep: '保持选择',
  21587. clear: '清除选择'
  21588. }
  21589. },
  21590. dataView: {
  21591. title: '数据视图',
  21592. lang: ['数据视图', '关闭', '刷新']
  21593. },
  21594. dataZoom: {
  21595. title: {
  21596. zoom: '区域缩放',
  21597. back: '区域缩放还原'
  21598. }
  21599. },
  21600. magicType: {
  21601. title: {
  21602. line: '切换为折线图',
  21603. bar: '切换为柱状图',
  21604. stack: '切换为堆叠',
  21605. tiled: '切换为平铺'
  21606. }
  21607. },
  21608. restore: {
  21609. title: '还原'
  21610. },
  21611. saveAsImage: {
  21612. title: '保存为图片',
  21613. lang: ['右键另存为图片']
  21614. }
  21615. },
  21616. series: {
  21617. typeNames: {
  21618. pie: '饼图',
  21619. bar: '柱状图',
  21620. line: '折线图',
  21621. scatter: '散点图',
  21622. effectScatter: '涟漪散点图',
  21623. radar: '雷达图',
  21624. tree: '树图',
  21625. treemap: '矩形树图',
  21626. boxplot: '箱型图',
  21627. candlestick: 'K线图',
  21628. k: 'K线图',
  21629. heatmap: '热力图',
  21630. map: '地图',
  21631. parallel: '平行坐标图',
  21632. lines: '线图',
  21633. graph: '关系图',
  21634. sankey: '桑基图',
  21635. funnel: '漏斗图',
  21636. gauge: '仪表盘图',
  21637. pictorialBar: '象形柱图',
  21638. themeRiver: '主题河流图',
  21639. sunburst: '旭日图'
  21640. }
  21641. },
  21642. aria: {
  21643. general: {
  21644. withTitle: '这是一个关于“{title}”的图表。',
  21645. withoutTitle: '这是一个图表,'
  21646. },
  21647. series: {
  21648. single: {
  21649. prefix: '',
  21650. withName: '图表类型是{seriesType},表示{seriesName}。',
  21651. withoutName: '图表类型是{seriesType}。'
  21652. },
  21653. multiple: {
  21654. prefix: '它由{seriesCount}个图表系列组成。',
  21655. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  21656. withoutName: '第{seriesId}个系列是一个{seriesType},',
  21657. separator: {
  21658. middle: ';',
  21659. end: '。'
  21660. }
  21661. }
  21662. },
  21663. data: {
  21664. allData: '其数据是——',
  21665. partialData: '其中,前{displayCnt}项是——',
  21666. withName: '{name}的数据是{value}',
  21667. withoutName: '{value}',
  21668. separator: {
  21669. middle: ',',
  21670. end: ''
  21671. }
  21672. }
  21673. }
  21674. };
  21675. /*
  21676. * Licensed to the Apache Software Foundation (ASF) under one
  21677. * or more contributor license agreements. See the NOTICE file
  21678. * distributed with this work for additional information
  21679. * regarding copyright ownership. The ASF licenses this file
  21680. * to you under the Apache License, Version 2.0 (the
  21681. * "License"); you may not use this file except in compliance
  21682. * with the License. You may obtain a copy of the License at
  21683. *
  21684. * http://www.apache.org/licenses/LICENSE-2.0
  21685. *
  21686. * Unless required by applicable law or agreed to in writing,
  21687. * software distributed under the License is distributed on an
  21688. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21689. * KIND, either express or implied. See the License for the
  21690. * specific language governing permissions and limitations
  21691. * under the License.
  21692. */
  21693. var aria = function (dom, ecModel) {
  21694. var ariaModel = ecModel.getModel('aria');
  21695. if (!ariaModel.get('show')) {
  21696. return;
  21697. }
  21698. else if (ariaModel.get('description')) {
  21699. dom.setAttribute('aria-label', ariaModel.get('description'));
  21700. return;
  21701. }
  21702. var seriesCnt = 0;
  21703. ecModel.eachSeries(function (seriesModel, idx) {
  21704. ++seriesCnt;
  21705. }, this);
  21706. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  21707. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  21708. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  21709. var ariaLabel;
  21710. if (seriesCnt < 1) {
  21711. // No series, no aria label
  21712. return;
  21713. }
  21714. else {
  21715. var title = getTitle();
  21716. if (title) {
  21717. ariaLabel = replace(getConfig('general.withTitle'), {
  21718. title: title
  21719. });
  21720. }
  21721. else {
  21722. ariaLabel = getConfig('general.withoutTitle');
  21723. }
  21724. var seriesLabels = [];
  21725. var prefix = seriesCnt > 1
  21726. ? 'series.multiple.prefix'
  21727. : 'series.single.prefix';
  21728. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  21729. ecModel.eachSeries(function (seriesModel, idx) {
  21730. if (idx < displaySeriesCnt) {
  21731. var seriesLabel;
  21732. var seriesName = seriesModel.get('name');
  21733. var seriesTpl = 'series.'
  21734. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  21735. seriesLabel = getConfig(seriesName
  21736. ? seriesTpl + 'withName'
  21737. : seriesTpl + 'withoutName');
  21738. seriesLabel = replace(seriesLabel, {
  21739. seriesId: seriesModel.seriesIndex,
  21740. seriesName: seriesModel.get('name'),
  21741. seriesType: getSeriesTypeName(seriesModel.subType)
  21742. });
  21743. var data = seriesModel.getData();
  21744. window.data = data;
  21745. if (data.count() > maxDataCnt) {
  21746. // Show part of data
  21747. seriesLabel += replace(getConfig('data.partialData'), {
  21748. displayCnt: maxDataCnt
  21749. });
  21750. }
  21751. else {
  21752. seriesLabel += getConfig('data.allData');
  21753. }
  21754. var dataLabels = [];
  21755. for (var i = 0; i < data.count(); i++) {
  21756. if (i < maxDataCnt) {
  21757. var name = data.getName(i);
  21758. var value = retrieveRawValue(data, i);
  21759. dataLabels.push(
  21760. replace(
  21761. name
  21762. ? getConfig('data.withName')
  21763. : getConfig('data.withoutName'),
  21764. {
  21765. name: name,
  21766. value: value
  21767. }
  21768. )
  21769. );
  21770. }
  21771. }
  21772. seriesLabel += dataLabels
  21773. .join(getConfig('data.separator.middle'))
  21774. + getConfig('data.separator.end');
  21775. seriesLabels.push(seriesLabel);
  21776. }
  21777. });
  21778. ariaLabel += seriesLabels
  21779. .join(getConfig('series.multiple.separator.middle'))
  21780. + getConfig('series.multiple.separator.end');
  21781. dom.setAttribute('aria-label', ariaLabel);
  21782. }
  21783. function replace(str, keyValues) {
  21784. if (typeof str !== 'string') {
  21785. return str;
  21786. }
  21787. var result = str;
  21788. each$1(keyValues, function (value, key) {
  21789. result = result.replace(
  21790. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21791. value
  21792. );
  21793. });
  21794. return result;
  21795. }
  21796. function getConfig(path) {
  21797. var userConfig = ariaModel.get(path);
  21798. if (userConfig == null) {
  21799. var pathArr = path.split('.');
  21800. var result = lang.aria;
  21801. for (var i = 0; i < pathArr.length; ++i) {
  21802. result = result[pathArr[i]];
  21803. }
  21804. return result;
  21805. }
  21806. else {
  21807. return userConfig;
  21808. }
  21809. }
  21810. function getTitle() {
  21811. var title = ecModel.getModel('title').option;
  21812. if (title && title.length) {
  21813. title = title[0];
  21814. }
  21815. return title && title.text;
  21816. }
  21817. function getSeriesTypeName(type) {
  21818. return lang.series.typeNames[type] || '自定义图';
  21819. }
  21820. };
  21821. /*
  21822. * Licensed to the Apache Software Foundation (ASF) under one
  21823. * or more contributor license agreements. See the NOTICE file
  21824. * distributed with this work for additional information
  21825. * regarding copyright ownership. The ASF licenses this file
  21826. * to you under the Apache License, Version 2.0 (the
  21827. * "License"); you may not use this file except in compliance
  21828. * with the License. You may obtain a copy of the License at
  21829. *
  21830. * http://www.apache.org/licenses/LICENSE-2.0
  21831. *
  21832. * Unless required by applicable law or agreed to in writing,
  21833. * software distributed under the License is distributed on an
  21834. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21835. * KIND, either express or implied. See the License for the
  21836. * specific language governing permissions and limitations
  21837. * under the License.
  21838. */
  21839. var PI$1 = Math.PI;
  21840. /**
  21841. * @param {module:echarts/ExtensionAPI} api
  21842. * @param {Object} [opts]
  21843. * @param {string} [opts.text]
  21844. * @param {string} [opts.color]
  21845. * @param {string} [opts.textColor]
  21846. * @return {module:zrender/Element}
  21847. */
  21848. var loadingDefault = function (api, opts) {
  21849. opts = opts || {};
  21850. defaults(opts, {
  21851. text: 'loading',
  21852. color: '#c23531',
  21853. textColor: '#000',
  21854. maskColor: 'rgba(255, 255, 255, 0.8)',
  21855. zlevel: 0
  21856. });
  21857. var mask = new Rect({
  21858. style: {
  21859. fill: opts.maskColor
  21860. },
  21861. zlevel: opts.zlevel,
  21862. z: 10000
  21863. });
  21864. var arc = new Arc({
  21865. shape: {
  21866. startAngle: -PI$1 / 2,
  21867. endAngle: -PI$1 / 2 + 0.1,
  21868. r: 10
  21869. },
  21870. style: {
  21871. stroke: opts.color,
  21872. lineCap: 'round',
  21873. lineWidth: 5
  21874. },
  21875. zlevel: opts.zlevel,
  21876. z: 10001
  21877. });
  21878. var labelRect = new Rect({
  21879. style: {
  21880. fill: 'none',
  21881. text: opts.text,
  21882. textPosition: 'right',
  21883. textDistance: 10,
  21884. textFill: opts.textColor
  21885. },
  21886. zlevel: opts.zlevel,
  21887. z: 10001
  21888. });
  21889. arc.animateShape(true)
  21890. .when(1000, {
  21891. endAngle: PI$1 * 3 / 2
  21892. })
  21893. .start('circularInOut');
  21894. arc.animateShape(true)
  21895. .when(1000, {
  21896. startAngle: PI$1 * 3 / 2
  21897. })
  21898. .delay(300)
  21899. .start('circularInOut');
  21900. var group = new Group();
  21901. group.add(arc);
  21902. group.add(labelRect);
  21903. group.add(mask);
  21904. // Inject resize
  21905. group.resize = function () {
  21906. var cx = api.getWidth() / 2;
  21907. var cy = api.getHeight() / 2;
  21908. arc.setShape({
  21909. cx: cx,
  21910. cy: cy
  21911. });
  21912. var r = arc.shape.r;
  21913. labelRect.setShape({
  21914. x: cx - r,
  21915. y: cy - r,
  21916. width: r * 2,
  21917. height: r * 2
  21918. });
  21919. mask.setShape({
  21920. x: 0,
  21921. y: 0,
  21922. width: api.getWidth(),
  21923. height: api.getHeight()
  21924. });
  21925. };
  21926. group.resize();
  21927. return group;
  21928. };
  21929. /*
  21930. * Licensed to the Apache Software Foundation (ASF) under one
  21931. * or more contributor license agreements. See the NOTICE file
  21932. * distributed with this work for additional information
  21933. * regarding copyright ownership. The ASF licenses this file
  21934. * to you under the Apache License, Version 2.0 (the
  21935. * "License"); you may not use this file except in compliance
  21936. * with the License. You may obtain a copy of the License at
  21937. *
  21938. * http://www.apache.org/licenses/LICENSE-2.0
  21939. *
  21940. * Unless required by applicable law or agreed to in writing,
  21941. * software distributed under the License is distributed on an
  21942. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21943. * KIND, either express or implied. See the License for the
  21944. * specific language governing permissions and limitations
  21945. * under the License.
  21946. */
  21947. /**
  21948. * @module echarts/stream/Scheduler
  21949. */
  21950. /**
  21951. * @constructor
  21952. */
  21953. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21954. this.ecInstance = ecInstance;
  21955. this.api = api;
  21956. this.unfinished;
  21957. // Fix current processors in case that in some rear cases that
  21958. // processors might be registered after echarts instance created.
  21959. // Register processors incrementally for a echarts instance is
  21960. // not supported by this stream architecture.
  21961. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21962. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21963. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21964. /**
  21965. * @private
  21966. * @type {
  21967. * [handlerUID: string]: {
  21968. * seriesTaskMap?: {
  21969. * [seriesUID: string]: Task
  21970. * },
  21971. * overallTask?: Task
  21972. * }
  21973. * }
  21974. */
  21975. this._stageTaskMap = createHashMap();
  21976. }
  21977. var proto = Scheduler.prototype;
  21978. /**
  21979. * @param {module:echarts/model/Global} ecModel
  21980. * @param {Object} payload
  21981. */
  21982. proto.restoreData = function (ecModel, payload) {
  21983. // TODO: Only restroe needed series and components, but not all components.
  21984. // Currently `restoreData` of all of the series and component will be called.
  21985. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21986. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21987. // and some components like coordinate system, axes, dataZoom, visualMap only
  21988. // need their target series refresh.
  21989. // (1) If we are implementing this feature some day, we should consider these cases:
  21990. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21991. // on the settings of `dataZoom`), it should be re-performed if the component
  21992. // is modified by `setOption`.
  21993. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21994. // it should be re-performed when the result array of `getTargetSeries` changed.
  21995. // We use `dependencies` to cover these issues.
  21996. // (3) How to update target series when coordinate system related components modified.
  21997. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21998. // and this case all of the tasks will be set as dirty.
  21999. ecModel.restoreData(payload);
  22000. // Theoretically an overall task not only depends on each of its target series, but also
  22001. // depends on all of the series.
  22002. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22003. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22004. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22005. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22006. // probably cause state chaos (consider `dataZoomProcessor`).
  22007. this._stageTaskMap.each(function (taskRecord) {
  22008. var overallTask = taskRecord.overallTask;
  22009. overallTask && overallTask.dirty();
  22010. });
  22011. };
  22012. // If seriesModel provided, incremental threshold is check by series data.
  22013. proto.getPerformArgs = function (task, isBlock) {
  22014. // For overall task
  22015. if (!task.__pipeline) {
  22016. return;
  22017. }
  22018. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22019. var pCtx = pipeline.context;
  22020. var incremental = !isBlock
  22021. && pipeline.progressiveEnabled
  22022. && (!pCtx || pCtx.progressiveRender)
  22023. && task.__idxInPipeline > pipeline.blockIndex;
  22024. var step = incremental ? pipeline.step : null;
  22025. var modDataCount = pCtx && pCtx.modDataCount;
  22026. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22027. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22028. };
  22029. proto.getPipeline = function (pipelineId) {
  22030. return this._pipelineMap.get(pipelineId);
  22031. };
  22032. /**
  22033. * Current, progressive rendering starts from visual and layout.
  22034. * Always detect render mode in the same stage, avoiding that incorrect
  22035. * detection caused by data filtering.
  22036. * Caution:
  22037. * `updateStreamModes` use `seriesModel.getData()`.
  22038. */
  22039. proto.updateStreamModes = function (seriesModel, view) {
  22040. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22041. var data = seriesModel.getData();
  22042. var dataLen = data.count();
  22043. // `progressiveRender` means that can render progressively in each
  22044. // animation frame. Note that some types of series do not provide
  22045. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22046. // use the term `incremental` but not `progressive` to describe the
  22047. // case that `chart.appendData`.
  22048. var progressiveRender = pipeline.progressiveEnabled
  22049. && view.incrementalPrepareRender
  22050. && dataLen >= pipeline.threshold;
  22051. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22052. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22053. // see `test/candlestick-large3.html`
  22054. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22055. seriesModel.pipelineContext = pipeline.context = {
  22056. progressiveRender: progressiveRender,
  22057. modDataCount: modDataCount,
  22058. large: large
  22059. };
  22060. };
  22061. proto.restorePipelines = function (ecModel) {
  22062. var scheduler = this;
  22063. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22064. ecModel.eachSeries(function (seriesModel) {
  22065. var progressive = seriesModel.getProgressive();
  22066. var pipelineId = seriesModel.uid;
  22067. pipelineMap.set(pipelineId, {
  22068. id: pipelineId,
  22069. head: null,
  22070. tail: null,
  22071. threshold: seriesModel.getProgressiveThreshold(),
  22072. progressiveEnabled: progressive
  22073. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22074. blockIndex: -1,
  22075. step: Math.round(progressive || 700),
  22076. count: 0
  22077. });
  22078. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22079. });
  22080. };
  22081. proto.prepareStageTasks = function () {
  22082. var stageTaskMap = this._stageTaskMap;
  22083. var ecModel = this.ecInstance.getModel();
  22084. var api = this.api;
  22085. each$1(this._allHandlers, function (handler) {
  22086. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22087. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22088. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22089. }, this);
  22090. };
  22091. proto.prepareView = function (view, model, ecModel, api) {
  22092. var renderTask = view.renderTask;
  22093. var context = renderTask.context;
  22094. context.model = model;
  22095. context.ecModel = ecModel;
  22096. context.api = api;
  22097. renderTask.__block = !view.incrementalPrepareRender;
  22098. pipe(this, model, renderTask);
  22099. };
  22100. proto.performDataProcessorTasks = function (ecModel, payload) {
  22101. // If we do not use `block` here, it should be considered when to update modes.
  22102. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22103. };
  22104. // opt
  22105. // opt.visualType: 'visual' or 'layout'
  22106. // opt.setDirty
  22107. proto.performVisualTasks = function (ecModel, payload, opt) {
  22108. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22109. };
  22110. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22111. opt = opt || {};
  22112. var unfinished;
  22113. each$1(stageHandlers, function (stageHandler, idx) {
  22114. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22115. return;
  22116. }
  22117. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22118. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22119. var overallTask = stageHandlerRecord.overallTask;
  22120. if (overallTask) {
  22121. var overallNeedDirty;
  22122. var agentStubMap = overallTask.agentStubMap;
  22123. agentStubMap.each(function (stub) {
  22124. if (needSetDirty(opt, stub)) {
  22125. stub.dirty();
  22126. overallNeedDirty = true;
  22127. }
  22128. });
  22129. overallNeedDirty && overallTask.dirty();
  22130. updatePayload(overallTask, payload);
  22131. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22132. // Execute stubs firstly, which may set the overall task dirty,
  22133. // then execute the overall task. And stub will call seriesModel.setData,
  22134. // which ensures that in the overallTask seriesModel.getData() will not
  22135. // return incorrect data.
  22136. agentStubMap.each(function (stub) {
  22137. stub.perform(performArgs);
  22138. });
  22139. unfinished |= overallTask.perform(performArgs);
  22140. }
  22141. else if (seriesTaskMap) {
  22142. seriesTaskMap.each(function (task, pipelineId) {
  22143. if (needSetDirty(opt, task)) {
  22144. task.dirty();
  22145. }
  22146. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22147. performArgs.skip = !stageHandler.performRawSeries
  22148. && ecModel.isSeriesFiltered(task.context.model);
  22149. updatePayload(task, payload);
  22150. unfinished |= task.perform(performArgs);
  22151. });
  22152. }
  22153. });
  22154. function needSetDirty(opt, task) {
  22155. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22156. }
  22157. scheduler.unfinished |= unfinished;
  22158. }
  22159. proto.performSeriesTasks = function (ecModel) {
  22160. var unfinished;
  22161. ecModel.eachSeries(function (seriesModel) {
  22162. // Progress to the end for dataInit and dataRestore.
  22163. unfinished |= seriesModel.dataTask.perform();
  22164. });
  22165. this.unfinished |= unfinished;
  22166. };
  22167. proto.plan = function () {
  22168. // Travel pipelines, check block.
  22169. this._pipelineMap.each(function (pipeline) {
  22170. var task = pipeline.tail;
  22171. do {
  22172. if (task.__block) {
  22173. pipeline.blockIndex = task.__idxInPipeline;
  22174. break;
  22175. }
  22176. task = task.getUpstream();
  22177. }
  22178. while (task);
  22179. });
  22180. };
  22181. var updatePayload = proto.updatePayload = function (task, payload) {
  22182. payload !== 'remain' && (task.context.payload = payload);
  22183. };
  22184. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22185. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  22186. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  22187. var seriesType = stageHandler.seriesType;
  22188. var getTargetSeries = stageHandler.getTargetSeries;
  22189. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22190. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22191. // it works but it may cause other irrelevant charts blocked.
  22192. if (stageHandler.createOnAllSeries) {
  22193. ecModel.eachRawSeries(create);
  22194. }
  22195. else if (seriesType) {
  22196. ecModel.eachRawSeriesByType(seriesType, create);
  22197. }
  22198. else if (getTargetSeries) {
  22199. getTargetSeries(ecModel, api).each(create);
  22200. }
  22201. function create(seriesModel) {
  22202. var pipelineId = seriesModel.uid;
  22203. // Init tasks for each seriesModel only once.
  22204. // Reuse original task instance.
  22205. var task = seriesTaskMap.get(pipelineId)
  22206. || seriesTaskMap.set(pipelineId, createTask({
  22207. plan: seriesTaskPlan,
  22208. reset: seriesTaskReset,
  22209. count: seriesTaskCount
  22210. }));
  22211. task.context = {
  22212. model: seriesModel,
  22213. ecModel: ecModel,
  22214. api: api,
  22215. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22216. plan: stageHandler.plan,
  22217. reset: stageHandler.reset,
  22218. scheduler: scheduler
  22219. };
  22220. pipe(scheduler, seriesModel, task);
  22221. }
  22222. // Clear unused series tasks.
  22223. var pipelineMap = scheduler._pipelineMap;
  22224. seriesTaskMap.each(function (task, pipelineId) {
  22225. if (!pipelineMap.get(pipelineId)) {
  22226. task.dispose();
  22227. seriesTaskMap.removeKey(pipelineId);
  22228. }
  22229. });
  22230. }
  22231. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22232. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  22233. // For overall task, the function only be called on reset stage.
  22234. || createTask({reset: overallTaskReset});
  22235. overallTask.context = {
  22236. ecModel: ecModel,
  22237. api: api,
  22238. overallReset: stageHandler.overallReset,
  22239. scheduler: scheduler
  22240. };
  22241. // Reuse orignal stubs.
  22242. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  22243. var seriesType = stageHandler.seriesType;
  22244. var getTargetSeries = stageHandler.getTargetSeries;
  22245. var overallProgress = true;
  22246. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  22247. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22248. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22249. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22250. // we set the pipeline block.
  22251. if (seriesType) {
  22252. ecModel.eachRawSeriesByType(seriesType, createStub);
  22253. }
  22254. else if (getTargetSeries) {
  22255. getTargetSeries(ecModel, api).each(createStub);
  22256. }
  22257. // Otherwise, (usually it is legancy case), the overall task will only be
  22258. // executed when upstream dirty. Otherwise the progressive rendering of all
  22259. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22260. // dirty info from upsteam.
  22261. else {
  22262. overallProgress = false;
  22263. each$1(ecModel.getSeries(), createStub);
  22264. }
  22265. function createStub(seriesModel) {
  22266. var pipelineId = seriesModel.uid;
  22267. var stub = agentStubMap.get(pipelineId);
  22268. if (!stub) {
  22269. stub = agentStubMap.set(pipelineId, createTask(
  22270. {reset: stubReset, onDirty: stubOnDirty}
  22271. ));
  22272. // When the result of `getTargetSeries` changed, the overallTask
  22273. // should be set as dirty and re-performed.
  22274. overallTask.dirty();
  22275. }
  22276. stub.context = {
  22277. model: seriesModel,
  22278. overallProgress: overallProgress,
  22279. modifyOutputEnd: modifyOutputEnd
  22280. };
  22281. stub.agent = overallTask;
  22282. stub.__block = overallProgress;
  22283. pipe(scheduler, seriesModel, stub);
  22284. }
  22285. // Clear unused stubs.
  22286. var pipelineMap = scheduler._pipelineMap;
  22287. agentStubMap.each(function (stub, pipelineId) {
  22288. if (!pipelineMap.get(pipelineId)) {
  22289. stub.dispose();
  22290. // When the result of `getTargetSeries` changed, the overallTask
  22291. // should be set as dirty and re-performed.
  22292. overallTask.dirty();
  22293. agentStubMap.removeKey(pipelineId);
  22294. }
  22295. });
  22296. }
  22297. function overallTaskReset(context) {
  22298. context.overallReset(
  22299. context.ecModel, context.api, context.payload
  22300. );
  22301. }
  22302. function stubReset(context, upstreamContext) {
  22303. return context.overallProgress && stubProgress;
  22304. }
  22305. function stubProgress() {
  22306. this.agent.dirty();
  22307. this.getDownstream().dirty();
  22308. }
  22309. function stubOnDirty() {
  22310. this.agent && this.agent.dirty();
  22311. }
  22312. function seriesTaskPlan(context) {
  22313. return context.plan && context.plan(
  22314. context.model, context.ecModel, context.api, context.payload
  22315. );
  22316. }
  22317. function seriesTaskReset(context) {
  22318. if (context.useClearVisual) {
  22319. context.data.clearAllVisual();
  22320. }
  22321. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  22322. context.model, context.ecModel, context.api, context.payload
  22323. ));
  22324. return resetDefines.length > 1
  22325. ? map(resetDefines, function (v, idx) {
  22326. return makeSeriesTaskProgress(idx);
  22327. })
  22328. : singleSeriesTaskProgress;
  22329. }
  22330. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  22331. function makeSeriesTaskProgress(resetDefineIdx) {
  22332. return function (params, context) {
  22333. var data = context.data;
  22334. var resetDefine = context.resetDefines[resetDefineIdx];
  22335. if (resetDefine && resetDefine.dataEach) {
  22336. for (var i = params.start; i < params.end; i++) {
  22337. resetDefine.dataEach(data, i);
  22338. }
  22339. }
  22340. else if (resetDefine && resetDefine.progress) {
  22341. resetDefine.progress(params, data);
  22342. }
  22343. };
  22344. }
  22345. function seriesTaskCount(context) {
  22346. return context.data.count();
  22347. }
  22348. function pipe(scheduler, seriesModel, task) {
  22349. var pipelineId = seriesModel.uid;
  22350. var pipeline = scheduler._pipelineMap.get(pipelineId);
  22351. !pipeline.head && (pipeline.head = task);
  22352. pipeline.tail && pipeline.tail.pipe(task);
  22353. pipeline.tail = task;
  22354. task.__idxInPipeline = pipeline.count++;
  22355. task.__pipeline = pipeline;
  22356. }
  22357. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  22358. if (isFunction$1(stageHandler)) {
  22359. stageHandler = {
  22360. overallReset: stageHandler,
  22361. seriesType: detectSeriseType(stageHandler)
  22362. };
  22363. }
  22364. stageHandler.uid = getUID('stageHandler');
  22365. visualType && (stageHandler.visualType = visualType);
  22366. return stageHandler;
  22367. };
  22368. /**
  22369. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  22370. * To ensure that they can work normally, they should work in block mode, that is,
  22371. * they should not be started util the previous tasks finished. So they cause the
  22372. * progressive rendering disabled. We try to detect the series type, to narrow down
  22373. * the block range to only the series type they concern, but not all series.
  22374. */
  22375. function detectSeriseType(legacyFunc) {
  22376. seriesType = null;
  22377. try {
  22378. // Assume there is no async when calling `eachSeriesByType`.
  22379. legacyFunc(ecModelMock, apiMock);
  22380. }
  22381. catch (e) {
  22382. }
  22383. return seriesType;
  22384. }
  22385. var ecModelMock = {};
  22386. var apiMock = {};
  22387. var seriesType;
  22388. mockMethods(ecModelMock, GlobalModel);
  22389. mockMethods(apiMock, ExtensionAPI);
  22390. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  22391. seriesType = type;
  22392. };
  22393. ecModelMock.eachComponent = function (cond) {
  22394. if (cond.mainType === 'series' && cond.subType) {
  22395. seriesType = cond.subType;
  22396. }
  22397. };
  22398. function mockMethods(target, Clz) {
  22399. /* eslint-disable */
  22400. for (var name in Clz.prototype) {
  22401. // Do not use hasOwnProperty
  22402. target[name] = noop;
  22403. }
  22404. /* eslint-enable */
  22405. }
  22406. /*
  22407. * Licensed to the Apache Software Foundation (ASF) under one
  22408. * or more contributor license agreements. See the NOTICE file
  22409. * distributed with this work for additional information
  22410. * regarding copyright ownership. The ASF licenses this file
  22411. * to you under the Apache License, Version 2.0 (the
  22412. * "License"); you may not use this file except in compliance
  22413. * with the License. You may obtain a copy of the License at
  22414. *
  22415. * http://www.apache.org/licenses/LICENSE-2.0
  22416. *
  22417. * Unless required by applicable law or agreed to in writing,
  22418. * software distributed under the License is distributed on an
  22419. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22420. * KIND, either express or implied. See the License for the
  22421. * specific language governing permissions and limitations
  22422. * under the License.
  22423. */
  22424. var colorAll = [
  22425. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  22426. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  22427. ];
  22428. var lightTheme = {
  22429. color: colorAll,
  22430. colorLayer: [
  22431. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  22432. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  22433. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  22434. colorAll
  22435. ]
  22436. };
  22437. /*
  22438. * Licensed to the Apache Software Foundation (ASF) under one
  22439. * or more contributor license agreements. See the NOTICE file
  22440. * distributed with this work for additional information
  22441. * regarding copyright ownership. The ASF licenses this file
  22442. * to you under the Apache License, Version 2.0 (the
  22443. * "License"); you may not use this file except in compliance
  22444. * with the License. You may obtain a copy of the License at
  22445. *
  22446. * http://www.apache.org/licenses/LICENSE-2.0
  22447. *
  22448. * Unless required by applicable law or agreed to in writing,
  22449. * software distributed under the License is distributed on an
  22450. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22451. * KIND, either express or implied. See the License for the
  22452. * specific language governing permissions and limitations
  22453. * under the License.
  22454. */
  22455. var contrastColor = '#eee';
  22456. var axisCommon = function () {
  22457. return {
  22458. axisLine: {
  22459. lineStyle: {
  22460. color: contrastColor
  22461. }
  22462. },
  22463. axisTick: {
  22464. lineStyle: {
  22465. color: contrastColor
  22466. }
  22467. },
  22468. axisLabel: {
  22469. textStyle: {
  22470. color: contrastColor
  22471. }
  22472. },
  22473. splitLine: {
  22474. lineStyle: {
  22475. type: 'dashed',
  22476. color: '#aaa'
  22477. }
  22478. },
  22479. splitArea: {
  22480. areaStyle: {
  22481. color: contrastColor
  22482. }
  22483. }
  22484. };
  22485. };
  22486. var colorPalette = [
  22487. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  22488. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  22489. ];
  22490. var theme = {
  22491. color: colorPalette,
  22492. backgroundColor: '#333',
  22493. tooltip: {
  22494. axisPointer: {
  22495. lineStyle: {
  22496. color: contrastColor
  22497. },
  22498. crossStyle: {
  22499. color: contrastColor
  22500. }
  22501. }
  22502. },
  22503. legend: {
  22504. textStyle: {
  22505. color: contrastColor
  22506. }
  22507. },
  22508. textStyle: {
  22509. color: contrastColor
  22510. },
  22511. title: {
  22512. textStyle: {
  22513. color: contrastColor
  22514. }
  22515. },
  22516. toolbox: {
  22517. iconStyle: {
  22518. normal: {
  22519. borderColor: contrastColor
  22520. }
  22521. }
  22522. },
  22523. dataZoom: {
  22524. textStyle: {
  22525. color: contrastColor
  22526. }
  22527. },
  22528. visualMap: {
  22529. textStyle: {
  22530. color: contrastColor
  22531. }
  22532. },
  22533. timeline: {
  22534. lineStyle: {
  22535. color: contrastColor
  22536. },
  22537. itemStyle: {
  22538. normal: {
  22539. color: colorPalette[1]
  22540. }
  22541. },
  22542. label: {
  22543. normal: {
  22544. textStyle: {
  22545. color: contrastColor
  22546. }
  22547. }
  22548. },
  22549. controlStyle: {
  22550. normal: {
  22551. color: contrastColor,
  22552. borderColor: contrastColor
  22553. }
  22554. }
  22555. },
  22556. timeAxis: axisCommon(),
  22557. logAxis: axisCommon(),
  22558. valueAxis: axisCommon(),
  22559. categoryAxis: axisCommon(),
  22560. line: {
  22561. symbol: 'circle'
  22562. },
  22563. graph: {
  22564. color: colorPalette
  22565. },
  22566. gauge: {
  22567. title: {
  22568. textStyle: {
  22569. color: contrastColor
  22570. }
  22571. }
  22572. },
  22573. candlestick: {
  22574. itemStyle: {
  22575. normal: {
  22576. color: '#FD1050',
  22577. color0: '#0CF49B',
  22578. borderColor: '#FD1050',
  22579. borderColor0: '#0CF49B'
  22580. }
  22581. }
  22582. }
  22583. };
  22584. theme.categoryAxis.splitLine.show = false;
  22585. /*
  22586. * Licensed to the Apache Software Foundation (ASF) under one
  22587. * or more contributor license agreements. See the NOTICE file
  22588. * distributed with this work for additional information
  22589. * regarding copyright ownership. The ASF licenses this file
  22590. * to you under the Apache License, Version 2.0 (the
  22591. * "License"); you may not use this file except in compliance
  22592. * with the License. You may obtain a copy of the License at
  22593. *
  22594. * http://www.apache.org/licenses/LICENSE-2.0
  22595. *
  22596. * Unless required by applicable law or agreed to in writing,
  22597. * software distributed under the License is distributed on an
  22598. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22599. * KIND, either express or implied. See the License for the
  22600. * specific language governing permissions and limitations
  22601. * under the License.
  22602. */
  22603. /**
  22604. * This module is imported by echarts directly.
  22605. *
  22606. * Notice:
  22607. * Always keep this file exists for backward compatibility.
  22608. * Because before 4.1.0, dataset is an optional component,
  22609. * some users may import this module manually.
  22610. */
  22611. ComponentModel.extend({
  22612. type: 'dataset',
  22613. /**
  22614. * @protected
  22615. */
  22616. defaultOption: {
  22617. // 'row', 'column'
  22618. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  22619. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  22620. sourceHeader: null,
  22621. dimensions: null,
  22622. source: null
  22623. },
  22624. optionUpdated: function () {
  22625. detectSourceFormat(this);
  22626. }
  22627. });
  22628. Component$1.extend({
  22629. type: 'dataset'
  22630. });
  22631. /**
  22632. * 椭圆形状
  22633. * @module zrender/graphic/shape/Ellipse
  22634. */
  22635. var Ellipse = Path.extend({
  22636. type: 'ellipse',
  22637. shape: {
  22638. cx: 0, cy: 0,
  22639. rx: 0, ry: 0
  22640. },
  22641. buildPath: function (ctx, shape) {
  22642. var k = 0.5522848;
  22643. var x = shape.cx;
  22644. var y = shape.cy;
  22645. var a = shape.rx;
  22646. var b = shape.ry;
  22647. var ox = a * k; // 水平控制点偏移量
  22648. var oy = b * k; // 垂直控制点偏移量
  22649. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  22650. ctx.moveTo(x - a, y);
  22651. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  22652. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  22653. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  22654. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  22655. ctx.closePath();
  22656. }
  22657. });
  22658. // import RadialGradient from '../graphic/RadialGradient';
  22659. // import Pattern from '../graphic/Pattern';
  22660. // import * as vector from '../core/vector';
  22661. // Most of the values can be separated by comma and/or white space.
  22662. var DILIMITER_REG = /[\s,]+/;
  22663. /**
  22664. * For big svg string, this method might be time consuming.
  22665. *
  22666. * @param {string} svg xml string
  22667. * @return {Object} xml root.
  22668. */
  22669. function parseXML(svg) {
  22670. if (isString(svg)) {
  22671. var parser = new DOMParser();
  22672. svg = parser.parseFromString(svg, 'text/xml');
  22673. }
  22674. // Document node. If using $.get, doc node may be input.
  22675. if (svg.nodeType === 9) {
  22676. svg = svg.firstChild;
  22677. }
  22678. // nodeName of <!DOCTYPE svg> is also 'svg'.
  22679. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  22680. svg = svg.nextSibling;
  22681. }
  22682. return svg;
  22683. }
  22684. function SVGParser() {
  22685. this._defs = {};
  22686. this._root = null;
  22687. this._isDefine = false;
  22688. this._isText = false;
  22689. }
  22690. SVGParser.prototype.parse = function (xml, opt) {
  22691. opt = opt || {};
  22692. var svg = parseXML(xml);
  22693. if (!svg) {
  22694. throw new Error('Illegal svg');
  22695. }
  22696. var root = new Group();
  22697. this._root = root;
  22698. // parse view port
  22699. var viewBox = svg.getAttribute('viewBox') || '';
  22700. // If width/height not specified, means "100%" of `opt.width/height`.
  22701. // TODO: Other percent value not supported yet.
  22702. var width = parseFloat(svg.getAttribute('width') || opt.width);
  22703. var height = parseFloat(svg.getAttribute('height') || opt.height);
  22704. // If width/height not specified, set as null for output.
  22705. isNaN(width) && (width = null);
  22706. isNaN(height) && (height = null);
  22707. // Apply inline style on svg element.
  22708. parseAttributes(svg, root, null, true);
  22709. var child = svg.firstChild;
  22710. while (child) {
  22711. this._parseNode(child, root);
  22712. child = child.nextSibling;
  22713. }
  22714. var viewBoxRect;
  22715. var viewBoxTransform;
  22716. if (viewBox) {
  22717. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  22718. // Some invalid case like viewBox: 'none'.
  22719. if (viewBoxArr.length >= 4) {
  22720. viewBoxRect = {
  22721. x: parseFloat(viewBoxArr[0] || 0),
  22722. y: parseFloat(viewBoxArr[1] || 0),
  22723. width: parseFloat(viewBoxArr[2]),
  22724. height: parseFloat(viewBoxArr[3])
  22725. };
  22726. }
  22727. }
  22728. if (viewBoxRect && width != null && height != null) {
  22729. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  22730. if (!opt.ignoreViewBox) {
  22731. // If set transform on the output group, it probably bring trouble when
  22732. // some users only intend to show the clipped content inside the viewBox,
  22733. // but not intend to transform the output group. So we keep the output
  22734. // group no transform. If the user intend to use the viewBox as a
  22735. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  22736. // manually according to the viewBox info in the output of this method.
  22737. var elRoot = root;
  22738. root = new Group();
  22739. root.add(elRoot);
  22740. elRoot.scale = viewBoxTransform.scale.slice();
  22741. elRoot.position = viewBoxTransform.position.slice();
  22742. }
  22743. }
  22744. // Some shapes might be overflow the viewport, which should be
  22745. // clipped despite whether the viewBox is used, as the SVG does.
  22746. if (!opt.ignoreRootClip && width != null && height != null) {
  22747. root.setClipPath(new Rect({
  22748. shape: {x: 0, y: 0, width: width, height: height}
  22749. }));
  22750. }
  22751. // Set width/height on group just for output the viewport size.
  22752. return {
  22753. root: root,
  22754. width: width,
  22755. height: height,
  22756. viewBoxRect: viewBoxRect,
  22757. viewBoxTransform: viewBoxTransform
  22758. };
  22759. };
  22760. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  22761. var nodeName = xmlNode.nodeName.toLowerCase();
  22762. // TODO
  22763. // support <style>...</style> in svg, where nodeName is 'style',
  22764. // CSS classes is defined globally wherever the style tags are declared.
  22765. if (nodeName === 'defs') {
  22766. // define flag
  22767. this._isDefine = true;
  22768. }
  22769. else if (nodeName === 'text') {
  22770. this._isText = true;
  22771. }
  22772. var el;
  22773. if (this._isDefine) {
  22774. var parser = defineParsers[nodeName];
  22775. if (parser) {
  22776. var def = parser.call(this, xmlNode);
  22777. var id = xmlNode.getAttribute('id');
  22778. if (id) {
  22779. this._defs[id] = def;
  22780. }
  22781. }
  22782. }
  22783. else {
  22784. var parser = nodeParsers[nodeName];
  22785. if (parser) {
  22786. el = parser.call(this, xmlNode, parentGroup);
  22787. parentGroup.add(el);
  22788. }
  22789. }
  22790. var child = xmlNode.firstChild;
  22791. while (child) {
  22792. if (child.nodeType === 1) {
  22793. this._parseNode(child, el);
  22794. }
  22795. // Is text
  22796. if (child.nodeType === 3 && this._isText) {
  22797. this._parseText(child, el);
  22798. }
  22799. child = child.nextSibling;
  22800. }
  22801. // Quit define
  22802. if (nodeName === 'defs') {
  22803. this._isDefine = false;
  22804. }
  22805. else if (nodeName === 'text') {
  22806. this._isText = false;
  22807. }
  22808. };
  22809. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  22810. if (xmlNode.nodeType === 1) {
  22811. var dx = xmlNode.getAttribute('dx') || 0;
  22812. var dy = xmlNode.getAttribute('dy') || 0;
  22813. this._textX += parseFloat(dx);
  22814. this._textY += parseFloat(dy);
  22815. }
  22816. var text = new Text({
  22817. style: {
  22818. text: xmlNode.textContent,
  22819. transformText: true
  22820. },
  22821. position: [this._textX || 0, this._textY || 0]
  22822. });
  22823. inheritStyle(parentGroup, text);
  22824. parseAttributes(xmlNode, text, this._defs);
  22825. var fontSize = text.style.fontSize;
  22826. if (fontSize && fontSize < 9) {
  22827. // PENDING
  22828. text.style.fontSize = 9;
  22829. text.scale = text.scale || [1, 1];
  22830. text.scale[0] *= fontSize / 9;
  22831. text.scale[1] *= fontSize / 9;
  22832. }
  22833. var rect = text.getBoundingRect();
  22834. this._textX += rect.width;
  22835. parentGroup.add(text);
  22836. return text;
  22837. };
  22838. var nodeParsers = {
  22839. 'g': function (xmlNode, parentGroup) {
  22840. var g = new Group();
  22841. inheritStyle(parentGroup, g);
  22842. parseAttributes(xmlNode, g, this._defs);
  22843. return g;
  22844. },
  22845. 'rect': function (xmlNode, parentGroup) {
  22846. var rect = new Rect();
  22847. inheritStyle(parentGroup, rect);
  22848. parseAttributes(xmlNode, rect, this._defs);
  22849. rect.setShape({
  22850. x: parseFloat(xmlNode.getAttribute('x') || 0),
  22851. y: parseFloat(xmlNode.getAttribute('y') || 0),
  22852. width: parseFloat(xmlNode.getAttribute('width') || 0),
  22853. height: parseFloat(xmlNode.getAttribute('height') || 0)
  22854. });
  22855. // console.log(xmlNode.getAttribute('transform'));
  22856. // console.log(rect.transform);
  22857. return rect;
  22858. },
  22859. 'circle': function (xmlNode, parentGroup) {
  22860. var circle = new Circle();
  22861. inheritStyle(parentGroup, circle);
  22862. parseAttributes(xmlNode, circle, this._defs);
  22863. circle.setShape({
  22864. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22865. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22866. r: parseFloat(xmlNode.getAttribute('r') || 0)
  22867. });
  22868. return circle;
  22869. },
  22870. 'line': function (xmlNode, parentGroup) {
  22871. var line = new Line();
  22872. inheritStyle(parentGroup, line);
  22873. parseAttributes(xmlNode, line, this._defs);
  22874. line.setShape({
  22875. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  22876. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  22877. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  22878. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  22879. });
  22880. return line;
  22881. },
  22882. 'ellipse': function (xmlNode, parentGroup) {
  22883. var ellipse = new Ellipse();
  22884. inheritStyle(parentGroup, ellipse);
  22885. parseAttributes(xmlNode, ellipse, this._defs);
  22886. ellipse.setShape({
  22887. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22888. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22889. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  22890. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  22891. });
  22892. return ellipse;
  22893. },
  22894. 'polygon': function (xmlNode, parentGroup) {
  22895. var points = xmlNode.getAttribute('points');
  22896. if (points) {
  22897. points = parsePoints(points);
  22898. }
  22899. var polygon = new Polygon({
  22900. shape: {
  22901. points: points || []
  22902. }
  22903. });
  22904. inheritStyle(parentGroup, polygon);
  22905. parseAttributes(xmlNode, polygon, this._defs);
  22906. return polygon;
  22907. },
  22908. 'polyline': function (xmlNode, parentGroup) {
  22909. var path = new Path();
  22910. inheritStyle(parentGroup, path);
  22911. parseAttributes(xmlNode, path, this._defs);
  22912. var points = xmlNode.getAttribute('points');
  22913. if (points) {
  22914. points = parsePoints(points);
  22915. }
  22916. var polyline = new Polyline({
  22917. shape: {
  22918. points: points || []
  22919. }
  22920. });
  22921. return polyline;
  22922. },
  22923. 'image': function (xmlNode, parentGroup) {
  22924. var img = new ZImage();
  22925. inheritStyle(parentGroup, img);
  22926. parseAttributes(xmlNode, img, this._defs);
  22927. img.setStyle({
  22928. image: xmlNode.getAttribute('xlink:href'),
  22929. x: xmlNode.getAttribute('x'),
  22930. y: xmlNode.getAttribute('y'),
  22931. width: xmlNode.getAttribute('width'),
  22932. height: xmlNode.getAttribute('height')
  22933. });
  22934. return img;
  22935. },
  22936. 'text': function (xmlNode, parentGroup) {
  22937. var x = xmlNode.getAttribute('x') || 0;
  22938. var y = xmlNode.getAttribute('y') || 0;
  22939. var dx = xmlNode.getAttribute('dx') || 0;
  22940. var dy = xmlNode.getAttribute('dy') || 0;
  22941. this._textX = parseFloat(x) + parseFloat(dx);
  22942. this._textY = parseFloat(y) + parseFloat(dy);
  22943. var g = new Group();
  22944. inheritStyle(parentGroup, g);
  22945. parseAttributes(xmlNode, g, this._defs);
  22946. return g;
  22947. },
  22948. 'tspan': function (xmlNode, parentGroup) {
  22949. var x = xmlNode.getAttribute('x');
  22950. var y = xmlNode.getAttribute('y');
  22951. if (x != null) {
  22952. // new offset x
  22953. this._textX = parseFloat(x);
  22954. }
  22955. if (y != null) {
  22956. // new offset y
  22957. this._textY = parseFloat(y);
  22958. }
  22959. var dx = xmlNode.getAttribute('dx') || 0;
  22960. var dy = xmlNode.getAttribute('dy') || 0;
  22961. var g = new Group();
  22962. inheritStyle(parentGroup, g);
  22963. parseAttributes(xmlNode, g, this._defs);
  22964. this._textX += dx;
  22965. this._textY += dy;
  22966. return g;
  22967. },
  22968. 'path': function (xmlNode, parentGroup) {
  22969. // TODO svg fill rule
  22970. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  22971. // path.style.globalCompositeOperation = 'xor';
  22972. var d = xmlNode.getAttribute('d') || '';
  22973. // Performance sensitive.
  22974. var path = createFromString(d);
  22975. inheritStyle(parentGroup, path);
  22976. parseAttributes(xmlNode, path, this._defs);
  22977. return path;
  22978. }
  22979. };
  22980. var defineParsers = {
  22981. 'lineargradient': function (xmlNode) {
  22982. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  22983. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  22984. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  22985. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  22986. var gradient = new LinearGradient(x1, y1, x2, y2);
  22987. _parseGradientColorStops(xmlNode, gradient);
  22988. return gradient;
  22989. },
  22990. 'radialgradient': function (xmlNode) {
  22991. }
  22992. };
  22993. function _parseGradientColorStops(xmlNode, gradient) {
  22994. var stop = xmlNode.firstChild;
  22995. while (stop) {
  22996. if (stop.nodeType === 1) {
  22997. var offset = stop.getAttribute('offset');
  22998. if (offset.indexOf('%') > 0) { // percentage
  22999. offset = parseInt(offset, 10) / 100;
  23000. }
  23001. else if (offset) { // number from 0 to 1
  23002. offset = parseFloat(offset);
  23003. }
  23004. else {
  23005. offset = 0;
  23006. }
  23007. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23008. gradient.addColorStop(offset, stopColor);
  23009. }
  23010. stop = stop.nextSibling;
  23011. }
  23012. }
  23013. function inheritStyle(parent, child) {
  23014. if (parent && parent.__inheritedStyle) {
  23015. if (!child.__inheritedStyle) {
  23016. child.__inheritedStyle = {};
  23017. }
  23018. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23019. }
  23020. }
  23021. function parsePoints(pointsString) {
  23022. var list = trim(pointsString).split(DILIMITER_REG);
  23023. var points = [];
  23024. for (var i = 0; i < list.length; i += 2) {
  23025. var x = parseFloat(list[i]);
  23026. var y = parseFloat(list[i + 1]);
  23027. points.push([x, y]);
  23028. }
  23029. return points;
  23030. }
  23031. var attributesMap = {
  23032. 'fill': 'fill',
  23033. 'stroke': 'stroke',
  23034. 'stroke-width': 'lineWidth',
  23035. 'opacity': 'opacity',
  23036. 'fill-opacity': 'fillOpacity',
  23037. 'stroke-opacity': 'strokeOpacity',
  23038. 'stroke-dasharray': 'lineDash',
  23039. 'stroke-dashoffset': 'lineDashOffset',
  23040. 'stroke-linecap': 'lineCap',
  23041. 'stroke-linejoin': 'lineJoin',
  23042. 'stroke-miterlimit': 'miterLimit',
  23043. 'font-family': 'fontFamily',
  23044. 'font-size': 'fontSize',
  23045. 'font-style': 'fontStyle',
  23046. 'font-weight': 'fontWeight',
  23047. 'text-align': 'textAlign',
  23048. 'alignment-baseline': 'textBaseline'
  23049. };
  23050. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23051. var zrStyle = el.__inheritedStyle || {};
  23052. var isTextEl = el.type === 'text';
  23053. // TODO Shadow
  23054. if (xmlNode.nodeType === 1) {
  23055. parseTransformAttribute(xmlNode, el);
  23056. extend(zrStyle, parseStyleAttribute(xmlNode));
  23057. if (!onlyInlineStyle) {
  23058. for (var svgAttrName in attributesMap) {
  23059. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23060. var attrValue = xmlNode.getAttribute(svgAttrName);
  23061. if (attrValue != null) {
  23062. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23063. }
  23064. }
  23065. }
  23066. }
  23067. }
  23068. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23069. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23070. el.style = el.style || new Style();
  23071. var elStyle = el.style;
  23072. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23073. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23074. each$1([
  23075. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23076. ], function (propName) {
  23077. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23078. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23079. });
  23080. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23081. zrStyle.textBaseline = 'alphabetic';
  23082. }
  23083. if (zrStyle.textBaseline === 'alphabetic') {
  23084. zrStyle.textBaseline = 'bottom';
  23085. }
  23086. if (zrStyle.textAlign === 'start') {
  23087. zrStyle.textAlign = 'left';
  23088. }
  23089. if (zrStyle.textAlign === 'end') {
  23090. zrStyle.textAlign = 'right';
  23091. }
  23092. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23093. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23094. ], function (propName) {
  23095. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23096. });
  23097. if (zrStyle.lineDash) {
  23098. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23099. }
  23100. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23101. // enable stroke
  23102. el[elStrokeProp] = true;
  23103. }
  23104. el.__inheritedStyle = zrStyle;
  23105. }
  23106. var urlRegex = /url\(\s*#(.*?)\)/;
  23107. function getPaint(str, defs) {
  23108. // if (str === 'none') {
  23109. // return;
  23110. // }
  23111. var urlMatch = defs && str && str.match(urlRegex);
  23112. if (urlMatch) {
  23113. var url = trim(urlMatch[1]);
  23114. var def = defs[url];
  23115. return def;
  23116. }
  23117. return str;
  23118. }
  23119. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23120. function parseTransformAttribute(xmlNode, node) {
  23121. var transform = xmlNode.getAttribute('transform');
  23122. if (transform) {
  23123. transform = transform.replace(/,/g, ' ');
  23124. var m = null;
  23125. var transformOps = [];
  23126. transform.replace(transformRegex, function (str, type, value) {
  23127. transformOps.push(type, value);
  23128. });
  23129. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23130. var value = transformOps[i];
  23131. var type = transformOps[i - 1];
  23132. m = m || create$1();
  23133. switch (type) {
  23134. case 'translate':
  23135. value = trim(value).split(DILIMITER_REG);
  23136. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23137. break;
  23138. case 'scale':
  23139. value = trim(value).split(DILIMITER_REG);
  23140. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23141. break;
  23142. case 'rotate':
  23143. value = trim(value).split(DILIMITER_REG);
  23144. rotate(m, m, parseFloat(value[0]));
  23145. break;
  23146. case 'skew':
  23147. value = trim(value).split(DILIMITER_REG);
  23148. console.warn('Skew transform is not supported yet');
  23149. break;
  23150. case 'matrix':
  23151. var value = trim(value).split(DILIMITER_REG);
  23152. m[0] = parseFloat(value[0]);
  23153. m[1] = parseFloat(value[1]);
  23154. m[2] = parseFloat(value[2]);
  23155. m[3] = parseFloat(value[3]);
  23156. m[4] = parseFloat(value[4]);
  23157. m[5] = parseFloat(value[5]);
  23158. break;
  23159. }
  23160. }
  23161. node.setLocalTransform(m);
  23162. }
  23163. }
  23164. // Value may contain space.
  23165. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23166. function parseStyleAttribute(xmlNode) {
  23167. var style = xmlNode.getAttribute('style');
  23168. var result = {};
  23169. if (!style) {
  23170. return result;
  23171. }
  23172. var styleList = {};
  23173. styleRegex.lastIndex = 0;
  23174. var styleRegResult;
  23175. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23176. styleList[styleRegResult[1]] = styleRegResult[2];
  23177. }
  23178. for (var svgAttrName in attributesMap) {
  23179. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  23180. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  23181. }
  23182. }
  23183. return result;
  23184. }
  23185. /**
  23186. * @param {Array.<number>} viewBoxRect
  23187. * @param {number} width
  23188. * @param {number} height
  23189. * @return {Object} {scale, position}
  23190. */
  23191. function makeViewBoxTransform(viewBoxRect, width, height) {
  23192. var scaleX = width / viewBoxRect.width;
  23193. var scaleY = height / viewBoxRect.height;
  23194. var scale = Math.min(scaleX, scaleY);
  23195. // preserveAspectRatio 'xMidYMid'
  23196. var viewBoxScale = [scale, scale];
  23197. var viewBoxPosition = [
  23198. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  23199. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  23200. ];
  23201. return {
  23202. scale: viewBoxScale,
  23203. position: viewBoxPosition
  23204. };
  23205. }
  23206. /**
  23207. * @param {string|XMLElement} xml
  23208. * @param {Object} [opt]
  23209. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  23210. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  23211. * @param {boolean} [opt.ignoreViewBox]
  23212. * @param {boolean} [opt.ignoreRootClip]
  23213. * @return {Object} result:
  23214. * {
  23215. * root: Group, The root of the the result tree of zrender shapes,
  23216. * width: number, the viewport width of the SVG,
  23217. * height: number, the viewport height of the SVG,
  23218. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  23219. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  23220. * }
  23221. */
  23222. /*
  23223. * Licensed to the Apache Software Foundation (ASF) under one
  23224. * or more contributor license agreements. See the NOTICE file
  23225. * distributed with this work for additional information
  23226. * regarding copyright ownership. The ASF licenses this file
  23227. * to you under the Apache License, Version 2.0 (the
  23228. * "License"); you may not use this file except in compliance
  23229. * with the License. You may obtain a copy of the License at
  23230. *
  23231. * http://www.apache.org/licenses/LICENSE-2.0
  23232. *
  23233. * Unless required by applicable law or agreed to in writing,
  23234. * software distributed under the License is distributed on an
  23235. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23236. * KIND, either express or implied. See the License for the
  23237. * specific language governing permissions and limitations
  23238. * under the License.
  23239. */
  23240. var storage = createHashMap();
  23241. // For minimize the code size of common echarts package,
  23242. // do not put too much logic in this module.
  23243. var mapDataStorage = {
  23244. // The format of record: see `echarts.registerMap`.
  23245. // Compatible with previous `echarts.registerMap`.
  23246. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  23247. var records;
  23248. if (isArray(rawGeoJson)) {
  23249. records = rawGeoJson;
  23250. }
  23251. else if (rawGeoJson.svg) {
  23252. records = [{
  23253. type: 'svg',
  23254. source: rawGeoJson.svg,
  23255. specialAreas: rawGeoJson.specialAreas
  23256. }];
  23257. }
  23258. else {
  23259. // Backward compatibility.
  23260. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  23261. rawSpecialAreas = rawGeoJson.specialAreas;
  23262. rawGeoJson = rawGeoJson.geoJson;
  23263. }
  23264. records = [{
  23265. type: 'geoJSON',
  23266. source: rawGeoJson,
  23267. specialAreas: rawSpecialAreas
  23268. }];
  23269. }
  23270. each$1(records, function (record) {
  23271. var type = record.type;
  23272. type === 'geoJson' && (type = record.type = 'geoJSON');
  23273. var parse = parsers[type];
  23274. if (__DEV__) {
  23275. assert$1(parse, 'Illegal map type: ' + type);
  23276. }
  23277. parse(record);
  23278. });
  23279. return storage.set(mapName, records);
  23280. },
  23281. retrieveMap: function (mapName) {
  23282. return storage.get(mapName);
  23283. }
  23284. };
  23285. var parsers = {
  23286. geoJSON: function (record) {
  23287. var source = record.source;
  23288. record.geoJSON = !isString(source)
  23289. ? source
  23290. : (typeof JSON !== 'undefined' && JSON.parse)
  23291. ? JSON.parse(source)
  23292. : (new Function('return (' + source + ');'))();
  23293. },
  23294. // Only perform parse to XML object here, which might be time
  23295. // consiming for large SVG.
  23296. // Although convert XML to zrender element is also time consiming,
  23297. // if we do it here, the clone of zrender elements has to be
  23298. // required. So we do it once for each geo instance, util real
  23299. // performance issues call for optimizing it.
  23300. svg: function (record) {
  23301. record.svgXML = parseXML(record.source);
  23302. }
  23303. };
  23304. /*
  23305. * Licensed to the Apache Software Foundation (ASF) under one
  23306. * or more contributor license agreements. See the NOTICE file
  23307. * distributed with this work for additional information
  23308. * regarding copyright ownership. The ASF licenses this file
  23309. * to you under the Apache License, Version 2.0 (the
  23310. * "License"); you may not use this file except in compliance
  23311. * with the License. You may obtain a copy of the License at
  23312. *
  23313. * http://www.apache.org/licenses/LICENSE-2.0
  23314. *
  23315. * Unless required by applicable law or agreed to in writing,
  23316. * software distributed under the License is distributed on an
  23317. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23318. * KIND, either express or implied. See the License for the
  23319. * specific language governing permissions and limitations
  23320. * under the License.
  23321. */
  23322. var assert = assert$1;
  23323. var each = each$1;
  23324. var isFunction = isFunction$1;
  23325. var isObject = isObject$1;
  23326. var parseClassType = ComponentModel.parseClassType;
  23327. var version = '4.2.1';
  23328. var dependencies = {
  23329. zrender: '4.0.6'
  23330. };
  23331. var TEST_FRAME_REMAIN_TIME = 1;
  23332. var PRIORITY_PROCESSOR_FILTER = 1000;
  23333. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  23334. var PRIORITY_VISUAL_LAYOUT = 1000;
  23335. var PRIORITY_VISUAL_GLOBAL = 2000;
  23336. var PRIORITY_VISUAL_CHART = 3000;
  23337. var PRIORITY_VISUAL_COMPONENT = 4000;
  23338. // FIXME
  23339. // necessary?
  23340. var PRIORITY_VISUAL_BRUSH = 5000;
  23341. var PRIORITY = {
  23342. PROCESSOR: {
  23343. FILTER: PRIORITY_PROCESSOR_FILTER,
  23344. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  23345. },
  23346. VISUAL: {
  23347. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  23348. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  23349. CHART: PRIORITY_VISUAL_CHART,
  23350. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  23351. BRUSH: PRIORITY_VISUAL_BRUSH
  23352. }
  23353. };
  23354. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  23355. // where they must not be invoked nestedly, except the only case: invoke
  23356. // dispatchAction with updateMethod "none" in main process.
  23357. // This flag is used to carry out this rule.
  23358. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  23359. var IN_MAIN_PROCESS = '__flagInMainProcess';
  23360. var OPTION_UPDATED = '__optionUpdated';
  23361. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  23362. function createRegisterEventWithLowercaseName(method) {
  23363. return function (eventName, handler, context) {
  23364. // Event name is all lowercase
  23365. eventName = eventName && eventName.toLowerCase();
  23366. Eventful.prototype[method].call(this, eventName, handler, context);
  23367. };
  23368. }
  23369. /**
  23370. * @module echarts~MessageCenter
  23371. */
  23372. function MessageCenter() {
  23373. Eventful.call(this);
  23374. }
  23375. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  23376. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  23377. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  23378. mixin(MessageCenter, Eventful);
  23379. /**
  23380. * @module echarts~ECharts
  23381. */
  23382. function ECharts(dom, theme$$1, opts) {
  23383. opts = opts || {};
  23384. // Get theme by name
  23385. if (typeof theme$$1 === 'string') {
  23386. theme$$1 = themeStorage[theme$$1];
  23387. }
  23388. /**
  23389. * @type {string}
  23390. */
  23391. this.id;
  23392. /**
  23393. * Group id
  23394. * @type {string}
  23395. */
  23396. this.group;
  23397. /**
  23398. * @type {HTMLElement}
  23399. * @private
  23400. */
  23401. this._dom = dom;
  23402. var defaultRenderer = 'canvas';
  23403. if (__DEV__) {
  23404. defaultRenderer = (
  23405. typeof window === 'undefined' ? global : window
  23406. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  23407. }
  23408. /**
  23409. * @type {module:zrender/ZRender}
  23410. * @private
  23411. */
  23412. var zr = this._zr = init$1(dom, {
  23413. renderer: opts.renderer || defaultRenderer,
  23414. devicePixelRatio: opts.devicePixelRatio,
  23415. width: opts.width,
  23416. height: opts.height
  23417. });
  23418. /**
  23419. * Expect 60 pfs.
  23420. * @type {Function}
  23421. * @private
  23422. */
  23423. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  23424. var theme$$1 = clone(theme$$1);
  23425. theme$$1 && backwardCompat(theme$$1, true);
  23426. /**
  23427. * @type {Object}
  23428. * @private
  23429. */
  23430. this._theme = theme$$1;
  23431. /**
  23432. * @type {Array.<module:echarts/view/Chart>}
  23433. * @private
  23434. */
  23435. this._chartsViews = [];
  23436. /**
  23437. * @type {Object.<string, module:echarts/view/Chart>}
  23438. * @private
  23439. */
  23440. this._chartsMap = {};
  23441. /**
  23442. * @type {Array.<module:echarts/view/Component>}
  23443. * @private
  23444. */
  23445. this._componentsViews = [];
  23446. /**
  23447. * @type {Object.<string, module:echarts/view/Component>}
  23448. * @private
  23449. */
  23450. this._componentsMap = {};
  23451. /**
  23452. * @type {module:echarts/CoordinateSystem}
  23453. * @private
  23454. */
  23455. this._coordSysMgr = new CoordinateSystemManager();
  23456. /**
  23457. * @type {module:echarts/ExtensionAPI}
  23458. * @private
  23459. */
  23460. var api = this._api = createExtensionAPI(this);
  23461. // Sort on demand
  23462. function prioritySortFunc(a, b) {
  23463. return a.__prio - b.__prio;
  23464. }
  23465. sort(visualFuncs, prioritySortFunc);
  23466. sort(dataProcessorFuncs, prioritySortFunc);
  23467. /**
  23468. * @type {module:echarts/stream/Scheduler}
  23469. */
  23470. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  23471. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  23472. /**
  23473. * @type {module:echarts~MessageCenter}
  23474. * @private
  23475. */
  23476. this._messageCenter = new MessageCenter();
  23477. // Init mouse events
  23478. this._initEvents();
  23479. // In case some people write `window.onresize = chart.resize`
  23480. this.resize = bind(this.resize, this);
  23481. // Can't dispatch action during rendering procedure
  23482. this._pendingActions = [];
  23483. zr.animation.on('frame', this._onframe, this);
  23484. bindRenderedEvent(zr, this);
  23485. // ECharts instance can be used as value.
  23486. setAsPrimitive(this);
  23487. }
  23488. var echartsProto = ECharts.prototype;
  23489. echartsProto._onframe = function () {
  23490. if (this._disposed) {
  23491. return;
  23492. }
  23493. var scheduler = this._scheduler;
  23494. // Lazy update
  23495. if (this[OPTION_UPDATED]) {
  23496. var silent = this[OPTION_UPDATED].silent;
  23497. this[IN_MAIN_PROCESS] = true;
  23498. prepare(this);
  23499. updateMethods.update.call(this);
  23500. this[IN_MAIN_PROCESS] = false;
  23501. this[OPTION_UPDATED] = false;
  23502. flushPendingActions.call(this, silent);
  23503. triggerUpdatedEvent.call(this, silent);
  23504. }
  23505. // Avoid do both lazy update and progress in one frame.
  23506. else if (scheduler.unfinished) {
  23507. // Stream progress.
  23508. var remainTime = TEST_FRAME_REMAIN_TIME;
  23509. var ecModel = this._model;
  23510. var api = this._api;
  23511. scheduler.unfinished = false;
  23512. do {
  23513. var startTime = +new Date();
  23514. scheduler.performSeriesTasks(ecModel);
  23515. // Currently dataProcessorFuncs do not check threshold.
  23516. scheduler.performDataProcessorTasks(ecModel);
  23517. updateStreamModes(this, ecModel);
  23518. // Do not update coordinate system here. Because that coord system update in
  23519. // each frame is not a good user experience. So we follow the rule that
  23520. // the extent of the coordinate system is determin in the first frame (the
  23521. // frame is executed immedietely after task reset.
  23522. // this._coordSysMgr.update(ecModel, api);
  23523. // console.log('--- ec frame visual ---', remainTime);
  23524. scheduler.performVisualTasks(ecModel);
  23525. renderSeries(this, this._model, api, 'remain');
  23526. remainTime -= (+new Date() - startTime);
  23527. }
  23528. while (remainTime > 0 && scheduler.unfinished);
  23529. // Call flush explicitly for trigger finished event.
  23530. if (!scheduler.unfinished) {
  23531. this._zr.flush();
  23532. }
  23533. // Else, zr flushing be ensue within the same frame,
  23534. // because zr flushing is after onframe event.
  23535. }
  23536. };
  23537. /**
  23538. * @return {HTMLElement}
  23539. */
  23540. echartsProto.getDom = function () {
  23541. return this._dom;
  23542. };
  23543. /**
  23544. * @return {module:zrender~ZRender}
  23545. */
  23546. echartsProto.getZr = function () {
  23547. return this._zr;
  23548. };
  23549. /**
  23550. * Usage:
  23551. * chart.setOption(option, notMerge, lazyUpdate);
  23552. * chart.setOption(option, {
  23553. * notMerge: ...,
  23554. * lazyUpdate: ...,
  23555. * silent: ...
  23556. * });
  23557. *
  23558. * @param {Object} option
  23559. * @param {Object|boolean} [opts] opts or notMerge.
  23560. * @param {boolean} [opts.notMerge=false]
  23561. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  23562. */
  23563. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  23564. if (__DEV__) {
  23565. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  23566. }
  23567. var silent;
  23568. if (isObject(notMerge)) {
  23569. lazyUpdate = notMerge.lazyUpdate;
  23570. silent = notMerge.silent;
  23571. notMerge = notMerge.notMerge;
  23572. }
  23573. this[IN_MAIN_PROCESS] = true;
  23574. if (!this._model || notMerge) {
  23575. var optionManager = new OptionManager(this._api);
  23576. var theme$$1 = this._theme;
  23577. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  23578. ecModel.scheduler = this._scheduler;
  23579. ecModel.init(null, null, theme$$1, optionManager);
  23580. }
  23581. this._model.setOption(option, optionPreprocessorFuncs);
  23582. if (lazyUpdate) {
  23583. this[OPTION_UPDATED] = {silent: silent};
  23584. this[IN_MAIN_PROCESS] = false;
  23585. }
  23586. else {
  23587. prepare(this);
  23588. updateMethods.update.call(this);
  23589. // Ensure zr refresh sychronously, and then pixel in canvas can be
  23590. // fetched after `setOption`.
  23591. this._zr.flush();
  23592. this[OPTION_UPDATED] = false;
  23593. this[IN_MAIN_PROCESS] = false;
  23594. flushPendingActions.call(this, silent);
  23595. triggerUpdatedEvent.call(this, silent);
  23596. }
  23597. };
  23598. /**
  23599. * @DEPRECATED
  23600. */
  23601. echartsProto.setTheme = function () {
  23602. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  23603. };
  23604. /**
  23605. * @return {module:echarts/model/Global}
  23606. */
  23607. echartsProto.getModel = function () {
  23608. return this._model;
  23609. };
  23610. /**
  23611. * @return {Object}
  23612. */
  23613. echartsProto.getOption = function () {
  23614. return this._model && this._model.getOption();
  23615. };
  23616. /**
  23617. * @return {number}
  23618. */
  23619. echartsProto.getWidth = function () {
  23620. return this._zr.getWidth();
  23621. };
  23622. /**
  23623. * @return {number}
  23624. */
  23625. echartsProto.getHeight = function () {
  23626. return this._zr.getHeight();
  23627. };
  23628. /**
  23629. * @return {number}
  23630. */
  23631. echartsProto.getDevicePixelRatio = function () {
  23632. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  23633. };
  23634. /**
  23635. * Get canvas which has all thing rendered
  23636. * @param {Object} opts
  23637. * @param {string} [opts.backgroundColor]
  23638. * @return {string}
  23639. */
  23640. echartsProto.getRenderedCanvas = function (opts) {
  23641. if (!env$1.canvasSupported) {
  23642. return;
  23643. }
  23644. opts = opts || {};
  23645. opts.pixelRatio = opts.pixelRatio || 1;
  23646. opts.backgroundColor = opts.backgroundColor
  23647. || this._model.get('backgroundColor');
  23648. var zr = this._zr;
  23649. // var list = zr.storage.getDisplayList();
  23650. // Stop animations
  23651. // Never works before in init animation, so remove it.
  23652. // zrUtil.each(list, function (el) {
  23653. // el.stopAnimation(true);
  23654. // });
  23655. return zr.painter.getRenderedCanvas(opts);
  23656. };
  23657. /**
  23658. * Get svg data url
  23659. * @return {string}
  23660. */
  23661. echartsProto.getSvgDataUrl = function () {
  23662. if (!env$1.svgSupported) {
  23663. return;
  23664. }
  23665. var zr = this._zr;
  23666. var list = zr.storage.getDisplayList();
  23667. // Stop animations
  23668. each$1(list, function (el) {
  23669. el.stopAnimation(true);
  23670. });
  23671. return zr.painter.pathToDataUrl();
  23672. };
  23673. /**
  23674. * @return {string}
  23675. * @param {Object} opts
  23676. * @param {string} [opts.type='png']
  23677. * @param {string} [opts.pixelRatio=1]
  23678. * @param {string} [opts.backgroundColor]
  23679. * @param {string} [opts.excludeComponents]
  23680. */
  23681. echartsProto.getDataURL = function (opts) {
  23682. opts = opts || {};
  23683. var excludeComponents = opts.excludeComponents;
  23684. var ecModel = this._model;
  23685. var excludesComponentViews = [];
  23686. var self = this;
  23687. each(excludeComponents, function (componentType) {
  23688. ecModel.eachComponent({
  23689. mainType: componentType
  23690. }, function (component) {
  23691. var view = self._componentsMap[component.__viewId];
  23692. if (!view.group.ignore) {
  23693. excludesComponentViews.push(view);
  23694. view.group.ignore = true;
  23695. }
  23696. });
  23697. });
  23698. var url = this._zr.painter.getType() === 'svg'
  23699. ? this.getSvgDataUrl()
  23700. : this.getRenderedCanvas(opts).toDataURL(
  23701. 'image/' + (opts && opts.type || 'png')
  23702. );
  23703. each(excludesComponentViews, function (view) {
  23704. view.group.ignore = false;
  23705. });
  23706. return url;
  23707. };
  23708. /**
  23709. * @return {string}
  23710. * @param {Object} opts
  23711. * @param {string} [opts.type='png']
  23712. * @param {string} [opts.pixelRatio=1]
  23713. * @param {string} [opts.backgroundColor]
  23714. */
  23715. echartsProto.getConnectedDataURL = function (opts) {
  23716. if (!env$1.canvasSupported) {
  23717. return;
  23718. }
  23719. var groupId = this.group;
  23720. var mathMin = Math.min;
  23721. var mathMax = Math.max;
  23722. var MAX_NUMBER = Infinity;
  23723. if (connectedGroups[groupId]) {
  23724. var left = MAX_NUMBER;
  23725. var top = MAX_NUMBER;
  23726. var right = -MAX_NUMBER;
  23727. var bottom = -MAX_NUMBER;
  23728. var canvasList = [];
  23729. var dpr = (opts && opts.pixelRatio) || 1;
  23730. each$1(instances, function (chart, id) {
  23731. if (chart.group === groupId) {
  23732. var canvas = chart.getRenderedCanvas(
  23733. clone(opts)
  23734. );
  23735. var boundingRect = chart.getDom().getBoundingClientRect();
  23736. left = mathMin(boundingRect.left, left);
  23737. top = mathMin(boundingRect.top, top);
  23738. right = mathMax(boundingRect.right, right);
  23739. bottom = mathMax(boundingRect.bottom, bottom);
  23740. canvasList.push({
  23741. dom: canvas,
  23742. left: boundingRect.left,
  23743. top: boundingRect.top
  23744. });
  23745. }
  23746. });
  23747. left *= dpr;
  23748. top *= dpr;
  23749. right *= dpr;
  23750. bottom *= dpr;
  23751. var width = right - left;
  23752. var height = bottom - top;
  23753. var targetCanvas = createCanvas();
  23754. targetCanvas.width = width;
  23755. targetCanvas.height = height;
  23756. var zr = init$1(targetCanvas);
  23757. each(canvasList, function (item) {
  23758. var img = new ZImage({
  23759. style: {
  23760. x: item.left * dpr - left,
  23761. y: item.top * dpr - top,
  23762. image: item.dom
  23763. }
  23764. });
  23765. zr.add(img);
  23766. });
  23767. zr.refreshImmediately();
  23768. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  23769. }
  23770. else {
  23771. return this.getDataURL(opts);
  23772. }
  23773. };
  23774. /**
  23775. * Convert from logical coordinate system to pixel coordinate system.
  23776. * See CoordinateSystem#convertToPixel.
  23777. * @param {string|Object} finder
  23778. * If string, e.g., 'geo', means {geoIndex: 0}.
  23779. * If Object, could contain some of these properties below:
  23780. * {
  23781. * seriesIndex / seriesId / seriesName,
  23782. * geoIndex / geoId, geoName,
  23783. * bmapIndex / bmapId / bmapName,
  23784. * xAxisIndex / xAxisId / xAxisName,
  23785. * yAxisIndex / yAxisId / yAxisName,
  23786. * gridIndex / gridId / gridName,
  23787. * ... (can be extended)
  23788. * }
  23789. * @param {Array|number} value
  23790. * @return {Array|number} result
  23791. */
  23792. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  23793. /**
  23794. * Convert from pixel coordinate system to logical coordinate system.
  23795. * See CoordinateSystem#convertFromPixel.
  23796. * @param {string|Object} finder
  23797. * If string, e.g., 'geo', means {geoIndex: 0}.
  23798. * If Object, could contain some of these properties below:
  23799. * {
  23800. * seriesIndex / seriesId / seriesName,
  23801. * geoIndex / geoId / geoName,
  23802. * bmapIndex / bmapId / bmapName,
  23803. * xAxisIndex / xAxisId / xAxisName,
  23804. * yAxisIndex / yAxisId / yAxisName
  23805. * gridIndex / gridId / gridName,
  23806. * ... (can be extended)
  23807. * }
  23808. * @param {Array|number} value
  23809. * @return {Array|number} result
  23810. */
  23811. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  23812. function doConvertPixel(methodName, finder, value) {
  23813. var ecModel = this._model;
  23814. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  23815. var result;
  23816. finder = parseFinder(ecModel, finder);
  23817. for (var i = 0; i < coordSysList.length; i++) {
  23818. var coordSys = coordSysList[i];
  23819. if (coordSys[methodName]
  23820. && (result = coordSys[methodName](ecModel, finder, value)) != null
  23821. ) {
  23822. return result;
  23823. }
  23824. }
  23825. if (__DEV__) {
  23826. console.warn(
  23827. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  23828. );
  23829. }
  23830. }
  23831. /**
  23832. * Is the specified coordinate systems or components contain the given pixel point.
  23833. * @param {string|Object} finder
  23834. * If string, e.g., 'geo', means {geoIndex: 0}.
  23835. * If Object, could contain some of these properties below:
  23836. * {
  23837. * seriesIndex / seriesId / seriesName,
  23838. * geoIndex / geoId / geoName,
  23839. * bmapIndex / bmapId / bmapName,
  23840. * xAxisIndex / xAxisId / xAxisName,
  23841. * yAxisIndex / yAxisId / yAxisName,
  23842. * gridIndex / gridId / gridName,
  23843. * ... (can be extended)
  23844. * }
  23845. * @param {Array|number} value
  23846. * @return {boolean} result
  23847. */
  23848. echartsProto.containPixel = function (finder, value) {
  23849. var ecModel = this._model;
  23850. var result;
  23851. finder = parseFinder(ecModel, finder);
  23852. each$1(finder, function (models, key) {
  23853. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  23854. var coordSys = model.coordinateSystem;
  23855. if (coordSys && coordSys.containPoint) {
  23856. result |= !!coordSys.containPoint(value);
  23857. }
  23858. else if (key === 'seriesModels') {
  23859. var view = this._chartsMap[model.__viewId];
  23860. if (view && view.containPoint) {
  23861. result |= view.containPoint(value, model);
  23862. }
  23863. else {
  23864. if (__DEV__) {
  23865. console.warn(key + ': ' + (view
  23866. ? 'The found component do not support containPoint.'
  23867. : 'No view mapping to the found component.'
  23868. ));
  23869. }
  23870. }
  23871. }
  23872. else {
  23873. if (__DEV__) {
  23874. console.warn(key + ': containPoint is not supported');
  23875. }
  23876. }
  23877. }, this);
  23878. }, this);
  23879. return !!result;
  23880. };
  23881. /**
  23882. * Get visual from series or data.
  23883. * @param {string|Object} finder
  23884. * If string, e.g., 'series', means {seriesIndex: 0}.
  23885. * If Object, could contain some of these properties below:
  23886. * {
  23887. * seriesIndex / seriesId / seriesName,
  23888. * dataIndex / dataIndexInside
  23889. * }
  23890. * If dataIndex is not specified, series visual will be fetched,
  23891. * but not data item visual.
  23892. * If all of seriesIndex, seriesId, seriesName are not specified,
  23893. * visual will be fetched from first series.
  23894. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  23895. */
  23896. echartsProto.getVisual = function (finder, visualType) {
  23897. var ecModel = this._model;
  23898. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  23899. var seriesModel = finder.seriesModel;
  23900. if (__DEV__) {
  23901. if (!seriesModel) {
  23902. console.warn('There is no specified seires model');
  23903. }
  23904. }
  23905. var data = seriesModel.getData();
  23906. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  23907. ? finder.dataIndexInside
  23908. : finder.hasOwnProperty('dataIndex')
  23909. ? data.indexOfRawIndex(finder.dataIndex)
  23910. : null;
  23911. return dataIndexInside != null
  23912. ? data.getItemVisual(dataIndexInside, visualType)
  23913. : data.getVisual(visualType);
  23914. };
  23915. /**
  23916. * Get view of corresponding component model
  23917. * @param {module:echarts/model/Component} componentModel
  23918. * @return {module:echarts/view/Component}
  23919. */
  23920. echartsProto.getViewOfComponentModel = function (componentModel) {
  23921. return this._componentsMap[componentModel.__viewId];
  23922. };
  23923. /**
  23924. * Get view of corresponding series model
  23925. * @param {module:echarts/model/Series} seriesModel
  23926. * @return {module:echarts/view/Chart}
  23927. */
  23928. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  23929. return this._chartsMap[seriesModel.__viewId];
  23930. };
  23931. var updateMethods = {
  23932. prepareAndUpdate: function (payload) {
  23933. prepare(this);
  23934. updateMethods.update.call(this, payload);
  23935. },
  23936. /**
  23937. * @param {Object} payload
  23938. * @private
  23939. */
  23940. update: function (payload) {
  23941. // console.profile && console.profile('update');
  23942. var ecModel = this._model;
  23943. var api = this._api;
  23944. var zr = this._zr;
  23945. var coordSysMgr = this._coordSysMgr;
  23946. var scheduler = this._scheduler;
  23947. // update before setOption
  23948. if (!ecModel) {
  23949. return;
  23950. }
  23951. scheduler.restoreData(ecModel, payload);
  23952. scheduler.performSeriesTasks(ecModel);
  23953. // TODO
  23954. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  23955. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  23956. // Create new coordinate system each update
  23957. // In LineView may save the old coordinate system and use it to get the orignal point
  23958. coordSysMgr.create(ecModel, api);
  23959. scheduler.performDataProcessorTasks(ecModel, payload);
  23960. // Current stream render is not supported in data process. So we can update
  23961. // stream modes after data processing, where the filtered data is used to
  23962. // deteming whether use progressive rendering.
  23963. updateStreamModes(this, ecModel);
  23964. // We update stream modes before coordinate system updated, then the modes info
  23965. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  23966. // the drawback is the full coord info can not be fetched. Fortunately this full
  23967. // coord is not requied in stream mode updater currently.
  23968. coordSysMgr.update(ecModel, api);
  23969. clearColorPalette(ecModel);
  23970. scheduler.performVisualTasks(ecModel, payload);
  23971. render(this, ecModel, api, payload);
  23972. // Set background
  23973. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  23974. // In IE8
  23975. if (!env$1.canvasSupported) {
  23976. var colorArr = parse(backgroundColor);
  23977. backgroundColor = stringify(colorArr, 'rgb');
  23978. if (colorArr[3] === 0) {
  23979. backgroundColor = 'transparent';
  23980. }
  23981. }
  23982. else {
  23983. zr.setBackgroundColor(backgroundColor);
  23984. }
  23985. performPostUpdateFuncs(ecModel, api);
  23986. // console.profile && console.profileEnd('update');
  23987. },
  23988. /**
  23989. * @param {Object} payload
  23990. * @private
  23991. */
  23992. updateTransform: function (payload) {
  23993. var ecModel = this._model;
  23994. var ecIns = this;
  23995. var api = this._api;
  23996. // update before setOption
  23997. if (!ecModel) {
  23998. return;
  23999. }
  24000. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24001. var componentDirtyList = [];
  24002. ecModel.eachComponent(function (componentType, componentModel) {
  24003. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24004. if (componentView && componentView.__alive) {
  24005. if (componentView.updateTransform) {
  24006. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24007. result && result.update && componentDirtyList.push(componentView);
  24008. }
  24009. else {
  24010. componentDirtyList.push(componentView);
  24011. }
  24012. }
  24013. });
  24014. var seriesDirtyMap = createHashMap();
  24015. ecModel.eachSeries(function (seriesModel) {
  24016. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24017. if (chartView.updateTransform) {
  24018. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24019. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24020. }
  24021. else {
  24022. seriesDirtyMap.set(seriesModel.uid, 1);
  24023. }
  24024. });
  24025. clearColorPalette(ecModel);
  24026. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24027. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24028. this._scheduler.performVisualTasks(
  24029. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24030. );
  24031. // Currently, not call render of components. Geo render cost a lot.
  24032. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24033. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24034. performPostUpdateFuncs(ecModel, this._api);
  24035. },
  24036. /**
  24037. * @param {Object} payload
  24038. * @private
  24039. */
  24040. updateView: function (payload) {
  24041. var ecModel = this._model;
  24042. // update before setOption
  24043. if (!ecModel) {
  24044. return;
  24045. }
  24046. Chart.markUpdateMethod(payload, 'updateView');
  24047. clearColorPalette(ecModel);
  24048. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24049. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24050. render(this, this._model, this._api, payload);
  24051. performPostUpdateFuncs(ecModel, this._api);
  24052. },
  24053. /**
  24054. * @param {Object} payload
  24055. * @private
  24056. */
  24057. updateVisual: function (payload) {
  24058. updateMethods.update.call(this, payload);
  24059. // var ecModel = this._model;
  24060. // // update before setOption
  24061. // if (!ecModel) {
  24062. // return;
  24063. // }
  24064. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24065. // clearColorPalette(ecModel);
  24066. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24067. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24068. // render(this, this._model, this._api, payload);
  24069. // performPostUpdateFuncs(ecModel, this._api);
  24070. },
  24071. /**
  24072. * @param {Object} payload
  24073. * @private
  24074. */
  24075. updateLayout: function (payload) {
  24076. updateMethods.update.call(this, payload);
  24077. // var ecModel = this._model;
  24078. // // update before setOption
  24079. // if (!ecModel) {
  24080. // return;
  24081. // }
  24082. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24083. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24084. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24085. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24086. // render(this, this._model, this._api, payload);
  24087. // performPostUpdateFuncs(ecModel, this._api);
  24088. }
  24089. };
  24090. function prepare(ecIns) {
  24091. var ecModel = ecIns._model;
  24092. var scheduler = ecIns._scheduler;
  24093. scheduler.restorePipelines(ecModel);
  24094. scheduler.prepareStageTasks();
  24095. prepareView(ecIns, 'component', ecModel, scheduler);
  24096. prepareView(ecIns, 'chart', ecModel, scheduler);
  24097. scheduler.plan();
  24098. }
  24099. /**
  24100. * @private
  24101. */
  24102. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24103. var ecModel = ecIns._model;
  24104. // broadcast
  24105. if (!mainType) {
  24106. // FIXME
  24107. // Chart will not be update directly here, except set dirty.
  24108. // But there is no such scenario now.
  24109. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24110. return;
  24111. }
  24112. var query = {};
  24113. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24114. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24115. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24116. var condition = {mainType: mainType, query: query};
  24117. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24118. var excludeSeriesId = payload.excludeSeriesId;
  24119. if (excludeSeriesId != null) {
  24120. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24121. }
  24122. // If dispatchAction before setOption, do nothing.
  24123. ecModel && ecModel.eachComponent(condition, function (model) {
  24124. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24125. callView(ecIns[
  24126. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24127. ][model.__viewId]);
  24128. }
  24129. }, ecIns);
  24130. function callView(view) {
  24131. view && view.__alive && view[method] && view[method](
  24132. view.__model, ecModel, ecIns._api, payload
  24133. );
  24134. }
  24135. }
  24136. /**
  24137. * Resize the chart
  24138. * @param {Object} opts
  24139. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  24140. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  24141. * @param {boolean} [opts.silent=false]
  24142. */
  24143. echartsProto.resize = function (opts) {
  24144. if (__DEV__) {
  24145. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  24146. }
  24147. this._zr.resize(opts);
  24148. var ecModel = this._model;
  24149. // Resize loading effect
  24150. this._loadingFX && this._loadingFX.resize();
  24151. if (!ecModel) {
  24152. return;
  24153. }
  24154. var optionChanged = ecModel.resetOption('media');
  24155. var silent = opts && opts.silent;
  24156. this[IN_MAIN_PROCESS] = true;
  24157. optionChanged && prepare(this);
  24158. updateMethods.update.call(this);
  24159. this[IN_MAIN_PROCESS] = false;
  24160. flushPendingActions.call(this, silent);
  24161. triggerUpdatedEvent.call(this, silent);
  24162. };
  24163. function updateStreamModes(ecIns, ecModel) {
  24164. var chartsMap = ecIns._chartsMap;
  24165. var scheduler = ecIns._scheduler;
  24166. ecModel.eachSeries(function (seriesModel) {
  24167. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  24168. });
  24169. }
  24170. /**
  24171. * Show loading effect
  24172. * @param {string} [name='default']
  24173. * @param {Object} [cfg]
  24174. */
  24175. echartsProto.showLoading = function (name, cfg) {
  24176. if (isObject(name)) {
  24177. cfg = name;
  24178. name = '';
  24179. }
  24180. name = name || 'default';
  24181. this.hideLoading();
  24182. if (!loadingEffects[name]) {
  24183. if (__DEV__) {
  24184. console.warn('Loading effects ' + name + ' not exists.');
  24185. }
  24186. return;
  24187. }
  24188. var el = loadingEffects[name](this._api, cfg);
  24189. var zr = this._zr;
  24190. this._loadingFX = el;
  24191. zr.add(el);
  24192. };
  24193. /**
  24194. * Hide loading effect
  24195. */
  24196. echartsProto.hideLoading = function () {
  24197. this._loadingFX && this._zr.remove(this._loadingFX);
  24198. this._loadingFX = null;
  24199. };
  24200. /**
  24201. * @param {Object} eventObj
  24202. * @return {Object}
  24203. */
  24204. echartsProto.makeActionFromEvent = function (eventObj) {
  24205. var payload = extend({}, eventObj);
  24206. payload.type = eventActionMap[eventObj.type];
  24207. return payload;
  24208. };
  24209. /**
  24210. * @pubilc
  24211. * @param {Object} payload
  24212. * @param {string} [payload.type] Action type
  24213. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  24214. * @param {boolean} [opt.silent=false] Whether trigger events.
  24215. * @param {boolean} [opt.flush=undefined]
  24216. * true: Flush immediately, and then pixel in canvas can be fetched
  24217. * immediately. Caution: it might affect performance.
  24218. * false: Not not flush.
  24219. * undefined: Auto decide whether perform flush.
  24220. */
  24221. echartsProto.dispatchAction = function (payload, opt) {
  24222. if (!isObject(opt)) {
  24223. opt = {silent: !!opt};
  24224. }
  24225. if (!actions[payload.type]) {
  24226. return;
  24227. }
  24228. // Avoid dispatch action before setOption. Especially in `connect`.
  24229. if (!this._model) {
  24230. return;
  24231. }
  24232. // May dispatchAction in rendering procedure
  24233. if (this[IN_MAIN_PROCESS]) {
  24234. this._pendingActions.push(payload);
  24235. return;
  24236. }
  24237. doDispatchAction.call(this, payload, opt.silent);
  24238. if (opt.flush) {
  24239. this._zr.flush(true);
  24240. }
  24241. else if (opt.flush !== false && env$1.browser.weChat) {
  24242. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  24243. // hang when sliding page (on touch event), which cause that zr does not
  24244. // refresh util user interaction finished, which is not expected.
  24245. // But `dispatchAction` may be called too frequently when pan on touch
  24246. // screen, which impacts performance if do not throttle them.
  24247. this._throttledZrFlush();
  24248. }
  24249. flushPendingActions.call(this, opt.silent);
  24250. triggerUpdatedEvent.call(this, opt.silent);
  24251. };
  24252. function doDispatchAction(payload, silent) {
  24253. var payloadType = payload.type;
  24254. var escapeConnect = payload.escapeConnect;
  24255. var actionWrap = actions[payloadType];
  24256. var actionInfo = actionWrap.actionInfo;
  24257. var cptType = (actionInfo.update || 'update').split(':');
  24258. var updateMethod = cptType.pop();
  24259. cptType = cptType[0] != null && parseClassType(cptType[0]);
  24260. this[IN_MAIN_PROCESS] = true;
  24261. var payloads = [payload];
  24262. var batched = false;
  24263. // Batch action
  24264. if (payload.batch) {
  24265. batched = true;
  24266. payloads = map(payload.batch, function (item) {
  24267. item = defaults(extend({}, item), payload);
  24268. item.batch = null;
  24269. return item;
  24270. });
  24271. }
  24272. var eventObjBatch = [];
  24273. var eventObj;
  24274. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  24275. each(payloads, function (batchItem) {
  24276. // Action can specify the event by return it.
  24277. eventObj = actionWrap.action(batchItem, this._model, this._api);
  24278. // Emit event outside
  24279. eventObj = eventObj || extend({}, batchItem);
  24280. // Convert type to eventType
  24281. eventObj.type = actionInfo.event || eventObj.type;
  24282. eventObjBatch.push(eventObj);
  24283. // light update does not perform data process, layout and visual.
  24284. if (isHighDown) {
  24285. // method, payload, mainType, subType
  24286. updateDirectly(this, updateMethod, batchItem, 'series');
  24287. }
  24288. else if (cptType) {
  24289. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  24290. }
  24291. }, this);
  24292. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  24293. // Still dirty
  24294. if (this[OPTION_UPDATED]) {
  24295. // FIXME Pass payload ?
  24296. prepare(this);
  24297. updateMethods.update.call(this, payload);
  24298. this[OPTION_UPDATED] = false;
  24299. }
  24300. else {
  24301. updateMethods[updateMethod].call(this, payload);
  24302. }
  24303. }
  24304. // Follow the rule of action batch
  24305. if (batched) {
  24306. eventObj = {
  24307. type: actionInfo.event || payloadType,
  24308. escapeConnect: escapeConnect,
  24309. batch: eventObjBatch
  24310. };
  24311. }
  24312. else {
  24313. eventObj = eventObjBatch[0];
  24314. }
  24315. this[IN_MAIN_PROCESS] = false;
  24316. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  24317. }
  24318. function flushPendingActions(silent) {
  24319. var pendingActions = this._pendingActions;
  24320. while (pendingActions.length) {
  24321. var payload = pendingActions.shift();
  24322. doDispatchAction.call(this, payload, silent);
  24323. }
  24324. }
  24325. function triggerUpdatedEvent(silent) {
  24326. !silent && this.trigger('updated');
  24327. }
  24328. /**
  24329. * Event `rendered` is triggered when zr
  24330. * rendered. It is useful for realtime
  24331. * snapshot (reflect animation).
  24332. *
  24333. * Event `finished` is triggered when:
  24334. * (1) zrender rendering finished.
  24335. * (2) initial animation finished.
  24336. * (3) progressive rendering finished.
  24337. * (4) no pending action.
  24338. * (5) no delayed setOption needs to be processed.
  24339. */
  24340. function bindRenderedEvent(zr, ecIns) {
  24341. zr.on('rendered', function () {
  24342. ecIns.trigger('rendered');
  24343. // The `finished` event should not be triggered repeatly,
  24344. // so it should only be triggered when rendering indeed happend
  24345. // in zrender. (Consider the case that dipatchAction is keep
  24346. // triggering when mouse move).
  24347. if (
  24348. // Although zr is dirty if initial animation is not finished
  24349. // and this checking is called on frame, we also check
  24350. // animation finished for robustness.
  24351. zr.animation.isFinished()
  24352. && !ecIns[OPTION_UPDATED]
  24353. && !ecIns._scheduler.unfinished
  24354. && !ecIns._pendingActions.length
  24355. ) {
  24356. ecIns.trigger('finished');
  24357. }
  24358. });
  24359. }
  24360. /**
  24361. * @param {Object} params
  24362. * @param {number} params.seriesIndex
  24363. * @param {Array|TypedArray} params.data
  24364. */
  24365. echartsProto.appendData = function (params) {
  24366. var seriesIndex = params.seriesIndex;
  24367. var ecModel = this.getModel();
  24368. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  24369. if (__DEV__) {
  24370. assert(params.data && seriesModel);
  24371. }
  24372. seriesModel.appendData(params);
  24373. // Note: `appendData` does not support that update extent of coordinate
  24374. // system, util some scenario require that. In the expected usage of
  24375. // `appendData`, the initial extent of coordinate system should better
  24376. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  24377. // the extent changed while `appendData`, the location of the painted
  24378. // graphic elements have to be changed, which make the usage of
  24379. // `appendData` meaningless.
  24380. this._scheduler.unfinished = true;
  24381. };
  24382. /**
  24383. * Register event
  24384. * @method
  24385. */
  24386. echartsProto.on = createRegisterEventWithLowercaseName('on');
  24387. echartsProto.off = createRegisterEventWithLowercaseName('off');
  24388. echartsProto.one = createRegisterEventWithLowercaseName('one');
  24389. /**
  24390. * Prepare view instances of charts and components
  24391. * @param {module:echarts/model/Global} ecModel
  24392. * @private
  24393. */
  24394. function prepareView(ecIns, type, ecModel, scheduler) {
  24395. var isComponent = type === 'component';
  24396. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  24397. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  24398. var zr = ecIns._zr;
  24399. var api = ecIns._api;
  24400. for (var i = 0; i < viewList.length; i++) {
  24401. viewList[i].__alive = false;
  24402. }
  24403. isComponent
  24404. ? ecModel.eachComponent(function (componentType, model) {
  24405. componentType !== 'series' && doPrepare(model);
  24406. })
  24407. : ecModel.eachSeries(doPrepare);
  24408. function doPrepare(model) {
  24409. // Consider: id same and type changed.
  24410. var viewId = '_ec_' + model.id + '_' + model.type;
  24411. var view = viewMap[viewId];
  24412. if (!view) {
  24413. var classType = parseClassType(model.type);
  24414. var Clazz = isComponent
  24415. ? Component$1.getClass(classType.main, classType.sub)
  24416. : Chart.getClass(classType.sub);
  24417. if (__DEV__) {
  24418. assert(Clazz, classType.sub + ' does not exist.');
  24419. }
  24420. view = new Clazz();
  24421. view.init(ecModel, api);
  24422. viewMap[viewId] = view;
  24423. viewList.push(view);
  24424. zr.add(view.group);
  24425. }
  24426. model.__viewId = view.__id = viewId;
  24427. view.__alive = true;
  24428. view.__model = model;
  24429. view.group.__ecComponentInfo = {
  24430. mainType: model.mainType,
  24431. index: model.componentIndex
  24432. };
  24433. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  24434. }
  24435. for (var i = 0; i < viewList.length;) {
  24436. var view = viewList[i];
  24437. if (!view.__alive) {
  24438. !isComponent && view.renderTask.dispose();
  24439. zr.remove(view.group);
  24440. view.dispose(ecModel, api);
  24441. viewList.splice(i, 1);
  24442. delete viewMap[view.__id];
  24443. view.__id = view.group.__ecComponentInfo = null;
  24444. }
  24445. else {
  24446. i++;
  24447. }
  24448. }
  24449. }
  24450. // /**
  24451. // * Encode visual infomation from data after data processing
  24452. // *
  24453. // * @param {module:echarts/model/Global} ecModel
  24454. // * @param {object} layout
  24455. // * @param {boolean} [layoutFilter] `true`: only layout,
  24456. // * `false`: only not layout,
  24457. // * `null`/`undefined`: all.
  24458. // * @param {string} taskBaseTag
  24459. // * @private
  24460. // */
  24461. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  24462. // each(visualFuncs, function (visual, index) {
  24463. // var isLayout = visual.isLayout;
  24464. // if (layoutFilter == null
  24465. // || (layoutFilter === false && !isLayout)
  24466. // || (layoutFilter === true && isLayout)
  24467. // ) {
  24468. // visual.func(ecModel, api, payload);
  24469. // }
  24470. // });
  24471. // }
  24472. function clearColorPalette(ecModel) {
  24473. ecModel.clearColorPalette();
  24474. ecModel.eachSeries(function (seriesModel) {
  24475. seriesModel.clearColorPalette();
  24476. });
  24477. }
  24478. function render(ecIns, ecModel, api, payload) {
  24479. renderComponents(ecIns, ecModel, api, payload);
  24480. each(ecIns._chartsViews, function (chart) {
  24481. chart.__alive = false;
  24482. });
  24483. renderSeries(ecIns, ecModel, api, payload);
  24484. // Remove groups of unrendered charts
  24485. each(ecIns._chartsViews, function (chart) {
  24486. if (!chart.__alive) {
  24487. chart.remove(ecModel, api);
  24488. }
  24489. });
  24490. }
  24491. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  24492. each(dirtyList || ecIns._componentsViews, function (componentView) {
  24493. var componentModel = componentView.__model;
  24494. componentView.render(componentModel, ecModel, api, payload);
  24495. updateZ(componentModel, componentView);
  24496. });
  24497. }
  24498. /**
  24499. * Render each chart and component
  24500. * @private
  24501. */
  24502. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  24503. // Render all charts
  24504. var scheduler = ecIns._scheduler;
  24505. var unfinished;
  24506. ecModel.eachSeries(function (seriesModel) {
  24507. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24508. chartView.__alive = true;
  24509. var renderTask = chartView.renderTask;
  24510. scheduler.updatePayload(renderTask, payload);
  24511. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  24512. renderTask.dirty();
  24513. }
  24514. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  24515. chartView.group.silent = !!seriesModel.get('silent');
  24516. updateZ(seriesModel, chartView);
  24517. updateBlend(seriesModel, chartView);
  24518. });
  24519. scheduler.unfinished |= unfinished;
  24520. // If use hover layer
  24521. updateHoverLayerStatus(ecIns._zr, ecModel);
  24522. // Add aria
  24523. aria(ecIns._zr.dom, ecModel);
  24524. }
  24525. function performPostUpdateFuncs(ecModel, api) {
  24526. each(postUpdateFuncs, function (func) {
  24527. func(ecModel, api);
  24528. });
  24529. }
  24530. var MOUSE_EVENT_NAMES = [
  24531. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  24532. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  24533. ];
  24534. /**
  24535. * @private
  24536. */
  24537. echartsProto._initEvents = function () {
  24538. each(MOUSE_EVENT_NAMES, function (eveName) {
  24539. var handler = function (e) {
  24540. var ecModel = this.getModel();
  24541. var el = e.target;
  24542. var params;
  24543. var isGlobalOut = eveName === 'globalout';
  24544. // no e.target when 'globalout'.
  24545. if (isGlobalOut) {
  24546. params = {};
  24547. }
  24548. else if (el && el.dataIndex != null) {
  24549. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  24550. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  24551. }
  24552. // If element has custom eventData of components
  24553. else if (el && el.eventData) {
  24554. params = extend({}, el.eventData);
  24555. }
  24556. // Contract: if params prepared in mouse event,
  24557. // these properties must be specified:
  24558. // {
  24559. // componentType: string (component main type)
  24560. // componentIndex: number
  24561. // }
  24562. // Otherwise event query can not work.
  24563. if (params) {
  24564. var componentType = params.componentType;
  24565. var componentIndex = params.componentIndex;
  24566. // Special handling for historic reason: when trigger by
  24567. // markLine/markPoint/markArea, the componentType is
  24568. // 'markLine'/'markPoint'/'markArea', but we should better
  24569. // enable them to be queried by seriesIndex, since their
  24570. // option is set in each series.
  24571. if (componentType === 'markLine'
  24572. || componentType === 'markPoint'
  24573. || componentType === 'markArea'
  24574. ) {
  24575. componentType = 'series';
  24576. componentIndex = params.seriesIndex;
  24577. }
  24578. var model = componentType && componentIndex != null
  24579. && ecModel.getComponent(componentType, componentIndex);
  24580. var view = model && this[
  24581. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24582. ][model.__viewId];
  24583. if (__DEV__) {
  24584. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24585. // be missed, otherwise there is no way to distinguish source component.
  24586. // See `dataFormat.getDataParams`.
  24587. if (!isGlobalOut && !(model && view)) {
  24588. console.warn('model or view can not be found by params');
  24589. }
  24590. }
  24591. params.event = e;
  24592. params.type = eveName;
  24593. this._ecEventProcessor.eventInfo = {
  24594. targetEl: el,
  24595. packedEvent: params,
  24596. model: model,
  24597. view: view
  24598. };
  24599. this.trigger(eveName, params);
  24600. }
  24601. };
  24602. // Consider that some component (like tooltip, brush, ...)
  24603. // register zr event handler, but user event handler might
  24604. // do anything, such as call `setOption` or `dispatchAction`,
  24605. // which probably update any of the content and probably
  24606. // cause problem if it is called previous other inner handlers.
  24607. handler.zrEventfulCallAtLast = true;
  24608. this._zr.on(eveName, handler, this);
  24609. }, this);
  24610. each(eventActionMap, function (actionType, eventType) {
  24611. this._messageCenter.on(eventType, function (event) {
  24612. this.trigger(eventType, event);
  24613. }, this);
  24614. }, this);
  24615. };
  24616. /**
  24617. * @return {boolean}
  24618. */
  24619. echartsProto.isDisposed = function () {
  24620. return this._disposed;
  24621. };
  24622. /**
  24623. * Clear
  24624. */
  24625. echartsProto.clear = function () {
  24626. this.setOption({ series: [] }, true);
  24627. };
  24628. /**
  24629. * Dispose instance
  24630. */
  24631. echartsProto.dispose = function () {
  24632. if (this._disposed) {
  24633. if (__DEV__) {
  24634. console.warn('Instance ' + this.id + ' has been disposed');
  24635. }
  24636. return;
  24637. }
  24638. this._disposed = true;
  24639. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24640. var api = this._api;
  24641. var ecModel = this._model;
  24642. each(this._componentsViews, function (component) {
  24643. component.dispose(ecModel, api);
  24644. });
  24645. each(this._chartsViews, function (chart) {
  24646. chart.dispose(ecModel, api);
  24647. });
  24648. // Dispose after all views disposed
  24649. this._zr.dispose();
  24650. delete instances[this.id];
  24651. };
  24652. mixin(ECharts, Eventful);
  24653. function updateHoverLayerStatus(zr, ecModel) {
  24654. var storage = zr.storage;
  24655. var elCount = 0;
  24656. storage.traverse(function (el) {
  24657. if (!el.isGroup) {
  24658. elCount++;
  24659. }
  24660. });
  24661. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  24662. storage.traverse(function (el) {
  24663. if (!el.isGroup) {
  24664. // Don't switch back.
  24665. el.useHoverLayer = true;
  24666. }
  24667. });
  24668. }
  24669. }
  24670. /**
  24671. * Update chart progressive and blend.
  24672. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24673. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24674. */
  24675. function updateBlend(seriesModel, chartView) {
  24676. var blendMode = seriesModel.get('blendMode') || null;
  24677. if (__DEV__) {
  24678. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  24679. console.warn('Only canvas support blendMode');
  24680. }
  24681. }
  24682. chartView.group.traverse(function (el) {
  24683. // FIXME marker and other components
  24684. if (!el.isGroup) {
  24685. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  24686. if (el.style.blend !== blendMode) {
  24687. el.setStyle('blend', blendMode);
  24688. }
  24689. }
  24690. if (el.eachPendingDisplayable) {
  24691. el.eachPendingDisplayable(function (displayable) {
  24692. displayable.setStyle('blend', blendMode);
  24693. });
  24694. }
  24695. });
  24696. }
  24697. /**
  24698. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24699. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24700. */
  24701. function updateZ(model, view) {
  24702. var z = model.get('z');
  24703. var zlevel = model.get('zlevel');
  24704. // Set z and zlevel
  24705. view.group.traverse(function (el) {
  24706. if (el.type !== 'group') {
  24707. z != null && (el.z = z);
  24708. zlevel != null && (el.zlevel = zlevel);
  24709. }
  24710. });
  24711. }
  24712. function createExtensionAPI(ecInstance) {
  24713. var coordSysMgr = ecInstance._coordSysMgr;
  24714. return extend(new ExtensionAPI(ecInstance), {
  24715. // Inject methods
  24716. getCoordinateSystems: bind(
  24717. coordSysMgr.getCoordinateSystems, coordSysMgr
  24718. ),
  24719. getComponentByElement: function (el) {
  24720. while (el) {
  24721. var modelInfo = el.__ecComponentInfo;
  24722. if (modelInfo != null) {
  24723. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  24724. }
  24725. el = el.parent;
  24726. }
  24727. }
  24728. });
  24729. }
  24730. /**
  24731. * @class
  24732. * Usage of query:
  24733. * `chart.on('click', query, handler);`
  24734. * The `query` can be:
  24735. * + The component type query string, only `mainType` or `mainType.subType`,
  24736. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  24737. * + The component query object, like:
  24738. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  24739. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  24740. * + The data query object, like:
  24741. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  24742. * + The other query object (cmponent customized query), like:
  24743. * `{element: 'some'}` (only available in custom series).
  24744. *
  24745. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  24746. * same as there is no such prop in the `query` object.
  24747. */
  24748. function EventProcessor() {
  24749. // These info required: targetEl, packedEvent, model, view
  24750. this.eventInfo;
  24751. }
  24752. EventProcessor.prototype = {
  24753. constructor: EventProcessor,
  24754. normalizeQuery: function (query) {
  24755. var cptQuery = {};
  24756. var dataQuery = {};
  24757. var otherQuery = {};
  24758. // `query` is `mainType` or `mainType.subType` of component.
  24759. if (isString(query)) {
  24760. var condCptType = parseClassType(query);
  24761. // `.main` and `.sub` may be ''.
  24762. cptQuery.mainType = condCptType.main || null;
  24763. cptQuery.subType = condCptType.sub || null;
  24764. }
  24765. // `query` is an object, convert to {mainType, index, name, id}.
  24766. else {
  24767. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  24768. // can not be used in `compomentModel.filterForExposedEvent`.
  24769. var suffixes = ['Index', 'Name', 'Id'];
  24770. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  24771. each$1(query, function (val, key) {
  24772. var reserved = false;
  24773. for (var i = 0; i < suffixes.length; i++) {
  24774. var propSuffix = suffixes[i];
  24775. var suffixPos = key.lastIndexOf(propSuffix);
  24776. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  24777. var mainType = key.slice(0, suffixPos);
  24778. // Consider `dataIndex`.
  24779. if (mainType !== 'data') {
  24780. cptQuery.mainType = mainType;
  24781. cptQuery[propSuffix.toLowerCase()] = val;
  24782. reserved = true;
  24783. }
  24784. }
  24785. }
  24786. if (dataKeys.hasOwnProperty(key)) {
  24787. dataQuery[key] = val;
  24788. reserved = true;
  24789. }
  24790. if (!reserved) {
  24791. otherQuery[key] = val;
  24792. }
  24793. });
  24794. }
  24795. return {
  24796. cptQuery: cptQuery,
  24797. dataQuery: dataQuery,
  24798. otherQuery: otherQuery
  24799. };
  24800. },
  24801. filter: function (eventType, query, args) {
  24802. // They should be assigned before each trigger call.
  24803. var eventInfo = this.eventInfo;
  24804. if (!eventInfo) {
  24805. return true;
  24806. }
  24807. var targetEl = eventInfo.targetEl;
  24808. var packedEvent = eventInfo.packedEvent;
  24809. var model = eventInfo.model;
  24810. var view = eventInfo.view;
  24811. // For event like 'globalout'.
  24812. if (!model || !view) {
  24813. return true;
  24814. }
  24815. var cptQuery = query.cptQuery;
  24816. var dataQuery = query.dataQuery;
  24817. return check(cptQuery, model, 'mainType')
  24818. && check(cptQuery, model, 'subType')
  24819. && check(cptQuery, model, 'index', 'componentIndex')
  24820. && check(cptQuery, model, 'name')
  24821. && check(cptQuery, model, 'id')
  24822. && check(dataQuery, packedEvent, 'name')
  24823. && check(dataQuery, packedEvent, 'dataIndex')
  24824. && check(dataQuery, packedEvent, 'dataType')
  24825. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  24826. eventType, query.otherQuery, targetEl, packedEvent
  24827. ));
  24828. function check(query, host, prop, propOnHost) {
  24829. return query[prop] == null || host[propOnHost || prop] === query[prop];
  24830. }
  24831. },
  24832. afterTrigger: function () {
  24833. // Make sure the eventInfo wont be used in next trigger.
  24834. this.eventInfo = null;
  24835. }
  24836. };
  24837. /**
  24838. * @type {Object} key: actionType.
  24839. * @inner
  24840. */
  24841. var actions = {};
  24842. /**
  24843. * Map eventType to actionType
  24844. * @type {Object}
  24845. */
  24846. var eventActionMap = {};
  24847. /**
  24848. * Data processor functions of each stage
  24849. * @type {Array.<Object.<string, Function>>}
  24850. * @inner
  24851. */
  24852. var dataProcessorFuncs = [];
  24853. /**
  24854. * @type {Array.<Function>}
  24855. * @inner
  24856. */
  24857. var optionPreprocessorFuncs = [];
  24858. /**
  24859. * @type {Array.<Function>}
  24860. * @inner
  24861. */
  24862. var postUpdateFuncs = [];
  24863. /**
  24864. * Visual encoding functions of each stage
  24865. * @type {Array.<Object.<string, Function>>}
  24866. */
  24867. var visualFuncs = [];
  24868. /**
  24869. * Theme storage
  24870. * @type {Object.<key, Object>}
  24871. */
  24872. var themeStorage = {};
  24873. /**
  24874. * Loading effects
  24875. */
  24876. var loadingEffects = {};
  24877. var instances = {};
  24878. var connectedGroups = {};
  24879. var idBase = new Date() - 0;
  24880. var groupIdBase = new Date() - 0;
  24881. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  24882. function enableConnect(chart) {
  24883. var STATUS_PENDING = 0;
  24884. var STATUS_UPDATING = 1;
  24885. var STATUS_UPDATED = 2;
  24886. var STATUS_KEY = '__connectUpdateStatus';
  24887. function updateConnectedChartsStatus(charts, status) {
  24888. for (var i = 0; i < charts.length; i++) {
  24889. var otherChart = charts[i];
  24890. otherChart[STATUS_KEY] = status;
  24891. }
  24892. }
  24893. each(eventActionMap, function (actionType, eventType) {
  24894. chart._messageCenter.on(eventType, function (event) {
  24895. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  24896. if (event && event.escapeConnect) {
  24897. return;
  24898. }
  24899. var action = chart.makeActionFromEvent(event);
  24900. var otherCharts = [];
  24901. each(instances, function (otherChart) {
  24902. if (otherChart !== chart && otherChart.group === chart.group) {
  24903. otherCharts.push(otherChart);
  24904. }
  24905. });
  24906. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  24907. each(otherCharts, function (otherChart) {
  24908. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  24909. otherChart.dispatchAction(action);
  24910. }
  24911. });
  24912. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  24913. }
  24914. });
  24915. });
  24916. }
  24917. /**
  24918. * @param {HTMLElement} dom
  24919. * @param {Object} [theme]
  24920. * @param {Object} opts
  24921. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  24922. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  24923. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  24924. * Can be 'auto' (the same as null/undefined)
  24925. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  24926. * Can be 'auto' (the same as null/undefined)
  24927. */
  24928. function init(dom, theme$$1, opts) {
  24929. if (__DEV__) {
  24930. // Check version
  24931. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  24932. throw new Error(
  24933. 'zrender/src ' + version$1
  24934. + ' is too old for ECharts ' + version
  24935. + '. Current version need ZRender '
  24936. + dependencies.zrender + '+'
  24937. );
  24938. }
  24939. if (!dom) {
  24940. throw new Error('Initialize failed: invalid dom.');
  24941. }
  24942. }
  24943. var existInstance = getInstanceByDom(dom);
  24944. if (existInstance) {
  24945. if (__DEV__) {
  24946. console.warn('There is a chart instance already initialized on the dom.');
  24947. }
  24948. return existInstance;
  24949. }
  24950. if (__DEV__) {
  24951. if (isDom(dom)
  24952. && dom.nodeName.toUpperCase() !== 'CANVAS'
  24953. && (
  24954. (!dom.clientWidth && (!opts || opts.width == null))
  24955. || (!dom.clientHeight && (!opts || opts.height == null))
  24956. )
  24957. ) {
  24958. console.warn('Can\'t get dom width or height');
  24959. }
  24960. }
  24961. var chart = new ECharts(dom, theme$$1, opts);
  24962. chart.id = 'ec_' + idBase++;
  24963. instances[chart.id] = chart;
  24964. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  24965. enableConnect(chart);
  24966. return chart;
  24967. }
  24968. /**
  24969. * @return {string|Array.<module:echarts~ECharts>} groupId
  24970. */
  24971. function connect(groupId) {
  24972. // Is array of charts
  24973. if (isArray(groupId)) {
  24974. var charts = groupId;
  24975. groupId = null;
  24976. // If any chart has group
  24977. each(charts, function (chart) {
  24978. if (chart.group != null) {
  24979. groupId = chart.group;
  24980. }
  24981. });
  24982. groupId = groupId || ('g_' + groupIdBase++);
  24983. each(charts, function (chart) {
  24984. chart.group = groupId;
  24985. });
  24986. }
  24987. connectedGroups[groupId] = true;
  24988. return groupId;
  24989. }
  24990. /**
  24991. * @DEPRECATED
  24992. * @return {string} groupId
  24993. */
  24994. function disConnect(groupId) {
  24995. connectedGroups[groupId] = false;
  24996. }
  24997. /**
  24998. * @return {string} groupId
  24999. */
  25000. var disconnect = disConnect;
  25001. /**
  25002. * Dispose a chart instance
  25003. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25004. */
  25005. function dispose(chart) {
  25006. if (typeof chart === 'string') {
  25007. chart = instances[chart];
  25008. }
  25009. else if (!(chart instanceof ECharts)) {
  25010. // Try to treat as dom
  25011. chart = getInstanceByDom(chart);
  25012. }
  25013. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25014. chart.dispose();
  25015. }
  25016. }
  25017. /**
  25018. * @param {HTMLElement} dom
  25019. * @return {echarts~ECharts}
  25020. */
  25021. function getInstanceByDom(dom) {
  25022. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25023. }
  25024. /**
  25025. * @param {string} key
  25026. * @return {echarts~ECharts}
  25027. */
  25028. function getInstanceById(key) {
  25029. return instances[key];
  25030. }
  25031. /**
  25032. * Register theme
  25033. */
  25034. function registerTheme(name, theme$$1) {
  25035. themeStorage[name] = theme$$1;
  25036. }
  25037. /**
  25038. * Register option preprocessor
  25039. * @param {Function} preprocessorFunc
  25040. */
  25041. function registerPreprocessor(preprocessorFunc) {
  25042. optionPreprocessorFuncs.push(preprocessorFunc);
  25043. }
  25044. /**
  25045. * @param {number} [priority=1000]
  25046. * @param {Object|Function} processor
  25047. */
  25048. function registerProcessor(priority, processor) {
  25049. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25050. }
  25051. /**
  25052. * Register postUpdater
  25053. * @param {Function} postUpdateFunc
  25054. */
  25055. function registerPostUpdate(postUpdateFunc) {
  25056. postUpdateFuncs.push(postUpdateFunc);
  25057. }
  25058. /**
  25059. * Usage:
  25060. * registerAction('someAction', 'someEvent', function () { ... });
  25061. * registerAction('someAction', function () { ... });
  25062. * registerAction(
  25063. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25064. * function () { ... }
  25065. * );
  25066. *
  25067. * @param {(string|Object)} actionInfo
  25068. * @param {string} actionInfo.type
  25069. * @param {string} [actionInfo.event]
  25070. * @param {string} [actionInfo.update]
  25071. * @param {string} [eventName]
  25072. * @param {Function} action
  25073. */
  25074. function registerAction(actionInfo, eventName, action) {
  25075. if (typeof eventName === 'function') {
  25076. action = eventName;
  25077. eventName = '';
  25078. }
  25079. var actionType = isObject(actionInfo)
  25080. ? actionInfo.type
  25081. : ([actionInfo, actionInfo = {
  25082. event: eventName
  25083. }][0]);
  25084. // Event name is all lowercase
  25085. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25086. eventName = actionInfo.event;
  25087. // Validate action type and event name.
  25088. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25089. if (!actions[actionType]) {
  25090. actions[actionType] = {action: action, actionInfo: actionInfo};
  25091. }
  25092. eventActionMap[eventName] = actionType;
  25093. }
  25094. /**
  25095. * @param {string} type
  25096. * @param {*} CoordinateSystem
  25097. */
  25098. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  25099. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  25100. }
  25101. /**
  25102. * Get dimensions of specified coordinate system.
  25103. * @param {string} type
  25104. * @return {Array.<string|Object>}
  25105. */
  25106. function getCoordinateSystemDimensions(type) {
  25107. var coordSysCreator = CoordinateSystemManager.get(type);
  25108. if (coordSysCreator) {
  25109. return coordSysCreator.getDimensionsInfo
  25110. ? coordSysCreator.getDimensionsInfo()
  25111. : coordSysCreator.dimensions.slice();
  25112. }
  25113. }
  25114. /**
  25115. * Layout is a special stage of visual encoding
  25116. * Most visual encoding like color are common for different chart
  25117. * But each chart has it's own layout algorithm
  25118. *
  25119. * @param {number} [priority=1000]
  25120. * @param {Function} layoutTask
  25121. */
  25122. function registerLayout(priority, layoutTask) {
  25123. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  25124. }
  25125. /**
  25126. * @param {number} [priority=3000]
  25127. * @param {module:echarts/stream/Task} visualTask
  25128. */
  25129. function registerVisual(priority, visualTask) {
  25130. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  25131. }
  25132. /**
  25133. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  25134. */
  25135. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  25136. if (isFunction(priority) || isObject(priority)) {
  25137. fn = priority;
  25138. priority = defaultPriority;
  25139. }
  25140. if (__DEV__) {
  25141. if (isNaN(priority) || priority == null) {
  25142. throw new Error('Illegal priority');
  25143. }
  25144. // Check duplicate
  25145. each(targetList, function (wrap) {
  25146. assert(wrap.__raw !== fn);
  25147. });
  25148. }
  25149. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  25150. stageHandler.__prio = priority;
  25151. stageHandler.__raw = fn;
  25152. targetList.push(stageHandler);
  25153. return stageHandler;
  25154. }
  25155. /**
  25156. * @param {string} name
  25157. */
  25158. function registerLoading(name, loadingFx) {
  25159. loadingEffects[name] = loadingFx;
  25160. }
  25161. /**
  25162. * @param {Object} opts
  25163. * @param {string} [superClass]
  25164. */
  25165. function extendComponentModel(opts/*, superClass*/) {
  25166. // var Clazz = ComponentModel;
  25167. // if (superClass) {
  25168. // var classType = parseClassType(superClass);
  25169. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25170. // }
  25171. return ComponentModel.extend(opts);
  25172. }
  25173. /**
  25174. * @param {Object} opts
  25175. * @param {string} [superClass]
  25176. */
  25177. function extendComponentView(opts/*, superClass*/) {
  25178. // var Clazz = ComponentView;
  25179. // if (superClass) {
  25180. // var classType = parseClassType(superClass);
  25181. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  25182. // }
  25183. return Component$1.extend(opts);
  25184. }
  25185. /**
  25186. * @param {Object} opts
  25187. * @param {string} [superClass]
  25188. */
  25189. function extendSeriesModel(opts/*, superClass*/) {
  25190. // var Clazz = SeriesModel;
  25191. // if (superClass) {
  25192. // superClass = 'series.' + superClass.replace('series.', '');
  25193. // var classType = parseClassType(superClass);
  25194. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25195. // }
  25196. return SeriesModel.extend(opts);
  25197. }
  25198. /**
  25199. * @param {Object} opts
  25200. * @param {string} [superClass]
  25201. */
  25202. function extendChartView(opts/*, superClass*/) {
  25203. // var Clazz = ChartView;
  25204. // if (superClass) {
  25205. // superClass = superClass.replace('series.', '');
  25206. // var classType = parseClassType(superClass);
  25207. // Clazz = ChartView.getClass(classType.main, true);
  25208. // }
  25209. return Chart.extend(opts);
  25210. }
  25211. /**
  25212. * ZRender need a canvas context to do measureText.
  25213. * But in node environment canvas may be created by node-canvas.
  25214. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  25215. *
  25216. * Be careful of using it in the browser.
  25217. *
  25218. * @param {Function} creator
  25219. * @example
  25220. * var Canvas = require('canvas');
  25221. * var echarts = require('echarts');
  25222. * echarts.setCanvasCreator(function () {
  25223. * // Small size is enough.
  25224. * return new Canvas(32, 32);
  25225. * });
  25226. */
  25227. function setCanvasCreator(creator) {
  25228. $override('createCanvas', creator);
  25229. }
  25230. /**
  25231. * @param {string} mapName
  25232. * @param {Array.<Object>|Object|string} geoJson
  25233. * @param {Object} [specialAreas]
  25234. *
  25235. * @example GeoJSON
  25236. * $.get('USA.json', function (geoJson) {
  25237. * echarts.registerMap('USA', geoJson);
  25238. * // Or
  25239. * echarts.registerMap('USA', {
  25240. * geoJson: geoJson,
  25241. * specialAreas: {}
  25242. * })
  25243. * });
  25244. *
  25245. * $.get('airport.svg', function (svg) {
  25246. * echarts.registerMap('airport', {
  25247. * svg: svg
  25248. * }
  25249. * });
  25250. *
  25251. * echarts.registerMap('eu', [
  25252. * {svg: eu-topographic.svg},
  25253. * {geoJSON: eu.json}
  25254. * ])
  25255. */
  25256. function registerMap(mapName, geoJson, specialAreas) {
  25257. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  25258. }
  25259. /**
  25260. * @param {string} mapName
  25261. * @return {Object}
  25262. */
  25263. function getMap(mapName) {
  25264. // For backward compatibility, only return the first one.
  25265. var records = mapDataStorage.retrieveMap(mapName);
  25266. return records && records[0] && {
  25267. geoJson: records[0].geoJSON,
  25268. specialAreas: records[0].specialAreas
  25269. };
  25270. }
  25271. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  25272. registerPreprocessor(backwardCompat);
  25273. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  25274. registerLoading('default', loadingDefault);
  25275. // Default actions
  25276. registerAction({
  25277. type: 'highlight',
  25278. event: 'highlight',
  25279. update: 'highlight'
  25280. }, noop);
  25281. registerAction({
  25282. type: 'downplay',
  25283. event: 'downplay',
  25284. update: 'downplay'
  25285. }, noop);
  25286. // Default theme
  25287. registerTheme('light', lightTheme);
  25288. registerTheme('dark', theme);
  25289. // For backward compatibility, where the namespace `dataTool` will
  25290. // be mounted on `echarts` is the extension `dataTool` is imported.
  25291. var dataTool = {};
  25292. /*
  25293. * Licensed to the Apache Software Foundation (ASF) under one
  25294. * or more contributor license agreements. See the NOTICE file
  25295. * distributed with this work for additional information
  25296. * regarding copyright ownership. The ASF licenses this file
  25297. * to you under the Apache License, Version 2.0 (the
  25298. * "License"); you may not use this file except in compliance
  25299. * with the License. You may obtain a copy of the License at
  25300. *
  25301. * http://www.apache.org/licenses/LICENSE-2.0
  25302. *
  25303. * Unless required by applicable law or agreed to in writing,
  25304. * software distributed under the License is distributed on an
  25305. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25306. * KIND, either express or implied. See the License for the
  25307. * specific language governing permissions and limitations
  25308. * under the License.
  25309. */
  25310. function defaultKeyGetter(item) {
  25311. return item;
  25312. }
  25313. /**
  25314. * @param {Array} oldArr
  25315. * @param {Array} newArr
  25316. * @param {Function} oldKeyGetter
  25317. * @param {Function} newKeyGetter
  25318. * @param {Object} [context] Can be visited by this.context in callback.
  25319. */
  25320. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  25321. this._old = oldArr;
  25322. this._new = newArr;
  25323. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  25324. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  25325. this.context = context;
  25326. }
  25327. DataDiffer.prototype = {
  25328. constructor: DataDiffer,
  25329. /**
  25330. * Callback function when add a data
  25331. */
  25332. add: function (func) {
  25333. this._add = func;
  25334. return this;
  25335. },
  25336. /**
  25337. * Callback function when update a data
  25338. */
  25339. update: function (func) {
  25340. this._update = func;
  25341. return this;
  25342. },
  25343. /**
  25344. * Callback function when remove a data
  25345. */
  25346. remove: function (func) {
  25347. this._remove = func;
  25348. return this;
  25349. },
  25350. execute: function () {
  25351. var oldArr = this._old;
  25352. var newArr = this._new;
  25353. var oldDataIndexMap = {};
  25354. var newDataIndexMap = {};
  25355. var oldDataKeyArr = [];
  25356. var newDataKeyArr = [];
  25357. var i;
  25358. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  25359. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  25360. // Travel by inverted order to make sure order consistency
  25361. // when duplicate keys exists (consider newDataIndex.pop() below).
  25362. // For performance consideration, these code below do not look neat.
  25363. for (i = 0; i < oldArr.length; i++) {
  25364. var key = oldDataKeyArr[i];
  25365. var idx = newDataIndexMap[key];
  25366. // idx can never be empty array here. see 'set null' logic below.
  25367. if (idx != null) {
  25368. // Consider there is duplicate key (for example, use dataItem.name as key).
  25369. // We should make sure every item in newArr and oldArr can be visited.
  25370. var len = idx.length;
  25371. if (len) {
  25372. len === 1 && (newDataIndexMap[key] = null);
  25373. idx = idx.unshift();
  25374. }
  25375. else {
  25376. newDataIndexMap[key] = null;
  25377. }
  25378. this._update && this._update(idx, i);
  25379. }
  25380. else {
  25381. this._remove && this._remove(i);
  25382. }
  25383. }
  25384. for (var i = 0; i < newDataKeyArr.length; i++) {
  25385. var key = newDataKeyArr[i];
  25386. if (newDataIndexMap.hasOwnProperty(key)) {
  25387. var idx = newDataIndexMap[key];
  25388. if (idx == null) {
  25389. continue;
  25390. }
  25391. // idx can never be empty array here. see 'set null' logic above.
  25392. if (!idx.length) {
  25393. this._add && this._add(idx);
  25394. }
  25395. else {
  25396. for (var j = 0, len = idx.length; j < len; j++) {
  25397. this._add && this._add(idx[j]);
  25398. }
  25399. }
  25400. }
  25401. }
  25402. }
  25403. };
  25404. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  25405. for (var i = 0; i < arr.length; i++) {
  25406. // Add prefix to avoid conflict with Object.prototype.
  25407. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  25408. var existence = map[key];
  25409. if (existence == null) {
  25410. keyArr.push(key);
  25411. map[key] = i;
  25412. }
  25413. else {
  25414. if (!existence.length) {
  25415. map[key] = existence = [existence];
  25416. }
  25417. existence.push(i);
  25418. }
  25419. }
  25420. }
  25421. /*
  25422. * Licensed to the Apache Software Foundation (ASF) under one
  25423. * or more contributor license agreements. See the NOTICE file
  25424. * distributed with this work for additional information
  25425. * regarding copyright ownership. The ASF licenses this file
  25426. * to you under the Apache License, Version 2.0 (the
  25427. * "License"); you may not use this file except in compliance
  25428. * with the License. You may obtain a copy of the License at
  25429. *
  25430. * http://www.apache.org/licenses/LICENSE-2.0
  25431. *
  25432. * Unless required by applicable law or agreed to in writing,
  25433. * software distributed under the License is distributed on an
  25434. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25435. * KIND, either express or implied. See the License for the
  25436. * specific language governing permissions and limitations
  25437. * under the License.
  25438. */
  25439. var OTHER_DIMENSIONS = createHashMap([
  25440. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  25441. ]);
  25442. function summarizeDimensions(data) {
  25443. var summary = {};
  25444. var encode = summary.encode = {};
  25445. var notExtraCoordDimMap = createHashMap();
  25446. var defaultedLabel = [];
  25447. var defaultedTooltip = [];
  25448. each$1(data.dimensions, function (dimName) {
  25449. var dimItem = data.getDimensionInfo(dimName);
  25450. var coordDim = dimItem.coordDim;
  25451. if (coordDim) {
  25452. if (__DEV__) {
  25453. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  25454. }
  25455. var coordDimArr = encode[coordDim];
  25456. if (!encode.hasOwnProperty(coordDim)) {
  25457. coordDimArr = encode[coordDim] = [];
  25458. }
  25459. coordDimArr[dimItem.coordDimIndex] = dimName;
  25460. if (!dimItem.isExtraCoord) {
  25461. notExtraCoordDimMap.set(coordDim, 1);
  25462. // Use the last coord dim (and label friendly) as default label,
  25463. // because when dataset is used, it is hard to guess which dimension
  25464. // can be value dimension. If both show x, y on label is not look good,
  25465. // and conventionally y axis is focused more.
  25466. if (mayLabelDimType(dimItem.type)) {
  25467. defaultedLabel[0] = dimName;
  25468. }
  25469. }
  25470. if (dimItem.defaultTooltip) {
  25471. defaultedTooltip.push(dimName);
  25472. }
  25473. }
  25474. OTHER_DIMENSIONS.each(function (v, otherDim) {
  25475. var otherDimArr = encode[otherDim];
  25476. if (!encode.hasOwnProperty(otherDim)) {
  25477. otherDimArr = encode[otherDim] = [];
  25478. }
  25479. var dimIndex = dimItem.otherDims[otherDim];
  25480. if (dimIndex != null && dimIndex !== false) {
  25481. otherDimArr[dimIndex] = dimItem.name;
  25482. }
  25483. });
  25484. });
  25485. var dataDimsOnCoord = [];
  25486. var encodeFirstDimNotExtra = {};
  25487. notExtraCoordDimMap.each(function (v, coordDim) {
  25488. var dimArr = encode[coordDim];
  25489. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  25490. // But should fix the case that radar axes: simplify the logic
  25491. // of `completeDimension`, remove `extraPrefix`.
  25492. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  25493. // Not necessary to remove duplicate, because a data
  25494. // dim canot on more than one coordDim.
  25495. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  25496. });
  25497. summary.dataDimsOnCoord = dataDimsOnCoord;
  25498. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  25499. var encodeLabel = encode.label;
  25500. // FIXME `encode.label` is not recommanded, because formatter can not be set
  25501. // in this way. Use label.formatter instead. May be remove this approach someday.
  25502. if (encodeLabel && encodeLabel.length) {
  25503. defaultedLabel = encodeLabel.slice();
  25504. }
  25505. var encodeTooltip = encode.tooltip;
  25506. if (encodeTooltip && encodeTooltip.length) {
  25507. defaultedTooltip = encodeTooltip.slice();
  25508. }
  25509. else if (!defaultedTooltip.length) {
  25510. defaultedTooltip = defaultedLabel.slice();
  25511. }
  25512. encode.defaultedLabel = defaultedLabel;
  25513. encode.defaultedTooltip = defaultedTooltip;
  25514. return summary;
  25515. }
  25516. function getDimensionTypeByAxis(axisType) {
  25517. return axisType === 'category'
  25518. ? 'ordinal'
  25519. : axisType === 'time'
  25520. ? 'time'
  25521. : 'float';
  25522. }
  25523. function mayLabelDimType(dimType) {
  25524. // In most cases, ordinal and time do not suitable for label.
  25525. // Ordinal info can be displayed on axis. Time is too long.
  25526. return !(dimType === 'ordinal' || dimType === 'time');
  25527. }
  25528. // function findTheLastDimMayLabel(data) {
  25529. // // Get last value dim
  25530. // var dimensions = data.dimensions.slice();
  25531. // var valueType;
  25532. // var valueDim;
  25533. // while (dimensions.length && (
  25534. // valueDim = dimensions.pop(),
  25535. // valueType = data.getDimensionInfo(valueDim).type,
  25536. // valueType === 'ordinal' || valueType === 'time'
  25537. // )) {} // jshint ignore:line
  25538. // return valueDim;
  25539. // }
  25540. /*
  25541. * Licensed to the Apache Software Foundation (ASF) under one
  25542. * or more contributor license agreements. See the NOTICE file
  25543. * distributed with this work for additional information
  25544. * regarding copyright ownership. The ASF licenses this file
  25545. * to you under the Apache License, Version 2.0 (the
  25546. * "License"); you may not use this file except in compliance
  25547. * with the License. You may obtain a copy of the License at
  25548. *
  25549. * http://www.apache.org/licenses/LICENSE-2.0
  25550. *
  25551. * Unless required by applicable law or agreed to in writing,
  25552. * software distributed under the License is distributed on an
  25553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25554. * KIND, either express or implied. See the License for the
  25555. * specific language governing permissions and limitations
  25556. * under the License.
  25557. */
  25558. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  25559. /**
  25560. * List for data storage
  25561. * @module echarts/data/List
  25562. */
  25563. var isObject$4 = isObject$1;
  25564. var UNDEFINED = 'undefined';
  25565. var INDEX_NOT_FOUND = -1;
  25566. // Use prefix to avoid index to be the same as otherIdList[idx],
  25567. // which will cause weird udpate animation.
  25568. var ID_PREFIX = 'e\0\0';
  25569. var dataCtors = {
  25570. 'float': typeof Float64Array === UNDEFINED
  25571. ? Array : Float64Array,
  25572. 'int': typeof Int32Array === UNDEFINED
  25573. ? Array : Int32Array,
  25574. // Ordinal data type can be string or int
  25575. 'ordinal': Array,
  25576. 'number': Array,
  25577. 'time': Array
  25578. };
  25579. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  25580. // different from the Ctor of typed array.
  25581. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  25582. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  25583. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  25584. function getIndicesCtor(list) {
  25585. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  25586. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  25587. }
  25588. function cloneChunk(originalChunk) {
  25589. var Ctor = originalChunk.constructor;
  25590. // Only shallow clone is enough when Array.
  25591. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  25592. }
  25593. var TRANSFERABLE_PROPERTIES = [
  25594. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  25595. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  25596. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  25597. ];
  25598. var CLONE_PROPERTIES = [
  25599. '_extent', '_approximateExtent', '_rawExtent'
  25600. ];
  25601. function transferProperties(target, source) {
  25602. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  25603. if (source.hasOwnProperty(propName)) {
  25604. target[propName] = source[propName];
  25605. }
  25606. });
  25607. target.__wrappedMethods = source.__wrappedMethods;
  25608. each$1(CLONE_PROPERTIES, function (propName) {
  25609. target[propName] = clone(source[propName]);
  25610. });
  25611. target._calculationInfo = extend(source._calculationInfo);
  25612. }
  25613. /**
  25614. * @constructor
  25615. * @alias module:echarts/data/List
  25616. *
  25617. * @param {Array.<string|Object>} dimensions
  25618. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  25619. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  25620. * Spetial fields: {
  25621. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  25622. * createInvertedIndices: <boolean>
  25623. * }
  25624. * @param {module:echarts/model/Model} hostModel
  25625. */
  25626. var List = function (dimensions, hostModel) {
  25627. dimensions = dimensions || ['x', 'y'];
  25628. var dimensionInfos = {};
  25629. var dimensionNames = [];
  25630. var invertedIndicesMap = {};
  25631. for (var i = 0; i < dimensions.length; i++) {
  25632. // Use the original dimensions[i], where other flag props may exists.
  25633. var dimensionInfo = dimensions[i];
  25634. if (isString(dimensionInfo)) {
  25635. dimensionInfo = {name: dimensionInfo};
  25636. }
  25637. var dimensionName = dimensionInfo.name;
  25638. dimensionInfo.type = dimensionInfo.type || 'float';
  25639. if (!dimensionInfo.coordDim) {
  25640. dimensionInfo.coordDim = dimensionName;
  25641. dimensionInfo.coordDimIndex = 0;
  25642. }
  25643. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  25644. dimensionNames.push(dimensionName);
  25645. dimensionInfos[dimensionName] = dimensionInfo;
  25646. dimensionInfo.index = i;
  25647. if (dimensionInfo.createInvertedIndices) {
  25648. invertedIndicesMap[dimensionName] = [];
  25649. }
  25650. }
  25651. /**
  25652. * @readOnly
  25653. * @type {Array.<string>}
  25654. */
  25655. this.dimensions = dimensionNames;
  25656. /**
  25657. * Infomation of each data dimension, like data type.
  25658. * @type {Object}
  25659. */
  25660. this._dimensionInfos = dimensionInfos;
  25661. /**
  25662. * @type {module:echarts/model/Model}
  25663. */
  25664. this.hostModel = hostModel;
  25665. /**
  25666. * @type {module:echarts/model/Model}
  25667. */
  25668. this.dataType;
  25669. /**
  25670. * Indices stores the indices of data subset after filtered.
  25671. * This data subset will be used in chart.
  25672. * @type {Array.<number>}
  25673. * @readOnly
  25674. */
  25675. this._indices = null;
  25676. this._count = 0;
  25677. this._rawCount = 0;
  25678. /**
  25679. * Data storage
  25680. * @type {Object.<key, Array.<TypedArray|Array>>}
  25681. * @private
  25682. */
  25683. this._storage = {};
  25684. /**
  25685. * @type {Array.<string>}
  25686. */
  25687. this._nameList = [];
  25688. /**
  25689. * @type {Array.<string>}
  25690. */
  25691. this._idList = [];
  25692. /**
  25693. * Models of data option is stored sparse for optimizing memory cost
  25694. * @type {Array.<module:echarts/model/Model>}
  25695. * @private
  25696. */
  25697. this._optionModels = [];
  25698. /**
  25699. * Global visual properties after visual coding
  25700. * @type {Object}
  25701. * @private
  25702. */
  25703. this._visual = {};
  25704. /**
  25705. * Globel layout properties.
  25706. * @type {Object}
  25707. * @private
  25708. */
  25709. this._layout = {};
  25710. /**
  25711. * Item visual properties after visual coding
  25712. * @type {Array.<Object>}
  25713. * @private
  25714. */
  25715. this._itemVisuals = [];
  25716. /**
  25717. * Key: visual type, Value: boolean
  25718. * @type {Object}
  25719. * @readOnly
  25720. */
  25721. this.hasItemVisual = {};
  25722. /**
  25723. * Item layout properties after layout
  25724. * @type {Array.<Object>}
  25725. * @private
  25726. */
  25727. this._itemLayouts = [];
  25728. /**
  25729. * Graphic elemnents
  25730. * @type {Array.<module:zrender/Element>}
  25731. * @private
  25732. */
  25733. this._graphicEls = [];
  25734. /**
  25735. * Max size of each chunk.
  25736. * @type {number}
  25737. * @private
  25738. */
  25739. this._chunkSize = 1e5;
  25740. /**
  25741. * @type {number}
  25742. * @private
  25743. */
  25744. this._chunkCount = 0;
  25745. /**
  25746. * @type {Array.<Array|Object>}
  25747. * @private
  25748. */
  25749. this._rawData;
  25750. /**
  25751. * Raw extent will not be cloned, but only transfered.
  25752. * It will not be calculated util needed.
  25753. * key: dim,
  25754. * value: {end: number, extent: Array.<number>}
  25755. * @type {Object}
  25756. * @private
  25757. */
  25758. this._rawExtent = {};
  25759. /**
  25760. * @type {Object}
  25761. * @private
  25762. */
  25763. this._extent = {};
  25764. /**
  25765. * key: dim
  25766. * value: extent
  25767. * @type {Object}
  25768. * @private
  25769. */
  25770. this._approximateExtent = {};
  25771. /**
  25772. * Cache summary info for fast visit. See "dimensionHelper".
  25773. * @type {Object}
  25774. * @private
  25775. */
  25776. this._dimensionsSummary = summarizeDimensions(this);
  25777. /**
  25778. * @type {Object.<Array|TypedArray>}
  25779. * @private
  25780. */
  25781. this._invertedIndicesMap = invertedIndicesMap;
  25782. /**
  25783. * @type {Object}
  25784. * @private
  25785. */
  25786. this._calculationInfo = {};
  25787. };
  25788. var listProto = List.prototype;
  25789. listProto.type = 'list';
  25790. /**
  25791. * If each data item has it's own option
  25792. * @type {boolean}
  25793. */
  25794. listProto.hasItemOption = true;
  25795. /**
  25796. * Get dimension name
  25797. * @param {string|number} dim
  25798. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25799. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25800. * @return {string} Concrete dim name.
  25801. */
  25802. listProto.getDimension = function (dim) {
  25803. if (!isNaN(dim)) {
  25804. dim = this.dimensions[dim] || dim;
  25805. }
  25806. return dim;
  25807. };
  25808. /**
  25809. * Get type and calculation info of particular dimension
  25810. * @param {string|number} dim
  25811. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25812. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25813. */
  25814. listProto.getDimensionInfo = function (dim) {
  25815. // Do not clone, because there may be categories in dimInfo.
  25816. return this._dimensionInfos[this.getDimension(dim)];
  25817. };
  25818. /**
  25819. * @return {Array.<string>} concrete dimension name list on coord.
  25820. */
  25821. listProto.getDimensionsOnCoord = function () {
  25822. return this._dimensionsSummary.dataDimsOnCoord.slice();
  25823. };
  25824. /**
  25825. * @param {string} coordDim
  25826. * @param {number} [idx] A coordDim may map to more than one data dim.
  25827. * If idx is `true`, return a array of all mapped dims.
  25828. * If idx is not specified, return the first dim not extra.
  25829. * @return {string|Array.<string>} concrete data dim.
  25830. * If idx is number, and not found, return null/undefined.
  25831. * If idx is `true`, and not found, return empty array (always return array).
  25832. */
  25833. listProto.mapDimension = function (coordDim, idx) {
  25834. var dimensionsSummary = this._dimensionsSummary;
  25835. if (idx == null) {
  25836. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  25837. }
  25838. var dims = dimensionsSummary.encode[coordDim];
  25839. return idx === true
  25840. // always return array if idx is `true`
  25841. ? (dims || []).slice()
  25842. : (dims && dims[idx]);
  25843. };
  25844. /**
  25845. * Initialize from data
  25846. * @param {Array.<Object|number|Array>} data source or data or data provider.
  25847. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  25848. * defualt label/tooltip.
  25849. * A name can be specified in encode.itemName,
  25850. * or dataItem.name (only for series option data),
  25851. * or provided in nameList from outside.
  25852. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  25853. */
  25854. listProto.initData = function (data, nameList, dimValueGetter) {
  25855. var notProvider = Source.isInstance(data) || isArrayLike(data);
  25856. if (notProvider) {
  25857. data = new DefaultDataProvider(data, this.dimensions.length);
  25858. }
  25859. if (__DEV__) {
  25860. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  25861. throw new Error('Inavlid data provider.');
  25862. }
  25863. }
  25864. this._rawData = data;
  25865. // Clear
  25866. this._storage = {};
  25867. this._indices = null;
  25868. this._nameList = nameList || [];
  25869. this._idList = [];
  25870. this._nameRepeatCount = {};
  25871. if (!dimValueGetter) {
  25872. this.hasItemOption = false;
  25873. }
  25874. /**
  25875. * @readOnly
  25876. */
  25877. this.defaultDimValueGetter = defaultDimValueGetters[
  25878. this._rawData.getSource().sourceFormat
  25879. ];
  25880. // Default dim value getter
  25881. this._dimValueGetter = dimValueGetter = dimValueGetter
  25882. || this.defaultDimValueGetter;
  25883. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  25884. // Reset raw extent.
  25885. this._rawExtent = {};
  25886. this._initDataFromProvider(0, data.count());
  25887. // If data has no item option.
  25888. if (data.pure) {
  25889. this.hasItemOption = false;
  25890. }
  25891. };
  25892. listProto.getProvider = function () {
  25893. return this._rawData;
  25894. };
  25895. /**
  25896. * Caution: Can be only called on raw data (before `this._indices` created).
  25897. */
  25898. listProto.appendData = function (data) {
  25899. if (__DEV__) {
  25900. assert$1(!this._indices, 'appendData can only be called on raw data.');
  25901. }
  25902. var rawData = this._rawData;
  25903. var start = this.count();
  25904. rawData.appendData(data);
  25905. var end = rawData.count();
  25906. if (!rawData.persistent) {
  25907. end += start;
  25908. }
  25909. this._initDataFromProvider(start, end);
  25910. };
  25911. /**
  25912. * Caution: Can be only called on raw data (before `this._indices` created).
  25913. * This method does not modify `rawData` (`dataProvider`), but only
  25914. * add values to storage.
  25915. *
  25916. * The final count will be increased by `Math.max(values.length, names.length)`.
  25917. *
  25918. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  25919. * [
  25920. * [12, 33, 44],
  25921. * [NaN, 43, 1],
  25922. * ['-', 'asdf', 0]
  25923. * ]
  25924. * Each item is exaclty cooresponding to a dimension.
  25925. * @param {Array.<string>} [names]
  25926. */
  25927. listProto.appendValues = function (values, names) {
  25928. var chunkSize = this._chunkSize;
  25929. var storage = this._storage;
  25930. var dimensions = this.dimensions;
  25931. var dimLen = dimensions.length;
  25932. var rawExtent = this._rawExtent;
  25933. var start = this.count();
  25934. var end = start + Math.max(values.length, names ? names.length : 0);
  25935. var originalChunkCount = this._chunkCount;
  25936. for (var i = 0; i < dimLen; i++) {
  25937. var dim = dimensions[i];
  25938. if (!rawExtent[dim]) {
  25939. rawExtent[dim] = getInitialExtent();
  25940. }
  25941. if (!storage[dim]) {
  25942. storage[dim] = [];
  25943. }
  25944. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  25945. this._chunkCount = storage[dim].length;
  25946. }
  25947. var emptyDataItem = new Array(dimLen);
  25948. for (var idx = start; idx < end; idx++) {
  25949. var sourceIdx = idx - start;
  25950. var chunkIndex = Math.floor(idx / chunkSize);
  25951. var chunkOffset = idx % chunkSize;
  25952. // Store the data by dimensions
  25953. for (var k = 0; k < dimLen; k++) {
  25954. var dim = dimensions[k];
  25955. var val = this._dimValueGetterArrayRows(
  25956. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  25957. );
  25958. storage[dim][chunkIndex][chunkOffset] = val;
  25959. var dimRawExtent = rawExtent[dim];
  25960. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  25961. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  25962. }
  25963. if (names) {
  25964. this._nameList[idx] = names[sourceIdx];
  25965. }
  25966. }
  25967. this._rawCount = this._count = end;
  25968. // Reset data extent
  25969. this._extent = {};
  25970. prepareInvertedIndex(this);
  25971. };
  25972. listProto._initDataFromProvider = function (start, end) {
  25973. // Optimize.
  25974. if (start >= end) {
  25975. return;
  25976. }
  25977. var chunkSize = this._chunkSize;
  25978. var rawData = this._rawData;
  25979. var storage = this._storage;
  25980. var dimensions = this.dimensions;
  25981. var dimLen = dimensions.length;
  25982. var dimensionInfoMap = this._dimensionInfos;
  25983. var nameList = this._nameList;
  25984. var idList = this._idList;
  25985. var rawExtent = this._rawExtent;
  25986. var nameRepeatCount = this._nameRepeatCount = {};
  25987. var nameDimIdx;
  25988. var originalChunkCount = this._chunkCount;
  25989. for (var i = 0; i < dimLen; i++) {
  25990. var dim = dimensions[i];
  25991. if (!rawExtent[dim]) {
  25992. rawExtent[dim] = getInitialExtent();
  25993. }
  25994. var dimInfo = dimensionInfoMap[dim];
  25995. if (dimInfo.otherDims.itemName === 0) {
  25996. nameDimIdx = this._nameDimIdx = i;
  25997. }
  25998. if (dimInfo.otherDims.itemId === 0) {
  25999. this._idDimIdx = i;
  26000. }
  26001. if (!storage[dim]) {
  26002. storage[dim] = [];
  26003. }
  26004. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  26005. this._chunkCount = storage[dim].length;
  26006. }
  26007. var dataItem = new Array(dimLen);
  26008. for (var idx = start; idx < end; idx++) {
  26009. // NOTICE: Try not to write things into dataItem
  26010. dataItem = rawData.getItem(idx, dataItem);
  26011. // Each data item is value
  26012. // [1, 2]
  26013. // 2
  26014. // Bar chart, line chart which uses category axis
  26015. // only gives the 'y' value. 'x' value is the indices of category
  26016. // Use a tempValue to normalize the value to be a (x, y) value
  26017. var chunkIndex = Math.floor(idx / chunkSize);
  26018. var chunkOffset = idx % chunkSize;
  26019. // Store the data by dimensions
  26020. for (var k = 0; k < dimLen; k++) {
  26021. var dim = dimensions[k];
  26022. var dimStorage = storage[dim][chunkIndex];
  26023. // PENDING NULL is empty or zero
  26024. var val = this._dimValueGetter(dataItem, dim, idx, k);
  26025. dimStorage[chunkOffset] = val;
  26026. var dimRawExtent = rawExtent[dim];
  26027. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26028. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26029. }
  26030. // ??? FIXME not check by pure but sourceFormat?
  26031. // TODO refactor these logic.
  26032. if (!rawData.pure) {
  26033. var name = nameList[idx];
  26034. if (dataItem && name == null) {
  26035. // If dataItem is {name: ...}, it has highest priority.
  26036. // That is appropriate for many common cases.
  26037. if (dataItem.name != null) {
  26038. // There is no other place to persistent dataItem.name,
  26039. // so save it to nameList.
  26040. nameList[idx] = name = dataItem.name;
  26041. }
  26042. else if (nameDimIdx != null) {
  26043. var nameDim = dimensions[nameDimIdx];
  26044. var nameDimChunk = storage[nameDim][chunkIndex];
  26045. if (nameDimChunk) {
  26046. name = nameDimChunk[chunkOffset];
  26047. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  26048. if (ordinalMeta && ordinalMeta.categories.length) {
  26049. name = ordinalMeta.categories[name];
  26050. }
  26051. }
  26052. }
  26053. }
  26054. // Try using the id in option
  26055. // id or name is used on dynamical data, mapping old and new items.
  26056. var id = dataItem == null ? null : dataItem.id;
  26057. if (id == null && name != null) {
  26058. // Use name as id and add counter to avoid same name
  26059. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  26060. id = name;
  26061. if (nameRepeatCount[name] > 0) {
  26062. id += '__ec__' + nameRepeatCount[name];
  26063. }
  26064. nameRepeatCount[name]++;
  26065. }
  26066. id != null && (idList[idx] = id);
  26067. }
  26068. }
  26069. if (!rawData.persistent && rawData.clean) {
  26070. // Clean unused data if data source is typed array.
  26071. rawData.clean();
  26072. }
  26073. this._rawCount = this._count = end;
  26074. // Reset data extent
  26075. this._extent = {};
  26076. prepareInvertedIndex(this);
  26077. };
  26078. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  26079. var DataCtor = dataCtors[dimInfo.type];
  26080. var lastChunkIndex = chunkCount - 1;
  26081. var dim = dimInfo.name;
  26082. var resizeChunkArray = storage[dim][lastChunkIndex];
  26083. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  26084. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  26085. // The cost of the copy is probably inconsiderable
  26086. // within the initial chunkSize.
  26087. for (var j = 0; j < resizeChunkArray.length; j++) {
  26088. newStore[j] = resizeChunkArray[j];
  26089. }
  26090. storage[dim][lastChunkIndex] = newStore;
  26091. }
  26092. // Create new chunks.
  26093. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  26094. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  26095. }
  26096. }
  26097. function prepareInvertedIndex(list) {
  26098. var invertedIndicesMap = list._invertedIndicesMap;
  26099. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  26100. var dimInfo = list._dimensionInfos[dim];
  26101. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  26102. var ordinalMeta = dimInfo.ordinalMeta;
  26103. if (ordinalMeta) {
  26104. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  26105. ordinalMeta.categories.length
  26106. );
  26107. // The default value of TypedArray is 0. To avoid miss
  26108. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  26109. for (var i = 0; i < invertedIndices.length; i++) {
  26110. invertedIndices[i] = INDEX_NOT_FOUND;
  26111. }
  26112. for (var i = 0; i < list._count; i++) {
  26113. // Only support the case that all values are distinct.
  26114. invertedIndices[list.get(dim, i)] = i;
  26115. }
  26116. }
  26117. });
  26118. }
  26119. function getRawValueFromStore(list, dimIndex, rawIndex) {
  26120. var val;
  26121. if (dimIndex != null) {
  26122. var chunkSize = list._chunkSize;
  26123. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26124. var chunkOffset = rawIndex % chunkSize;
  26125. var dim = list.dimensions[dimIndex];
  26126. var chunk = list._storage[dim][chunkIndex];
  26127. if (chunk) {
  26128. val = chunk[chunkOffset];
  26129. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  26130. if (ordinalMeta && ordinalMeta.categories.length) {
  26131. val = ordinalMeta.categories[val];
  26132. }
  26133. }
  26134. }
  26135. return val;
  26136. }
  26137. /**
  26138. * @return {number}
  26139. */
  26140. listProto.count = function () {
  26141. return this._count;
  26142. };
  26143. listProto.getIndices = function () {
  26144. var newIndices;
  26145. var indices = this._indices;
  26146. if (indices) {
  26147. var Ctor = indices.constructor;
  26148. var thisCount = this._count;
  26149. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  26150. if (Ctor === Array) {
  26151. newIndices = new Ctor(thisCount);
  26152. for (var i = 0; i < thisCount; i++) {
  26153. newIndices[i] = indices[i];
  26154. }
  26155. }
  26156. else {
  26157. newIndices = new Ctor(indices.buffer, 0, thisCount);
  26158. }
  26159. }
  26160. else {
  26161. var Ctor = getIndicesCtor(this);
  26162. var newIndices = new Ctor(this.count());
  26163. for (var i = 0; i < newIndices.length; i++) {
  26164. newIndices[i] = i;
  26165. }
  26166. }
  26167. return newIndices;
  26168. };
  26169. /**
  26170. * Get value. Return NaN if idx is out of range.
  26171. * @param {string} dim Dim must be concrete name.
  26172. * @param {number} idx
  26173. * @param {boolean} stack
  26174. * @return {number}
  26175. */
  26176. listProto.get = function (dim, idx /*, stack */) {
  26177. if (!(idx >= 0 && idx < this._count)) {
  26178. return NaN;
  26179. }
  26180. var storage = this._storage;
  26181. if (!storage[dim]) {
  26182. // TODO Warn ?
  26183. return NaN;
  26184. }
  26185. idx = this.getRawIndex(idx);
  26186. var chunkIndex = Math.floor(idx / this._chunkSize);
  26187. var chunkOffset = idx % this._chunkSize;
  26188. var chunkStore = storage[dim][chunkIndex];
  26189. var value = chunkStore[chunkOffset];
  26190. // FIXME ordinal data type is not stackable
  26191. // if (stack) {
  26192. // var dimensionInfo = this._dimensionInfos[dim];
  26193. // if (dimensionInfo && dimensionInfo.stackable) {
  26194. // var stackedOn = this.stackedOn;
  26195. // while (stackedOn) {
  26196. // // Get no stacked data of stacked on
  26197. // var stackedValue = stackedOn.get(dim, idx);
  26198. // // Considering positive stack, negative stack and empty data
  26199. // if ((value >= 0 && stackedValue > 0) // Positive stack
  26200. // || (value <= 0 && stackedValue < 0) // Negative stack
  26201. // ) {
  26202. // value += stackedValue;
  26203. // }
  26204. // stackedOn = stackedOn.stackedOn;
  26205. // }
  26206. // }
  26207. // }
  26208. return value;
  26209. };
  26210. /**
  26211. * @param {string} dim concrete dim
  26212. * @param {number} rawIndex
  26213. * @return {number|string}
  26214. */
  26215. listProto.getByRawIndex = function (dim, rawIdx) {
  26216. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  26217. return NaN;
  26218. }
  26219. var dimStore = this._storage[dim];
  26220. if (!dimStore) {
  26221. // TODO Warn ?
  26222. return NaN;
  26223. }
  26224. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26225. var chunkOffset = rawIdx % this._chunkSize;
  26226. var chunkStore = dimStore[chunkIndex];
  26227. return chunkStore[chunkOffset];
  26228. };
  26229. /**
  26230. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  26231. * Hack a much simpler _getFast
  26232. * @private
  26233. */
  26234. listProto._getFast = function (dim, rawIdx) {
  26235. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26236. var chunkOffset = rawIdx % this._chunkSize;
  26237. var chunkStore = this._storage[dim][chunkIndex];
  26238. return chunkStore[chunkOffset];
  26239. };
  26240. /**
  26241. * Get value for multi dimensions.
  26242. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  26243. * @param {number} idx
  26244. * @return {number}
  26245. */
  26246. listProto.getValues = function (dimensions, idx /*, stack */) {
  26247. var values = [];
  26248. if (!isArray(dimensions)) {
  26249. // stack = idx;
  26250. idx = dimensions;
  26251. dimensions = this.dimensions;
  26252. }
  26253. for (var i = 0, len = dimensions.length; i < len; i++) {
  26254. values.push(this.get(dimensions[i], idx /*, stack */));
  26255. }
  26256. return values;
  26257. };
  26258. /**
  26259. * If value is NaN. Inlcuding '-'
  26260. * Only check the coord dimensions.
  26261. * @param {string} dim
  26262. * @param {number} idx
  26263. * @return {number}
  26264. */
  26265. listProto.hasValue = function (idx) {
  26266. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  26267. var dimensionInfos = this._dimensionInfos;
  26268. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  26269. if (
  26270. // Ordinal type can be string or number
  26271. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  26272. // FIXME check ordinal when using index?
  26273. && isNaN(this.get(dataDimsOnCoord[i], idx))
  26274. ) {
  26275. return false;
  26276. }
  26277. }
  26278. return true;
  26279. };
  26280. /**
  26281. * Get extent of data in one dimension
  26282. * @param {string} dim
  26283. * @param {boolean} stack
  26284. */
  26285. listProto.getDataExtent = function (dim /*, stack */) {
  26286. // Make sure use concrete dim as cache name.
  26287. dim = this.getDimension(dim);
  26288. var dimData = this._storage[dim];
  26289. var initialExtent = getInitialExtent();
  26290. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  26291. if (!dimData) {
  26292. return initialExtent;
  26293. }
  26294. // Make more strict checkings to ensure hitting cache.
  26295. var currEnd = this.count();
  26296. // var cacheName = [dim, !!stack].join('_');
  26297. // var cacheName = dim;
  26298. // Consider the most cases when using data zoom, `getDataExtent`
  26299. // happened before filtering. We cache raw extent, which is not
  26300. // necessary to be cleared and recalculated when restore data.
  26301. var useRaw = !this._indices; // && !stack;
  26302. var dimExtent;
  26303. if (useRaw) {
  26304. return this._rawExtent[dim].slice();
  26305. }
  26306. dimExtent = this._extent[dim];
  26307. if (dimExtent) {
  26308. return dimExtent.slice();
  26309. }
  26310. dimExtent = initialExtent;
  26311. var min = dimExtent[0];
  26312. var max = dimExtent[1];
  26313. for (var i = 0; i < currEnd; i++) {
  26314. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  26315. var value = this._getFast(dim, this.getRawIndex(i));
  26316. value < min && (min = value);
  26317. value > max && (max = value);
  26318. }
  26319. dimExtent = [min, max];
  26320. this._extent[dim] = dimExtent;
  26321. return dimExtent;
  26322. };
  26323. /**
  26324. * Optimize for the scenario that data is filtered by a given extent.
  26325. * Consider that if data amount is more than hundreds of thousand,
  26326. * extent calculation will cost more than 10ms and the cache will
  26327. * be erased because of the filtering.
  26328. */
  26329. listProto.getApproximateExtent = function (dim /*, stack */) {
  26330. dim = this.getDimension(dim);
  26331. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  26332. };
  26333. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  26334. dim = this.getDimension(dim);
  26335. this._approximateExtent[dim] = extent.slice();
  26336. };
  26337. /**
  26338. * @param {string} key
  26339. * @return {*}
  26340. */
  26341. listProto.getCalculationInfo = function (key) {
  26342. return this._calculationInfo[key];
  26343. };
  26344. /**
  26345. * @param {string|Object} key or k-v object
  26346. * @param {*} [value]
  26347. */
  26348. listProto.setCalculationInfo = function (key, value) {
  26349. isObject$4(key)
  26350. ? extend(this._calculationInfo, key)
  26351. : (this._calculationInfo[key] = value);
  26352. };
  26353. /**
  26354. * Get sum of data in one dimension
  26355. * @param {string} dim
  26356. */
  26357. listProto.getSum = function (dim /*, stack */) {
  26358. var dimData = this._storage[dim];
  26359. var sum = 0;
  26360. if (dimData) {
  26361. for (var i = 0, len = this.count(); i < len; i++) {
  26362. var value = this.get(dim, i /*, stack */);
  26363. if (!isNaN(value)) {
  26364. sum += value;
  26365. }
  26366. }
  26367. }
  26368. return sum;
  26369. };
  26370. /**
  26371. * Get median of data in one dimension
  26372. * @param {string} dim
  26373. */
  26374. listProto.getMedian = function (dim /*, stack */) {
  26375. var dimDataArray = [];
  26376. // map all data of one dimension
  26377. this.each(dim, function (val, idx) {
  26378. if (!isNaN(val)) {
  26379. dimDataArray.push(val);
  26380. }
  26381. });
  26382. // TODO
  26383. // Use quick select?
  26384. // immutability & sort
  26385. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  26386. return a - b;
  26387. });
  26388. var len = this.count();
  26389. // calculate median
  26390. return len === 0
  26391. ? 0
  26392. : len % 2 === 1
  26393. ? sortedDimDataArray[(len - 1) / 2]
  26394. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  26395. };
  26396. // /**
  26397. // * Retreive the index with given value
  26398. // * @param {string} dim Concrete dimension.
  26399. // * @param {number} value
  26400. // * @return {number}
  26401. // */
  26402. // Currently incorrect: should return dataIndex but not rawIndex.
  26403. // Do not fix it until this method is to be used somewhere.
  26404. // FIXME Precision of float value
  26405. // listProto.indexOf = function (dim, value) {
  26406. // var storage = this._storage;
  26407. // var dimData = storage[dim];
  26408. // var chunkSize = this._chunkSize;
  26409. // if (dimData) {
  26410. // for (var i = 0, len = this.count(); i < len; i++) {
  26411. // var chunkIndex = Math.floor(i / chunkSize);
  26412. // var chunkOffset = i % chunkSize;
  26413. // if (dimData[chunkIndex][chunkOffset] === value) {
  26414. // return i;
  26415. // }
  26416. // }
  26417. // }
  26418. // return -1;
  26419. // };
  26420. /**
  26421. * Only support the dimension which inverted index created.
  26422. * Do not support other cases until required.
  26423. * @param {string} concrete dim
  26424. * @param {number|string} value
  26425. * @return {number} rawIndex
  26426. */
  26427. listProto.rawIndexOf = function (dim, value) {
  26428. var invertedIndices = dim && this._invertedIndicesMap[dim];
  26429. if (__DEV__) {
  26430. if (!invertedIndices) {
  26431. throw new Error('Do not supported yet');
  26432. }
  26433. }
  26434. var rawIndex = invertedIndices[value];
  26435. if (rawIndex == null || isNaN(rawIndex)) {
  26436. return INDEX_NOT_FOUND;
  26437. }
  26438. return rawIndex;
  26439. };
  26440. /**
  26441. * Retreive the index with given name
  26442. * @param {number} idx
  26443. * @param {number} name
  26444. * @return {number}
  26445. */
  26446. listProto.indexOfName = function (name) {
  26447. for (var i = 0, len = this.count(); i < len; i++) {
  26448. if (this.getName(i) === name) {
  26449. return i;
  26450. }
  26451. }
  26452. return -1;
  26453. };
  26454. /**
  26455. * Retreive the index with given raw data index
  26456. * @param {number} idx
  26457. * @param {number} name
  26458. * @return {number}
  26459. */
  26460. listProto.indexOfRawIndex = function (rawIndex) {
  26461. if (!this._indices) {
  26462. return rawIndex;
  26463. }
  26464. if (rawIndex >= this._rawCount || rawIndex < 0) {
  26465. return -1;
  26466. }
  26467. // Indices are ascending
  26468. var indices = this._indices;
  26469. // If rawIndex === dataIndex
  26470. var rawDataIndex = indices[rawIndex];
  26471. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  26472. return rawIndex;
  26473. }
  26474. var left = 0;
  26475. var right = this._count - 1;
  26476. while (left <= right) {
  26477. var mid = (left + right) / 2 | 0;
  26478. if (indices[mid] < rawIndex) {
  26479. left = mid + 1;
  26480. }
  26481. else if (indices[mid] > rawIndex) {
  26482. right = mid - 1;
  26483. }
  26484. else {
  26485. return mid;
  26486. }
  26487. }
  26488. return -1;
  26489. };
  26490. /**
  26491. * Retreive the index of nearest value
  26492. * @param {string} dim
  26493. * @param {number} value
  26494. * @param {number} [maxDistance=Infinity]
  26495. * @return {Array.<number>} Considere multiple points has the same value.
  26496. */
  26497. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  26498. var storage = this._storage;
  26499. var dimData = storage[dim];
  26500. var nearestIndices = [];
  26501. if (!dimData) {
  26502. return nearestIndices;
  26503. }
  26504. if (maxDistance == null) {
  26505. maxDistance = Infinity;
  26506. }
  26507. var minDist = Number.MAX_VALUE;
  26508. var minDiff = -1;
  26509. for (var i = 0, len = this.count(); i < len; i++) {
  26510. var diff = value - this.get(dim, i /*, stack */);
  26511. var dist = Math.abs(diff);
  26512. if (diff <= maxDistance && dist <= minDist) {
  26513. // For the case of two data are same on xAxis, which has sequence data.
  26514. // Show the nearest index
  26515. // https://github.com/ecomfe/echarts/issues/2869
  26516. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  26517. minDist = dist;
  26518. minDiff = diff;
  26519. nearestIndices.length = 0;
  26520. }
  26521. nearestIndices.push(i);
  26522. }
  26523. }
  26524. return nearestIndices;
  26525. };
  26526. /**
  26527. * Get raw data index
  26528. * @param {number} idx
  26529. * @return {number}
  26530. */
  26531. listProto.getRawIndex = getRawIndexWithoutIndices;
  26532. function getRawIndexWithoutIndices(idx) {
  26533. return idx;
  26534. }
  26535. function getRawIndexWithIndices(idx) {
  26536. if (idx < this._count && idx >= 0) {
  26537. return this._indices[idx];
  26538. }
  26539. return -1;
  26540. }
  26541. /**
  26542. * Get raw data item
  26543. * @param {number} idx
  26544. * @return {number}
  26545. */
  26546. listProto.getRawDataItem = function (idx) {
  26547. if (!this._rawData.persistent) {
  26548. var val = [];
  26549. for (var i = 0; i < this.dimensions.length; i++) {
  26550. var dim = this.dimensions[i];
  26551. val.push(this.get(dim, idx));
  26552. }
  26553. return val;
  26554. }
  26555. else {
  26556. return this._rawData.getItem(this.getRawIndex(idx));
  26557. }
  26558. };
  26559. /**
  26560. * @param {number} idx
  26561. * @param {boolean} [notDefaultIdx=false]
  26562. * @return {string}
  26563. */
  26564. listProto.getName = function (idx) {
  26565. var rawIndex = this.getRawIndex(idx);
  26566. return this._nameList[rawIndex]
  26567. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  26568. || '';
  26569. };
  26570. /**
  26571. * @param {number} idx
  26572. * @param {boolean} [notDefaultIdx=false]
  26573. * @return {string}
  26574. */
  26575. listProto.getId = function (idx) {
  26576. return getId(this, this.getRawIndex(idx));
  26577. };
  26578. function getId(list, rawIndex) {
  26579. var id = list._idList[rawIndex];
  26580. if (id == null) {
  26581. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  26582. }
  26583. if (id == null) {
  26584. // FIXME Check the usage in graph, should not use prefix.
  26585. id = ID_PREFIX + rawIndex;
  26586. }
  26587. return id;
  26588. }
  26589. function normalizeDimensions(dimensions) {
  26590. if (!isArray(dimensions)) {
  26591. dimensions = [dimensions];
  26592. }
  26593. return dimensions;
  26594. }
  26595. function validateDimensions(list, dims) {
  26596. for (var i = 0; i < dims.length; i++) {
  26597. // stroage may be empty when no data, so use
  26598. // dimensionInfos to check.
  26599. if (!list._dimensionInfos[dims[i]]) {
  26600. console.error('Unkown dimension ' + dims[i]);
  26601. }
  26602. }
  26603. }
  26604. /**
  26605. * Data iteration
  26606. * @param {string|Array.<string>}
  26607. * @param {Function} cb
  26608. * @param {*} [context=this]
  26609. *
  26610. * @example
  26611. * list.each('x', function (x, idx) {});
  26612. * list.each(['x', 'y'], function (x, y, idx) {});
  26613. * list.each(function (idx) {})
  26614. */
  26615. listProto.each = function (dims, cb, context, contextCompat) {
  26616. 'use strict';
  26617. if (!this._count) {
  26618. return;
  26619. }
  26620. if (typeof dims === 'function') {
  26621. contextCompat = context;
  26622. context = cb;
  26623. cb = dims;
  26624. dims = [];
  26625. }
  26626. // contextCompat just for compat echarts3
  26627. context = context || contextCompat || this;
  26628. dims = map(normalizeDimensions(dims), this.getDimension, this);
  26629. if (__DEV__) {
  26630. validateDimensions(this, dims);
  26631. }
  26632. var dimSize = dims.length;
  26633. for (var i = 0; i < this.count(); i++) {
  26634. // Simple optimization
  26635. switch (dimSize) {
  26636. case 0:
  26637. cb.call(context, i);
  26638. break;
  26639. case 1:
  26640. cb.call(context, this.get(dims[0], i), i);
  26641. break;
  26642. case 2:
  26643. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  26644. break;
  26645. default:
  26646. var k = 0;
  26647. var value = [];
  26648. for (; k < dimSize; k++) {
  26649. value[k] = this.get(dims[k], i);
  26650. }
  26651. // Index
  26652. value[k] = i;
  26653. cb.apply(context, value);
  26654. }
  26655. }
  26656. };
  26657. /**
  26658. * Data filter
  26659. * @param {string|Array.<string>}
  26660. * @param {Function} cb
  26661. * @param {*} [context=this]
  26662. */
  26663. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  26664. 'use strict';
  26665. if (!this._count) {
  26666. return;
  26667. }
  26668. if (typeof dimensions === 'function') {
  26669. contextCompat = context;
  26670. context = cb;
  26671. cb = dimensions;
  26672. dimensions = [];
  26673. }
  26674. // contextCompat just for compat echarts3
  26675. context = context || contextCompat || this;
  26676. dimensions = map(
  26677. normalizeDimensions(dimensions), this.getDimension, this
  26678. );
  26679. if (__DEV__) {
  26680. validateDimensions(this, dimensions);
  26681. }
  26682. var count = this.count();
  26683. var Ctor = getIndicesCtor(this);
  26684. var newIndices = new Ctor(count);
  26685. var value = [];
  26686. var dimSize = dimensions.length;
  26687. var offset = 0;
  26688. var dim0 = dimensions[0];
  26689. for (var i = 0; i < count; i++) {
  26690. var keep;
  26691. var rawIdx = this.getRawIndex(i);
  26692. // Simple optimization
  26693. if (dimSize === 0) {
  26694. keep = cb.call(context, i);
  26695. }
  26696. else if (dimSize === 1) {
  26697. var val = this._getFast(dim0, rawIdx);
  26698. keep = cb.call(context, val, i);
  26699. }
  26700. else {
  26701. for (var k = 0; k < dimSize; k++) {
  26702. value[k] = this._getFast(dim0, rawIdx);
  26703. }
  26704. value[k] = i;
  26705. keep = cb.apply(context, value);
  26706. }
  26707. if (keep) {
  26708. newIndices[offset++] = rawIdx;
  26709. }
  26710. }
  26711. // Set indices after filtered.
  26712. if (offset < count) {
  26713. this._indices = newIndices;
  26714. }
  26715. this._count = offset;
  26716. // Reset data extent
  26717. this._extent = {};
  26718. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26719. return this;
  26720. };
  26721. /**
  26722. * Select data in range. (For optimization of filter)
  26723. * (Manually inline code, support 5 million data filtering in data zoom.)
  26724. */
  26725. listProto.selectRange = function (range) {
  26726. 'use strict';
  26727. if (!this._count) {
  26728. return;
  26729. }
  26730. var dimensions = [];
  26731. for (var dim in range) {
  26732. if (range.hasOwnProperty(dim)) {
  26733. dimensions.push(dim);
  26734. }
  26735. }
  26736. if (__DEV__) {
  26737. validateDimensions(this, dimensions);
  26738. }
  26739. var dimSize = dimensions.length;
  26740. if (!dimSize) {
  26741. return;
  26742. }
  26743. var originalCount = this.count();
  26744. var Ctor = getIndicesCtor(this);
  26745. var newIndices = new Ctor(originalCount);
  26746. var offset = 0;
  26747. var dim0 = dimensions[0];
  26748. var min = range[dim0][0];
  26749. var max = range[dim0][1];
  26750. var quickFinished = false;
  26751. if (!this._indices) {
  26752. // Extreme optimization for common case. About 2x faster in chrome.
  26753. var idx = 0;
  26754. if (dimSize === 1) {
  26755. var dimStorage = this._storage[dimensions[0]];
  26756. for (var k = 0; k < this._chunkCount; k++) {
  26757. var chunkStorage = dimStorage[k];
  26758. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26759. for (var i = 0; i < len; i++) {
  26760. var val = chunkStorage[i];
  26761. // NaN will not be filtered. Consider the case, in line chart, empty
  26762. // value indicates the line should be broken. But for the case like
  26763. // scatter plot, a data item with empty value will not be rendered,
  26764. // but the axis extent may be effected if some other dim of the data
  26765. // item has value. Fortunately it is not a significant negative effect.
  26766. if (
  26767. (val >= min && val <= max) || isNaN(val)
  26768. ) {
  26769. newIndices[offset++] = idx;
  26770. }
  26771. idx++;
  26772. }
  26773. }
  26774. quickFinished = true;
  26775. }
  26776. else if (dimSize === 2) {
  26777. var dimStorage = this._storage[dim0];
  26778. var dimStorage2 = this._storage[dimensions[1]];
  26779. var min2 = range[dimensions[1]][0];
  26780. var max2 = range[dimensions[1]][1];
  26781. for (var k = 0; k < this._chunkCount; k++) {
  26782. var chunkStorage = dimStorage[k];
  26783. var chunkStorage2 = dimStorage2[k];
  26784. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26785. for (var i = 0; i < len; i++) {
  26786. var val = chunkStorage[i];
  26787. var val2 = chunkStorage2[i];
  26788. // Do not filter NaN, see comment above.
  26789. if ((
  26790. (val >= min && val <= max) || isNaN(val)
  26791. )
  26792. && (
  26793. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  26794. )
  26795. ) {
  26796. newIndices[offset++] = idx;
  26797. }
  26798. idx++;
  26799. }
  26800. }
  26801. quickFinished = true;
  26802. }
  26803. }
  26804. if (!quickFinished) {
  26805. if (dimSize === 1) {
  26806. for (var i = 0; i < originalCount; i++) {
  26807. var rawIndex = this.getRawIndex(i);
  26808. var val = this._getFast(dim0, rawIndex);
  26809. // Do not filter NaN, see comment above.
  26810. if (
  26811. (val >= min && val <= max) || isNaN(val)
  26812. ) {
  26813. newIndices[offset++] = rawIndex;
  26814. }
  26815. }
  26816. }
  26817. else {
  26818. for (var i = 0; i < originalCount; i++) {
  26819. var keep = true;
  26820. var rawIndex = this.getRawIndex(i);
  26821. for (var k = 0; k < dimSize; k++) {
  26822. var dimk = dimensions[k];
  26823. var val = this._getFast(dim, rawIndex);
  26824. // Do not filter NaN, see comment above.
  26825. if (val < range[dimk][0] || val > range[dimk][1]) {
  26826. keep = false;
  26827. }
  26828. }
  26829. if (keep) {
  26830. newIndices[offset++] = this.getRawIndex(i);
  26831. }
  26832. }
  26833. }
  26834. }
  26835. // Set indices after filtered.
  26836. if (offset < originalCount) {
  26837. this._indices = newIndices;
  26838. }
  26839. this._count = offset;
  26840. // Reset data extent
  26841. this._extent = {};
  26842. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26843. return this;
  26844. };
  26845. /**
  26846. * Data mapping to a plain array
  26847. * @param {string|Array.<string>} [dimensions]
  26848. * @param {Function} cb
  26849. * @param {*} [context=this]
  26850. * @return {Array}
  26851. */
  26852. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  26853. 'use strict';
  26854. if (typeof dimensions === 'function') {
  26855. contextCompat = context;
  26856. context = cb;
  26857. cb = dimensions;
  26858. dimensions = [];
  26859. }
  26860. // contextCompat just for compat echarts3
  26861. context = context || contextCompat || this;
  26862. var result = [];
  26863. this.each(dimensions, function () {
  26864. result.push(cb && cb.apply(this, arguments));
  26865. }, context);
  26866. return result;
  26867. };
  26868. // Data in excludeDimensions is copied, otherwise transfered.
  26869. function cloneListForMapAndSample(original, excludeDimensions) {
  26870. var allDimensions = original.dimensions;
  26871. var list = new List(
  26872. map(allDimensions, original.getDimensionInfo, original),
  26873. original.hostModel
  26874. );
  26875. // FIXME If needs stackedOn, value may already been stacked
  26876. transferProperties(list, original);
  26877. var storage = list._storage = {};
  26878. var originalStorage = original._storage;
  26879. // Init storage
  26880. for (var i = 0; i < allDimensions.length; i++) {
  26881. var dim = allDimensions[i];
  26882. if (originalStorage[dim]) {
  26883. // Notice that we do not reset invertedIndicesMap here, becuase
  26884. // there is no scenario of mapping or sampling ordinal dimension.
  26885. if (indexOf(excludeDimensions, dim) >= 0) {
  26886. storage[dim] = cloneDimStore(originalStorage[dim]);
  26887. list._rawExtent[dim] = getInitialExtent();
  26888. list._extent[dim] = null;
  26889. }
  26890. else {
  26891. // Direct reference for other dimensions
  26892. storage[dim] = originalStorage[dim];
  26893. }
  26894. }
  26895. }
  26896. return list;
  26897. }
  26898. function cloneDimStore(originalDimStore) {
  26899. var newDimStore = new Array(originalDimStore.length);
  26900. for (var j = 0; j < originalDimStore.length; j++) {
  26901. newDimStore[j] = cloneChunk(originalDimStore[j]);
  26902. }
  26903. return newDimStore;
  26904. }
  26905. function getInitialExtent() {
  26906. return [Infinity, -Infinity];
  26907. }
  26908. /**
  26909. * Data mapping to a new List with given dimensions
  26910. * @param {string|Array.<string>} dimensions
  26911. * @param {Function} cb
  26912. * @param {*} [context=this]
  26913. * @return {Array}
  26914. */
  26915. listProto.map = function (dimensions, cb, context, contextCompat) {
  26916. 'use strict';
  26917. // contextCompat just for compat echarts3
  26918. context = context || contextCompat || this;
  26919. dimensions = map(
  26920. normalizeDimensions(dimensions), this.getDimension, this
  26921. );
  26922. if (__DEV__) {
  26923. validateDimensions(this, dimensions);
  26924. }
  26925. var list = cloneListForMapAndSample(this, dimensions);
  26926. // Following properties are all immutable.
  26927. // So we can reference to the same value
  26928. list._indices = this._indices;
  26929. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26930. var storage = list._storage;
  26931. var tmpRetValue = [];
  26932. var chunkSize = this._chunkSize;
  26933. var dimSize = dimensions.length;
  26934. var dataCount = this.count();
  26935. var values = [];
  26936. var rawExtent = list._rawExtent;
  26937. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  26938. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  26939. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  26940. }
  26941. values[dimSize] = dataIndex;
  26942. var retValue = cb && cb.apply(context, values);
  26943. if (retValue != null) {
  26944. // a number or string (in oridinal dimension)?
  26945. if (typeof retValue !== 'object') {
  26946. tmpRetValue[0] = retValue;
  26947. retValue = tmpRetValue;
  26948. }
  26949. var rawIndex = this.getRawIndex(dataIndex);
  26950. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26951. var chunkOffset = rawIndex % chunkSize;
  26952. for (var i = 0; i < retValue.length; i++) {
  26953. var dim = dimensions[i];
  26954. var val = retValue[i];
  26955. var rawExtentOnDim = rawExtent[dim];
  26956. var dimStore = storage[dim];
  26957. if (dimStore) {
  26958. dimStore[chunkIndex][chunkOffset] = val;
  26959. }
  26960. if (val < rawExtentOnDim[0]) {
  26961. rawExtentOnDim[0] = val;
  26962. }
  26963. if (val > rawExtentOnDim[1]) {
  26964. rawExtentOnDim[1] = val;
  26965. }
  26966. }
  26967. }
  26968. }
  26969. return list;
  26970. };
  26971. /**
  26972. * Large data down sampling on given dimension
  26973. * @param {string} dimension
  26974. * @param {number} rate
  26975. * @param {Function} sampleValue
  26976. * @param {Function} sampleIndex Sample index for name and id
  26977. */
  26978. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  26979. var list = cloneListForMapAndSample(this, [dimension]);
  26980. var targetStorage = list._storage;
  26981. var frameValues = [];
  26982. var frameSize = Math.floor(1 / rate);
  26983. var dimStore = targetStorage[dimension];
  26984. var len = this.count();
  26985. var chunkSize = this._chunkSize;
  26986. var rawExtentOnDim = list._rawExtent[dimension];
  26987. var newIndices = new (getIndicesCtor(this))(len);
  26988. var offset = 0;
  26989. for (var i = 0; i < len; i += frameSize) {
  26990. // Last frame
  26991. if (frameSize > len - i) {
  26992. frameSize = len - i;
  26993. frameValues.length = frameSize;
  26994. }
  26995. for (var k = 0; k < frameSize; k++) {
  26996. var dataIdx = this.getRawIndex(i + k);
  26997. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  26998. var originalChunkOffset = dataIdx % chunkSize;
  26999. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  27000. }
  27001. var value = sampleValue(frameValues);
  27002. var sampleFrameIdx = this.getRawIndex(
  27003. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  27004. );
  27005. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  27006. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  27007. // Only write value on the filtered data
  27008. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  27009. if (value < rawExtentOnDim[0]) {
  27010. rawExtentOnDim[0] = value;
  27011. }
  27012. if (value > rawExtentOnDim[1]) {
  27013. rawExtentOnDim[1] = value;
  27014. }
  27015. newIndices[offset++] = sampleFrameIdx;
  27016. }
  27017. list._count = offset;
  27018. list._indices = newIndices;
  27019. list.getRawIndex = getRawIndexWithIndices;
  27020. return list;
  27021. };
  27022. /**
  27023. * Get model of one data item.
  27024. *
  27025. * @param {number} idx
  27026. */
  27027. // FIXME Model proxy ?
  27028. listProto.getItemModel = function (idx) {
  27029. var hostModel = this.hostModel;
  27030. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  27031. };
  27032. /**
  27033. * Create a data differ
  27034. * @param {module:echarts/data/List} otherList
  27035. * @return {module:echarts/data/DataDiffer}
  27036. */
  27037. listProto.diff = function (otherList) {
  27038. var thisList = this;
  27039. return new DataDiffer(
  27040. otherList ? otherList.getIndices() : [],
  27041. this.getIndices(),
  27042. function (idx) {
  27043. return getId(otherList, idx);
  27044. },
  27045. function (idx) {
  27046. return getId(thisList, idx);
  27047. }
  27048. );
  27049. };
  27050. /**
  27051. * Get visual property.
  27052. * @param {string} key
  27053. */
  27054. listProto.getVisual = function (key) {
  27055. var visual = this._visual;
  27056. return visual && visual[key];
  27057. };
  27058. /**
  27059. * Set visual property
  27060. * @param {string|Object} key
  27061. * @param {*} [value]
  27062. *
  27063. * @example
  27064. * setVisual('color', color);
  27065. * setVisual({
  27066. * 'color': color
  27067. * });
  27068. */
  27069. listProto.setVisual = function (key, val) {
  27070. if (isObject$4(key)) {
  27071. for (var name in key) {
  27072. if (key.hasOwnProperty(name)) {
  27073. this.setVisual(name, key[name]);
  27074. }
  27075. }
  27076. return;
  27077. }
  27078. this._visual = this._visual || {};
  27079. this._visual[key] = val;
  27080. };
  27081. /**
  27082. * Set layout property.
  27083. * @param {string|Object} key
  27084. * @param {*} [val]
  27085. */
  27086. listProto.setLayout = function (key, val) {
  27087. if (isObject$4(key)) {
  27088. for (var name in key) {
  27089. if (key.hasOwnProperty(name)) {
  27090. this.setLayout(name, key[name]);
  27091. }
  27092. }
  27093. return;
  27094. }
  27095. this._layout[key] = val;
  27096. };
  27097. /**
  27098. * Get layout property.
  27099. * @param {string} key.
  27100. * @return {*}
  27101. */
  27102. listProto.getLayout = function (key) {
  27103. return this._layout[key];
  27104. };
  27105. /**
  27106. * Get layout of single data item
  27107. * @param {number} idx
  27108. */
  27109. listProto.getItemLayout = function (idx) {
  27110. return this._itemLayouts[idx];
  27111. };
  27112. /**
  27113. * Set layout of single data item
  27114. * @param {number} idx
  27115. * @param {Object} layout
  27116. * @param {boolean=} [merge=false]
  27117. */
  27118. listProto.setItemLayout = function (idx, layout, merge$$1) {
  27119. this._itemLayouts[idx] = merge$$1
  27120. ? extend(this._itemLayouts[idx] || {}, layout)
  27121. : layout;
  27122. };
  27123. /**
  27124. * Clear all layout of single data item
  27125. */
  27126. listProto.clearItemLayouts = function () {
  27127. this._itemLayouts.length = 0;
  27128. };
  27129. /**
  27130. * Get visual property of single data item
  27131. * @param {number} idx
  27132. * @param {string} key
  27133. * @param {boolean} [ignoreParent=false]
  27134. */
  27135. listProto.getItemVisual = function (idx, key, ignoreParent) {
  27136. var itemVisual = this._itemVisuals[idx];
  27137. var val = itemVisual && itemVisual[key];
  27138. if (val == null && !ignoreParent) {
  27139. // Use global visual property
  27140. return this.getVisual(key);
  27141. }
  27142. return val;
  27143. };
  27144. /**
  27145. * Set visual property of single data item
  27146. *
  27147. * @param {number} idx
  27148. * @param {string|Object} key
  27149. * @param {*} [value]
  27150. *
  27151. * @example
  27152. * setItemVisual(0, 'color', color);
  27153. * setItemVisual(0, {
  27154. * 'color': color
  27155. * });
  27156. */
  27157. listProto.setItemVisual = function (idx, key, value) {
  27158. var itemVisual = this._itemVisuals[idx] || {};
  27159. var hasItemVisual = this.hasItemVisual;
  27160. this._itemVisuals[idx] = itemVisual;
  27161. if (isObject$4(key)) {
  27162. for (var name in key) {
  27163. if (key.hasOwnProperty(name)) {
  27164. itemVisual[name] = key[name];
  27165. hasItemVisual[name] = true;
  27166. }
  27167. }
  27168. return;
  27169. }
  27170. itemVisual[key] = value;
  27171. hasItemVisual[key] = true;
  27172. };
  27173. /**
  27174. * Clear itemVisuals and list visual.
  27175. */
  27176. listProto.clearAllVisual = function () {
  27177. this._visual = {};
  27178. this._itemVisuals = [];
  27179. this.hasItemVisual = {};
  27180. };
  27181. var setItemDataAndSeriesIndex = function (child) {
  27182. child.seriesIndex = this.seriesIndex;
  27183. child.dataIndex = this.dataIndex;
  27184. child.dataType = this.dataType;
  27185. };
  27186. /**
  27187. * Set graphic element relative to data. It can be set as null
  27188. * @param {number} idx
  27189. * @param {module:zrender/Element} [el]
  27190. */
  27191. listProto.setItemGraphicEl = function (idx, el) {
  27192. var hostModel = this.hostModel;
  27193. if (el) {
  27194. // Add data index and series index for indexing the data by element
  27195. // Useful in tooltip
  27196. el.dataIndex = idx;
  27197. el.dataType = this.dataType;
  27198. el.seriesIndex = hostModel && hostModel.seriesIndex;
  27199. if (el.type === 'group') {
  27200. el.traverse(setItemDataAndSeriesIndex, el);
  27201. }
  27202. }
  27203. this._graphicEls[idx] = el;
  27204. };
  27205. /**
  27206. * @param {number} idx
  27207. * @return {module:zrender/Element}
  27208. */
  27209. listProto.getItemGraphicEl = function (idx) {
  27210. return this._graphicEls[idx];
  27211. };
  27212. /**
  27213. * @param {Function} cb
  27214. * @param {*} context
  27215. */
  27216. listProto.eachItemGraphicEl = function (cb, context) {
  27217. each$1(this._graphicEls, function (el, idx) {
  27218. if (el) {
  27219. cb && cb.call(context, el, idx);
  27220. }
  27221. });
  27222. };
  27223. /**
  27224. * Shallow clone a new list except visual and layout properties, and graph elements.
  27225. * New list only change the indices.
  27226. */
  27227. listProto.cloneShallow = function (list) {
  27228. if (!list) {
  27229. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  27230. list = new List(dimensionInfoList, this.hostModel);
  27231. }
  27232. // FIXME
  27233. list._storage = this._storage;
  27234. transferProperties(list, this);
  27235. // Clone will not change the data extent and indices
  27236. if (this._indices) {
  27237. var Ctor = this._indices.constructor;
  27238. list._indices = new Ctor(this._indices);
  27239. }
  27240. else {
  27241. list._indices = null;
  27242. }
  27243. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27244. return list;
  27245. };
  27246. /**
  27247. * Wrap some method to add more feature
  27248. * @param {string} methodName
  27249. * @param {Function} injectFunction
  27250. */
  27251. listProto.wrapMethod = function (methodName, injectFunction) {
  27252. var originalMethod = this[methodName];
  27253. if (typeof originalMethod !== 'function') {
  27254. return;
  27255. }
  27256. this.__wrappedMethods = this.__wrappedMethods || [];
  27257. this.__wrappedMethods.push(methodName);
  27258. this[methodName] = function () {
  27259. var res = originalMethod.apply(this, arguments);
  27260. return injectFunction.apply(this, [res].concat(slice(arguments)));
  27261. };
  27262. };
  27263. // Methods that create a new list based on this list should be listed here.
  27264. // Notice that those method should `RETURN` the new list.
  27265. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  27266. // Methods that change indices of this list should be listed here.
  27267. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27268. /*
  27269. * Licensed to the Apache Software Foundation (ASF) under one
  27270. * or more contributor license agreements. See the NOTICE file
  27271. * distributed with this work for additional information
  27272. * regarding copyright ownership. The ASF licenses this file
  27273. * to you under the Apache License, Version 2.0 (the
  27274. * "License"); you may not use this file except in compliance
  27275. * with the License. You may obtain a copy of the License at
  27276. *
  27277. * http://www.apache.org/licenses/LICENSE-2.0
  27278. *
  27279. * Unless required by applicable law or agreed to in writing,
  27280. * software distributed under the License is distributed on an
  27281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27282. * KIND, either express or implied. See the License for the
  27283. * specific language governing permissions and limitations
  27284. * under the License.
  27285. */
  27286. /**
  27287. * @deprecated
  27288. * Use `echarts/data/helper/createDimensions` instead.
  27289. */
  27290. /**
  27291. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  27292. *
  27293. * Complete the dimensions array, by user defined `dimension` and `encode`,
  27294. * and guessing from the data structure.
  27295. * If no 'value' dimension specified, the first no-named dimension will be
  27296. * named as 'value'.
  27297. *
  27298. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  27299. * provides not only dim template, but also default order.
  27300. * properties: 'name', 'type', 'displayName'.
  27301. * `name` of each item provides default coord name.
  27302. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  27303. * provide dims count that the sysDim required.
  27304. * [{ordinalMeta}] can be specified.
  27305. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  27306. * @param {Object} [opt]
  27307. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  27308. * For example: ['asdf', {name, type}, ...].
  27309. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  27310. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  27311. * If not specified, extra dim names will be:
  27312. * 'value', 'value0', 'value1', ...
  27313. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  27314. * If `generateCoordCount` specified, the generated dim names will be:
  27315. * `generateCoord` + 0, `generateCoord` + 1, ...
  27316. * can be Infinity, indicate that use all of the remain columns.
  27317. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  27318. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  27319. * @return {Array.<Object>} [{
  27320. * name: string mandatory,
  27321. * displayName: string, the origin name in dimsDef, see source helper.
  27322. * If displayName given, the tooltip will displayed vertically.
  27323. * coordDim: string mandatory,
  27324. * coordDimIndex: number mandatory,
  27325. * type: string optional,
  27326. * otherDims: { never null/undefined
  27327. * tooltip: number optional,
  27328. * label: number optional,
  27329. * itemName: number optional,
  27330. * seriesName: number optional,
  27331. * },
  27332. * isExtraCoord: boolean true if coord is generated
  27333. * (not specified in encode and not series specified)
  27334. * other props ...
  27335. * }]
  27336. */
  27337. function completeDimensions(sysDims, source, opt) {
  27338. if (!Source.isInstance(source)) {
  27339. source = Source.seriesDataToSource(source);
  27340. }
  27341. opt = opt || {};
  27342. sysDims = (sysDims || []).slice();
  27343. var dimsDef = (opt.dimsDef || []).slice();
  27344. var encodeDef = createHashMap(opt.encodeDef);
  27345. var dataDimNameMap = createHashMap();
  27346. var coordDimNameMap = createHashMap();
  27347. // var valueCandidate;
  27348. var result = [];
  27349. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  27350. // Apply user defined dims (`name` and `type`) and init result.
  27351. for (var i = 0; i < dimCount; i++) {
  27352. var dimDefItem = dimsDef[i] = extend(
  27353. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  27354. );
  27355. var userDimName = dimDefItem.name;
  27356. var resultItem = result[i] = {otherDims: {}};
  27357. // Name will be applied later for avoiding duplication.
  27358. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27359. // Only if `series.dimensions` is defined in option
  27360. // displayName, will be set, and dimension will be diplayed vertically in
  27361. // tooltip by default.
  27362. resultItem.name = resultItem.displayName = userDimName;
  27363. dataDimNameMap.set(userDimName, i);
  27364. }
  27365. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  27366. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  27367. }
  27368. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  27369. encodeDef.each(function (dataDims, coordDim) {
  27370. dataDims = normalizeToArray(dataDims).slice();
  27371. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  27372. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  27373. // this case.
  27374. if (dataDims.length === 1 && dataDims[0] < 0) {
  27375. encodeDef.set(coordDim, false);
  27376. return;
  27377. }
  27378. var validDataDims = encodeDef.set(coordDim, []);
  27379. each$1(dataDims, function (resultDimIdx, idx) {
  27380. // The input resultDimIdx can be dim name or index.
  27381. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  27382. if (resultDimIdx != null && resultDimIdx < dimCount) {
  27383. validDataDims[idx] = resultDimIdx;
  27384. applyDim(result[resultDimIdx], coordDim, idx);
  27385. }
  27386. });
  27387. });
  27388. // Apply templetes and default order from `sysDims`.
  27389. var availDimIdx = 0;
  27390. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  27391. var coordDim;
  27392. var sysDimItem;
  27393. var sysDimItemDimsDef;
  27394. var sysDimItemOtherDims;
  27395. if (isString(sysDimItem)) {
  27396. coordDim = sysDimItem;
  27397. sysDimItem = {};
  27398. }
  27399. else {
  27400. coordDim = sysDimItem.name;
  27401. var ordinalMeta = sysDimItem.ordinalMeta;
  27402. sysDimItem.ordinalMeta = null;
  27403. sysDimItem = clone(sysDimItem);
  27404. sysDimItem.ordinalMeta = ordinalMeta;
  27405. // `coordDimIndex` should not be set directly.
  27406. sysDimItemDimsDef = sysDimItem.dimsDef;
  27407. sysDimItemOtherDims = sysDimItem.otherDims;
  27408. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  27409. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  27410. }
  27411. var dataDims = encodeDef.get(coordDim);
  27412. // negative resultDimIdx means no need to mapping.
  27413. if (dataDims === false) {
  27414. return;
  27415. }
  27416. var dataDims = normalizeToArray(dataDims);
  27417. // dimensions provides default dim sequences.
  27418. if (!dataDims.length) {
  27419. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  27420. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  27421. availDimIdx++;
  27422. }
  27423. availDimIdx < result.length && dataDims.push(availDimIdx++);
  27424. }
  27425. }
  27426. // Apply templates.
  27427. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  27428. var resultItem = result[resultDimIdx];
  27429. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  27430. if (resultItem.name == null && sysDimItemDimsDef) {
  27431. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  27432. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  27433. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  27434. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  27435. }
  27436. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  27437. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  27438. });
  27439. });
  27440. function applyDim(resultItem, coordDim, coordDimIndex) {
  27441. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  27442. resultItem.otherDims[coordDim] = coordDimIndex;
  27443. }
  27444. else {
  27445. resultItem.coordDim = coordDim;
  27446. resultItem.coordDimIndex = coordDimIndex;
  27447. coordDimNameMap.set(coordDim, true);
  27448. }
  27449. }
  27450. // Make sure the first extra dim is 'value'.
  27451. var generateCoord = opt.generateCoord;
  27452. var generateCoordCount = opt.generateCoordCount;
  27453. var fromZero = generateCoordCount != null;
  27454. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  27455. var extra = generateCoord || 'value';
  27456. // Set dim `name` and other `coordDim` and other props.
  27457. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  27458. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  27459. var coordDim = resultItem.coordDim;
  27460. if (coordDim == null) {
  27461. resultItem.coordDim = genName(
  27462. extra, coordDimNameMap, fromZero
  27463. );
  27464. resultItem.coordDimIndex = 0;
  27465. if (!generateCoord || generateCoordCount <= 0) {
  27466. resultItem.isExtraCoord = true;
  27467. }
  27468. generateCoordCount--;
  27469. }
  27470. resultItem.name == null && (resultItem.name = genName(
  27471. resultItem.coordDim,
  27472. dataDimNameMap
  27473. ));
  27474. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  27475. resultItem.type = 'ordinal';
  27476. }
  27477. }
  27478. return result;
  27479. }
  27480. // ??? TODO
  27481. // Originally detect dimCount by data[0]. Should we
  27482. // optimize it to only by sysDims and dimensions and encode.
  27483. // So only necessary dims will be initialized.
  27484. // But
  27485. // (1) custom series should be considered. where other dims
  27486. // may be visited.
  27487. // (2) sometimes user need to calcualte bubble size or use visualMap
  27488. // on other dimensions besides coordSys needed.
  27489. // So, dims that is not used by system, should be shared in storage?
  27490. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  27491. // Note that the result dimCount should not small than columns count
  27492. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  27493. var dimCount = Math.max(
  27494. source.dimensionsDetectCount || 1,
  27495. sysDims.length,
  27496. dimsDef.length,
  27497. optDimCount || 0
  27498. );
  27499. each$1(sysDims, function (sysDimItem) {
  27500. var sysDimItemDimsDef = sysDimItem.dimsDef;
  27501. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  27502. });
  27503. return dimCount;
  27504. }
  27505. function genName(name, map$$1, fromZero) {
  27506. if (fromZero || map$$1.get(name) != null) {
  27507. var i = 0;
  27508. while (map$$1.get(name + i) != null) {
  27509. i++;
  27510. }
  27511. name += i;
  27512. }
  27513. map$$1.set(name, true);
  27514. return name;
  27515. }
  27516. /*
  27517. * Licensed to the Apache Software Foundation (ASF) under one
  27518. * or more contributor license agreements. See the NOTICE file
  27519. * distributed with this work for additional information
  27520. * regarding copyright ownership. The ASF licenses this file
  27521. * to you under the Apache License, Version 2.0 (the
  27522. * "License"); you may not use this file except in compliance
  27523. * with the License. You may obtain a copy of the License at
  27524. *
  27525. * http://www.apache.org/licenses/LICENSE-2.0
  27526. *
  27527. * Unless required by applicable law or agreed to in writing,
  27528. * software distributed under the License is distributed on an
  27529. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27530. * KIND, either express or implied. See the License for the
  27531. * specific language governing permissions and limitations
  27532. * under the License.
  27533. */
  27534. /**
  27535. * Substitute `completeDimensions`.
  27536. * `completeDimensions` is to be deprecated.
  27537. */
  27538. /**
  27539. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  27540. * @param {Object|Array} [opt]
  27541. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  27542. * @param {number} [opt.dimensionsCount]
  27543. * @param {string} [opt.generateCoord]
  27544. * @param {string} [opt.generateCoordCount]
  27545. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  27546. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  27547. * @return {Array.<Object>} dimensionsInfo
  27548. */
  27549. var createDimensions = function (source, opt) {
  27550. opt = opt || {};
  27551. return completeDimensions(opt.coordDimensions || [], source, {
  27552. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  27553. encodeDef: opt.encodeDefine || source.encodeDefine,
  27554. dimCount: opt.dimensionsCount,
  27555. generateCoord: opt.generateCoord,
  27556. generateCoordCount: opt.generateCoordCount
  27557. });
  27558. };
  27559. /*
  27560. * Licensed to the Apache Software Foundation (ASF) under one
  27561. * or more contributor license agreements. See the NOTICE file
  27562. * distributed with this work for additional information
  27563. * regarding copyright ownership. The ASF licenses this file
  27564. * to you under the Apache License, Version 2.0 (the
  27565. * "License"); you may not use this file except in compliance
  27566. * with the License. You may obtain a copy of the License at
  27567. *
  27568. * http://www.apache.org/licenses/LICENSE-2.0
  27569. *
  27570. * Unless required by applicable law or agreed to in writing,
  27571. * software distributed under the License is distributed on an
  27572. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27573. * KIND, either express or implied. See the License for the
  27574. * specific language governing permissions and limitations
  27575. * under the License.
  27576. */
  27577. /**
  27578. * Note that it is too complicated to support 3d stack by value
  27579. * (have to create two-dimension inverted index), so in 3d case
  27580. * we just support that stacked by index.
  27581. *
  27582. * @param {module:echarts/model/Series} seriesModel
  27583. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  27584. * The input dimensionInfoList will be modified.
  27585. * @param {Object} [opt]
  27586. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  27587. * @param {boolean} [opt.byIndex=false]
  27588. * @return {Object} calculationInfo
  27589. * {
  27590. * stackedDimension: string
  27591. * stackedByDimension: string
  27592. * isStackedByIndex: boolean
  27593. * stackedOverDimension: string
  27594. * stackResultDimension: string
  27595. * }
  27596. */
  27597. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  27598. opt = opt || {};
  27599. var byIndex = opt.byIndex;
  27600. var stackedCoordDimension = opt.stackedCoordDimension;
  27601. // Compatibal: when `stack` is set as '', do not stack.
  27602. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  27603. var stackedByDimInfo;
  27604. var stackedDimInfo;
  27605. var stackResultDimension;
  27606. var stackedOverDimension;
  27607. each$1(dimensionInfoList, function (dimensionInfo, index) {
  27608. if (isString(dimensionInfo)) {
  27609. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  27610. }
  27611. if (mayStack && !dimensionInfo.isExtraCoord) {
  27612. // Find the first ordinal dimension as the stackedByDimInfo.
  27613. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  27614. stackedByDimInfo = dimensionInfo;
  27615. }
  27616. // Find the first stackable dimension as the stackedDimInfo.
  27617. if (!stackedDimInfo
  27618. && dimensionInfo.type !== 'ordinal'
  27619. && dimensionInfo.type !== 'time'
  27620. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  27621. ) {
  27622. stackedDimInfo = dimensionInfo;
  27623. }
  27624. }
  27625. });
  27626. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  27627. // Compatible with previous design, value axis (time axis) only stack by index.
  27628. // It may make sense if the user provides elaborately constructed data.
  27629. byIndex = true;
  27630. }
  27631. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  27632. // That put stack logic in List is for using conveniently in echarts extensions, but it
  27633. // might not be a good way.
  27634. if (stackedDimInfo) {
  27635. // Use a weird name that not duplicated with other names.
  27636. stackResultDimension = '__\0ecstackresult';
  27637. stackedOverDimension = '__\0ecstackedover';
  27638. // Create inverted index to fast query index by value.
  27639. if (stackedByDimInfo) {
  27640. stackedByDimInfo.createInvertedIndices = true;
  27641. }
  27642. var stackedDimCoordDim = stackedDimInfo.coordDim;
  27643. var stackedDimType = stackedDimInfo.type;
  27644. var stackedDimCoordIndex = 0;
  27645. each$1(dimensionInfoList, function (dimensionInfo) {
  27646. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  27647. stackedDimCoordIndex++;
  27648. }
  27649. });
  27650. dimensionInfoList.push({
  27651. name: stackResultDimension,
  27652. coordDim: stackedDimCoordDim,
  27653. coordDimIndex: stackedDimCoordIndex,
  27654. type: stackedDimType,
  27655. isExtraCoord: true,
  27656. isCalculationCoord: true
  27657. });
  27658. stackedDimCoordIndex++;
  27659. dimensionInfoList.push({
  27660. name: stackedOverDimension,
  27661. // This dimension contains stack base (generally, 0), so do not set it as
  27662. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  27663. coordDim: stackedOverDimension,
  27664. coordDimIndex: stackedDimCoordIndex,
  27665. type: stackedDimType,
  27666. isExtraCoord: true,
  27667. isCalculationCoord: true
  27668. });
  27669. }
  27670. return {
  27671. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  27672. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  27673. isStackedByIndex: byIndex,
  27674. stackedOverDimension: stackedOverDimension,
  27675. stackResultDimension: stackResultDimension
  27676. };
  27677. }
  27678. /**
  27679. * @param {module:echarts/data/List} data
  27680. * @param {string} stackedDim
  27681. */
  27682. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  27683. // Each single series only maps to one pair of axis. So we do not need to
  27684. // check stackByDim, whatever stacked by a dimension or stacked by index.
  27685. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  27686. // && (
  27687. // stackedByDim != null
  27688. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  27689. // : data.getCalculationInfo('isStackedByIndex')
  27690. // );
  27691. }
  27692. /**
  27693. * @param {module:echarts/data/List} data
  27694. * @param {string} targetDim
  27695. * @param {string} [stackedByDim] If not input this parameter, check whether
  27696. * stacked by index.
  27697. * @return {string} dimension
  27698. */
  27699. function getStackedDimension(data, targetDim) {
  27700. return isDimensionStacked(data, targetDim)
  27701. ? data.getCalculationInfo('stackResultDimension')
  27702. : targetDim;
  27703. }
  27704. /*
  27705. * Licensed to the Apache Software Foundation (ASF) under one
  27706. * or more contributor license agreements. See the NOTICE file
  27707. * distributed with this work for additional information
  27708. * regarding copyright ownership. The ASF licenses this file
  27709. * to you under the Apache License, Version 2.0 (the
  27710. * "License"); you may not use this file except in compliance
  27711. * with the License. You may obtain a copy of the License at
  27712. *
  27713. * http://www.apache.org/licenses/LICENSE-2.0
  27714. *
  27715. * Unless required by applicable law or agreed to in writing,
  27716. * software distributed under the License is distributed on an
  27717. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27718. * KIND, either express or implied. See the License for the
  27719. * specific language governing permissions and limitations
  27720. * under the License.
  27721. */
  27722. /**
  27723. * @param {module:echarts/data/Source|Array} source Or raw data.
  27724. * @param {module:echarts/model/Series} seriesModel
  27725. * @param {Object} [opt]
  27726. * @param {string} [opt.generateCoord]
  27727. */
  27728. function createListFromArray(source, seriesModel, opt) {
  27729. opt = opt || {};
  27730. if (!Source.isInstance(source)) {
  27731. source = Source.seriesDataToSource(source);
  27732. }
  27733. var coordSysName = seriesModel.get('coordinateSystem');
  27734. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  27735. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  27736. var coordSysDimDefs;
  27737. if (coordSysDefine) {
  27738. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  27739. var dimInfo = {name: dim};
  27740. var axisModel = coordSysDefine.axisMap.get(dim);
  27741. if (axisModel) {
  27742. var axisType = axisModel.get('type');
  27743. dimInfo.type = getDimensionTypeByAxis(axisType);
  27744. // dimInfo.stackable = isStackable(axisType);
  27745. }
  27746. return dimInfo;
  27747. });
  27748. }
  27749. if (!coordSysDimDefs) {
  27750. // Get dimensions from registered coordinate system
  27751. coordSysDimDefs = (registeredCoordSys && (
  27752. registeredCoordSys.getDimensionsInfo
  27753. ? registeredCoordSys.getDimensionsInfo()
  27754. : registeredCoordSys.dimensions.slice()
  27755. )) || ['x', 'y'];
  27756. }
  27757. var dimInfoList = createDimensions(source, {
  27758. coordDimensions: coordSysDimDefs,
  27759. generateCoord: opt.generateCoord
  27760. });
  27761. var firstCategoryDimIndex;
  27762. var hasNameEncode;
  27763. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  27764. var coordDim = dimInfo.coordDim;
  27765. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  27766. if (categoryAxisModel) {
  27767. if (firstCategoryDimIndex == null) {
  27768. firstCategoryDimIndex = dimIndex;
  27769. }
  27770. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  27771. }
  27772. if (dimInfo.otherDims.itemName != null) {
  27773. hasNameEncode = true;
  27774. }
  27775. });
  27776. if (!hasNameEncode && firstCategoryDimIndex != null) {
  27777. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  27778. }
  27779. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  27780. var list = new List(dimInfoList, seriesModel);
  27781. list.setCalculationInfo(stackCalculationInfo);
  27782. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  27783. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  27784. // Use dataIndex as ordinal value in categoryAxis
  27785. return dimIndex === firstCategoryDimIndex
  27786. ? dataIndex
  27787. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  27788. }
  27789. : null;
  27790. list.hasItemOption = false;
  27791. list.initData(source, null, dimValueGetter);
  27792. return list;
  27793. }
  27794. function isNeedCompleteOrdinalData(source) {
  27795. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  27796. var sampleItem = firstDataNotNull(source.data || []);
  27797. return sampleItem != null
  27798. && !isArray(getDataItemValue(sampleItem));
  27799. }
  27800. }
  27801. function firstDataNotNull(data) {
  27802. var i = 0;
  27803. while (i < data.length && data[i] == null) {
  27804. i++;
  27805. }
  27806. return data[i];
  27807. }
  27808. /*
  27809. * Licensed to the Apache Software Foundation (ASF) under one
  27810. * or more contributor license agreements. See the NOTICE file
  27811. * distributed with this work for additional information
  27812. * regarding copyright ownership. The ASF licenses this file
  27813. * to you under the Apache License, Version 2.0 (the
  27814. * "License"); you may not use this file except in compliance
  27815. * with the License. You may obtain a copy of the License at
  27816. *
  27817. * http://www.apache.org/licenses/LICENSE-2.0
  27818. *
  27819. * Unless required by applicable law or agreed to in writing,
  27820. * software distributed under the License is distributed on an
  27821. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27822. * KIND, either express or implied. See the License for the
  27823. * specific language governing permissions and limitations
  27824. * under the License.
  27825. */
  27826. /**
  27827. * // Scale class management
  27828. * @module echarts/scale/Scale
  27829. */
  27830. /**
  27831. * @param {Object} [setting]
  27832. */
  27833. function Scale(setting) {
  27834. this._setting = setting || {};
  27835. /**
  27836. * Extent
  27837. * @type {Array.<number>}
  27838. * @protected
  27839. */
  27840. this._extent = [Infinity, -Infinity];
  27841. /**
  27842. * Step is calculated in adjustExtent
  27843. * @type {Array.<number>}
  27844. * @protected
  27845. */
  27846. this._interval = 0;
  27847. this.init && this.init.apply(this, arguments);
  27848. }
  27849. /**
  27850. * Parse input val to valid inner number.
  27851. * @param {*} val
  27852. * @return {number}
  27853. */
  27854. Scale.prototype.parse = function (val) {
  27855. // Notice: This would be a trap here, If the implementation
  27856. // of this method depends on extent, and this method is used
  27857. // before extent set (like in dataZoom), it would be wrong.
  27858. // Nevertheless, parse does not depend on extent generally.
  27859. return val;
  27860. };
  27861. Scale.prototype.getSetting = function (name) {
  27862. return this._setting[name];
  27863. };
  27864. Scale.prototype.contain = function (val) {
  27865. var extent = this._extent;
  27866. return val >= extent[0] && val <= extent[1];
  27867. };
  27868. /**
  27869. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  27870. * @param {number} val
  27871. * @return {number}
  27872. */
  27873. Scale.prototype.normalize = function (val) {
  27874. var extent = this._extent;
  27875. if (extent[1] === extent[0]) {
  27876. return 0.5;
  27877. }
  27878. return (val - extent[0]) / (extent[1] - extent[0]);
  27879. };
  27880. /**
  27881. * Scale normalized value
  27882. * @param {number} val
  27883. * @return {number}
  27884. */
  27885. Scale.prototype.scale = function (val) {
  27886. var extent = this._extent;
  27887. return val * (extent[1] - extent[0]) + extent[0];
  27888. };
  27889. /**
  27890. * Set extent from data
  27891. * @param {Array.<number>} other
  27892. */
  27893. Scale.prototype.unionExtent = function (other) {
  27894. var extent = this._extent;
  27895. other[0] < extent[0] && (extent[0] = other[0]);
  27896. other[1] > extent[1] && (extent[1] = other[1]);
  27897. // not setExtent because in log axis it may transformed to power
  27898. // this.setExtent(extent[0], extent[1]);
  27899. };
  27900. /**
  27901. * Set extent from data
  27902. * @param {module:echarts/data/List} data
  27903. * @param {string} dim
  27904. */
  27905. Scale.prototype.unionExtentFromData = function (data, dim) {
  27906. this.unionExtent(data.getApproximateExtent(dim));
  27907. };
  27908. /**
  27909. * Get extent
  27910. * @return {Array.<number>}
  27911. */
  27912. Scale.prototype.getExtent = function () {
  27913. return this._extent.slice();
  27914. };
  27915. /**
  27916. * Set extent
  27917. * @param {number} start
  27918. * @param {number} end
  27919. */
  27920. Scale.prototype.setExtent = function (start, end) {
  27921. var thisExtent = this._extent;
  27922. if (!isNaN(start)) {
  27923. thisExtent[0] = start;
  27924. }
  27925. if (!isNaN(end)) {
  27926. thisExtent[1] = end;
  27927. }
  27928. };
  27929. /**
  27930. * When axis extent depends on data and no data exists,
  27931. * axis ticks should not be drawn, which is named 'blank'.
  27932. */
  27933. Scale.prototype.isBlank = function () {
  27934. return this._isBlank;
  27935. },
  27936. /**
  27937. * When axis extent depends on data and no data exists,
  27938. * axis ticks should not be drawn, which is named 'blank'.
  27939. */
  27940. Scale.prototype.setBlank = function (isBlank) {
  27941. this._isBlank = isBlank;
  27942. };
  27943. /**
  27944. * @abstract
  27945. * @param {*} tick
  27946. * @return {string} label of the tick.
  27947. */
  27948. Scale.prototype.getLabel = null;
  27949. enableClassExtend(Scale);
  27950. enableClassManagement(Scale, {
  27951. registerWhenExtend: true
  27952. });
  27953. /*
  27954. * Licensed to the Apache Software Foundation (ASF) under one
  27955. * or more contributor license agreements. See the NOTICE file
  27956. * distributed with this work for additional information
  27957. * regarding copyright ownership. The ASF licenses this file
  27958. * to you under the Apache License, Version 2.0 (the
  27959. * "License"); you may not use this file except in compliance
  27960. * with the License. You may obtain a copy of the License at
  27961. *
  27962. * http://www.apache.org/licenses/LICENSE-2.0
  27963. *
  27964. * Unless required by applicable law or agreed to in writing,
  27965. * software distributed under the License is distributed on an
  27966. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27967. * KIND, either express or implied. See the License for the
  27968. * specific language governing permissions and limitations
  27969. * under the License.
  27970. */
  27971. /**
  27972. * @constructor
  27973. * @param {Object} [opt]
  27974. * @param {Object} [opt.categories=[]]
  27975. * @param {Object} [opt.needCollect=false]
  27976. * @param {Object} [opt.deduplication=false]
  27977. */
  27978. function OrdinalMeta(opt) {
  27979. /**
  27980. * @readOnly
  27981. * @type {Array.<string>}
  27982. */
  27983. this.categories = opt.categories || [];
  27984. /**
  27985. * @private
  27986. * @type {boolean}
  27987. */
  27988. this._needCollect = opt.needCollect;
  27989. /**
  27990. * @private
  27991. * @type {boolean}
  27992. */
  27993. this._deduplication = opt.deduplication;
  27994. /**
  27995. * @private
  27996. * @type {boolean}
  27997. */
  27998. this._map;
  27999. }
  28000. /**
  28001. * @param {module:echarts/model/Model} axisModel
  28002. * @return {module:echarts/data/OrdinalMeta}
  28003. */
  28004. OrdinalMeta.createByAxisModel = function (axisModel) {
  28005. var option = axisModel.option;
  28006. var data = option.data;
  28007. var categories = data && map(data, getName);
  28008. return new OrdinalMeta({
  28009. categories: categories,
  28010. needCollect: !categories,
  28011. // deduplication is default in axis.
  28012. deduplication: option.dedplication !== false
  28013. });
  28014. };
  28015. var proto$1 = OrdinalMeta.prototype;
  28016. /**
  28017. * @param {string} category
  28018. * @return {number} ordinal
  28019. */
  28020. proto$1.getOrdinal = function (category) {
  28021. return getOrCreateMap(this).get(category);
  28022. };
  28023. /**
  28024. * @param {*} category
  28025. * @return {number} The ordinal. If not found, return NaN.
  28026. */
  28027. proto$1.parseAndCollect = function (category) {
  28028. var index;
  28029. var needCollect = this._needCollect;
  28030. // The value of category dim can be the index of the given category set.
  28031. // This feature is only supported when !needCollect, because we should
  28032. // consider a common case: a value is 2017, which is a number but is
  28033. // expected to be tread as a category. This case usually happen in dataset,
  28034. // where it happent to be no need of the index feature.
  28035. if (typeof category !== 'string' && !needCollect) {
  28036. return category;
  28037. }
  28038. // Optimize for the scenario:
  28039. // category is ['2012-01-01', '2012-01-02', ...], where the input
  28040. // data has been ensured not duplicate and is large data.
  28041. // Notice, if a dataset dimension provide categroies, usually echarts
  28042. // should remove duplication except user tell echarts dont do that
  28043. // (set axis.deduplication = false), because echarts do not know whether
  28044. // the values in the category dimension has duplication (consider the
  28045. // parallel-aqi example)
  28046. if (needCollect && !this._deduplication) {
  28047. index = this.categories.length;
  28048. this.categories[index] = category;
  28049. return index;
  28050. }
  28051. var map$$1 = getOrCreateMap(this);
  28052. index = map$$1.get(category);
  28053. if (index == null) {
  28054. if (needCollect) {
  28055. index = this.categories.length;
  28056. this.categories[index] = category;
  28057. map$$1.set(category, index);
  28058. }
  28059. else {
  28060. index = NaN;
  28061. }
  28062. }
  28063. return index;
  28064. };
  28065. // Consider big data, do not create map until needed.
  28066. function getOrCreateMap(ordinalMeta) {
  28067. return ordinalMeta._map || (
  28068. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  28069. );
  28070. }
  28071. function getName(obj) {
  28072. if (isObject$1(obj) && obj.value != null) {
  28073. return obj.value;
  28074. }
  28075. else {
  28076. return obj + '';
  28077. }
  28078. }
  28079. /*
  28080. * Licensed to the Apache Software Foundation (ASF) under one
  28081. * or more contributor license agreements. See the NOTICE file
  28082. * distributed with this work for additional information
  28083. * regarding copyright ownership. The ASF licenses this file
  28084. * to you under the Apache License, Version 2.0 (the
  28085. * "License"); you may not use this file except in compliance
  28086. * with the License. You may obtain a copy of the License at
  28087. *
  28088. * http://www.apache.org/licenses/LICENSE-2.0
  28089. *
  28090. * Unless required by applicable law or agreed to in writing,
  28091. * software distributed under the License is distributed on an
  28092. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28093. * KIND, either express or implied. See the License for the
  28094. * specific language governing permissions and limitations
  28095. * under the License.
  28096. */
  28097. /**
  28098. * Linear continuous scale
  28099. * @module echarts/coord/scale/Ordinal
  28100. *
  28101. * http://en.wikipedia.org/wiki/Level_of_measurement
  28102. */
  28103. // FIXME only one data
  28104. var scaleProto = Scale.prototype;
  28105. var OrdinalScale = Scale.extend({
  28106. type: 'ordinal',
  28107. /**
  28108. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  28109. */
  28110. init: function (ordinalMeta, extent) {
  28111. // Caution: Should not use instanceof, consider ec-extensions using
  28112. // import approach to get OrdinalMeta class.
  28113. if (!ordinalMeta || isArray(ordinalMeta)) {
  28114. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  28115. }
  28116. this._ordinalMeta = ordinalMeta;
  28117. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  28118. },
  28119. parse: function (val) {
  28120. return typeof val === 'string'
  28121. ? this._ordinalMeta.getOrdinal(val)
  28122. // val might be float.
  28123. : Math.round(val);
  28124. },
  28125. contain: function (rank) {
  28126. rank = this.parse(rank);
  28127. return scaleProto.contain.call(this, rank)
  28128. && this._ordinalMeta.categories[rank] != null;
  28129. },
  28130. /**
  28131. * Normalize given rank or name to linear [0, 1]
  28132. * @param {number|string} [val]
  28133. * @return {number}
  28134. */
  28135. normalize: function (val) {
  28136. return scaleProto.normalize.call(this, this.parse(val));
  28137. },
  28138. scale: function (val) {
  28139. return Math.round(scaleProto.scale.call(this, val));
  28140. },
  28141. /**
  28142. * @return {Array}
  28143. */
  28144. getTicks: function () {
  28145. var ticks = [];
  28146. var extent = this._extent;
  28147. var rank = extent[0];
  28148. while (rank <= extent[1]) {
  28149. ticks.push(rank);
  28150. rank++;
  28151. }
  28152. return ticks;
  28153. },
  28154. /**
  28155. * Get item on rank n
  28156. * @param {number} n
  28157. * @return {string}
  28158. */
  28159. getLabel: function (n) {
  28160. if (!this.isBlank()) {
  28161. // Note that if no data, ordinalMeta.categories is an empty array.
  28162. return this._ordinalMeta.categories[n];
  28163. }
  28164. },
  28165. /**
  28166. * @return {number}
  28167. */
  28168. count: function () {
  28169. return this._extent[1] - this._extent[0] + 1;
  28170. },
  28171. /**
  28172. * @override
  28173. */
  28174. unionExtentFromData: function (data, dim) {
  28175. this.unionExtent(data.getApproximateExtent(dim));
  28176. },
  28177. getOrdinalMeta: function () {
  28178. return this._ordinalMeta;
  28179. },
  28180. niceTicks: noop,
  28181. niceExtent: noop
  28182. });
  28183. /**
  28184. * @return {module:echarts/scale/Time}
  28185. */
  28186. OrdinalScale.create = function () {
  28187. return new OrdinalScale();
  28188. };
  28189. /*
  28190. * Licensed to the Apache Software Foundation (ASF) under one
  28191. * or more contributor license agreements. See the NOTICE file
  28192. * distributed with this work for additional information
  28193. * regarding copyright ownership. The ASF licenses this file
  28194. * to you under the Apache License, Version 2.0 (the
  28195. * "License"); you may not use this file except in compliance
  28196. * with the License. You may obtain a copy of the License at
  28197. *
  28198. * http://www.apache.org/licenses/LICENSE-2.0
  28199. *
  28200. * Unless required by applicable law or agreed to in writing,
  28201. * software distributed under the License is distributed on an
  28202. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28203. * KIND, either express or implied. See the License for the
  28204. * specific language governing permissions and limitations
  28205. * under the License.
  28206. */
  28207. /**
  28208. * For testable.
  28209. */
  28210. var roundNumber$1 = round$2;
  28211. /**
  28212. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  28213. * Should be extent[0] < extent[1].
  28214. * @param {number} splitNumber splitNumber should be >= 1.
  28215. * @param {number} [minInterval]
  28216. * @param {number} [maxInterval]
  28217. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  28218. */
  28219. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  28220. var result = {};
  28221. var span = extent[1] - extent[0];
  28222. var interval = result.interval = nice(span / splitNumber, true);
  28223. if (minInterval != null && interval < minInterval) {
  28224. interval = result.interval = minInterval;
  28225. }
  28226. if (maxInterval != null && interval > maxInterval) {
  28227. interval = result.interval = maxInterval;
  28228. }
  28229. // Tow more digital for tick.
  28230. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  28231. // Niced extent inside original extent
  28232. var niceTickExtent = result.niceTickExtent = [
  28233. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  28234. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  28235. ];
  28236. fixExtent(niceTickExtent, extent);
  28237. return result;
  28238. }
  28239. /**
  28240. * @param {number} interval
  28241. * @return {number} interval precision
  28242. */
  28243. function getIntervalPrecision(interval) {
  28244. // Tow more digital for tick.
  28245. return getPrecisionSafe(interval) + 2;
  28246. }
  28247. function clamp(niceTickExtent, idx, extent) {
  28248. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  28249. }
  28250. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  28251. function fixExtent(niceTickExtent, extent) {
  28252. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  28253. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  28254. clamp(niceTickExtent, 0, extent);
  28255. clamp(niceTickExtent, 1, extent);
  28256. if (niceTickExtent[0] > niceTickExtent[1]) {
  28257. niceTickExtent[0] = niceTickExtent[1];
  28258. }
  28259. }
  28260. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  28261. var ticks = [];
  28262. // If interval is 0, return [];
  28263. if (!interval) {
  28264. return ticks;
  28265. }
  28266. // Consider this case: using dataZoom toolbox, zoom and zoom.
  28267. var safeLimit = 10000;
  28268. if (extent[0] < niceTickExtent[0]) {
  28269. ticks.push(extent[0]);
  28270. }
  28271. var tick = niceTickExtent[0];
  28272. while (tick <= niceTickExtent[1]) {
  28273. ticks.push(tick);
  28274. // Avoid rounding error
  28275. tick = roundNumber$1(tick + interval, intervalPrecision);
  28276. if (tick === ticks[ticks.length - 1]) {
  28277. // Consider out of safe float point, e.g.,
  28278. // -3711126.9907707 + 2e-10 === -3711126.9907707
  28279. break;
  28280. }
  28281. if (ticks.length > safeLimit) {
  28282. return [];
  28283. }
  28284. }
  28285. // Consider this case: the last item of ticks is smaller
  28286. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  28287. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  28288. ticks.push(extent[1]);
  28289. }
  28290. return ticks;
  28291. }
  28292. /*
  28293. * Licensed to the Apache Software Foundation (ASF) under one
  28294. * or more contributor license agreements. See the NOTICE file
  28295. * distributed with this work for additional information
  28296. * regarding copyright ownership. The ASF licenses this file
  28297. * to you under the Apache License, Version 2.0 (the
  28298. * "License"); you may not use this file except in compliance
  28299. * with the License. You may obtain a copy of the License at
  28300. *
  28301. * http://www.apache.org/licenses/LICENSE-2.0
  28302. *
  28303. * Unless required by applicable law or agreed to in writing,
  28304. * software distributed under the License is distributed on an
  28305. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28306. * KIND, either express or implied. See the License for the
  28307. * specific language governing permissions and limitations
  28308. * under the License.
  28309. */
  28310. /**
  28311. * Interval scale
  28312. * @module echarts/scale/Interval
  28313. */
  28314. var roundNumber = round$2;
  28315. /**
  28316. * @alias module:echarts/coord/scale/Interval
  28317. * @constructor
  28318. */
  28319. var IntervalScale = Scale.extend({
  28320. type: 'interval',
  28321. _interval: 0,
  28322. _intervalPrecision: 2,
  28323. setExtent: function (start, end) {
  28324. var thisExtent = this._extent;
  28325. //start,end may be a Number like '25',so...
  28326. if (!isNaN(start)) {
  28327. thisExtent[0] = parseFloat(start);
  28328. }
  28329. if (!isNaN(end)) {
  28330. thisExtent[1] = parseFloat(end);
  28331. }
  28332. },
  28333. unionExtent: function (other) {
  28334. var extent = this._extent;
  28335. other[0] < extent[0] && (extent[0] = other[0]);
  28336. other[1] > extent[1] && (extent[1] = other[1]);
  28337. // unionExtent may called by it's sub classes
  28338. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  28339. },
  28340. /**
  28341. * Get interval
  28342. */
  28343. getInterval: function () {
  28344. return this._interval;
  28345. },
  28346. /**
  28347. * Set interval
  28348. */
  28349. setInterval: function (interval) {
  28350. this._interval = interval;
  28351. // Dropped auto calculated niceExtent and use user setted extent
  28352. // We assume user wan't to set both interval, min, max to get a better result
  28353. this._niceExtent = this._extent.slice();
  28354. this._intervalPrecision = getIntervalPrecision(interval);
  28355. },
  28356. /**
  28357. * @return {Array.<number>}
  28358. */
  28359. getTicks: function () {
  28360. return intervalScaleGetTicks(
  28361. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  28362. );
  28363. },
  28364. /**
  28365. * @param {number} data
  28366. * @param {Object} [opt]
  28367. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  28368. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  28369. * @return {string}
  28370. */
  28371. getLabel: function (data, opt) {
  28372. if (data == null) {
  28373. return '';
  28374. }
  28375. var precision = opt && opt.precision;
  28376. if (precision == null) {
  28377. precision = getPrecisionSafe(data) || 0;
  28378. }
  28379. else if (precision === 'auto') {
  28380. // Should be more precise then tick.
  28381. precision = this._intervalPrecision;
  28382. }
  28383. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  28384. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  28385. data = roundNumber(data, precision, true);
  28386. return addCommas(data);
  28387. },
  28388. /**
  28389. * Update interval and extent of intervals for nice ticks
  28390. *
  28391. * @param {number} [splitNumber = 5] Desired number of ticks
  28392. * @param {number} [minInterval]
  28393. * @param {number} [maxInterval]
  28394. */
  28395. niceTicks: function (splitNumber, minInterval, maxInterval) {
  28396. splitNumber = splitNumber || 5;
  28397. var extent = this._extent;
  28398. var span = extent[1] - extent[0];
  28399. if (!isFinite(span)) {
  28400. return;
  28401. }
  28402. // User may set axis min 0 and data are all negative
  28403. // FIXME If it needs to reverse ?
  28404. if (span < 0) {
  28405. span = -span;
  28406. extent.reverse();
  28407. }
  28408. var result = intervalScaleNiceTicks(
  28409. extent, splitNumber, minInterval, maxInterval
  28410. );
  28411. this._intervalPrecision = result.intervalPrecision;
  28412. this._interval = result.interval;
  28413. this._niceExtent = result.niceTickExtent;
  28414. },
  28415. /**
  28416. * Nice extent.
  28417. * @param {Object} opt
  28418. * @param {number} [opt.splitNumber = 5] Given approx tick number
  28419. * @param {boolean} [opt.fixMin=false]
  28420. * @param {boolean} [opt.fixMax=false]
  28421. * @param {boolean} [opt.minInterval]
  28422. * @param {boolean} [opt.maxInterval]
  28423. */
  28424. niceExtent: function (opt) {
  28425. var extent = this._extent;
  28426. // If extent start and end are same, expand them
  28427. if (extent[0] === extent[1]) {
  28428. if (extent[0] !== 0) {
  28429. // Expand extent
  28430. var expandSize = extent[0];
  28431. // In the fowllowing case
  28432. // Axis has been fixed max 100
  28433. // Plus data are all 100 and axis extent are [100, 100].
  28434. // Extend to the both side will cause expanded max is larger than fixed max.
  28435. // So only expand to the smaller side.
  28436. if (!opt.fixMax) {
  28437. extent[1] += expandSize / 2;
  28438. extent[0] -= expandSize / 2;
  28439. }
  28440. else {
  28441. extent[0] -= expandSize / 2;
  28442. }
  28443. }
  28444. else {
  28445. extent[1] = 1;
  28446. }
  28447. }
  28448. var span = extent[1] - extent[0];
  28449. // If there are no data and extent are [Infinity, -Infinity]
  28450. if (!isFinite(span)) {
  28451. extent[0] = 0;
  28452. extent[1] = 1;
  28453. }
  28454. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  28455. // var extent = this._extent;
  28456. var interval = this._interval;
  28457. if (!opt.fixMin) {
  28458. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  28459. }
  28460. if (!opt.fixMax) {
  28461. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  28462. }
  28463. }
  28464. });
  28465. /**
  28466. * @return {module:echarts/scale/Time}
  28467. */
  28468. IntervalScale.create = function () {
  28469. return new IntervalScale();
  28470. };
  28471. /*
  28472. * Licensed to the Apache Software Foundation (ASF) under one
  28473. * or more contributor license agreements. See the NOTICE file
  28474. * distributed with this work for additional information
  28475. * regarding copyright ownership. The ASF licenses this file
  28476. * to you under the Apache License, Version 2.0 (the
  28477. * "License"); you may not use this file except in compliance
  28478. * with the License. You may obtain a copy of the License at
  28479. *
  28480. * http://www.apache.org/licenses/LICENSE-2.0
  28481. *
  28482. * Unless required by applicable law or agreed to in writing,
  28483. * software distributed under the License is distributed on an
  28484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28485. * KIND, either express or implied. See the License for the
  28486. * specific language governing permissions and limitations
  28487. * under the License.
  28488. */
  28489. /* global Float32Array */
  28490. var STACK_PREFIX = '__ec_stack_';
  28491. var LARGE_BAR_MIN_WIDTH = 0.5;
  28492. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  28493. function getSeriesStackId(seriesModel) {
  28494. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  28495. }
  28496. function getAxisKey(axis) {
  28497. return axis.dim + axis.index;
  28498. }
  28499. /**
  28500. * @param {Object} opt
  28501. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  28502. * @param {number} opt.count Positive interger.
  28503. * @param {number} [opt.barWidth]
  28504. * @param {number} [opt.barMaxWidth]
  28505. * @param {number} [opt.barGap]
  28506. * @param {number} [opt.barCategoryGap]
  28507. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  28508. */
  28509. function prepareLayoutBarSeries(seriesType, ecModel) {
  28510. var seriesModels = [];
  28511. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  28512. // Check series coordinate, do layout for cartesian2d only
  28513. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  28514. seriesModels.push(seriesModel);
  28515. }
  28516. });
  28517. return seriesModels;
  28518. }
  28519. function makeColumnLayout(barSeries) {
  28520. var seriesInfoList = [];
  28521. each$1(barSeries, function (seriesModel) {
  28522. var data = seriesModel.getData();
  28523. var cartesian = seriesModel.coordinateSystem;
  28524. var baseAxis = cartesian.getBaseAxis();
  28525. var axisExtent = baseAxis.getExtent();
  28526. var bandWidth = baseAxis.type === 'category'
  28527. ? baseAxis.getBandWidth()
  28528. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  28529. var barWidth = parsePercent$1(
  28530. seriesModel.get('barWidth'), bandWidth
  28531. );
  28532. var barMaxWidth = parsePercent$1(
  28533. seriesModel.get('barMaxWidth'), bandWidth
  28534. );
  28535. var barGap = seriesModel.get('barGap');
  28536. var barCategoryGap = seriesModel.get('barCategoryGap');
  28537. seriesInfoList.push({
  28538. bandWidth: bandWidth,
  28539. barWidth: barWidth,
  28540. barMaxWidth: barMaxWidth,
  28541. barGap: barGap,
  28542. barCategoryGap: barCategoryGap,
  28543. axisKey: getAxisKey(baseAxis),
  28544. stackId: getSeriesStackId(seriesModel)
  28545. });
  28546. });
  28547. return doCalBarWidthAndOffset(seriesInfoList);
  28548. }
  28549. function doCalBarWidthAndOffset(seriesInfoList) {
  28550. // Columns info on each category axis. Key is cartesian name
  28551. var columnsMap = {};
  28552. each$1(seriesInfoList, function (seriesInfo, idx) {
  28553. var axisKey = seriesInfo.axisKey;
  28554. var bandWidth = seriesInfo.bandWidth;
  28555. var columnsOnAxis = columnsMap[axisKey] || {
  28556. bandWidth: bandWidth,
  28557. remainedWidth: bandWidth,
  28558. autoWidthCount: 0,
  28559. categoryGap: '20%',
  28560. gap: '30%',
  28561. stacks: {}
  28562. };
  28563. var stacks = columnsOnAxis.stacks;
  28564. columnsMap[axisKey] = columnsOnAxis;
  28565. var stackId = seriesInfo.stackId;
  28566. if (!stacks[stackId]) {
  28567. columnsOnAxis.autoWidthCount++;
  28568. }
  28569. stacks[stackId] = stacks[stackId] || {
  28570. width: 0,
  28571. maxWidth: 0
  28572. };
  28573. // Caution: In a single coordinate system, these barGrid attributes
  28574. // will be shared by series. Consider that they have default values,
  28575. // only the attributes set on the last series will work.
  28576. // Do not change this fact unless there will be a break change.
  28577. // TODO
  28578. var barWidth = seriesInfo.barWidth;
  28579. if (barWidth && !stacks[stackId].width) {
  28580. // See #6312, do not restrict width.
  28581. stacks[stackId].width = barWidth;
  28582. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  28583. columnsOnAxis.remainedWidth -= barWidth;
  28584. }
  28585. var barMaxWidth = seriesInfo.barMaxWidth;
  28586. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  28587. var barGap = seriesInfo.barGap;
  28588. (barGap != null) && (columnsOnAxis.gap = barGap);
  28589. var barCategoryGap = seriesInfo.barCategoryGap;
  28590. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  28591. });
  28592. var result = {};
  28593. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  28594. result[coordSysName] = {};
  28595. var stacks = columnsOnAxis.stacks;
  28596. var bandWidth = columnsOnAxis.bandWidth;
  28597. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  28598. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  28599. var remainedWidth = columnsOnAxis.remainedWidth;
  28600. var autoWidthCount = columnsOnAxis.autoWidthCount;
  28601. var autoWidth = (remainedWidth - categoryGap)
  28602. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  28603. autoWidth = Math.max(autoWidth, 0);
  28604. // Find if any auto calculated bar exceeded maxBarWidth
  28605. each$1(stacks, function (column, stack) {
  28606. var maxWidth = column.maxWidth;
  28607. if (maxWidth && maxWidth < autoWidth) {
  28608. maxWidth = Math.min(maxWidth, remainedWidth);
  28609. if (column.width) {
  28610. maxWidth = Math.min(maxWidth, column.width);
  28611. }
  28612. remainedWidth -= maxWidth;
  28613. column.width = maxWidth;
  28614. autoWidthCount--;
  28615. }
  28616. });
  28617. // Recalculate width again
  28618. autoWidth = (remainedWidth - categoryGap)
  28619. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  28620. autoWidth = Math.max(autoWidth, 0);
  28621. var widthSum = 0;
  28622. var lastColumn;
  28623. each$1(stacks, function (column, idx) {
  28624. if (!column.width) {
  28625. column.width = autoWidth;
  28626. }
  28627. lastColumn = column;
  28628. widthSum += column.width * (1 + barGapPercent);
  28629. });
  28630. if (lastColumn) {
  28631. widthSum -= lastColumn.width * barGapPercent;
  28632. }
  28633. var offset = -widthSum / 2;
  28634. each$1(stacks, function (column, stackId) {
  28635. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  28636. offset: offset,
  28637. width: column.width
  28638. };
  28639. offset += column.width * (1 + barGapPercent);
  28640. });
  28641. });
  28642. return result;
  28643. }
  28644. /**
  28645. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  28646. * @param {module:echarts/coord/Axis} axis
  28647. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  28648. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  28649. */
  28650. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  28651. if (barWidthAndOffset && axis) {
  28652. var result = barWidthAndOffset[getAxisKey(axis)];
  28653. if (result != null && seriesModel != null) {
  28654. result = result[getSeriesStackId(seriesModel)];
  28655. }
  28656. return result;
  28657. }
  28658. }
  28659. /**
  28660. * @param {string} seriesType
  28661. * @param {module:echarts/model/Global} ecModel
  28662. */
  28663. function layout(seriesType, ecModel) {
  28664. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  28665. var barWidthAndOffset = makeColumnLayout(seriesModels);
  28666. var lastStackCoords = {};
  28667. each$1(seriesModels, function (seriesModel) {
  28668. var data = seriesModel.getData();
  28669. var cartesian = seriesModel.coordinateSystem;
  28670. var baseAxis = cartesian.getBaseAxis();
  28671. var stackId = getSeriesStackId(seriesModel);
  28672. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  28673. var columnOffset = columnLayoutInfo.offset;
  28674. var columnWidth = columnLayoutInfo.width;
  28675. var valueAxis = cartesian.getOtherAxis(baseAxis);
  28676. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  28677. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  28678. data.setLayout({
  28679. offset: columnOffset,
  28680. size: columnWidth
  28681. });
  28682. var valueDim = data.mapDimension(valueAxis.dim);
  28683. var baseDim = data.mapDimension(baseAxis.dim);
  28684. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  28685. var isValueAxisH = valueAxis.isHorizontal();
  28686. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  28687. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28688. var value = data.get(valueDim, idx);
  28689. var baseValue = data.get(baseDim, idx);
  28690. if (isNaN(value)) {
  28691. continue;
  28692. }
  28693. var sign = value >= 0 ? 'p' : 'n';
  28694. var baseCoord = valueAxisStart;
  28695. // Because of the barMinHeight, we can not use the value in
  28696. // stackResultDimension directly.
  28697. if (stacked) {
  28698. // Only ordinal axis can be stacked.
  28699. if (!lastStackCoords[stackId][baseValue]) {
  28700. lastStackCoords[stackId][baseValue] = {
  28701. p: valueAxisStart, // Positive stack
  28702. n: valueAxisStart // Negative stack
  28703. };
  28704. }
  28705. // Should also consider #4243
  28706. baseCoord = lastStackCoords[stackId][baseValue][sign];
  28707. }
  28708. var x;
  28709. var y;
  28710. var width;
  28711. var height;
  28712. if (isValueAxisH) {
  28713. var coord = cartesian.dataToPoint([value, baseValue]);
  28714. x = baseCoord;
  28715. y = coord[1] + columnOffset;
  28716. width = coord[0] - valueAxisStart;
  28717. height = columnWidth;
  28718. if (Math.abs(width) < barMinHeight) {
  28719. width = (width < 0 ? -1 : 1) * barMinHeight;
  28720. }
  28721. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  28722. }
  28723. else {
  28724. var coord = cartesian.dataToPoint([baseValue, value]);
  28725. x = coord[0] + columnOffset;
  28726. y = baseCoord;
  28727. width = columnWidth;
  28728. height = coord[1] - valueAxisStart;
  28729. if (Math.abs(height) < barMinHeight) {
  28730. // Include zero to has a positive bar
  28731. height = (height <= 0 ? -1 : 1) * barMinHeight;
  28732. }
  28733. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  28734. }
  28735. data.setItemLayout(idx, {
  28736. x: x,
  28737. y: y,
  28738. width: width,
  28739. height: height
  28740. });
  28741. }
  28742. }, this);
  28743. }
  28744. // TODO: Do not support stack in large mode yet.
  28745. var largeLayout = {
  28746. seriesType: 'bar',
  28747. plan: createRenderPlanner(),
  28748. reset: function (seriesModel) {
  28749. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  28750. return;
  28751. }
  28752. var data = seriesModel.getData();
  28753. var cartesian = seriesModel.coordinateSystem;
  28754. var baseAxis = cartesian.getBaseAxis();
  28755. var valueAxis = cartesian.getOtherAxis(baseAxis);
  28756. var valueDim = data.mapDimension(valueAxis.dim);
  28757. var baseDim = data.mapDimension(baseAxis.dim);
  28758. var valueAxisHorizontal = valueAxis.isHorizontal();
  28759. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  28760. var barWidth = retrieveColumnLayout(
  28761. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  28762. ).width;
  28763. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  28764. barWidth = LARGE_BAR_MIN_WIDTH;
  28765. }
  28766. return {progress: progress};
  28767. function progress(params, data) {
  28768. var largePoints = new LargeArr(params.count * 2);
  28769. var dataIndex;
  28770. var coord = [];
  28771. var valuePair = [];
  28772. var offset = 0;
  28773. while ((dataIndex = params.next()) != null) {
  28774. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  28775. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  28776. coord = cartesian.dataToPoint(valuePair, null, coord);
  28777. largePoints[offset++] = coord[0];
  28778. largePoints[offset++] = coord[1];
  28779. }
  28780. data.setLayout({
  28781. largePoints: largePoints,
  28782. barWidth: barWidth,
  28783. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  28784. valueAxisHorizontal: valueAxisHorizontal
  28785. });
  28786. }
  28787. }
  28788. };
  28789. function isOnCartesian(seriesModel) {
  28790. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  28791. }
  28792. function isInLargeMode(seriesModel) {
  28793. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  28794. }
  28795. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  28796. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  28797. var extent = valueAxis.getGlobalExtent();
  28798. var min;
  28799. var max;
  28800. if (extent[0] > extent[1]) {
  28801. min = extent[1];
  28802. max = extent[0];
  28803. }
  28804. else {
  28805. min = extent[0];
  28806. max = extent[1];
  28807. }
  28808. var valueStart = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  28809. valueStart < min && (valueStart = min);
  28810. valueStart > max && (valueStart = max);
  28811. return valueStart;
  28812. }
  28813. /*
  28814. * Licensed to the Apache Software Foundation (ASF) under one
  28815. * or more contributor license agreements. See the NOTICE file
  28816. * distributed with this work for additional information
  28817. * regarding copyright ownership. The ASF licenses this file
  28818. * to you under the Apache License, Version 2.0 (the
  28819. * "License"); you may not use this file except in compliance
  28820. * with the License. You may obtain a copy of the License at
  28821. *
  28822. * http://www.apache.org/licenses/LICENSE-2.0
  28823. *
  28824. * Unless required by applicable law or agreed to in writing,
  28825. * software distributed under the License is distributed on an
  28826. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28827. * KIND, either express or implied. See the License for the
  28828. * specific language governing permissions and limitations
  28829. * under the License.
  28830. */
  28831. /*
  28832. * A third-party license is embeded for some of the code in this file:
  28833. * The "scaleLevels" was originally copied from "d3.js" with some
  28834. * modifications made for this project.
  28835. * (See more details in the comment on the definition of "scaleLevels" below.)
  28836. * The use of the source code of this file is also subject to the terms
  28837. * and consitions of the license of "d3.js" (BSD-3Clause, see
  28838. * </licenses/LICENSE-d3>).
  28839. */
  28840. // [About UTC and local time zone]:
  28841. // In most cases, `number.parseDate` will treat input data string as local time
  28842. // (except time zone is specified in time string). And `format.formateTime` returns
  28843. // local time by default. option.useUTC is false by default. This design have
  28844. // concidered these common case:
  28845. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  28846. // in local time by default.
  28847. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  28848. // as its original time, without any time difference.
  28849. var intervalScaleProto = IntervalScale.prototype;
  28850. var mathCeil = Math.ceil;
  28851. var mathFloor = Math.floor;
  28852. var ONE_SECOND = 1000;
  28853. var ONE_MINUTE = ONE_SECOND * 60;
  28854. var ONE_HOUR = ONE_MINUTE * 60;
  28855. var ONE_DAY = ONE_HOUR * 24;
  28856. // FIXME 公用?
  28857. var bisect = function (a, x, lo, hi) {
  28858. while (lo < hi) {
  28859. var mid = lo + hi >>> 1;
  28860. if (a[mid][1] < x) {
  28861. lo = mid + 1;
  28862. }
  28863. else {
  28864. hi = mid;
  28865. }
  28866. }
  28867. return lo;
  28868. };
  28869. /**
  28870. * @alias module:echarts/coord/scale/Time
  28871. * @constructor
  28872. */
  28873. var TimeScale = IntervalScale.extend({
  28874. type: 'time',
  28875. /**
  28876. * @override
  28877. */
  28878. getLabel: function (val) {
  28879. var stepLvl = this._stepLvl;
  28880. var date = new Date(val);
  28881. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  28882. },
  28883. /**
  28884. * @override
  28885. */
  28886. niceExtent: function (opt) {
  28887. var extent = this._extent;
  28888. // If extent start and end are same, expand them
  28889. if (extent[0] === extent[1]) {
  28890. // Expand extent
  28891. extent[0] -= ONE_DAY;
  28892. extent[1] += ONE_DAY;
  28893. }
  28894. // If there are no data and extent are [Infinity, -Infinity]
  28895. if (extent[1] === -Infinity && extent[0] === Infinity) {
  28896. var d = new Date();
  28897. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  28898. extent[0] = extent[1] - ONE_DAY;
  28899. }
  28900. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  28901. // var extent = this._extent;
  28902. var interval = this._interval;
  28903. if (!opt.fixMin) {
  28904. extent[0] = round$2(mathFloor(extent[0] / interval) * interval);
  28905. }
  28906. if (!opt.fixMax) {
  28907. extent[1] = round$2(mathCeil(extent[1] / interval) * interval);
  28908. }
  28909. },
  28910. /**
  28911. * @override
  28912. */
  28913. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  28914. approxTickNum = approxTickNum || 10;
  28915. var extent = this._extent;
  28916. var span = extent[1] - extent[0];
  28917. var approxInterval = span / approxTickNum;
  28918. if (minInterval != null && approxInterval < minInterval) {
  28919. approxInterval = minInterval;
  28920. }
  28921. if (maxInterval != null && approxInterval > maxInterval) {
  28922. approxInterval = maxInterval;
  28923. }
  28924. var scaleLevelsLen = scaleLevels.length;
  28925. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  28926. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  28927. var interval = level[1];
  28928. // Same with interval scale if span is much larger than 1 year
  28929. if (level[0] === 'year') {
  28930. var yearSpan = span / interval;
  28931. // From "Nice Numbers for Graph Labels" of Graphic Gems
  28932. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  28933. var yearStep = nice(yearSpan / approxTickNum, true);
  28934. interval *= yearStep;
  28935. }
  28936. var timezoneOffset = this.getSetting('useUTC')
  28937. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  28938. var niceExtent = [
  28939. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  28940. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  28941. ];
  28942. fixExtent(niceExtent, extent);
  28943. this._stepLvl = level;
  28944. // Interval will be used in getTicks
  28945. this._interval = interval;
  28946. this._niceExtent = niceExtent;
  28947. },
  28948. parse: function (val) {
  28949. // val might be float.
  28950. return +parseDate(val);
  28951. }
  28952. });
  28953. each$1(['contain', 'normalize'], function (methodName) {
  28954. TimeScale.prototype[methodName] = function (val) {
  28955. return intervalScaleProto[methodName].call(this, this.parse(val));
  28956. };
  28957. });
  28958. /**
  28959. * This implementation was originally copied from "d3.js"
  28960. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  28961. * with some modifications made for this program.
  28962. * See the license statement at the head of this file.
  28963. */
  28964. var scaleLevels = [
  28965. // Format interval
  28966. ['hh:mm:ss', ONE_SECOND], // 1s
  28967. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  28968. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  28969. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  28970. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  28971. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  28972. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  28973. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  28974. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  28975. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  28976. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  28977. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  28978. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  28979. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  28980. ['MM-dd\nyyyy', ONE_DAY], // 1d
  28981. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  28982. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  28983. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  28984. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  28985. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  28986. ['week', ONE_DAY * 7], // 7d
  28987. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  28988. ['week', ONE_DAY * 14], // 2w
  28989. ['week', ONE_DAY * 21], // 3w
  28990. ['month', ONE_DAY * 31], // 1M
  28991. ['week', ONE_DAY * 42], // 6w
  28992. ['month', ONE_DAY * 62], // 2M
  28993. ['week', ONE_DAY * 70], // 10w
  28994. ['quarter', ONE_DAY * 95], // 3M
  28995. ['month', ONE_DAY * 31 * 4], // 4M
  28996. ['month', ONE_DAY * 31 * 5], // 5M
  28997. ['half-year', ONE_DAY * 380 / 2], // 6M
  28998. ['month', ONE_DAY * 31 * 8], // 8M
  28999. ['month', ONE_DAY * 31 * 10], // 10M
  29000. ['year', ONE_DAY * 380] // 1Y
  29001. ];
  29002. /**
  29003. * @param {module:echarts/model/Model}
  29004. * @return {module:echarts/scale/Time}
  29005. */
  29006. TimeScale.create = function (model) {
  29007. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  29008. };
  29009. /*
  29010. * Licensed to the Apache Software Foundation (ASF) under one
  29011. * or more contributor license agreements. See the NOTICE file
  29012. * distributed with this work for additional information
  29013. * regarding copyright ownership. The ASF licenses this file
  29014. * to you under the Apache License, Version 2.0 (the
  29015. * "License"); you may not use this file except in compliance
  29016. * with the License. You may obtain a copy of the License at
  29017. *
  29018. * http://www.apache.org/licenses/LICENSE-2.0
  29019. *
  29020. * Unless required by applicable law or agreed to in writing,
  29021. * software distributed under the License is distributed on an
  29022. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29023. * KIND, either express or implied. See the License for the
  29024. * specific language governing permissions and limitations
  29025. * under the License.
  29026. */
  29027. /**
  29028. * Log scale
  29029. * @module echarts/scale/Log
  29030. */
  29031. // Use some method of IntervalScale
  29032. var scaleProto$1 = Scale.prototype;
  29033. var intervalScaleProto$1 = IntervalScale.prototype;
  29034. var getPrecisionSafe$1 = getPrecisionSafe;
  29035. var roundingErrorFix = round$2;
  29036. var mathFloor$1 = Math.floor;
  29037. var mathCeil$1 = Math.ceil;
  29038. var mathPow$1 = Math.pow;
  29039. var mathLog = Math.log;
  29040. var LogScale = Scale.extend({
  29041. type: 'log',
  29042. base: 10,
  29043. $constructor: function () {
  29044. Scale.apply(this, arguments);
  29045. this._originalScale = new IntervalScale();
  29046. },
  29047. /**
  29048. * @return {Array.<number>}
  29049. */
  29050. getTicks: function () {
  29051. var originalScale = this._originalScale;
  29052. var extent = this._extent;
  29053. var originalExtent = originalScale.getExtent();
  29054. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  29055. var powVal = round$2(mathPow$1(this.base, val));
  29056. // Fix #4158
  29057. powVal = (val === extent[0] && originalScale.__fixMin)
  29058. ? fixRoundingError(powVal, originalExtent[0])
  29059. : powVal;
  29060. powVal = (val === extent[1] && originalScale.__fixMax)
  29061. ? fixRoundingError(powVal, originalExtent[1])
  29062. : powVal;
  29063. return powVal;
  29064. }, this);
  29065. },
  29066. /**
  29067. * @param {number} val
  29068. * @return {string}
  29069. */
  29070. getLabel: intervalScaleProto$1.getLabel,
  29071. /**
  29072. * @param {number} val
  29073. * @return {number}
  29074. */
  29075. scale: function (val) {
  29076. val = scaleProto$1.scale.call(this, val);
  29077. return mathPow$1(this.base, val);
  29078. },
  29079. /**
  29080. * @param {number} start
  29081. * @param {number} end
  29082. */
  29083. setExtent: function (start, end) {
  29084. var base = this.base;
  29085. start = mathLog(start) / mathLog(base);
  29086. end = mathLog(end) / mathLog(base);
  29087. intervalScaleProto$1.setExtent.call(this, start, end);
  29088. },
  29089. /**
  29090. * @return {number} end
  29091. */
  29092. getExtent: function () {
  29093. var base = this.base;
  29094. var extent = scaleProto$1.getExtent.call(this);
  29095. extent[0] = mathPow$1(base, extent[0]);
  29096. extent[1] = mathPow$1(base, extent[1]);
  29097. // Fix #4158
  29098. var originalScale = this._originalScale;
  29099. var originalExtent = originalScale.getExtent();
  29100. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  29101. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  29102. return extent;
  29103. },
  29104. /**
  29105. * @param {Array.<number>} extent
  29106. */
  29107. unionExtent: function (extent) {
  29108. this._originalScale.unionExtent(extent);
  29109. var base = this.base;
  29110. extent[0] = mathLog(extent[0]) / mathLog(base);
  29111. extent[1] = mathLog(extent[1]) / mathLog(base);
  29112. scaleProto$1.unionExtent.call(this, extent);
  29113. },
  29114. /**
  29115. * @override
  29116. */
  29117. unionExtentFromData: function (data, dim) {
  29118. // TODO
  29119. // filter value that <= 0
  29120. this.unionExtent(data.getApproximateExtent(dim));
  29121. },
  29122. /**
  29123. * Update interval and extent of intervals for nice ticks
  29124. * @param {number} [approxTickNum = 10] Given approx tick number
  29125. */
  29126. niceTicks: function (approxTickNum) {
  29127. approxTickNum = approxTickNum || 10;
  29128. var extent = this._extent;
  29129. var span = extent[1] - extent[0];
  29130. if (span === Infinity || span <= 0) {
  29131. return;
  29132. }
  29133. var interval = quantity(span);
  29134. var err = approxTickNum / span * interval;
  29135. // Filter ticks to get closer to the desired count.
  29136. if (err <= 0.5) {
  29137. interval *= 10;
  29138. }
  29139. // Interval should be integer
  29140. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  29141. interval *= 10;
  29142. }
  29143. var niceExtent = [
  29144. round$2(mathCeil$1(extent[0] / interval) * interval),
  29145. round$2(mathFloor$1(extent[1] / interval) * interval)
  29146. ];
  29147. this._interval = interval;
  29148. this._niceExtent = niceExtent;
  29149. },
  29150. /**
  29151. * Nice extent.
  29152. * @override
  29153. */
  29154. niceExtent: function (opt) {
  29155. intervalScaleProto$1.niceExtent.call(this, opt);
  29156. var originalScale = this._originalScale;
  29157. originalScale.__fixMin = opt.fixMin;
  29158. originalScale.__fixMax = opt.fixMax;
  29159. }
  29160. });
  29161. each$1(['contain', 'normalize'], function (methodName) {
  29162. LogScale.prototype[methodName] = function (val) {
  29163. val = mathLog(val) / mathLog(this.base);
  29164. return scaleProto$1[methodName].call(this, val);
  29165. };
  29166. });
  29167. LogScale.create = function () {
  29168. return new LogScale();
  29169. };
  29170. function fixRoundingError(val, originalVal) {
  29171. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  29172. }
  29173. /*
  29174. * Licensed to the Apache Software Foundation (ASF) under one
  29175. * or more contributor license agreements. See the NOTICE file
  29176. * distributed with this work for additional information
  29177. * regarding copyright ownership. The ASF licenses this file
  29178. * to you under the Apache License, Version 2.0 (the
  29179. * "License"); you may not use this file except in compliance
  29180. * with the License. You may obtain a copy of the License at
  29181. *
  29182. * http://www.apache.org/licenses/LICENSE-2.0
  29183. *
  29184. * Unless required by applicable law or agreed to in writing,
  29185. * software distributed under the License is distributed on an
  29186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29187. * KIND, either express or implied. See the License for the
  29188. * specific language governing permissions and limitations
  29189. * under the License.
  29190. */
  29191. /**
  29192. * Get axis scale extent before niced.
  29193. * Item of returned array can only be number (including Infinity and NaN).
  29194. */
  29195. function getScaleExtent(scale, model) {
  29196. var scaleType = scale.type;
  29197. var min = model.getMin();
  29198. var max = model.getMax();
  29199. var fixMin = min != null;
  29200. var fixMax = max != null;
  29201. var originalExtent = scale.getExtent();
  29202. var axisDataLen;
  29203. var boundaryGap;
  29204. var span;
  29205. if (scaleType === 'ordinal') {
  29206. axisDataLen = model.getCategories().length;
  29207. }
  29208. else {
  29209. boundaryGap = model.get('boundaryGap');
  29210. if (!isArray(boundaryGap)) {
  29211. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  29212. }
  29213. if (typeof boundaryGap[0] === 'boolean') {
  29214. if (__DEV__) {
  29215. console.warn('Boolean type for boundaryGap is only '
  29216. + 'allowed for ordinal axis. Please use string in '
  29217. + 'percentage instead, e.g., "20%". Currently, '
  29218. + 'boundaryGap is set to be 0.');
  29219. }
  29220. boundaryGap = [0, 0];
  29221. }
  29222. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  29223. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  29224. span = (originalExtent[1] - originalExtent[0])
  29225. || Math.abs(originalExtent[0]);
  29226. }
  29227. // Notice: When min/max is not set (that is, when there are null/undefined,
  29228. // which is the most common case), these cases should be ensured:
  29229. // (1) For 'ordinal', show all axis.data.
  29230. // (2) For others:
  29231. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  29232. // disabled).
  29233. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  29234. // be the result that originalExtent enlarged by boundaryGap.
  29235. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  29236. // FIXME
  29237. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  29238. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  29239. // that the results processed by boundaryGap are positive/negative?
  29240. if (min == null) {
  29241. min = scaleType === 'ordinal'
  29242. ? (axisDataLen ? 0 : NaN)
  29243. : originalExtent[0] - boundaryGap[0] * span;
  29244. }
  29245. if (max == null) {
  29246. max = scaleType === 'ordinal'
  29247. ? (axisDataLen ? axisDataLen - 1 : NaN)
  29248. : originalExtent[1] + boundaryGap[1] * span;
  29249. }
  29250. if (min === 'dataMin') {
  29251. min = originalExtent[0];
  29252. }
  29253. else if (typeof min === 'function') {
  29254. min = min({
  29255. min: originalExtent[0],
  29256. max: originalExtent[1]
  29257. });
  29258. }
  29259. if (max === 'dataMax') {
  29260. max = originalExtent[1];
  29261. }
  29262. else if (typeof max === 'function') {
  29263. max = max({
  29264. min: originalExtent[0],
  29265. max: originalExtent[1]
  29266. });
  29267. }
  29268. (min == null || !isFinite(min)) && (min = NaN);
  29269. (max == null || !isFinite(max)) && (max = NaN);
  29270. scale.setBlank(
  29271. eqNaN(min)
  29272. || eqNaN(max)
  29273. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  29274. );
  29275. // Evaluate if axis needs cross zero
  29276. if (model.getNeedCrossZero()) {
  29277. // Axis is over zero and min is not set
  29278. if (min > 0 && max > 0 && !fixMin) {
  29279. min = 0;
  29280. }
  29281. // Axis is under zero and max is not set
  29282. if (min < 0 && max < 0 && !fixMax) {
  29283. max = 0;
  29284. }
  29285. }
  29286. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  29287. // is base axis
  29288. // FIXME
  29289. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  29290. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  29291. // Should not depend on series type `bar`?
  29292. // (3) Fix that might overlap when using dataZoom.
  29293. // (4) Consider other chart types using `barGrid`?
  29294. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  29295. var ecModel = model.ecModel;
  29296. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  29297. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  29298. var isBaseAxisAndHasBarSeries;
  29299. each$1(barSeriesModels, function (seriesModel) {
  29300. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  29301. });
  29302. if (isBaseAxisAndHasBarSeries) {
  29303. // Calculate placement of bars on axis
  29304. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  29305. // Adjust axis min and max to account for overflow
  29306. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  29307. min = adjustedScale.min;
  29308. max = adjustedScale.max;
  29309. }
  29310. }
  29311. return [min, max];
  29312. }
  29313. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  29314. // Get Axis Length
  29315. var axisExtent = model.axis.getExtent();
  29316. var axisLength = axisExtent[1] - axisExtent[0];
  29317. // Get bars on current base axis and calculate min and max overflow
  29318. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  29319. if (barsOnCurrentAxis === undefined) {
  29320. return {min: min, max: max};
  29321. }
  29322. var minOverflow = Infinity;
  29323. each$1(barsOnCurrentAxis, function (item) {
  29324. minOverflow = Math.min(item.offset, minOverflow);
  29325. });
  29326. var maxOverflow = -Infinity;
  29327. each$1(barsOnCurrentAxis, function (item) {
  29328. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  29329. });
  29330. minOverflow = Math.abs(minOverflow);
  29331. maxOverflow = Math.abs(maxOverflow);
  29332. var totalOverFlow = minOverflow + maxOverflow;
  29333. // Calulate required buffer based on old range and overflow
  29334. var oldRange = max - min;
  29335. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  29336. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  29337. max += overflowBuffer * (maxOverflow / totalOverFlow);
  29338. min -= overflowBuffer * (minOverflow / totalOverFlow);
  29339. return {min: min, max: max};
  29340. }
  29341. function niceScaleExtent(scale, model) {
  29342. var extent = getScaleExtent(scale, model);
  29343. var fixMin = model.getMin() != null;
  29344. var fixMax = model.getMax() != null;
  29345. var splitNumber = model.get('splitNumber');
  29346. if (scale.type === 'log') {
  29347. scale.base = model.get('logBase');
  29348. }
  29349. var scaleType = scale.type;
  29350. scale.setExtent(extent[0], extent[1]);
  29351. scale.niceExtent({
  29352. splitNumber: splitNumber,
  29353. fixMin: fixMin,
  29354. fixMax: fixMax,
  29355. minInterval: (scaleType === 'interval' || scaleType === 'time')
  29356. ? model.get('minInterval') : null,
  29357. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  29358. ? model.get('maxInterval') : null
  29359. });
  29360. // If some one specified the min, max. And the default calculated interval
  29361. // is not good enough. He can specify the interval. It is often appeared
  29362. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  29363. // to be 60.
  29364. // FIXME
  29365. var interval = model.get('interval');
  29366. if (interval != null) {
  29367. scale.setInterval && scale.setInterval(interval);
  29368. }
  29369. }
  29370. /**
  29371. * @param {module:echarts/model/Model} model
  29372. * @param {string} [axisType] Default retrieve from model.type
  29373. * @return {module:echarts/scale/*}
  29374. */
  29375. function createScaleByModel(model, axisType) {
  29376. axisType = axisType || model.get('type');
  29377. if (axisType) {
  29378. switch (axisType) {
  29379. // Buildin scale
  29380. case 'category':
  29381. return new OrdinalScale(
  29382. model.getOrdinalMeta
  29383. ? model.getOrdinalMeta()
  29384. : model.getCategories(),
  29385. [Infinity, -Infinity]
  29386. );
  29387. case 'value':
  29388. return new IntervalScale();
  29389. // Extended scale, like time and log
  29390. default:
  29391. return (Scale.getClass(axisType) || IntervalScale).create(model);
  29392. }
  29393. }
  29394. }
  29395. /**
  29396. * Check if the axis corss 0
  29397. */
  29398. function ifAxisCrossZero(axis) {
  29399. var dataExtent = axis.scale.getExtent();
  29400. var min = dataExtent[0];
  29401. var max = dataExtent[1];
  29402. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  29403. }
  29404. /**
  29405. * @param {module:echarts/coord/Axis} axis
  29406. * @return {Function} Label formatter function.
  29407. * param: {number} tickValue,
  29408. * param: {number} idx, the index in all ticks.
  29409. * If category axis, this param is not requied.
  29410. * return: {string} label string.
  29411. */
  29412. function makeLabelFormatter(axis) {
  29413. var labelFormatter = axis.getLabelModel().get('formatter');
  29414. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  29415. if (typeof labelFormatter === 'string') {
  29416. labelFormatter = (function (tpl) {
  29417. return function (val) {
  29418. // For category axis, get raw value; for numeric axis,
  29419. // get foramtted label like '1,333,444'.
  29420. val = axis.scale.getLabel(val);
  29421. return tpl.replace('{value}', val != null ? val : '');
  29422. };
  29423. })(labelFormatter);
  29424. // Consider empty array
  29425. return labelFormatter;
  29426. }
  29427. else if (typeof labelFormatter === 'function') {
  29428. return function (tickValue, idx) {
  29429. // The original intention of `idx` is "the index of the tick in all ticks".
  29430. // But the previous implementation of category axis do not consider the
  29431. // `axisLabel.interval`, which cause that, for example, the `interval` is
  29432. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  29433. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  29434. // the definition here for back compatibility.
  29435. if (categoryTickStart != null) {
  29436. idx = tickValue - categoryTickStart;
  29437. }
  29438. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  29439. };
  29440. }
  29441. else {
  29442. return function (tick) {
  29443. return axis.scale.getLabel(tick);
  29444. };
  29445. }
  29446. }
  29447. function getAxisRawValue(axis, value) {
  29448. // In category axis with data zoom, tick is not the original
  29449. // index of axis.data. So tick should not be exposed to user
  29450. // in category axis.
  29451. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  29452. }
  29453. /**
  29454. * @param {module:echarts/coord/Axis} axis
  29455. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  29456. */
  29457. function estimateLabelUnionRect(axis) {
  29458. var axisModel = axis.model;
  29459. var scale = axis.scale;
  29460. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  29461. return;
  29462. }
  29463. var isCategory = axis.type === 'category';
  29464. var realNumberScaleTicks;
  29465. var tickCount;
  29466. var categoryScaleExtent = scale.getExtent();
  29467. // Optimize for large category data, avoid call `getTicks()`.
  29468. if (isCategory) {
  29469. tickCount = scale.count();
  29470. }
  29471. else {
  29472. realNumberScaleTicks = scale.getTicks();
  29473. tickCount = realNumberScaleTicks.length;
  29474. }
  29475. var axisLabelModel = axis.getLabelModel();
  29476. var labelFormatter = makeLabelFormatter(axis);
  29477. var rect;
  29478. var step = 1;
  29479. // Simple optimization for large amount of labels
  29480. if (tickCount > 40) {
  29481. step = Math.ceil(tickCount / 40);
  29482. }
  29483. for (var i = 0; i < tickCount; i += step) {
  29484. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  29485. var label = labelFormatter(tickValue);
  29486. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  29487. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29488. rect ? rect.union(singleRect) : (rect = singleRect);
  29489. }
  29490. return rect;
  29491. }
  29492. function rotateTextRect(textRect, rotate) {
  29493. var rotateRadians = rotate * Math.PI / 180;
  29494. var boundingBox = textRect.plain();
  29495. var beforeWidth = boundingBox.width;
  29496. var beforeHeight = boundingBox.height;
  29497. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29498. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29499. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29500. return rotatedRect;
  29501. }
  29502. /**
  29503. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  29504. * @return {number|String} Can be null|'auto'|number|function
  29505. */
  29506. function getOptionCategoryInterval(model) {
  29507. var interval = model.get('interval');
  29508. return interval == null ? 'auto' : interval;
  29509. }
  29510. /**
  29511. * Set `categoryInterval` as 0 implicitly indicates that
  29512. * show all labels reguardless of overlap.
  29513. * @param {Object} axis axisModel.axis
  29514. * @return {boolean}
  29515. */
  29516. function shouldShowAllLabels(axis) {
  29517. return axis.type === 'category'
  29518. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  29519. }
  29520. /*
  29521. * Licensed to the Apache Software Foundation (ASF) under one
  29522. * or more contributor license agreements. See the NOTICE file
  29523. * distributed with this work for additional information
  29524. * regarding copyright ownership. The ASF licenses this file
  29525. * to you under the Apache License, Version 2.0 (the
  29526. * "License"); you may not use this file except in compliance
  29527. * with the License. You may obtain a copy of the License at
  29528. *
  29529. * http://www.apache.org/licenses/LICENSE-2.0
  29530. *
  29531. * Unless required by applicable law or agreed to in writing,
  29532. * software distributed under the License is distributed on an
  29533. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29534. * KIND, either express or implied. See the License for the
  29535. * specific language governing permissions and limitations
  29536. * under the License.
  29537. */
  29538. // import * as axisHelper from './axisHelper';
  29539. var axisModelCommonMixin = {
  29540. /**
  29541. * @param {boolean} origin
  29542. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  29543. */
  29544. getMin: function (origin) {
  29545. var option = this.option;
  29546. var min = (!origin && option.rangeStart != null)
  29547. ? option.rangeStart : option.min;
  29548. if (this.axis
  29549. && min != null
  29550. && min !== 'dataMin'
  29551. && typeof min !== 'function'
  29552. && !eqNaN(min)
  29553. ) {
  29554. min = this.axis.scale.parse(min);
  29555. }
  29556. return min;
  29557. },
  29558. /**
  29559. * @param {boolean} origin
  29560. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  29561. */
  29562. getMax: function (origin) {
  29563. var option = this.option;
  29564. var max = (!origin && option.rangeEnd != null)
  29565. ? option.rangeEnd : option.max;
  29566. if (this.axis
  29567. && max != null
  29568. && max !== 'dataMax'
  29569. && typeof max !== 'function'
  29570. && !eqNaN(max)
  29571. ) {
  29572. max = this.axis.scale.parse(max);
  29573. }
  29574. return max;
  29575. },
  29576. /**
  29577. * @return {boolean}
  29578. */
  29579. getNeedCrossZero: function () {
  29580. var option = this.option;
  29581. return (option.rangeStart != null || option.rangeEnd != null)
  29582. ? false : !option.scale;
  29583. },
  29584. /**
  29585. * Should be implemented by each axis model if necessary.
  29586. * @return {module:echarts/model/Component} coordinate system model
  29587. */
  29588. getCoordSysModel: noop,
  29589. /**
  29590. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  29591. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  29592. */
  29593. setRange: function (rangeStart, rangeEnd) {
  29594. this.option.rangeStart = rangeStart;
  29595. this.option.rangeEnd = rangeEnd;
  29596. },
  29597. /**
  29598. * Reset range
  29599. */
  29600. resetRange: function () {
  29601. // rangeStart and rangeEnd is readonly.
  29602. this.option.rangeStart = this.option.rangeEnd = null;
  29603. }
  29604. };
  29605. /*
  29606. * Licensed to the Apache Software Foundation (ASF) under one
  29607. * or more contributor license agreements. See the NOTICE file
  29608. * distributed with this work for additional information
  29609. * regarding copyright ownership. The ASF licenses this file
  29610. * to you under the Apache License, Version 2.0 (the
  29611. * "License"); you may not use this file except in compliance
  29612. * with the License. You may obtain a copy of the License at
  29613. *
  29614. * http://www.apache.org/licenses/LICENSE-2.0
  29615. *
  29616. * Unless required by applicable law or agreed to in writing,
  29617. * software distributed under the License is distributed on an
  29618. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29619. * KIND, either express or implied. See the License for the
  29620. * specific language governing permissions and limitations
  29621. * under the License.
  29622. */
  29623. // Symbol factory
  29624. /**
  29625. * Triangle shape
  29626. * @inner
  29627. */
  29628. var Triangle = extendShape({
  29629. type: 'triangle',
  29630. shape: {
  29631. cx: 0,
  29632. cy: 0,
  29633. width: 0,
  29634. height: 0
  29635. },
  29636. buildPath: function (path, shape) {
  29637. var cx = shape.cx;
  29638. var cy = shape.cy;
  29639. var width = shape.width / 2;
  29640. var height = shape.height / 2;
  29641. path.moveTo(cx, cy - height);
  29642. path.lineTo(cx + width, cy + height);
  29643. path.lineTo(cx - width, cy + height);
  29644. path.closePath();
  29645. }
  29646. });
  29647. /**
  29648. * Diamond shape
  29649. * @inner
  29650. */
  29651. var Diamond = extendShape({
  29652. type: 'diamond',
  29653. shape: {
  29654. cx: 0,
  29655. cy: 0,
  29656. width: 0,
  29657. height: 0
  29658. },
  29659. buildPath: function (path, shape) {
  29660. var cx = shape.cx;
  29661. var cy = shape.cy;
  29662. var width = shape.width / 2;
  29663. var height = shape.height / 2;
  29664. path.moveTo(cx, cy - height);
  29665. path.lineTo(cx + width, cy);
  29666. path.lineTo(cx, cy + height);
  29667. path.lineTo(cx - width, cy);
  29668. path.closePath();
  29669. }
  29670. });
  29671. /**
  29672. * Pin shape
  29673. * @inner
  29674. */
  29675. var Pin = extendShape({
  29676. type: 'pin',
  29677. shape: {
  29678. // x, y on the cusp
  29679. x: 0,
  29680. y: 0,
  29681. width: 0,
  29682. height: 0
  29683. },
  29684. buildPath: function (path, shape) {
  29685. var x = shape.x;
  29686. var y = shape.y;
  29687. var w = shape.width / 5 * 3;
  29688. // Height must be larger than width
  29689. var h = Math.max(w, shape.height);
  29690. var r = w / 2;
  29691. // Dist on y with tangent point and circle center
  29692. var dy = r * r / (h - r);
  29693. var cy = y - h + r + dy;
  29694. var angle = Math.asin(dy / r);
  29695. // Dist on x with tangent point and circle center
  29696. var dx = Math.cos(angle) * r;
  29697. var tanX = Math.sin(angle);
  29698. var tanY = Math.cos(angle);
  29699. var cpLen = r * 0.6;
  29700. var cpLen2 = r * 0.7;
  29701. path.moveTo(x - dx, cy + dy);
  29702. path.arc(
  29703. x, cy, r,
  29704. Math.PI - angle,
  29705. Math.PI * 2 + angle
  29706. );
  29707. path.bezierCurveTo(
  29708. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  29709. x, y - cpLen2,
  29710. x, y
  29711. );
  29712. path.bezierCurveTo(
  29713. x, y - cpLen2,
  29714. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  29715. x - dx, cy + dy
  29716. );
  29717. path.closePath();
  29718. }
  29719. });
  29720. /**
  29721. * Arrow shape
  29722. * @inner
  29723. */
  29724. var Arrow = extendShape({
  29725. type: 'arrow',
  29726. shape: {
  29727. x: 0,
  29728. y: 0,
  29729. width: 0,
  29730. height: 0
  29731. },
  29732. buildPath: function (ctx, shape) {
  29733. var height = shape.height;
  29734. var width = shape.width;
  29735. var x = shape.x;
  29736. var y = shape.y;
  29737. var dx = width / 3 * 2;
  29738. ctx.moveTo(x, y);
  29739. ctx.lineTo(x + dx, y + height);
  29740. ctx.lineTo(x, y + height / 4 * 3);
  29741. ctx.lineTo(x - dx, y + height);
  29742. ctx.lineTo(x, y);
  29743. ctx.closePath();
  29744. }
  29745. });
  29746. /**
  29747. * Map of path contructors
  29748. * @type {Object.<string, module:zrender/graphic/Path>}
  29749. */
  29750. var symbolCtors = {
  29751. line: Line,
  29752. rect: Rect,
  29753. roundRect: Rect,
  29754. square: Rect,
  29755. circle: Circle,
  29756. diamond: Diamond,
  29757. pin: Pin,
  29758. arrow: Arrow,
  29759. triangle: Triangle
  29760. };
  29761. var symbolShapeMakers = {
  29762. line: function (x, y, w, h, shape) {
  29763. // FIXME
  29764. shape.x1 = x;
  29765. shape.y1 = y + h / 2;
  29766. shape.x2 = x + w;
  29767. shape.y2 = y + h / 2;
  29768. },
  29769. rect: function (x, y, w, h, shape) {
  29770. shape.x = x;
  29771. shape.y = y;
  29772. shape.width = w;
  29773. shape.height = h;
  29774. },
  29775. roundRect: function (x, y, w, h, shape) {
  29776. shape.x = x;
  29777. shape.y = y;
  29778. shape.width = w;
  29779. shape.height = h;
  29780. shape.r = Math.min(w, h) / 4;
  29781. },
  29782. square: function (x, y, w, h, shape) {
  29783. var size = Math.min(w, h);
  29784. shape.x = x;
  29785. shape.y = y;
  29786. shape.width = size;
  29787. shape.height = size;
  29788. },
  29789. circle: function (x, y, w, h, shape) {
  29790. // Put circle in the center of square
  29791. shape.cx = x + w / 2;
  29792. shape.cy = y + h / 2;
  29793. shape.r = Math.min(w, h) / 2;
  29794. },
  29795. diamond: function (x, y, w, h, shape) {
  29796. shape.cx = x + w / 2;
  29797. shape.cy = y + h / 2;
  29798. shape.width = w;
  29799. shape.height = h;
  29800. },
  29801. pin: function (x, y, w, h, shape) {
  29802. shape.x = x + w / 2;
  29803. shape.y = y + h / 2;
  29804. shape.width = w;
  29805. shape.height = h;
  29806. },
  29807. arrow: function (x, y, w, h, shape) {
  29808. shape.x = x + w / 2;
  29809. shape.y = y + h / 2;
  29810. shape.width = w;
  29811. shape.height = h;
  29812. },
  29813. triangle: function (x, y, w, h, shape) {
  29814. shape.cx = x + w / 2;
  29815. shape.cy = y + h / 2;
  29816. shape.width = w;
  29817. shape.height = h;
  29818. }
  29819. };
  29820. var symbolBuildProxies = {};
  29821. each$1(symbolCtors, function (Ctor, name) {
  29822. symbolBuildProxies[name] = new Ctor();
  29823. });
  29824. var SymbolClz = extendShape({
  29825. type: 'symbol',
  29826. shape: {
  29827. symbolType: '',
  29828. x: 0,
  29829. y: 0,
  29830. width: 0,
  29831. height: 0
  29832. },
  29833. beforeBrush: function () {
  29834. var style = this.style;
  29835. var shape = this.shape;
  29836. // FIXME
  29837. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  29838. style.textPosition = ['50%', '40%'];
  29839. style.textAlign = 'center';
  29840. style.textVerticalAlign = 'middle';
  29841. }
  29842. },
  29843. buildPath: function (ctx, shape, inBundle) {
  29844. var symbolType = shape.symbolType;
  29845. var proxySymbol = symbolBuildProxies[symbolType];
  29846. if (shape.symbolType !== 'none') {
  29847. if (!proxySymbol) {
  29848. // Default rect
  29849. symbolType = 'rect';
  29850. proxySymbol = symbolBuildProxies[symbolType];
  29851. }
  29852. symbolShapeMakers[symbolType](
  29853. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  29854. );
  29855. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  29856. }
  29857. }
  29858. });
  29859. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  29860. function symbolPathSetColor(color, innerColor) {
  29861. if (this.type !== 'image') {
  29862. var symbolStyle = this.style;
  29863. var symbolShape = this.shape;
  29864. if (symbolShape && symbolShape.symbolType === 'line') {
  29865. symbolStyle.stroke = color;
  29866. }
  29867. else if (this.__isEmptyBrush) {
  29868. symbolStyle.stroke = color;
  29869. symbolStyle.fill = innerColor || '#fff';
  29870. }
  29871. else {
  29872. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  29873. symbolStyle.fill && (symbolStyle.fill = color);
  29874. symbolStyle.stroke && (symbolStyle.stroke = color);
  29875. }
  29876. this.dirty(false);
  29877. }
  29878. }
  29879. /**
  29880. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  29881. * @param {string} symbolType
  29882. * @param {number} x
  29883. * @param {number} y
  29884. * @param {number} w
  29885. * @param {number} h
  29886. * @param {string} color
  29887. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  29888. * for path and image only.
  29889. */
  29890. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  29891. // TODO Support image object, DynamicImage.
  29892. var isEmpty = symbolType.indexOf('empty') === 0;
  29893. if (isEmpty) {
  29894. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  29895. }
  29896. var symbolPath;
  29897. if (symbolType.indexOf('image://') === 0) {
  29898. symbolPath = makeImage(
  29899. symbolType.slice(8),
  29900. new BoundingRect(x, y, w, h),
  29901. keepAspect ? 'center' : 'cover'
  29902. );
  29903. }
  29904. else if (symbolType.indexOf('path://') === 0) {
  29905. symbolPath = makePath(
  29906. symbolType.slice(7),
  29907. {},
  29908. new BoundingRect(x, y, w, h),
  29909. keepAspect ? 'center' : 'cover'
  29910. );
  29911. }
  29912. else {
  29913. symbolPath = new SymbolClz({
  29914. shape: {
  29915. symbolType: symbolType,
  29916. x: x,
  29917. y: y,
  29918. width: w,
  29919. height: h
  29920. }
  29921. });
  29922. }
  29923. symbolPath.__isEmptyBrush = isEmpty;
  29924. symbolPath.setColor = symbolPathSetColor;
  29925. symbolPath.setColor(color);
  29926. return symbolPath;
  29927. }
  29928. /*
  29929. * Licensed to the Apache Software Foundation (ASF) under one
  29930. * or more contributor license agreements. See the NOTICE file
  29931. * distributed with this work for additional information
  29932. * regarding copyright ownership. The ASF licenses this file
  29933. * to you under the Apache License, Version 2.0 (the
  29934. * "License"); you may not use this file except in compliance
  29935. * with the License. You may obtain a copy of the License at
  29936. *
  29937. * http://www.apache.org/licenses/LICENSE-2.0
  29938. *
  29939. * Unless required by applicable law or agreed to in writing,
  29940. * software distributed under the License is distributed on an
  29941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29942. * KIND, either express or implied. See the License for the
  29943. * specific language governing permissions and limitations
  29944. * under the License.
  29945. */
  29946. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  29947. /**
  29948. * Create a muti dimension List structure from seriesModel.
  29949. * @param {module:echarts/model/Model} seriesModel
  29950. * @return {module:echarts/data/List} list
  29951. */
  29952. function createList(seriesModel) {
  29953. return createListFromArray(seriesModel.getSource(), seriesModel);
  29954. }
  29955. var dataStack$1 = {
  29956. isDimensionStacked: isDimensionStacked,
  29957. enableDataStack: enableDataStack,
  29958. getStackedDimension: getStackedDimension
  29959. };
  29960. /**
  29961. * Create scale
  29962. * @param {Array.<number>} dataExtent
  29963. * @param {Object|module:echarts/Model} option
  29964. */
  29965. function createScale(dataExtent, option) {
  29966. var axisModel = option;
  29967. if (!Model.isInstance(option)) {
  29968. axisModel = new Model(option);
  29969. mixin(axisModel, axisModelCommonMixin);
  29970. }
  29971. var scale = createScaleByModel(axisModel);
  29972. scale.setExtent(dataExtent[0], dataExtent[1]);
  29973. niceScaleExtent(scale, axisModel);
  29974. return scale;
  29975. }
  29976. /**
  29977. * Mixin common methods to axis model,
  29978. *
  29979. * Inlcude methods
  29980. * `getFormattedLabels() => Array.<string>`
  29981. * `getCategories() => Array.<string>`
  29982. * `getMin(origin: boolean) => number`
  29983. * `getMax(origin: boolean) => number`
  29984. * `getNeedCrossZero() => boolean`
  29985. * `setRange(start: number, end: number)`
  29986. * `resetRange()`
  29987. */
  29988. function mixinAxisModelCommonMethods(Model$$1) {
  29989. mixin(Model$$1, axisModelCommonMixin);
  29990. }
  29991. var helper = (Object.freeze || Object)({
  29992. createList: createList,
  29993. getLayoutRect: getLayoutRect,
  29994. dataStack: dataStack$1,
  29995. createScale: createScale,
  29996. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  29997. completeDimensions: completeDimensions,
  29998. createDimensions: createDimensions,
  29999. createSymbol: createSymbol
  30000. });
  30001. var EPSILON$3 = 1e-8;
  30002. function isAroundEqual$1(a, b) {
  30003. return Math.abs(a - b) < EPSILON$3;
  30004. }
  30005. function contain$1(points, x, y) {
  30006. var w = 0;
  30007. var p = points[0];
  30008. if (!p) {
  30009. return false;
  30010. }
  30011. for (var i = 1; i < points.length; i++) {
  30012. var p2 = points[i];
  30013. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  30014. p = p2;
  30015. }
  30016. // Close polygon
  30017. var p0 = points[0];
  30018. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  30019. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  30020. }
  30021. return w !== 0;
  30022. }
  30023. /*
  30024. * Licensed to the Apache Software Foundation (ASF) under one
  30025. * or more contributor license agreements. See the NOTICE file
  30026. * distributed with this work for additional information
  30027. * regarding copyright ownership. The ASF licenses this file
  30028. * to you under the Apache License, Version 2.0 (the
  30029. * "License"); you may not use this file except in compliance
  30030. * with the License. You may obtain a copy of the License at
  30031. *
  30032. * http://www.apache.org/licenses/LICENSE-2.0
  30033. *
  30034. * Unless required by applicable law or agreed to in writing,
  30035. * software distributed under the License is distributed on an
  30036. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30037. * KIND, either express or implied. See the License for the
  30038. * specific language governing permissions and limitations
  30039. * under the License.
  30040. */
  30041. /**
  30042. * @module echarts/coord/geo/Region
  30043. */
  30044. /**
  30045. * @param {string|Region} name
  30046. * @param {Array} geometries
  30047. * @param {Array.<number>} cp
  30048. */
  30049. function Region(name, geometries, cp) {
  30050. /**
  30051. * @type {string}
  30052. * @readOnly
  30053. */
  30054. this.name = name;
  30055. /**
  30056. * @type {Array.<Array>}
  30057. * @readOnly
  30058. */
  30059. this.geometries = geometries;
  30060. if (!cp) {
  30061. var rect = this.getBoundingRect();
  30062. cp = [
  30063. rect.x + rect.width / 2,
  30064. rect.y + rect.height / 2
  30065. ];
  30066. }
  30067. else {
  30068. cp = [cp[0], cp[1]];
  30069. }
  30070. /**
  30071. * @type {Array.<number>}
  30072. */
  30073. this.center = cp;
  30074. }
  30075. Region.prototype = {
  30076. constructor: Region,
  30077. properties: null,
  30078. /**
  30079. * @return {module:zrender/core/BoundingRect}
  30080. */
  30081. getBoundingRect: function () {
  30082. var rect = this._rect;
  30083. if (rect) {
  30084. return rect;
  30085. }
  30086. var MAX_NUMBER = Number.MAX_VALUE;
  30087. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  30088. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  30089. var min2 = [];
  30090. var max2 = [];
  30091. var geometries = this.geometries;
  30092. for (var i = 0; i < geometries.length; i++) {
  30093. // Only support polygon
  30094. if (geometries[i].type !== 'polygon') {
  30095. continue;
  30096. }
  30097. // Doesn't consider hole
  30098. var exterior = geometries[i].exterior;
  30099. fromPoints(exterior, min2, max2);
  30100. min(min$$1, min$$1, min2);
  30101. max(max$$1, max$$1, max2);
  30102. }
  30103. // No data
  30104. if (i === 0) {
  30105. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  30106. }
  30107. return (this._rect = new BoundingRect(
  30108. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  30109. ));
  30110. },
  30111. /**
  30112. * @param {<Array.<number>} coord
  30113. * @return {boolean}
  30114. */
  30115. contain: function (coord) {
  30116. var rect = this.getBoundingRect();
  30117. var geometries = this.geometries;
  30118. if (!rect.contain(coord[0], coord[1])) {
  30119. return false;
  30120. }
  30121. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  30122. // Only support polygon.
  30123. if (geometries[i].type !== 'polygon') {
  30124. continue;
  30125. }
  30126. var exterior = geometries[i].exterior;
  30127. var interiors = geometries[i].interiors;
  30128. if (contain$1(exterior, coord[0], coord[1])) {
  30129. // Not in the region if point is in the hole.
  30130. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  30131. if (contain$1(interiors[k])) {
  30132. continue loopGeo;
  30133. }
  30134. }
  30135. return true;
  30136. }
  30137. }
  30138. return false;
  30139. },
  30140. transformTo: function (x, y, width, height) {
  30141. var rect = this.getBoundingRect();
  30142. var aspect = rect.width / rect.height;
  30143. if (!width) {
  30144. width = aspect * height;
  30145. }
  30146. else if (!height) {
  30147. height = width / aspect;
  30148. }
  30149. var target = new BoundingRect(x, y, width, height);
  30150. var transform = rect.calculateTransform(target);
  30151. var geometries = this.geometries;
  30152. for (var i = 0; i < geometries.length; i++) {
  30153. // Only support polygon.
  30154. if (geometries[i].type !== 'polygon') {
  30155. continue;
  30156. }
  30157. var exterior = geometries[i].exterior;
  30158. var interiors = geometries[i].interiors;
  30159. for (var p = 0; p < exterior.length; p++) {
  30160. applyTransform(exterior[p], exterior[p], transform);
  30161. }
  30162. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  30163. for (var p = 0; p < interiors[h].length; p++) {
  30164. applyTransform(interiors[h][p], interiors[h][p], transform);
  30165. }
  30166. }
  30167. }
  30168. rect = this._rect;
  30169. rect.copy(target);
  30170. // Update center
  30171. this.center = [
  30172. rect.x + rect.width / 2,
  30173. rect.y + rect.height / 2
  30174. ];
  30175. },
  30176. cloneShallow: function (name) {
  30177. name == null && (name = this.name);
  30178. var newRegion = new Region(name, this.geometries, this.center);
  30179. newRegion._rect = this._rect;
  30180. newRegion.transformTo = null; // Simply avoid to be called.
  30181. return newRegion;
  30182. }
  30183. };
  30184. /*
  30185. * Licensed to the Apache Software Foundation (ASF) under one
  30186. * or more contributor license agreements. See the NOTICE file
  30187. * distributed with this work for additional information
  30188. * regarding copyright ownership. The ASF licenses this file
  30189. * to you under the Apache License, Version 2.0 (the
  30190. * "License"); you may not use this file except in compliance
  30191. * with the License. You may obtain a copy of the License at
  30192. *
  30193. * http://www.apache.org/licenses/LICENSE-2.0
  30194. *
  30195. * Unless required by applicable law or agreed to in writing,
  30196. * software distributed under the License is distributed on an
  30197. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30198. * KIND, either express or implied. See the License for the
  30199. * specific language governing permissions and limitations
  30200. * under the License.
  30201. */
  30202. /**
  30203. * Parse and decode geo json
  30204. * @module echarts/coord/geo/parseGeoJson
  30205. */
  30206. function decode(json) {
  30207. if (!json.UTF8Encoding) {
  30208. return json;
  30209. }
  30210. var encodeScale = json.UTF8Scale;
  30211. if (encodeScale == null) {
  30212. encodeScale = 1024;
  30213. }
  30214. var features = json.features;
  30215. for (var f = 0; f < features.length; f++) {
  30216. var feature = features[f];
  30217. var geometry = feature.geometry;
  30218. var coordinates = geometry.coordinates;
  30219. var encodeOffsets = geometry.encodeOffsets;
  30220. for (var c = 0; c < coordinates.length; c++) {
  30221. var coordinate = coordinates[c];
  30222. if (geometry.type === 'Polygon') {
  30223. coordinates[c] = decodePolygon(
  30224. coordinate,
  30225. encodeOffsets[c],
  30226. encodeScale
  30227. );
  30228. }
  30229. else if (geometry.type === 'MultiPolygon') {
  30230. for (var c2 = 0; c2 < coordinate.length; c2++) {
  30231. var polygon = coordinate[c2];
  30232. coordinate[c2] = decodePolygon(
  30233. polygon,
  30234. encodeOffsets[c][c2],
  30235. encodeScale
  30236. );
  30237. }
  30238. }
  30239. }
  30240. }
  30241. // Has been decoded
  30242. json.UTF8Encoding = false;
  30243. return json;
  30244. }
  30245. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  30246. var result = [];
  30247. var prevX = encodeOffsets[0];
  30248. var prevY = encodeOffsets[1];
  30249. for (var i = 0; i < coordinate.length; i += 2) {
  30250. var x = coordinate.charCodeAt(i) - 64;
  30251. var y = coordinate.charCodeAt(i + 1) - 64;
  30252. // ZigZag decoding
  30253. x = (x >> 1) ^ (-(x & 1));
  30254. y = (y >> 1) ^ (-(y & 1));
  30255. // Delta deocding
  30256. x += prevX;
  30257. y += prevY;
  30258. prevX = x;
  30259. prevY = y;
  30260. // Dequantize
  30261. result.push([x / encodeScale, y / encodeScale]);
  30262. }
  30263. return result;
  30264. }
  30265. /**
  30266. * @alias module:echarts/coord/geo/parseGeoJson
  30267. * @param {Object} geoJson
  30268. * @return {module:zrender/container/Group}
  30269. */
  30270. var parseGeoJSON = function (geoJson) {
  30271. decode(geoJson);
  30272. return map(filter(geoJson.features, function (featureObj) {
  30273. // Output of mapshaper may have geometry null
  30274. return featureObj.geometry
  30275. && featureObj.properties
  30276. && featureObj.geometry.coordinates.length > 0;
  30277. }), function (featureObj) {
  30278. var properties = featureObj.properties;
  30279. var geo = featureObj.geometry;
  30280. var coordinates = geo.coordinates;
  30281. var geometries = [];
  30282. if (geo.type === 'Polygon') {
  30283. geometries.push({
  30284. type: 'polygon',
  30285. // According to the GeoJSON specification.
  30286. // First must be exterior, and the rest are all interior(holes).
  30287. exterior: coordinates[0],
  30288. interiors: coordinates.slice(1)
  30289. });
  30290. }
  30291. if (geo.type === 'MultiPolygon') {
  30292. each$1(coordinates, function (item) {
  30293. if (item[0]) {
  30294. geometries.push({
  30295. type: 'polygon',
  30296. exterior: item[0],
  30297. interiors: item.slice(1)
  30298. });
  30299. }
  30300. });
  30301. }
  30302. var region = new Region(
  30303. properties.name,
  30304. geometries,
  30305. properties.cp
  30306. );
  30307. region.properties = properties;
  30308. return region;
  30309. });
  30310. };
  30311. /*
  30312. * Licensed to the Apache Software Foundation (ASF) under one
  30313. * or more contributor license agreements. See the NOTICE file
  30314. * distributed with this work for additional information
  30315. * regarding copyright ownership. The ASF licenses this file
  30316. * to you under the Apache License, Version 2.0 (the
  30317. * "License"); you may not use this file except in compliance
  30318. * with the License. You may obtain a copy of the License at
  30319. *
  30320. * http://www.apache.org/licenses/LICENSE-2.0
  30321. *
  30322. * Unless required by applicable law or agreed to in writing,
  30323. * software distributed under the License is distributed on an
  30324. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30325. * KIND, either express or implied. See the License for the
  30326. * specific language governing permissions and limitations
  30327. * under the License.
  30328. */
  30329. var inner$6 = makeInner();
  30330. /**
  30331. * @param {module:echats/coord/Axis} axis
  30332. * @return {Object} {
  30333. * labels: [{
  30334. * formattedLabel: string,
  30335. * rawLabel: string,
  30336. * tickValue: number
  30337. * }, ...],
  30338. * labelCategoryInterval: number
  30339. * }
  30340. */
  30341. function createAxisLabels(axis) {
  30342. // Only ordinal scale support tick interval
  30343. return axis.type === 'category'
  30344. ? makeCategoryLabels(axis)
  30345. : makeRealNumberLabels(axis);
  30346. }
  30347. /**
  30348. * @param {module:echats/coord/Axis} axis
  30349. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  30350. * @return {Object} {
  30351. * ticks: Array.<number>
  30352. * tickCategoryInterval: number
  30353. * }
  30354. */
  30355. function createAxisTicks(axis, tickModel) {
  30356. // Only ordinal scale support tick interval
  30357. return axis.type === 'category'
  30358. ? makeCategoryTicks(axis, tickModel)
  30359. : {ticks: axis.scale.getTicks()};
  30360. }
  30361. function makeCategoryLabels(axis) {
  30362. var labelModel = axis.getLabelModel();
  30363. var result = makeCategoryLabelsActually(axis, labelModel);
  30364. return (!labelModel.get('show') || axis.scale.isBlank())
  30365. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  30366. : result;
  30367. }
  30368. function makeCategoryLabelsActually(axis, labelModel) {
  30369. var labelsCache = getListCache(axis, 'labels');
  30370. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  30371. var result = listCacheGet(labelsCache, optionLabelInterval);
  30372. if (result) {
  30373. return result;
  30374. }
  30375. var labels;
  30376. var numericLabelInterval;
  30377. if (isFunction$1(optionLabelInterval)) {
  30378. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  30379. }
  30380. else {
  30381. numericLabelInterval = optionLabelInterval === 'auto'
  30382. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  30383. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  30384. }
  30385. // Cache to avoid calling interval function repeatly.
  30386. return listCacheSet(labelsCache, optionLabelInterval, {
  30387. labels: labels, labelCategoryInterval: numericLabelInterval
  30388. });
  30389. }
  30390. function makeCategoryTicks(axis, tickModel) {
  30391. var ticksCache = getListCache(axis, 'ticks');
  30392. var optionTickInterval = getOptionCategoryInterval(tickModel);
  30393. var result = listCacheGet(ticksCache, optionTickInterval);
  30394. if (result) {
  30395. return result;
  30396. }
  30397. var ticks;
  30398. var tickCategoryInterval;
  30399. // Optimize for the case that large category data and no label displayed,
  30400. // we should not return all ticks.
  30401. if (!tickModel.get('show') || axis.scale.isBlank()) {
  30402. ticks = [];
  30403. }
  30404. if (isFunction$1(optionTickInterval)) {
  30405. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  30406. }
  30407. // Always use label interval by default despite label show. Consider this
  30408. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  30409. // labels. `splitLine` and `axisTick` should be consistent in this case.
  30410. else if (optionTickInterval === 'auto') {
  30411. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  30412. tickCategoryInterval = labelsResult.labelCategoryInterval;
  30413. ticks = map(labelsResult.labels, function (labelItem) {
  30414. return labelItem.tickValue;
  30415. });
  30416. }
  30417. else {
  30418. tickCategoryInterval = optionTickInterval;
  30419. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  30420. }
  30421. // Cache to avoid calling interval function repeatly.
  30422. return listCacheSet(ticksCache, optionTickInterval, {
  30423. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  30424. });
  30425. }
  30426. function makeRealNumberLabels(axis) {
  30427. var ticks = axis.scale.getTicks();
  30428. var labelFormatter = makeLabelFormatter(axis);
  30429. return {
  30430. labels: map(ticks, function (tickValue, idx) {
  30431. return {
  30432. formattedLabel: labelFormatter(tickValue, idx),
  30433. rawLabel: axis.scale.getLabel(tickValue),
  30434. tickValue: tickValue
  30435. };
  30436. })
  30437. };
  30438. }
  30439. // Large category data calculation is performence sensitive, and ticks and label
  30440. // probably be fetched by multiple times. So we cache the result.
  30441. // axis is created each time during a ec process, so we do not need to clear cache.
  30442. function getListCache(axis, prop) {
  30443. // Because key can be funciton, and cache size always be small, we use array cache.
  30444. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  30445. }
  30446. function listCacheGet(cache, key) {
  30447. for (var i = 0; i < cache.length; i++) {
  30448. if (cache[i].key === key) {
  30449. return cache[i].value;
  30450. }
  30451. }
  30452. }
  30453. function listCacheSet(cache, key, value) {
  30454. cache.push({key: key, value: value});
  30455. return value;
  30456. }
  30457. function makeAutoCategoryInterval(axis) {
  30458. var result = inner$6(axis).autoInterval;
  30459. return result != null
  30460. ? result
  30461. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  30462. }
  30463. /**
  30464. * Calculate interval for category axis ticks and labels.
  30465. * To get precise result, at least one of `getRotate` and `isHorizontal`
  30466. * should be implemented in axis.
  30467. */
  30468. function calculateCategoryInterval(axis) {
  30469. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  30470. var labelFormatter = makeLabelFormatter(axis);
  30471. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  30472. var ordinalScale = axis.scale;
  30473. var ordinalExtent = ordinalScale.getExtent();
  30474. // Providing this method is for optimization:
  30475. // avoid generating a long array by `getTicks`
  30476. // in large category data case.
  30477. var tickCount = ordinalScale.count();
  30478. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  30479. return 0;
  30480. }
  30481. var step = 1;
  30482. // Simple optimization. Empirical value: tick count should less than 40.
  30483. if (tickCount > 40) {
  30484. step = Math.max(1, Math.floor(tickCount / 40));
  30485. }
  30486. var tickValue = ordinalExtent[0];
  30487. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  30488. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  30489. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  30490. var maxW = 0;
  30491. var maxH = 0;
  30492. // Caution: Performance sensitive for large category data.
  30493. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  30494. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  30495. var width = 0;
  30496. var height = 0;
  30497. // Not precise, do not consider align and vertical align
  30498. // and each distance from axis line yet.
  30499. var rect = getBoundingRect(
  30500. labelFormatter(tickValue), params.font, 'center', 'top'
  30501. );
  30502. // Magic number
  30503. width = rect.width * 1.3;
  30504. height = rect.height * 1.3;
  30505. // Min size, void long loop.
  30506. maxW = Math.max(maxW, width, 7);
  30507. maxH = Math.max(maxH, height, 7);
  30508. }
  30509. var dw = maxW / unitW;
  30510. var dh = maxH / unitH;
  30511. // 0/0 is NaN, 1/0 is Infinity.
  30512. isNaN(dw) && (dw = Infinity);
  30513. isNaN(dh) && (dh = Infinity);
  30514. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  30515. var cache = inner$6(axis.model);
  30516. var lastAutoInterval = cache.lastAutoInterval;
  30517. var lastTickCount = cache.lastTickCount;
  30518. // Use cache to keep interval stable while moving zoom window,
  30519. // otherwise the calculated interval might jitter when the zoom
  30520. // window size is close to the interval-changing size.
  30521. if (lastAutoInterval != null
  30522. && lastTickCount != null
  30523. && Math.abs(lastAutoInterval - interval) <= 1
  30524. && Math.abs(lastTickCount - tickCount) <= 1
  30525. // Always choose the bigger one, otherwise the critical
  30526. // point is not the same when zooming in or zooming out.
  30527. && lastAutoInterval > interval
  30528. ) {
  30529. interval = lastAutoInterval;
  30530. }
  30531. // Only update cache if cache not used, otherwise the
  30532. // changing of interval is too insensitive.
  30533. else {
  30534. cache.lastTickCount = tickCount;
  30535. cache.lastAutoInterval = interval;
  30536. }
  30537. return interval;
  30538. }
  30539. function fetchAutoCategoryIntervalCalculationParams(axis) {
  30540. var labelModel = axis.getLabelModel();
  30541. return {
  30542. axisRotate: axis.getRotate
  30543. ? axis.getRotate()
  30544. : (axis.isHorizontal && !axis.isHorizontal())
  30545. ? 90
  30546. : 0,
  30547. labelRotate: labelModel.get('rotate') || 0,
  30548. font: labelModel.getFont()
  30549. };
  30550. }
  30551. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  30552. var labelFormatter = makeLabelFormatter(axis);
  30553. var ordinalScale = axis.scale;
  30554. var ordinalExtent = ordinalScale.getExtent();
  30555. var labelModel = axis.getLabelModel();
  30556. var result = [];
  30557. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  30558. var step = Math.max((categoryInterval || 0) + 1, 1);
  30559. var startTick = ordinalExtent[0];
  30560. var tickCount = ordinalScale.count();
  30561. // Calculate start tick based on zero if possible to keep label consistent
  30562. // while zooming and moving while interval > 0. Otherwise the selection
  30563. // of displayable ticks and symbols probably keep changing.
  30564. // 3 is empirical value.
  30565. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  30566. startTick = Math.round(Math.ceil(startTick / step) * step);
  30567. }
  30568. // (1) Only add min max label here but leave overlap checking
  30569. // to render stage, which also ensure the returned list
  30570. // suitable for splitLine and splitArea rendering.
  30571. // (2) Scales except category always contain min max label so
  30572. // do not need to perform this process.
  30573. var showAllLabel = shouldShowAllLabels(axis);
  30574. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  30575. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  30576. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  30577. addItem(ordinalExtent[0]);
  30578. }
  30579. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  30580. var tickValue = startTick;
  30581. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  30582. addItem(tickValue);
  30583. }
  30584. if (includeMaxLabel && tickValue !== ordinalExtent[1]) {
  30585. addItem(ordinalExtent[1]);
  30586. }
  30587. function addItem(tVal) {
  30588. result.push(onlyTick
  30589. ? tVal
  30590. : {
  30591. formattedLabel: labelFormatter(tVal),
  30592. rawLabel: ordinalScale.getLabel(tVal),
  30593. tickValue: tVal
  30594. }
  30595. );
  30596. }
  30597. return result;
  30598. }
  30599. // When interval is function, the result `false` means ignore the tick.
  30600. // It is time consuming for large category data.
  30601. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  30602. var ordinalScale = axis.scale;
  30603. var labelFormatter = makeLabelFormatter(axis);
  30604. var result = [];
  30605. each$1(ordinalScale.getTicks(), function (tickValue) {
  30606. var rawLabel = ordinalScale.getLabel(tickValue);
  30607. if (categoryInterval(tickValue, rawLabel)) {
  30608. result.push(onlyTick
  30609. ? tickValue
  30610. : {
  30611. formattedLabel: labelFormatter(tickValue),
  30612. rawLabel: rawLabel,
  30613. tickValue: tickValue
  30614. }
  30615. );
  30616. }
  30617. });
  30618. return result;
  30619. }
  30620. /*
  30621. * Licensed to the Apache Software Foundation (ASF) under one
  30622. * or more contributor license agreements. See the NOTICE file
  30623. * distributed with this work for additional information
  30624. * regarding copyright ownership. The ASF licenses this file
  30625. * to you under the Apache License, Version 2.0 (the
  30626. * "License"); you may not use this file except in compliance
  30627. * with the License. You may obtain a copy of the License at
  30628. *
  30629. * http://www.apache.org/licenses/LICENSE-2.0
  30630. *
  30631. * Unless required by applicable law or agreed to in writing,
  30632. * software distributed under the License is distributed on an
  30633. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30634. * KIND, either express or implied. See the License for the
  30635. * specific language governing permissions and limitations
  30636. * under the License.
  30637. */
  30638. var NORMALIZED_EXTENT = [0, 1];
  30639. /**
  30640. * Base class of Axis.
  30641. * @constructor
  30642. */
  30643. var Axis = function (dim, scale, extent) {
  30644. /**
  30645. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  30646. * @type {string}
  30647. */
  30648. this.dim = dim;
  30649. /**
  30650. * Axis scale
  30651. * @type {module:echarts/coord/scale/*}
  30652. */
  30653. this.scale = scale;
  30654. /**
  30655. * @type {Array.<number>}
  30656. * @private
  30657. */
  30658. this._extent = extent || [0, 0];
  30659. /**
  30660. * @type {boolean}
  30661. */
  30662. this.inverse = false;
  30663. /**
  30664. * Usually true when axis has a ordinal scale
  30665. * @type {boolean}
  30666. */
  30667. this.onBand = false;
  30668. };
  30669. Axis.prototype = {
  30670. constructor: Axis,
  30671. /**
  30672. * If axis extent contain given coord
  30673. * @param {number} coord
  30674. * @return {boolean}
  30675. */
  30676. contain: function (coord) {
  30677. var extent = this._extent;
  30678. var min = Math.min(extent[0], extent[1]);
  30679. var max = Math.max(extent[0], extent[1]);
  30680. return coord >= min && coord <= max;
  30681. },
  30682. /**
  30683. * If axis extent contain given data
  30684. * @param {number} data
  30685. * @return {boolean}
  30686. */
  30687. containData: function (data) {
  30688. return this.contain(this.dataToCoord(data));
  30689. },
  30690. /**
  30691. * Get coord extent.
  30692. * @return {Array.<number>}
  30693. */
  30694. getExtent: function () {
  30695. return this._extent.slice();
  30696. },
  30697. /**
  30698. * Get precision used for formatting
  30699. * @param {Array.<number>} [dataExtent]
  30700. * @return {number}
  30701. */
  30702. getPixelPrecision: function (dataExtent) {
  30703. return getPixelPrecision(
  30704. dataExtent || this.scale.getExtent(),
  30705. this._extent
  30706. );
  30707. },
  30708. /**
  30709. * Set coord extent
  30710. * @param {number} start
  30711. * @param {number} end
  30712. */
  30713. setExtent: function (start, end) {
  30714. var extent = this._extent;
  30715. extent[0] = start;
  30716. extent[1] = end;
  30717. },
  30718. /**
  30719. * Convert data to coord. Data is the rank if it has an ordinal scale
  30720. * @param {number} data
  30721. * @param {boolean} clamp
  30722. * @return {number}
  30723. */
  30724. dataToCoord: function (data, clamp) {
  30725. var extent = this._extent;
  30726. var scale = this.scale;
  30727. data = scale.normalize(data);
  30728. if (this.onBand && scale.type === 'ordinal') {
  30729. extent = extent.slice();
  30730. fixExtentWithBands(extent, scale.count());
  30731. }
  30732. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  30733. },
  30734. /**
  30735. * Convert coord to data. Data is the rank if it has an ordinal scale
  30736. * @param {number} coord
  30737. * @param {boolean} clamp
  30738. * @return {number}
  30739. */
  30740. coordToData: function (coord, clamp) {
  30741. var extent = this._extent;
  30742. var scale = this.scale;
  30743. if (this.onBand && scale.type === 'ordinal') {
  30744. extent = extent.slice();
  30745. fixExtentWithBands(extent, scale.count());
  30746. }
  30747. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  30748. return this.scale.scale(t);
  30749. },
  30750. /**
  30751. * Convert pixel point to data in axis
  30752. * @param {Array.<number>} point
  30753. * @param {boolean} clamp
  30754. * @return {number} data
  30755. */
  30756. pointToData: function (point, clamp) {
  30757. // Should be implemented in derived class if necessary.
  30758. },
  30759. /**
  30760. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  30761. * `axis.getTicksCoords` considers `onBand`, which is used by
  30762. * `boundaryGap:true` of category axis and splitLine and splitArea.
  30763. * @param {Object} [opt]
  30764. * @param {number} [opt.tickModel=axis.model.getModel('axisTick')]
  30765. * @param {boolean} [opt.clamp] If `true`, the first and the last
  30766. * tick must be at the axis end points. Otherwise, clip ticks
  30767. * that outside the axis extent.
  30768. * @return {Array.<Object>} [{
  30769. * coord: ...,
  30770. * tickValue: ...
  30771. * }, ...]
  30772. */
  30773. getTicksCoords: function (opt) {
  30774. opt = opt || {};
  30775. var tickModel = opt.tickModel || this.getTickModel();
  30776. var result = createAxisTicks(this, tickModel);
  30777. var ticks = result.ticks;
  30778. var ticksCoords = map(ticks, function (tickValue) {
  30779. return {
  30780. coord: this.dataToCoord(tickValue),
  30781. tickValue: tickValue
  30782. };
  30783. }, this);
  30784. var alignWithLabel = tickModel.get('alignWithLabel');
  30785. fixOnBandTicksCoords(
  30786. this, ticksCoords, result.tickCategoryInterval, alignWithLabel, opt.clamp
  30787. );
  30788. return ticksCoords;
  30789. },
  30790. /**
  30791. * @return {Array.<Object>} [{
  30792. * formattedLabel: string,
  30793. * rawLabel: axis.scale.getLabel(tickValue)
  30794. * tickValue: number
  30795. * }, ...]
  30796. */
  30797. getViewLabels: function () {
  30798. return createAxisLabels(this).labels;
  30799. },
  30800. /**
  30801. * @return {module:echarts/coord/model/Model}
  30802. */
  30803. getLabelModel: function () {
  30804. return this.model.getModel('axisLabel');
  30805. },
  30806. /**
  30807. * Notice here we only get the default tick model. For splitLine
  30808. * or splitArea, we should pass the splitLineModel or splitAreaModel
  30809. * manually when calling `getTicksCoords`.
  30810. * In GL, this method may be overrided to:
  30811. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  30812. * @return {module:echarts/coord/model/Model}
  30813. */
  30814. getTickModel: function () {
  30815. return this.model.getModel('axisTick');
  30816. },
  30817. /**
  30818. * Get width of band
  30819. * @return {number}
  30820. */
  30821. getBandWidth: function () {
  30822. var axisExtent = this._extent;
  30823. var dataExtent = this.scale.getExtent();
  30824. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  30825. // Fix #2728, avoid NaN when only one data.
  30826. len === 0 && (len = 1);
  30827. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  30828. return Math.abs(size) / len;
  30829. },
  30830. /**
  30831. * @abstract
  30832. * @return {boolean} Is horizontal
  30833. */
  30834. isHorizontal: null,
  30835. /**
  30836. * @abstract
  30837. * @return {number} Get axis rotate, by degree.
  30838. */
  30839. getRotate: null,
  30840. /**
  30841. * Only be called in category axis.
  30842. * Can be overrided, consider other axes like in 3D.
  30843. * @return {number} Auto interval for cateogry axis tick and label
  30844. */
  30845. calculateCategoryInterval: function () {
  30846. return calculateCategoryInterval(this);
  30847. }
  30848. };
  30849. function fixExtentWithBands(extent, nTick) {
  30850. var size = extent[1] - extent[0];
  30851. var len = nTick;
  30852. var margin = size / len / 2;
  30853. extent[0] += margin;
  30854. extent[1] -= margin;
  30855. }
  30856. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  30857. // |---1---|---2---|---3---|---4---|.
  30858. // So the displayed ticks and splitLine/splitArea should between
  30859. // each data item, otherwise cause misleading (e.g., split tow bars
  30860. // of a single data item when there are two bar series).
  30861. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  30862. // splitLine/spliteArea should layout appropriately corresponding
  30863. // to displayed labels. (So we should not use `getBandWidth` in this
  30864. // case).
  30865. function fixOnBandTicksCoords(axis, ticksCoords, tickCategoryInterval, alignWithLabel, clamp) {
  30866. var ticksLen = ticksCoords.length;
  30867. if (!axis.onBand || alignWithLabel || !ticksLen) {
  30868. return;
  30869. }
  30870. var axisExtent = axis.getExtent();
  30871. var last;
  30872. if (ticksLen === 1) {
  30873. ticksCoords[0].coord = axisExtent[0];
  30874. last = ticksCoords[1] = {coord: axisExtent[0]};
  30875. }
  30876. else {
  30877. var shift = (ticksCoords[1].coord - ticksCoords[0].coord);
  30878. each$1(ticksCoords, function (ticksItem) {
  30879. ticksItem.coord -= shift / 2;
  30880. var tickCategoryInterval = tickCategoryInterval || 0;
  30881. // Avoid split a single data item when odd interval.
  30882. if (tickCategoryInterval % 2 > 0) {
  30883. ticksItem.coord -= shift / ((tickCategoryInterval + 1) * 2);
  30884. }
  30885. });
  30886. last = {coord: ticksCoords[ticksLen - 1].coord + shift};
  30887. ticksCoords.push(last);
  30888. }
  30889. var inverse = axisExtent[0] > axisExtent[1];
  30890. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  30891. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  30892. }
  30893. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  30894. ticksCoords.unshift({coord: axisExtent[0]});
  30895. }
  30896. if (littleThan(axisExtent[1], last.coord)) {
  30897. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  30898. }
  30899. if (clamp && littleThan(last.coord, axisExtent[1])) {
  30900. ticksCoords.push({coord: axisExtent[1]});
  30901. }
  30902. function littleThan(a, b) {
  30903. return inverse ? a > b : a < b;
  30904. }
  30905. }
  30906. /*
  30907. * Licensed to the Apache Software Foundation (ASF) under one
  30908. * or more contributor license agreements. See the NOTICE file
  30909. * distributed with this work for additional information
  30910. * regarding copyright ownership. The ASF licenses this file
  30911. * to you under the Apache License, Version 2.0 (the
  30912. * "License"); you may not use this file except in compliance
  30913. * with the License. You may obtain a copy of the License at
  30914. *
  30915. * http://www.apache.org/licenses/LICENSE-2.0
  30916. *
  30917. * Unless required by applicable law or agreed to in writing,
  30918. * software distributed under the License is distributed on an
  30919. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30920. * KIND, either express or implied. See the License for the
  30921. * specific language governing permissions and limitations
  30922. * under the License.
  30923. */
  30924. /**
  30925. * Do not mount those modules on 'src/echarts' for better tree shaking.
  30926. */
  30927. var parseGeoJson = parseGeoJSON;
  30928. var ecUtil = {};
  30929. each$1(
  30930. [
  30931. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  30932. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  30933. 'extend', 'defaults', 'clone', 'merge'
  30934. ],
  30935. function (name) {
  30936. ecUtil[name] = zrUtil[name];
  30937. }
  30938. );
  30939. var graphic$1 = {};
  30940. each$1(
  30941. [
  30942. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  30943. 'mergePath', 'resizePath', 'createIcon',
  30944. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  30945. 'getFont', 'updateProps', 'initProps', 'getTransform',
  30946. 'clipPointsByRect', 'clipRectByRect',
  30947. 'Group',
  30948. 'Image',
  30949. 'Text',
  30950. 'Circle',
  30951. 'Sector',
  30952. 'Ring',
  30953. 'Polygon',
  30954. 'Polyline',
  30955. 'Rect',
  30956. 'Line',
  30957. 'BezierCurve',
  30958. 'Arc',
  30959. 'IncrementalDisplayable',
  30960. 'CompoundPath',
  30961. 'LinearGradient',
  30962. 'RadialGradient',
  30963. 'BoundingRect'
  30964. ],
  30965. function (name) {
  30966. graphic$1[name] = graphic[name];
  30967. }
  30968. );
  30969. /*
  30970. * Licensed to the Apache Software Foundation (ASF) under one
  30971. * or more contributor license agreements. See the NOTICE file
  30972. * distributed with this work for additional information
  30973. * regarding copyright ownership. The ASF licenses this file
  30974. * to you under the Apache License, Version 2.0 (the
  30975. * "License"); you may not use this file except in compliance
  30976. * with the License. You may obtain a copy of the License at
  30977. *
  30978. * http://www.apache.org/licenses/LICENSE-2.0
  30979. *
  30980. * Unless required by applicable law or agreed to in writing,
  30981. * software distributed under the License is distributed on an
  30982. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30983. * KIND, either express or implied. See the License for the
  30984. * specific language governing permissions and limitations
  30985. * under the License.
  30986. */
  30987. SeriesModel.extend({
  30988. type: 'series.line',
  30989. dependencies: ['grid', 'polar'],
  30990. getInitialData: function (option, ecModel) {
  30991. if (__DEV__) {
  30992. var coordSys = option.coordinateSystem;
  30993. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  30994. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  30995. }
  30996. }
  30997. return createListFromArray(this.getSource(), this);
  30998. },
  30999. defaultOption: {
  31000. zlevel: 0,
  31001. z: 2,
  31002. coordinateSystem: 'cartesian2d',
  31003. legendHoverLink: true,
  31004. hoverAnimation: true,
  31005. // stack: null
  31006. // xAxisIndex: 0,
  31007. // yAxisIndex: 0,
  31008. // polarIndex: 0,
  31009. // If clip the overflow value
  31010. clipOverflow: true,
  31011. // cursor: null,
  31012. label: {
  31013. position: 'top'
  31014. },
  31015. // itemStyle: {
  31016. // },
  31017. lineStyle: {
  31018. width: 2,
  31019. type: 'solid'
  31020. },
  31021. // areaStyle: {
  31022. // origin of areaStyle. Valid values:
  31023. // `'auto'/null/undefined`: from axisLine to data
  31024. // `'start'`: from min to data
  31025. // `'end'`: from data to max
  31026. // origin: 'auto'
  31027. // },
  31028. // false, 'start', 'end', 'middle'
  31029. step: false,
  31030. // Disabled if step is true
  31031. smooth: false,
  31032. smoothMonotone: null,
  31033. symbol: 'emptyCircle',
  31034. symbolSize: 4,
  31035. symbolRotate: null,
  31036. showSymbol: true,
  31037. // `false`: follow the label interval strategy.
  31038. // `true`: show all symbols.
  31039. // `'auto'`: If possible, show all symbols, otherwise
  31040. // follow the label interval strategy.
  31041. showAllSymbol: 'auto',
  31042. // Whether to connect break point.
  31043. connectNulls: false,
  31044. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  31045. sampling: 'none',
  31046. animationEasing: 'linear',
  31047. // Disable progressive
  31048. progressive: 0,
  31049. hoverLayerThreshold: Infinity
  31050. }
  31051. });
  31052. /*
  31053. * Licensed to the Apache Software Foundation (ASF) under one
  31054. * or more contributor license agreements. See the NOTICE file
  31055. * distributed with this work for additional information
  31056. * regarding copyright ownership. The ASF licenses this file
  31057. * to you under the Apache License, Version 2.0 (the
  31058. * "License"); you may not use this file except in compliance
  31059. * with the License. You may obtain a copy of the License at
  31060. *
  31061. * http://www.apache.org/licenses/LICENSE-2.0
  31062. *
  31063. * Unless required by applicable law or agreed to in writing,
  31064. * software distributed under the License is distributed on an
  31065. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31066. * KIND, either express or implied. See the License for the
  31067. * specific language governing permissions and limitations
  31068. * under the License.
  31069. */
  31070. /**
  31071. * @param {module:echarts/data/List} data
  31072. * @param {number} dataIndex
  31073. * @return {string} label string. Not null/undefined
  31074. */
  31075. function getDefaultLabel(data, dataIndex) {
  31076. var labelDims = data.mapDimension('defaultedLabel', true);
  31077. var len = labelDims.length;
  31078. // Simple optimization (in lots of cases, label dims length is 1)
  31079. if (len === 1) {
  31080. return retrieveRawValue(data, dataIndex, labelDims[0]);
  31081. }
  31082. else if (len) {
  31083. var vals = [];
  31084. for (var i = 0; i < labelDims.length; i++) {
  31085. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  31086. vals.push(val);
  31087. }
  31088. return vals.join(' ');
  31089. }
  31090. }
  31091. /*
  31092. * Licensed to the Apache Software Foundation (ASF) under one
  31093. * or more contributor license agreements. See the NOTICE file
  31094. * distributed with this work for additional information
  31095. * regarding copyright ownership. The ASF licenses this file
  31096. * to you under the Apache License, Version 2.0 (the
  31097. * "License"); you may not use this file except in compliance
  31098. * with the License. You may obtain a copy of the License at
  31099. *
  31100. * http://www.apache.org/licenses/LICENSE-2.0
  31101. *
  31102. * Unless required by applicable law or agreed to in writing,
  31103. * software distributed under the License is distributed on an
  31104. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31105. * KIND, either express or implied. See the License for the
  31106. * specific language governing permissions and limitations
  31107. * under the License.
  31108. */
  31109. /**
  31110. * @module echarts/chart/helper/Symbol
  31111. */
  31112. /**
  31113. * @constructor
  31114. * @alias {module:echarts/chart/helper/Symbol}
  31115. * @param {module:echarts/data/List} data
  31116. * @param {number} idx
  31117. * @extends {module:zrender/graphic/Group}
  31118. */
  31119. function SymbolClz$1(data, idx, seriesScope) {
  31120. Group.call(this);
  31121. this.updateData(data, idx, seriesScope);
  31122. }
  31123. var symbolProto = SymbolClz$1.prototype;
  31124. /**
  31125. * @public
  31126. * @static
  31127. * @param {module:echarts/data/List} data
  31128. * @param {number} dataIndex
  31129. * @return {Array.<number>} [width, height]
  31130. */
  31131. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  31132. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  31133. return symbolSize instanceof Array
  31134. ? symbolSize.slice()
  31135. : [+symbolSize, +symbolSize];
  31136. };
  31137. function getScale(symbolSize) {
  31138. return [symbolSize[0] / 2, symbolSize[1] / 2];
  31139. }
  31140. function driftSymbol(dx, dy) {
  31141. this.parent.drift(dx, dy);
  31142. }
  31143. symbolProto._createSymbol = function (
  31144. symbolType,
  31145. data,
  31146. idx,
  31147. symbolSize,
  31148. keepAspect
  31149. ) {
  31150. // Remove paths created before
  31151. this.removeAll();
  31152. var color = data.getItemVisual(idx, 'color');
  31153. // var symbolPath = createSymbol(
  31154. // symbolType, -0.5, -0.5, 1, 1, color
  31155. // );
  31156. // If width/height are set too small (e.g., set to 1) on ios10
  31157. // and macOS Sierra, a circle stroke become a rect, no matter what
  31158. // the scale is set. So we set width/height as 2. See #4150.
  31159. var symbolPath = createSymbol(
  31160. symbolType, -1, -1, 2, 2, color, keepAspect
  31161. );
  31162. symbolPath.attr({
  31163. z2: 100,
  31164. culling: true,
  31165. scale: getScale(symbolSize)
  31166. });
  31167. // Rewrite drift method
  31168. symbolPath.drift = driftSymbol;
  31169. this._symbolType = symbolType;
  31170. this.add(symbolPath);
  31171. };
  31172. /**
  31173. * Stop animation
  31174. * @param {boolean} toLastFrame
  31175. */
  31176. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  31177. this.childAt(0).stopAnimation(toLastFrame);
  31178. };
  31179. /**
  31180. * FIXME:
  31181. * Caution: This method breaks the encapsulation of this module,
  31182. * but it indeed brings convenience. So do not use the method
  31183. * unless you detailedly know all the implements of `Symbol`,
  31184. * especially animation.
  31185. *
  31186. * Get symbol path element.
  31187. */
  31188. symbolProto.getSymbolPath = function () {
  31189. return this.childAt(0);
  31190. };
  31191. /**
  31192. * Get scale(aka, current symbol size).
  31193. * Including the change caused by animation
  31194. */
  31195. symbolProto.getScale = function () {
  31196. return this.childAt(0).scale;
  31197. };
  31198. /**
  31199. * Highlight symbol
  31200. */
  31201. symbolProto.highlight = function () {
  31202. this.childAt(0).trigger('emphasis');
  31203. };
  31204. /**
  31205. * Downplay symbol
  31206. */
  31207. symbolProto.downplay = function () {
  31208. this.childAt(0).trigger('normal');
  31209. };
  31210. /**
  31211. * @param {number} zlevel
  31212. * @param {number} z
  31213. */
  31214. symbolProto.setZ = function (zlevel, z) {
  31215. var symbolPath = this.childAt(0);
  31216. symbolPath.zlevel = zlevel;
  31217. symbolPath.z = z;
  31218. };
  31219. symbolProto.setDraggable = function (draggable) {
  31220. var symbolPath = this.childAt(0);
  31221. symbolPath.draggable = draggable;
  31222. symbolPath.cursor = draggable ? 'move' : 'pointer';
  31223. };
  31224. /**
  31225. * Update symbol properties
  31226. * @param {module:echarts/data/List} data
  31227. * @param {number} idx
  31228. * @param {Object} [seriesScope]
  31229. * @param {Object} [seriesScope.itemStyle]
  31230. * @param {Object} [seriesScope.hoverItemStyle]
  31231. * @param {Object} [seriesScope.symbolRotate]
  31232. * @param {Object} [seriesScope.symbolOffset]
  31233. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  31234. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  31235. * @param {boolean} [seriesScope.hoverAnimation]
  31236. * @param {Object} [seriesScope.cursorStyle]
  31237. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  31238. * @param {string} [seriesScope.symbolInnerColor]
  31239. * @param {Object} [seriesScope.fadeIn=false]
  31240. */
  31241. symbolProto.updateData = function (data, idx, seriesScope) {
  31242. this.silent = false;
  31243. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  31244. var seriesModel = data.hostModel;
  31245. var symbolSize = getSymbolSize(data, idx);
  31246. var isInit = symbolType !== this._symbolType;
  31247. if (isInit) {
  31248. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  31249. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  31250. }
  31251. else {
  31252. var symbolPath = this.childAt(0);
  31253. symbolPath.silent = false;
  31254. updateProps(symbolPath, {
  31255. scale: getScale(symbolSize)
  31256. }, seriesModel, idx);
  31257. }
  31258. this._updateCommon(data, idx, symbolSize, seriesScope);
  31259. if (isInit) {
  31260. var symbolPath = this.childAt(0);
  31261. var fadeIn = seriesScope && seriesScope.fadeIn;
  31262. var target = {scale: symbolPath.scale.slice()};
  31263. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  31264. symbolPath.scale = [0, 0];
  31265. fadeIn && (symbolPath.style.opacity = 0);
  31266. initProps(symbolPath, target, seriesModel, idx);
  31267. }
  31268. this._seriesModel = seriesModel;
  31269. };
  31270. // Update common properties
  31271. var normalStyleAccessPath = ['itemStyle'];
  31272. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  31273. var normalLabelAccessPath = ['label'];
  31274. var emphasisLabelAccessPath = ['emphasis', 'label'];
  31275. /**
  31276. * @param {module:echarts/data/List} data
  31277. * @param {number} idx
  31278. * @param {Array.<number>} symbolSize
  31279. * @param {Object} [seriesScope]
  31280. */
  31281. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  31282. var symbolPath = this.childAt(0);
  31283. var seriesModel = data.hostModel;
  31284. var color = data.getItemVisual(idx, 'color');
  31285. // Reset style
  31286. if (symbolPath.type !== 'image') {
  31287. symbolPath.useStyle({
  31288. strokeNoScale: true
  31289. });
  31290. }
  31291. var itemStyle = seriesScope && seriesScope.itemStyle;
  31292. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  31293. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  31294. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  31295. var labelModel = seriesScope && seriesScope.labelModel;
  31296. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  31297. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  31298. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  31299. if (!seriesScope || data.hasItemOption) {
  31300. var itemModel = (seriesScope && seriesScope.itemModel)
  31301. ? seriesScope.itemModel : data.getItemModel(idx);
  31302. // Color must be excluded.
  31303. // Because symbol provide setColor individually to set fill and stroke
  31304. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  31305. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  31306. symbolRotate = itemModel.getShallow('symbolRotate');
  31307. symbolOffset = itemModel.getShallow('symbolOffset');
  31308. labelModel = itemModel.getModel(normalLabelAccessPath);
  31309. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  31310. hoverAnimation = itemModel.getShallow('hoverAnimation');
  31311. cursorStyle = itemModel.getShallow('cursor');
  31312. }
  31313. else {
  31314. hoverItemStyle = extend({}, hoverItemStyle);
  31315. }
  31316. var elStyle = symbolPath.style;
  31317. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  31318. if (symbolOffset) {
  31319. symbolPath.attr('position', [
  31320. parsePercent$1(symbolOffset[0], symbolSize[0]),
  31321. parsePercent$1(symbolOffset[1], symbolSize[1])
  31322. ]);
  31323. }
  31324. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  31325. // PENDING setColor before setStyle!!!
  31326. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  31327. symbolPath.setStyle(itemStyle);
  31328. var opacity = data.getItemVisual(idx, 'opacity');
  31329. if (opacity != null) {
  31330. elStyle.opacity = opacity;
  31331. }
  31332. var liftZ = data.getItemVisual(idx, 'liftZ');
  31333. var z2Origin = symbolPath.__z2Origin;
  31334. if (liftZ != null) {
  31335. if (z2Origin == null) {
  31336. symbolPath.__z2Origin = symbolPath.z2;
  31337. symbolPath.z2 += liftZ;
  31338. }
  31339. }
  31340. else if (z2Origin != null) {
  31341. symbolPath.z2 = z2Origin;
  31342. symbolPath.__z2Origin = null;
  31343. }
  31344. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  31345. setLabelStyle(
  31346. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  31347. {
  31348. labelFetcher: seriesModel,
  31349. labelDataIndex: idx,
  31350. defaultText: getLabelDefaultText,
  31351. isRectText: true,
  31352. autoColor: color
  31353. }
  31354. );
  31355. // Do not execute util needed.
  31356. function getLabelDefaultText(idx, opt) {
  31357. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  31358. }
  31359. symbolPath.off('mouseover')
  31360. .off('mouseout')
  31361. .off('emphasis')
  31362. .off('normal');
  31363. symbolPath.hoverStyle = hoverItemStyle;
  31364. // FIXME
  31365. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  31366. setHoverStyle(symbolPath);
  31367. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  31368. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  31369. // Note: consider `off`, should use static function here.
  31370. symbolPath.on('mouseover', onMouseOver)
  31371. .on('mouseout', onMouseOut)
  31372. .on('emphasis', onEmphasis)
  31373. .on('normal', onNormal);
  31374. }
  31375. };
  31376. function onMouseOver() {
  31377. // see comment in `graphic.isInEmphasis`
  31378. !isInEmphasis(this) && onEmphasis.call(this);
  31379. }
  31380. function onMouseOut() {
  31381. // see comment in `graphic.isInEmphasis`
  31382. !isInEmphasis(this) && onNormal.call(this);
  31383. }
  31384. function onEmphasis() {
  31385. // Do not support this hover animation util some scenario required.
  31386. // Animation can only be supported in hover layer when using `el.incremetal`.
  31387. if (this.incremental || this.useHoverLayer) {
  31388. return;
  31389. }
  31390. var scale = this.__symbolOriginalScale;
  31391. var ratio = scale[1] / scale[0];
  31392. this.animateTo({
  31393. scale: [
  31394. Math.max(scale[0] * 1.1, scale[0] + 3),
  31395. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  31396. ]
  31397. }, 400, 'elasticOut');
  31398. }
  31399. function onNormal() {
  31400. if (this.incremental || this.useHoverLayer) {
  31401. return;
  31402. }
  31403. this.animateTo({
  31404. scale: this.__symbolOriginalScale
  31405. }, 400, 'elasticOut');
  31406. }
  31407. /**
  31408. * @param {Function} cb
  31409. * @param {Object} [opt]
  31410. * @param {Object} [opt.keepLabel=true]
  31411. */
  31412. symbolProto.fadeOut = function (cb, opt) {
  31413. var symbolPath = this.childAt(0);
  31414. // Avoid mistaken hover when fading out
  31415. this.silent = symbolPath.silent = true;
  31416. // Not show text when animating
  31417. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  31418. updateProps(
  31419. symbolPath,
  31420. {
  31421. style: {opacity: 0},
  31422. scale: [0, 0]
  31423. },
  31424. this._seriesModel,
  31425. this.dataIndex,
  31426. cb
  31427. );
  31428. };
  31429. inherits(SymbolClz$1, Group);
  31430. /*
  31431. * Licensed to the Apache Software Foundation (ASF) under one
  31432. * or more contributor license agreements. See the NOTICE file
  31433. * distributed with this work for additional information
  31434. * regarding copyright ownership. The ASF licenses this file
  31435. * to you under the Apache License, Version 2.0 (the
  31436. * "License"); you may not use this file except in compliance
  31437. * with the License. You may obtain a copy of the License at
  31438. *
  31439. * http://www.apache.org/licenses/LICENSE-2.0
  31440. *
  31441. * Unless required by applicable law or agreed to in writing,
  31442. * software distributed under the License is distributed on an
  31443. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31444. * KIND, either express or implied. See the License for the
  31445. * specific language governing permissions and limitations
  31446. * under the License.
  31447. */
  31448. /**
  31449. * @module echarts/chart/helper/SymbolDraw
  31450. */
  31451. /**
  31452. * @constructor
  31453. * @alias module:echarts/chart/helper/SymbolDraw
  31454. * @param {module:zrender/graphic/Group} [symbolCtor]
  31455. */
  31456. function SymbolDraw(symbolCtor) {
  31457. this.group = new Group();
  31458. this._symbolCtor = symbolCtor || SymbolClz$1;
  31459. }
  31460. var symbolDrawProto = SymbolDraw.prototype;
  31461. function symbolNeedsDraw(data, point, idx, opt) {
  31462. return point && !isNaN(point[0]) && !isNaN(point[1])
  31463. && !(opt.isIgnore && opt.isIgnore(idx))
  31464. // We do not set clipShape on group, because it will cut part of
  31465. // the symbol element shape. We use the same clip shape here as
  31466. // the line clip.
  31467. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  31468. && data.getItemVisual(idx, 'symbol') !== 'none';
  31469. }
  31470. /**
  31471. * Update symbols draw by new data
  31472. * @param {module:echarts/data/List} data
  31473. * @param {Object} [opt] Or isIgnore
  31474. * @param {Function} [opt.isIgnore]
  31475. * @param {Object} [opt.clipShape]
  31476. */
  31477. symbolDrawProto.updateData = function (data, opt) {
  31478. opt = normalizeUpdateOpt(opt);
  31479. var group = this.group;
  31480. var seriesModel = data.hostModel;
  31481. var oldData = this._data;
  31482. var SymbolCtor = this._symbolCtor;
  31483. var seriesScope = makeSeriesScope(data);
  31484. // There is no oldLineData only when first rendering or switching from
  31485. // stream mode to normal mode, where previous elements should be removed.
  31486. if (!oldData) {
  31487. group.removeAll();
  31488. }
  31489. data.diff(oldData)
  31490. .add(function (newIdx) {
  31491. var point = data.getItemLayout(newIdx);
  31492. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  31493. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  31494. symbolEl.attr('position', point);
  31495. data.setItemGraphicEl(newIdx, symbolEl);
  31496. group.add(symbolEl);
  31497. }
  31498. })
  31499. .update(function (newIdx, oldIdx) {
  31500. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  31501. var point = data.getItemLayout(newIdx);
  31502. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  31503. group.remove(symbolEl);
  31504. return;
  31505. }
  31506. if (!symbolEl) {
  31507. symbolEl = new SymbolCtor(data, newIdx);
  31508. symbolEl.attr('position', point);
  31509. }
  31510. else {
  31511. symbolEl.updateData(data, newIdx, seriesScope);
  31512. updateProps(symbolEl, {
  31513. position: point
  31514. }, seriesModel);
  31515. }
  31516. // Add back
  31517. group.add(symbolEl);
  31518. data.setItemGraphicEl(newIdx, symbolEl);
  31519. })
  31520. .remove(function (oldIdx) {
  31521. var el = oldData.getItemGraphicEl(oldIdx);
  31522. el && el.fadeOut(function () {
  31523. group.remove(el);
  31524. });
  31525. })
  31526. .execute();
  31527. this._data = data;
  31528. };
  31529. symbolDrawProto.isPersistent = function () {
  31530. return true;
  31531. };
  31532. symbolDrawProto.updateLayout = function () {
  31533. var data = this._data;
  31534. if (data) {
  31535. // Not use animation
  31536. data.eachItemGraphicEl(function (el, idx) {
  31537. var point = data.getItemLayout(idx);
  31538. el.attr('position', point);
  31539. });
  31540. }
  31541. };
  31542. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  31543. this._seriesScope = makeSeriesScope(data);
  31544. this._data = null;
  31545. this.group.removeAll();
  31546. };
  31547. /**
  31548. * Update symbols draw by new data
  31549. * @param {module:echarts/data/List} data
  31550. * @param {Object} [opt] Or isIgnore
  31551. * @param {Function} [opt.isIgnore]
  31552. * @param {Object} [opt.clipShape]
  31553. */
  31554. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  31555. opt = normalizeUpdateOpt(opt);
  31556. function updateIncrementalAndHover(el) {
  31557. if (!el.isGroup) {
  31558. el.incremental = el.useHoverLayer = true;
  31559. }
  31560. }
  31561. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  31562. var point = data.getItemLayout(idx);
  31563. if (symbolNeedsDraw(data, point, idx, opt)) {
  31564. var el = new this._symbolCtor(data, idx, this._seriesScope);
  31565. el.traverse(updateIncrementalAndHover);
  31566. el.attr('position', point);
  31567. this.group.add(el);
  31568. data.setItemGraphicEl(idx, el);
  31569. }
  31570. }
  31571. };
  31572. function normalizeUpdateOpt(opt) {
  31573. if (opt != null && !isObject$1(opt)) {
  31574. opt = {isIgnore: opt};
  31575. }
  31576. return opt || {};
  31577. }
  31578. symbolDrawProto.remove = function (enableAnimation) {
  31579. var group = this.group;
  31580. var data = this._data;
  31581. // Incremental model do not have this._data.
  31582. if (data && enableAnimation) {
  31583. data.eachItemGraphicEl(function (el) {
  31584. el.fadeOut(function () {
  31585. group.remove(el);
  31586. });
  31587. });
  31588. }
  31589. else {
  31590. group.removeAll();
  31591. }
  31592. };
  31593. function makeSeriesScope(data) {
  31594. var seriesModel = data.hostModel;
  31595. return {
  31596. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  31597. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  31598. symbolRotate: seriesModel.get('symbolRotate'),
  31599. symbolOffset: seriesModel.get('symbolOffset'),
  31600. hoverAnimation: seriesModel.get('hoverAnimation'),
  31601. labelModel: seriesModel.getModel('label'),
  31602. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  31603. cursorStyle: seriesModel.get('cursor')
  31604. };
  31605. }
  31606. /*
  31607. * Licensed to the Apache Software Foundation (ASF) under one
  31608. * or more contributor license agreements. See the NOTICE file
  31609. * distributed with this work for additional information
  31610. * regarding copyright ownership. The ASF licenses this file
  31611. * to you under the Apache License, Version 2.0 (the
  31612. * "License"); you may not use this file except in compliance
  31613. * with the License. You may obtain a copy of the License at
  31614. *
  31615. * http://www.apache.org/licenses/LICENSE-2.0
  31616. *
  31617. * Unless required by applicable law or agreed to in writing,
  31618. * software distributed under the License is distributed on an
  31619. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31620. * KIND, either express or implied. See the License for the
  31621. * specific language governing permissions and limitations
  31622. * under the License.
  31623. */
  31624. /**
  31625. * @param {Object} coordSys
  31626. * @param {module:echarts/data/List} data
  31627. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  31628. */
  31629. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  31630. var baseAxis = coordSys.getBaseAxis();
  31631. var valueAxis = coordSys.getOtherAxis(baseAxis);
  31632. var valueStart = getValueStart(valueAxis, valueOrigin);
  31633. var baseAxisDim = baseAxis.dim;
  31634. var valueAxisDim = valueAxis.dim;
  31635. var valueDim = data.mapDimension(valueAxisDim);
  31636. var baseDim = data.mapDimension(baseAxisDim);
  31637. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  31638. var dims = map(coordSys.dimensions, function (coordDim) {
  31639. return data.mapDimension(coordDim);
  31640. });
  31641. var stacked;
  31642. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  31643. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  31644. dims[0] = stackResultDim;
  31645. }
  31646. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  31647. dims[1] = stackResultDim;
  31648. }
  31649. return {
  31650. dataDimsForPoint: dims,
  31651. valueStart: valueStart,
  31652. valueAxisDim: valueAxisDim,
  31653. baseAxisDim: baseAxisDim,
  31654. stacked: !!stacked,
  31655. valueDim: valueDim,
  31656. baseDim: baseDim,
  31657. baseDataOffset: baseDataOffset,
  31658. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  31659. };
  31660. }
  31661. function getValueStart(valueAxis, valueOrigin) {
  31662. var valueStart = 0;
  31663. var extent = valueAxis.scale.getExtent();
  31664. if (valueOrigin === 'start') {
  31665. valueStart = extent[0];
  31666. }
  31667. else if (valueOrigin === 'end') {
  31668. valueStart = extent[1];
  31669. }
  31670. // auto
  31671. else {
  31672. // Both positive
  31673. if (extent[0] > 0) {
  31674. valueStart = extent[0];
  31675. }
  31676. // Both negative
  31677. else if (extent[1] < 0) {
  31678. valueStart = extent[1];
  31679. }
  31680. // If is one positive, and one negative, onZero shall be true
  31681. }
  31682. return valueStart;
  31683. }
  31684. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  31685. var value = NaN;
  31686. if (dataCoordInfo.stacked) {
  31687. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  31688. }
  31689. if (isNaN(value)) {
  31690. value = dataCoordInfo.valueStart;
  31691. }
  31692. var baseDataOffset = dataCoordInfo.baseDataOffset;
  31693. var stackedData = [];
  31694. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  31695. stackedData[1 - baseDataOffset] = value;
  31696. return coordSys.dataToPoint(stackedData);
  31697. }
  31698. /*
  31699. * Licensed to the Apache Software Foundation (ASF) under one
  31700. * or more contributor license agreements. See the NOTICE file
  31701. * distributed with this work for additional information
  31702. * regarding copyright ownership. The ASF licenses this file
  31703. * to you under the Apache License, Version 2.0 (the
  31704. * "License"); you may not use this file except in compliance
  31705. * with the License. You may obtain a copy of the License at
  31706. *
  31707. * http://www.apache.org/licenses/LICENSE-2.0
  31708. *
  31709. * Unless required by applicable law or agreed to in writing,
  31710. * software distributed under the License is distributed on an
  31711. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31712. * KIND, either express or implied. See the License for the
  31713. * specific language governing permissions and limitations
  31714. * under the License.
  31715. */
  31716. // var arrayDiff = require('zrender/src/core/arrayDiff');
  31717. // 'zrender/src/core/arrayDiff' has been used before, but it did
  31718. // not do well in performance when roam with fixed dataZoom window.
  31719. // function convertToIntId(newIdList, oldIdList) {
  31720. // // Generate int id instead of string id.
  31721. // // Compare string maybe slow in score function of arrDiff
  31722. // // Assume id in idList are all unique
  31723. // var idIndicesMap = {};
  31724. // var idx = 0;
  31725. // for (var i = 0; i < newIdList.length; i++) {
  31726. // idIndicesMap[newIdList[i]] = idx;
  31727. // newIdList[i] = idx++;
  31728. // }
  31729. // for (var i = 0; i < oldIdList.length; i++) {
  31730. // var oldId = oldIdList[i];
  31731. // // Same with newIdList
  31732. // if (idIndicesMap[oldId]) {
  31733. // oldIdList[i] = idIndicesMap[oldId];
  31734. // }
  31735. // else {
  31736. // oldIdList[i] = idx++;
  31737. // }
  31738. // }
  31739. // }
  31740. function diffData(oldData, newData) {
  31741. var diffResult = [];
  31742. newData.diff(oldData)
  31743. .add(function (idx) {
  31744. diffResult.push({cmd: '+', idx: idx});
  31745. })
  31746. .update(function (newIdx, oldIdx) {
  31747. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  31748. })
  31749. .remove(function (idx) {
  31750. diffResult.push({cmd: '-', idx: idx});
  31751. })
  31752. .execute();
  31753. return diffResult;
  31754. }
  31755. var lineAnimationDiff = function (
  31756. oldData, newData,
  31757. oldStackedOnPoints, newStackedOnPoints,
  31758. oldCoordSys, newCoordSys,
  31759. oldValueOrigin, newValueOrigin
  31760. ) {
  31761. var diff = diffData(oldData, newData);
  31762. // var newIdList = newData.mapArray(newData.getId);
  31763. // var oldIdList = oldData.mapArray(oldData.getId);
  31764. // convertToIntId(newIdList, oldIdList);
  31765. // // FIXME One data ?
  31766. // diff = arrayDiff(oldIdList, newIdList);
  31767. var currPoints = [];
  31768. var nextPoints = [];
  31769. // Points for stacking base line
  31770. var currStackedPoints = [];
  31771. var nextStackedPoints = [];
  31772. var status = [];
  31773. var sortedIndices = [];
  31774. var rawIndices = [];
  31775. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  31776. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  31777. for (var i = 0; i < diff.length; i++) {
  31778. var diffItem = diff[i];
  31779. var pointAdded = true;
  31780. // FIXME, animation is not so perfect when dataZoom window moves fast
  31781. // Which is in case remvoing or add more than one data in the tail or head
  31782. switch (diffItem.cmd) {
  31783. case '=':
  31784. var currentPt = oldData.getItemLayout(diffItem.idx);
  31785. var nextPt = newData.getItemLayout(diffItem.idx1);
  31786. // If previous data is NaN, use next point directly
  31787. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  31788. currentPt = nextPt.slice();
  31789. }
  31790. currPoints.push(currentPt);
  31791. nextPoints.push(nextPt);
  31792. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  31793. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  31794. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  31795. break;
  31796. case '+':
  31797. var idx = diffItem.idx;
  31798. currPoints.push(
  31799. oldCoordSys.dataToPoint([
  31800. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  31801. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  31802. ])
  31803. );
  31804. nextPoints.push(newData.getItemLayout(idx).slice());
  31805. currStackedPoints.push(
  31806. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  31807. );
  31808. nextStackedPoints.push(newStackedOnPoints[idx]);
  31809. rawIndices.push(newData.getRawIndex(idx));
  31810. break;
  31811. case '-':
  31812. var idx = diffItem.idx;
  31813. var rawIndex = oldData.getRawIndex(idx);
  31814. // Data is replaced. In the case of dynamic data queue
  31815. // FIXME FIXME FIXME
  31816. if (rawIndex !== idx) {
  31817. currPoints.push(oldData.getItemLayout(idx));
  31818. nextPoints.push(newCoordSys.dataToPoint([
  31819. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  31820. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  31821. ]));
  31822. currStackedPoints.push(oldStackedOnPoints[idx]);
  31823. nextStackedPoints.push(
  31824. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  31825. );
  31826. rawIndices.push(rawIndex);
  31827. }
  31828. else {
  31829. pointAdded = false;
  31830. }
  31831. }
  31832. // Original indices
  31833. if (pointAdded) {
  31834. status.push(diffItem);
  31835. sortedIndices.push(sortedIndices.length);
  31836. }
  31837. }
  31838. // Diff result may be crossed if all items are changed
  31839. // Sort by data index
  31840. sortedIndices.sort(function (a, b) {
  31841. return rawIndices[a] - rawIndices[b];
  31842. });
  31843. var sortedCurrPoints = [];
  31844. var sortedNextPoints = [];
  31845. var sortedCurrStackedPoints = [];
  31846. var sortedNextStackedPoints = [];
  31847. var sortedStatus = [];
  31848. for (var i = 0; i < sortedIndices.length; i++) {
  31849. var idx = sortedIndices[i];
  31850. sortedCurrPoints[i] = currPoints[idx];
  31851. sortedNextPoints[i] = nextPoints[idx];
  31852. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  31853. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  31854. sortedStatus[i] = status[idx];
  31855. }
  31856. return {
  31857. current: sortedCurrPoints,
  31858. next: sortedNextPoints,
  31859. stackedOnCurrent: sortedCurrStackedPoints,
  31860. stackedOnNext: sortedNextStackedPoints,
  31861. status: sortedStatus
  31862. };
  31863. };
  31864. /*
  31865. * Licensed to the Apache Software Foundation (ASF) under one
  31866. * or more contributor license agreements. See the NOTICE file
  31867. * distributed with this work for additional information
  31868. * regarding copyright ownership. The ASF licenses this file
  31869. * to you under the Apache License, Version 2.0 (the
  31870. * "License"); you may not use this file except in compliance
  31871. * with the License. You may obtain a copy of the License at
  31872. *
  31873. * http://www.apache.org/licenses/LICENSE-2.0
  31874. *
  31875. * Unless required by applicable law or agreed to in writing,
  31876. * software distributed under the License is distributed on an
  31877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31878. * KIND, either express or implied. See the License for the
  31879. * specific language governing permissions and limitations
  31880. * under the License.
  31881. */
  31882. // Poly path support NaN point
  31883. var vec2Min = min;
  31884. var vec2Max = max;
  31885. var scaleAndAdd$1 = scaleAndAdd;
  31886. var v2Copy = copy;
  31887. // Temporary variable
  31888. var v = [];
  31889. var cp0 = [];
  31890. var cp1 = [];
  31891. function isPointNull(p) {
  31892. return isNaN(p[0]) || isNaN(p[1]);
  31893. }
  31894. function drawSegment(
  31895. ctx, points, start, segLen, allLen,
  31896. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  31897. ) {
  31898. // if (smoothMonotone == null) {
  31899. // if (isMono(points, 'x')) {
  31900. // return drawMono(ctx, points, start, segLen, allLen,
  31901. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  31902. // }
  31903. // else if (isMono(points, 'y')) {
  31904. // return drawMono(ctx, points, start, segLen, allLen,
  31905. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  31906. // }
  31907. // else {
  31908. // return drawNonMono.apply(this, arguments);
  31909. // }
  31910. // }
  31911. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  31912. // return drawMono.apply(this, arguments);
  31913. // }
  31914. // else {
  31915. // return drawNonMono.apply(this, arguments);
  31916. // }
  31917. if (smoothMonotone === 'none' || !smoothMonotone) {
  31918. return drawNonMono.apply(this, arguments);
  31919. }
  31920. else {
  31921. return drawMono.apply(this, arguments);
  31922. }
  31923. }
  31924. /**
  31925. * Check if points is in monotone.
  31926. *
  31927. * @param {number[][]} points Array of points which is in [x, y] form
  31928. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  31929. * dimension that is checking.
  31930. * If is 'none', `drawNonMono` should be
  31931. * called.
  31932. * If is undefined, either being monotone
  31933. * in 'x' or 'y' will call `drawMono`.
  31934. */
  31935. // function isMono(points, smoothMonotone) {
  31936. // if (points.length <= 1) {
  31937. // return true;
  31938. // }
  31939. // var dim = smoothMonotone === 'x' ? 0 : 1;
  31940. // var last = points[0][dim];
  31941. // var lastDiff = 0;
  31942. // for (var i = 1; i < points.length; ++i) {
  31943. // var diff = points[i][dim] - last;
  31944. // if (!isNaN(diff) && !isNaN(lastDiff)
  31945. // && diff !== 0 && lastDiff !== 0
  31946. // && ((diff >= 0) !== (lastDiff >= 0))
  31947. // ) {
  31948. // return false;
  31949. // }
  31950. // if (!isNaN(diff) && diff !== 0) {
  31951. // lastDiff = diff;
  31952. // last = points[i][dim];
  31953. // }
  31954. // }
  31955. // return true;
  31956. // }
  31957. /**
  31958. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  31959. * control points will be used. This should be used when points are monotone
  31960. * either in x or y dimension.
  31961. */
  31962. function drawMono(
  31963. ctx, points, start, segLen, allLen,
  31964. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  31965. ) {
  31966. var prevIdx = 0;
  31967. var idx = start;
  31968. for (var k = 0; k < segLen; k++) {
  31969. var p = points[idx];
  31970. if (idx >= allLen || idx < 0) {
  31971. break;
  31972. }
  31973. if (isPointNull(p)) {
  31974. if (connectNulls) {
  31975. idx += dir;
  31976. continue;
  31977. }
  31978. break;
  31979. }
  31980. if (idx === start) {
  31981. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  31982. }
  31983. else {
  31984. if (smooth > 0) {
  31985. var prevP = points[prevIdx];
  31986. var dim = smoothMonotone === 'y' ? 1 : 0;
  31987. // Length of control point to p, either in x or y, but not both
  31988. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  31989. v2Copy(cp0, prevP);
  31990. cp0[dim] = prevP[dim] + ctrlLen;
  31991. v2Copy(cp1, p);
  31992. cp1[dim] = p[dim] - ctrlLen;
  31993. ctx.bezierCurveTo(
  31994. cp0[0], cp0[1],
  31995. cp1[0], cp1[1],
  31996. p[0], p[1]
  31997. );
  31998. }
  31999. else {
  32000. ctx.lineTo(p[0], p[1]);
  32001. }
  32002. }
  32003. prevIdx = idx;
  32004. idx += dir;
  32005. }
  32006. return k;
  32007. }
  32008. /**
  32009. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  32010. * situations. This should be used when points are non-monotone neither in x or
  32011. * y dimension.
  32012. */
  32013. function drawNonMono(
  32014. ctx, points, start, segLen, allLen,
  32015. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  32016. ) {
  32017. var prevIdx = 0;
  32018. var idx = start;
  32019. for (var k = 0; k < segLen; k++) {
  32020. var p = points[idx];
  32021. if (idx >= allLen || idx < 0) {
  32022. break;
  32023. }
  32024. if (isPointNull(p)) {
  32025. if (connectNulls) {
  32026. idx += dir;
  32027. continue;
  32028. }
  32029. break;
  32030. }
  32031. if (idx === start) {
  32032. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  32033. v2Copy(cp0, p);
  32034. }
  32035. else {
  32036. if (smooth > 0) {
  32037. var nextIdx = idx + dir;
  32038. var nextP = points[nextIdx];
  32039. if (connectNulls) {
  32040. // Find next point not null
  32041. while (nextP && isPointNull(points[nextIdx])) {
  32042. nextIdx += dir;
  32043. nextP = points[nextIdx];
  32044. }
  32045. }
  32046. var ratioNextSeg = 0.5;
  32047. var prevP = points[prevIdx];
  32048. var nextP = points[nextIdx];
  32049. // Last point
  32050. if (!nextP || isPointNull(nextP)) {
  32051. v2Copy(cp1, p);
  32052. }
  32053. else {
  32054. // If next data is null in not connect case
  32055. if (isPointNull(nextP) && !connectNulls) {
  32056. nextP = p;
  32057. }
  32058. sub(v, nextP, prevP);
  32059. var lenPrevSeg;
  32060. var lenNextSeg;
  32061. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  32062. var dim = smoothMonotone === 'x' ? 0 : 1;
  32063. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  32064. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  32065. }
  32066. else {
  32067. lenPrevSeg = dist(p, prevP);
  32068. lenNextSeg = dist(p, nextP);
  32069. }
  32070. // Use ratio of seg length
  32071. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  32072. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  32073. }
  32074. // Smooth constraint
  32075. vec2Min(cp0, cp0, smoothMax);
  32076. vec2Max(cp0, cp0, smoothMin);
  32077. vec2Min(cp1, cp1, smoothMax);
  32078. vec2Max(cp1, cp1, smoothMin);
  32079. ctx.bezierCurveTo(
  32080. cp0[0], cp0[1],
  32081. cp1[0], cp1[1],
  32082. p[0], p[1]
  32083. );
  32084. // cp0 of next segment
  32085. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  32086. }
  32087. else {
  32088. ctx.lineTo(p[0], p[1]);
  32089. }
  32090. }
  32091. prevIdx = idx;
  32092. idx += dir;
  32093. }
  32094. return k;
  32095. }
  32096. function getBoundingBox(points, smoothConstraint) {
  32097. var ptMin = [Infinity, Infinity];
  32098. var ptMax = [-Infinity, -Infinity];
  32099. if (smoothConstraint) {
  32100. for (var i = 0; i < points.length; i++) {
  32101. var pt = points[i];
  32102. if (pt[0] < ptMin[0]) {
  32103. ptMin[0] = pt[0];
  32104. }
  32105. if (pt[1] < ptMin[1]) {
  32106. ptMin[1] = pt[1];
  32107. }
  32108. if (pt[0] > ptMax[0]) {
  32109. ptMax[0] = pt[0];
  32110. }
  32111. if (pt[1] > ptMax[1]) {
  32112. ptMax[1] = pt[1];
  32113. }
  32114. }
  32115. }
  32116. return {
  32117. min: smoothConstraint ? ptMin : ptMax,
  32118. max: smoothConstraint ? ptMax : ptMin
  32119. };
  32120. }
  32121. var Polyline$1 = Path.extend({
  32122. type: 'ec-polyline',
  32123. shape: {
  32124. points: [],
  32125. smooth: 0,
  32126. smoothConstraint: true,
  32127. smoothMonotone: null,
  32128. connectNulls: false
  32129. },
  32130. style: {
  32131. fill: null,
  32132. stroke: '#000'
  32133. },
  32134. brush: fixClipWithShadow(Path.prototype.brush),
  32135. buildPath: function (ctx, shape) {
  32136. var points = shape.points;
  32137. var i = 0;
  32138. var len$$1 = points.length;
  32139. var result = getBoundingBox(points, shape.smoothConstraint);
  32140. if (shape.connectNulls) {
  32141. // Must remove first and last null values avoid draw error in polygon
  32142. for (; len$$1 > 0; len$$1--) {
  32143. if (!isPointNull(points[len$$1 - 1])) {
  32144. break;
  32145. }
  32146. }
  32147. for (; i < len$$1; i++) {
  32148. if (!isPointNull(points[i])) {
  32149. break;
  32150. }
  32151. }
  32152. }
  32153. while (i < len$$1) {
  32154. i += drawSegment(
  32155. ctx, points, i, len$$1, len$$1,
  32156. 1, result.min, result.max, shape.smooth,
  32157. shape.smoothMonotone, shape.connectNulls
  32158. ) + 1;
  32159. }
  32160. }
  32161. });
  32162. var Polygon$1 = Path.extend({
  32163. type: 'ec-polygon',
  32164. shape: {
  32165. points: [],
  32166. // Offset between stacked base points and points
  32167. stackedOnPoints: [],
  32168. smooth: 0,
  32169. stackedOnSmooth: 0,
  32170. smoothConstraint: true,
  32171. smoothMonotone: null,
  32172. connectNulls: false
  32173. },
  32174. brush: fixClipWithShadow(Path.prototype.brush),
  32175. buildPath: function (ctx, shape) {
  32176. var points = shape.points;
  32177. var stackedOnPoints = shape.stackedOnPoints;
  32178. var i = 0;
  32179. var len$$1 = points.length;
  32180. var smoothMonotone = shape.smoothMonotone;
  32181. var bbox = getBoundingBox(points, shape.smoothConstraint);
  32182. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  32183. if (shape.connectNulls) {
  32184. // Must remove first and last null values avoid draw error in polygon
  32185. for (; len$$1 > 0; len$$1--) {
  32186. if (!isPointNull(points[len$$1 - 1])) {
  32187. break;
  32188. }
  32189. }
  32190. for (; i < len$$1; i++) {
  32191. if (!isPointNull(points[i])) {
  32192. break;
  32193. }
  32194. }
  32195. }
  32196. while (i < len$$1) {
  32197. var k = drawSegment(
  32198. ctx, points, i, len$$1, len$$1,
  32199. 1, bbox.min, bbox.max, shape.smooth,
  32200. smoothMonotone, shape.connectNulls
  32201. );
  32202. drawSegment(
  32203. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  32204. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  32205. smoothMonotone, shape.connectNulls
  32206. );
  32207. i += k + 1;
  32208. ctx.closePath();
  32209. }
  32210. }
  32211. });
  32212. /*
  32213. * Licensed to the Apache Software Foundation (ASF) under one
  32214. * or more contributor license agreements. See the NOTICE file
  32215. * distributed with this work for additional information
  32216. * regarding copyright ownership. The ASF licenses this file
  32217. * to you under the Apache License, Version 2.0 (the
  32218. * "License"); you may not use this file except in compliance
  32219. * with the License. You may obtain a copy of the License at
  32220. *
  32221. * http://www.apache.org/licenses/LICENSE-2.0
  32222. *
  32223. * Unless required by applicable law or agreed to in writing,
  32224. * software distributed under the License is distributed on an
  32225. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32226. * KIND, either express or implied. See the License for the
  32227. * specific language governing permissions and limitations
  32228. * under the License.
  32229. */
  32230. // FIXME step not support polar
  32231. function isPointsSame(points1, points2) {
  32232. if (points1.length !== points2.length) {
  32233. return;
  32234. }
  32235. for (var i = 0; i < points1.length; i++) {
  32236. var p1 = points1[i];
  32237. var p2 = points2[i];
  32238. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  32239. return;
  32240. }
  32241. }
  32242. return true;
  32243. }
  32244. function getSmooth(smooth) {
  32245. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  32246. }
  32247. function getAxisExtentWithGap(axis) {
  32248. var extent = axis.getGlobalExtent();
  32249. if (axis.onBand) {
  32250. // Remove extra 1px to avoid line miter in clipped edge
  32251. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  32252. var dir = extent[1] > extent[0] ? 1 : -1;
  32253. extent[0] += dir * halfBandWidth;
  32254. extent[1] -= dir * halfBandWidth;
  32255. }
  32256. return extent;
  32257. }
  32258. /**
  32259. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  32260. * @param {module:echarts/data/List} data
  32261. * @param {Object} dataCoordInfo
  32262. * @param {Array.<Array.<number>>} points
  32263. */
  32264. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  32265. if (!dataCoordInfo.valueDim) {
  32266. return [];
  32267. }
  32268. var points = [];
  32269. for (var idx = 0, len = data.count(); idx < len; idx++) {
  32270. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  32271. }
  32272. return points;
  32273. }
  32274. function createGridClipShape(cartesian, hasAnimation, forSymbol, seriesModel) {
  32275. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  32276. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  32277. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  32278. var x = Math.min(xExtent[0], xExtent[1]);
  32279. var y = Math.min(yExtent[0], yExtent[1]);
  32280. var width = Math.max(xExtent[0], xExtent[1]) - x;
  32281. var height = Math.max(yExtent[0], yExtent[1]) - y;
  32282. // Avoid float number rounding error for symbol on the edge of axis extent.
  32283. // See #7913 and `test/dataZoom-clip.html`.
  32284. if (forSymbol) {
  32285. x -= 0.5;
  32286. width += 0.5;
  32287. y -= 0.5;
  32288. height += 0.5;
  32289. }
  32290. else {
  32291. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  32292. // Expand clip shape to avoid clipping when line value exceeds axis
  32293. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  32294. if (isHorizontal) {
  32295. y -= expandSize;
  32296. height += expandSize * 2;
  32297. }
  32298. else {
  32299. x -= expandSize;
  32300. width += expandSize * 2;
  32301. }
  32302. }
  32303. var clipPath = new Rect({
  32304. shape: {
  32305. x: x,
  32306. y: y,
  32307. width: width,
  32308. height: height
  32309. }
  32310. });
  32311. if (hasAnimation) {
  32312. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  32313. initProps(clipPath, {
  32314. shape: {
  32315. width: width,
  32316. height: height
  32317. }
  32318. }, seriesModel);
  32319. }
  32320. return clipPath;
  32321. }
  32322. function createPolarClipShape(polar, hasAnimation, forSymbol, seriesModel) {
  32323. var angleAxis = polar.getAngleAxis();
  32324. var radiusAxis = polar.getRadiusAxis();
  32325. var radiusExtent = radiusAxis.getExtent().slice();
  32326. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  32327. var angleExtent = angleAxis.getExtent();
  32328. var RADIAN = Math.PI / 180;
  32329. // Avoid float number rounding error for symbol on the edge of axis extent.
  32330. if (forSymbol) {
  32331. radiusExtent[0] -= 0.5;
  32332. radiusExtent[1] += 0.5;
  32333. }
  32334. var clipPath = new Sector({
  32335. shape: {
  32336. cx: round$2(polar.cx, 1),
  32337. cy: round$2(polar.cy, 1),
  32338. r0: round$2(radiusExtent[0], 1),
  32339. r: round$2(radiusExtent[1], 1),
  32340. startAngle: -angleExtent[0] * RADIAN,
  32341. endAngle: -angleExtent[1] * RADIAN,
  32342. clockwise: angleAxis.inverse
  32343. }
  32344. });
  32345. if (hasAnimation) {
  32346. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  32347. initProps(clipPath, {
  32348. shape: {
  32349. endAngle: -angleExtent[1] * RADIAN
  32350. }
  32351. }, seriesModel);
  32352. }
  32353. return clipPath;
  32354. }
  32355. function createClipShape(coordSys, hasAnimation, forSymbol, seriesModel) {
  32356. return coordSys.type === 'polar'
  32357. ? createPolarClipShape(coordSys, hasAnimation, forSymbol, seriesModel)
  32358. : createGridClipShape(coordSys, hasAnimation, forSymbol, seriesModel);
  32359. }
  32360. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  32361. var baseAxis = coordSys.getBaseAxis();
  32362. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  32363. var stepPoints = [];
  32364. for (var i = 0; i < points.length - 1; i++) {
  32365. var nextPt = points[i + 1];
  32366. var pt = points[i];
  32367. stepPoints.push(pt);
  32368. var stepPt = [];
  32369. switch (stepTurnAt) {
  32370. case 'end':
  32371. stepPt[baseIndex] = nextPt[baseIndex];
  32372. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  32373. // default is start
  32374. stepPoints.push(stepPt);
  32375. break;
  32376. case 'middle':
  32377. // default is start
  32378. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  32379. var stepPt2 = [];
  32380. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  32381. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  32382. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  32383. stepPoints.push(stepPt);
  32384. stepPoints.push(stepPt2);
  32385. break;
  32386. default:
  32387. stepPt[baseIndex] = pt[baseIndex];
  32388. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  32389. // default is start
  32390. stepPoints.push(stepPt);
  32391. }
  32392. }
  32393. // Last points
  32394. points[i] && stepPoints.push(points[i]);
  32395. return stepPoints;
  32396. }
  32397. function getVisualGradient(data, coordSys) {
  32398. var visualMetaList = data.getVisual('visualMeta');
  32399. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  32400. // When data.count() is 0, gradient range can not be calculated.
  32401. return;
  32402. }
  32403. if (coordSys.type !== 'cartesian2d') {
  32404. if (__DEV__) {
  32405. console.warn('Visual map on line style is only supported on cartesian2d.');
  32406. }
  32407. return;
  32408. }
  32409. var coordDim;
  32410. var visualMeta;
  32411. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  32412. var dimIndex = visualMetaList[i].dimension;
  32413. var dimName = data.dimensions[dimIndex];
  32414. var dimInfo = data.getDimensionInfo(dimName);
  32415. coordDim = dimInfo && dimInfo.coordDim;
  32416. // Can only be x or y
  32417. if (coordDim === 'x' || coordDim === 'y') {
  32418. visualMeta = visualMetaList[i];
  32419. break;
  32420. }
  32421. }
  32422. if (!visualMeta) {
  32423. if (__DEV__) {
  32424. console.warn('Visual map on line style only support x or y dimension.');
  32425. }
  32426. return;
  32427. }
  32428. // If the area to be rendered is bigger than area defined by LinearGradient,
  32429. // the canvas spec prescribes that the color of the first stop and the last
  32430. // stop should be used. But if two stops are added at offset 0, in effect
  32431. // browsers use the color of the second stop to render area outside
  32432. // LinearGradient. So we can only infinitesimally extend area defined in
  32433. // LinearGradient to render `outerColors`.
  32434. var axis = coordSys.getAxis(coordDim);
  32435. // dataToCoor mapping may not be linear, but must be monotonic.
  32436. var colorStops = map(visualMeta.stops, function (stop) {
  32437. return {
  32438. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  32439. color: stop.color
  32440. };
  32441. });
  32442. var stopLen = colorStops.length;
  32443. var outerColors = visualMeta.outerColors.slice();
  32444. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  32445. colorStops.reverse();
  32446. outerColors.reverse();
  32447. }
  32448. var tinyExtent = 10; // Arbitrary value: 10px
  32449. var minCoord = colorStops[0].coord - tinyExtent;
  32450. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  32451. var coordSpan = maxCoord - minCoord;
  32452. if (coordSpan < 1e-3) {
  32453. return 'transparent';
  32454. }
  32455. each$1(colorStops, function (stop) {
  32456. stop.offset = (stop.coord - minCoord) / coordSpan;
  32457. });
  32458. colorStops.push({
  32459. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  32460. color: outerColors[1] || 'transparent'
  32461. });
  32462. colorStops.unshift({ // notice colorStops.length have been changed.
  32463. offset: stopLen ? colorStops[0].offset : 0.5,
  32464. color: outerColors[0] || 'transparent'
  32465. });
  32466. // zrUtil.each(colorStops, function (colorStop) {
  32467. // // Make sure each offset has rounded px to avoid not sharp edge
  32468. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  32469. // });
  32470. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  32471. gradient[coordDim] = minCoord;
  32472. gradient[coordDim + '2'] = maxCoord;
  32473. return gradient;
  32474. }
  32475. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  32476. var showAllSymbol = seriesModel.get('showAllSymbol');
  32477. var isAuto = showAllSymbol === 'auto';
  32478. if (showAllSymbol && !isAuto) {
  32479. return;
  32480. }
  32481. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  32482. if (!categoryAxis) {
  32483. return;
  32484. }
  32485. // Note that category label interval strategy might bring some weird effect
  32486. // in some scenario: users may wonder why some of the symbols are not
  32487. // displayed. So we show all symbols as possible as we can.
  32488. if (isAuto
  32489. // Simplify the logic, do not determine label overlap here.
  32490. && canShowAllSymbolForCategory(categoryAxis, data)
  32491. ) {
  32492. return;
  32493. }
  32494. // Otherwise follow the label interval strategy on category axis.
  32495. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  32496. var labelMap = {};
  32497. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  32498. labelMap[labelItem.tickValue] = 1;
  32499. });
  32500. return function (dataIndex) {
  32501. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  32502. };
  32503. }
  32504. function canShowAllSymbolForCategory(categoryAxis, data) {
  32505. // In mose cases, line is monotonous on category axis, and the label size
  32506. // is close with each other. So we check the symbol size and some of the
  32507. // label size alone with the category axis to estimate whether all symbol
  32508. // can be shown without overlap.
  32509. var axisExtent = categoryAxis.getExtent();
  32510. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  32511. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  32512. // Sampling some points, max 5.
  32513. var dataLen = data.count();
  32514. var step = Math.max(1, Math.round(dataLen / 5));
  32515. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  32516. if (SymbolClz$1.getSymbolSize(
  32517. data, dataIndex
  32518. // Only for cartesian, where `isHorizontal` exists.
  32519. )[categoryAxis.isHorizontal() ? 1 : 0]
  32520. // Empirical number
  32521. * 1.5 > availSize
  32522. ) {
  32523. return false;
  32524. }
  32525. }
  32526. return true;
  32527. }
  32528. Chart.extend({
  32529. type: 'line',
  32530. init: function () {
  32531. var lineGroup = new Group();
  32532. var symbolDraw = new SymbolDraw();
  32533. this.group.add(symbolDraw.group);
  32534. this._symbolDraw = symbolDraw;
  32535. this._lineGroup = lineGroup;
  32536. },
  32537. render: function (seriesModel, ecModel, api) {
  32538. var coordSys = seriesModel.coordinateSystem;
  32539. var group = this.group;
  32540. var data = seriesModel.getData();
  32541. var lineStyleModel = seriesModel.getModel('lineStyle');
  32542. var areaStyleModel = seriesModel.getModel('areaStyle');
  32543. var points = data.mapArray(data.getItemLayout);
  32544. var isCoordSysPolar = coordSys.type === 'polar';
  32545. var prevCoordSys = this._coordSys;
  32546. var symbolDraw = this._symbolDraw;
  32547. var polyline = this._polyline;
  32548. var polygon = this._polygon;
  32549. var lineGroup = this._lineGroup;
  32550. var hasAnimation = seriesModel.get('animation');
  32551. var isAreaChart = !areaStyleModel.isEmpty();
  32552. var valueOrigin = areaStyleModel.get('origin');
  32553. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  32554. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  32555. var showSymbol = seriesModel.get('showSymbol');
  32556. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  32557. && getIsIgnoreFunc(seriesModel, data, coordSys);
  32558. // Remove temporary symbols
  32559. var oldData = this._data;
  32560. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  32561. if (el.__temp) {
  32562. group.remove(el);
  32563. oldData.setItemGraphicEl(idx, null);
  32564. }
  32565. });
  32566. // Remove previous created symbols if showSymbol changed to false
  32567. if (!showSymbol) {
  32568. symbolDraw.remove();
  32569. }
  32570. group.add(lineGroup);
  32571. // FIXME step not support polar
  32572. var step = !isCoordSysPolar && seriesModel.get('step');
  32573. // Initialization animation or coordinate system changed
  32574. if (
  32575. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  32576. ) {
  32577. showSymbol && symbolDraw.updateData(data, {
  32578. isIgnore: isIgnoreFunc,
  32579. clipShape: createClipShape(coordSys, false, true, seriesModel)
  32580. });
  32581. if (step) {
  32582. // TODO If stacked series is not step
  32583. points = turnPointsIntoStep(points, coordSys, step);
  32584. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  32585. }
  32586. polyline = this._newPolyline(points, coordSys, hasAnimation);
  32587. if (isAreaChart) {
  32588. polygon = this._newPolygon(
  32589. points, stackedOnPoints,
  32590. coordSys, hasAnimation
  32591. );
  32592. }
  32593. lineGroup.setClipPath(createClipShape(coordSys, true, false, seriesModel));
  32594. }
  32595. else {
  32596. if (isAreaChart && !polygon) {
  32597. // If areaStyle is added
  32598. polygon = this._newPolygon(
  32599. points, stackedOnPoints,
  32600. coordSys, hasAnimation
  32601. );
  32602. }
  32603. else if (polygon && !isAreaChart) {
  32604. // If areaStyle is removed
  32605. lineGroup.remove(polygon);
  32606. polygon = this._polygon = null;
  32607. }
  32608. // Update clipPath
  32609. lineGroup.setClipPath(createClipShape(coordSys, false, false, seriesModel));
  32610. // Always update, or it is wrong in the case turning on legend
  32611. // because points are not changed
  32612. showSymbol && symbolDraw.updateData(data, {
  32613. isIgnore: isIgnoreFunc,
  32614. clipShape: createClipShape(coordSys, false, true, seriesModel)
  32615. });
  32616. // Stop symbol animation and sync with line points
  32617. // FIXME performance?
  32618. data.eachItemGraphicEl(function (el) {
  32619. el.stopAnimation(true);
  32620. });
  32621. // In the case data zoom triggerred refreshing frequently
  32622. // Data may not change if line has a category axis. So it should animate nothing
  32623. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  32624. || !isPointsSame(this._points, points)
  32625. ) {
  32626. if (hasAnimation) {
  32627. this._updateAnimation(
  32628. data, stackedOnPoints, coordSys, api, step, valueOrigin
  32629. );
  32630. }
  32631. else {
  32632. // Not do it in update with animation
  32633. if (step) {
  32634. // TODO If stacked series is not step
  32635. points = turnPointsIntoStep(points, coordSys, step);
  32636. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  32637. }
  32638. polyline.setShape({
  32639. points: points
  32640. });
  32641. polygon && polygon.setShape({
  32642. points: points,
  32643. stackedOnPoints: stackedOnPoints
  32644. });
  32645. }
  32646. }
  32647. }
  32648. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  32649. polyline.useStyle(defaults(
  32650. // Use color in lineStyle first
  32651. lineStyleModel.getLineStyle(),
  32652. {
  32653. fill: 'none',
  32654. stroke: visualColor,
  32655. lineJoin: 'bevel'
  32656. }
  32657. ));
  32658. var smooth = seriesModel.get('smooth');
  32659. smooth = getSmooth(seriesModel.get('smooth'));
  32660. polyline.setShape({
  32661. smooth: smooth,
  32662. smoothMonotone: seriesModel.get('smoothMonotone'),
  32663. connectNulls: seriesModel.get('connectNulls')
  32664. });
  32665. if (polygon) {
  32666. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  32667. var stackedOnSmooth = 0;
  32668. polygon.useStyle(defaults(
  32669. areaStyleModel.getAreaStyle(),
  32670. {
  32671. fill: visualColor,
  32672. opacity: 0.7,
  32673. lineJoin: 'bevel'
  32674. }
  32675. ));
  32676. if (stackedOnSeries) {
  32677. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  32678. }
  32679. polygon.setShape({
  32680. smooth: smooth,
  32681. stackedOnSmooth: stackedOnSmooth,
  32682. smoothMonotone: seriesModel.get('smoothMonotone'),
  32683. connectNulls: seriesModel.get('connectNulls')
  32684. });
  32685. }
  32686. this._data = data;
  32687. // Save the coordinate system for transition animation when data changed
  32688. this._coordSys = coordSys;
  32689. this._stackedOnPoints = stackedOnPoints;
  32690. this._points = points;
  32691. this._step = step;
  32692. this._valueOrigin = valueOrigin;
  32693. },
  32694. dispose: function () {},
  32695. highlight: function (seriesModel, ecModel, api, payload) {
  32696. var data = seriesModel.getData();
  32697. var dataIndex = queryDataIndex(data, payload);
  32698. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  32699. var symbol = data.getItemGraphicEl(dataIndex);
  32700. if (!symbol) {
  32701. // Create a temporary symbol if it is not exists
  32702. var pt = data.getItemLayout(dataIndex);
  32703. if (!pt) {
  32704. // Null data
  32705. return;
  32706. }
  32707. symbol = new SymbolClz$1(data, dataIndex);
  32708. symbol.position = pt;
  32709. symbol.setZ(
  32710. seriesModel.get('zlevel'),
  32711. seriesModel.get('z')
  32712. );
  32713. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  32714. symbol.__temp = true;
  32715. data.setItemGraphicEl(dataIndex, symbol);
  32716. // Stop scale animation
  32717. symbol.stopSymbolAnimation(true);
  32718. this.group.add(symbol);
  32719. }
  32720. symbol.highlight();
  32721. }
  32722. else {
  32723. // Highlight whole series
  32724. Chart.prototype.highlight.call(
  32725. this, seriesModel, ecModel, api, payload
  32726. );
  32727. }
  32728. },
  32729. downplay: function (seriesModel, ecModel, api, payload) {
  32730. var data = seriesModel.getData();
  32731. var dataIndex = queryDataIndex(data, payload);
  32732. if (dataIndex != null && dataIndex >= 0) {
  32733. var symbol = data.getItemGraphicEl(dataIndex);
  32734. if (symbol) {
  32735. if (symbol.__temp) {
  32736. data.setItemGraphicEl(dataIndex, null);
  32737. this.group.remove(symbol);
  32738. }
  32739. else {
  32740. symbol.downplay();
  32741. }
  32742. }
  32743. }
  32744. else {
  32745. // FIXME
  32746. // can not downplay completely.
  32747. // Downplay whole series
  32748. Chart.prototype.downplay.call(
  32749. this, seriesModel, ecModel, api, payload
  32750. );
  32751. }
  32752. },
  32753. /**
  32754. * @param {module:zrender/container/Group} group
  32755. * @param {Array.<Array.<number>>} points
  32756. * @private
  32757. */
  32758. _newPolyline: function (points) {
  32759. var polyline = this._polyline;
  32760. // Remove previous created polyline
  32761. if (polyline) {
  32762. this._lineGroup.remove(polyline);
  32763. }
  32764. polyline = new Polyline$1({
  32765. shape: {
  32766. points: points
  32767. },
  32768. silent: true,
  32769. z2: 10
  32770. });
  32771. this._lineGroup.add(polyline);
  32772. this._polyline = polyline;
  32773. return polyline;
  32774. },
  32775. /**
  32776. * @param {module:zrender/container/Group} group
  32777. * @param {Array.<Array.<number>>} stackedOnPoints
  32778. * @param {Array.<Array.<number>>} points
  32779. * @private
  32780. */
  32781. _newPolygon: function (points, stackedOnPoints) {
  32782. var polygon = this._polygon;
  32783. // Remove previous created polygon
  32784. if (polygon) {
  32785. this._lineGroup.remove(polygon);
  32786. }
  32787. polygon = new Polygon$1({
  32788. shape: {
  32789. points: points,
  32790. stackedOnPoints: stackedOnPoints
  32791. },
  32792. silent: true
  32793. });
  32794. this._lineGroup.add(polygon);
  32795. this._polygon = polygon;
  32796. return polygon;
  32797. },
  32798. /**
  32799. * @private
  32800. */
  32801. // FIXME Two value axis
  32802. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  32803. var polyline = this._polyline;
  32804. var polygon = this._polygon;
  32805. var seriesModel = data.hostModel;
  32806. var diff = lineAnimationDiff(
  32807. this._data, data,
  32808. this._stackedOnPoints, stackedOnPoints,
  32809. this._coordSys, coordSys,
  32810. this._valueOrigin, valueOrigin
  32811. );
  32812. var current = diff.current;
  32813. var stackedOnCurrent = diff.stackedOnCurrent;
  32814. var next = diff.next;
  32815. var stackedOnNext = diff.stackedOnNext;
  32816. if (step) {
  32817. // TODO If stacked series is not step
  32818. current = turnPointsIntoStep(diff.current, coordSys, step);
  32819. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  32820. next = turnPointsIntoStep(diff.next, coordSys, step);
  32821. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  32822. }
  32823. // `diff.current` is subset of `current` (which should be ensured by
  32824. // turnPointsIntoStep), so points in `__points` can be updated when
  32825. // points in `current` are update during animation.
  32826. polyline.shape.__points = diff.current;
  32827. polyline.shape.points = current;
  32828. updateProps(polyline, {
  32829. shape: {
  32830. points: next
  32831. }
  32832. }, seriesModel);
  32833. if (polygon) {
  32834. polygon.setShape({
  32835. points: current,
  32836. stackedOnPoints: stackedOnCurrent
  32837. });
  32838. updateProps(polygon, {
  32839. shape: {
  32840. points: next,
  32841. stackedOnPoints: stackedOnNext
  32842. }
  32843. }, seriesModel);
  32844. }
  32845. var updatedDataInfo = [];
  32846. var diffStatus = diff.status;
  32847. for (var i = 0; i < diffStatus.length; i++) {
  32848. var cmd = diffStatus[i].cmd;
  32849. if (cmd === '=') {
  32850. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  32851. if (el) {
  32852. updatedDataInfo.push({
  32853. el: el,
  32854. ptIdx: i // Index of points
  32855. });
  32856. }
  32857. }
  32858. }
  32859. if (polyline.animators && polyline.animators.length) {
  32860. polyline.animators[0].during(function () {
  32861. for (var i = 0; i < updatedDataInfo.length; i++) {
  32862. var el = updatedDataInfo[i].el;
  32863. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  32864. }
  32865. });
  32866. }
  32867. },
  32868. remove: function (ecModel) {
  32869. var group = this.group;
  32870. var oldData = this._data;
  32871. this._lineGroup.removeAll();
  32872. this._symbolDraw.remove(true);
  32873. // Remove temporary created elements when highlighting
  32874. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  32875. if (el.__temp) {
  32876. group.remove(el);
  32877. oldData.setItemGraphicEl(idx, null);
  32878. }
  32879. });
  32880. this._polyline
  32881. = this._polygon
  32882. = this._coordSys
  32883. = this._points
  32884. = this._stackedOnPoints
  32885. = this._data = null;
  32886. }
  32887. });
  32888. /*
  32889. * Licensed to the Apache Software Foundation (ASF) under one
  32890. * or more contributor license agreements. See the NOTICE file
  32891. * distributed with this work for additional information
  32892. * regarding copyright ownership. The ASF licenses this file
  32893. * to you under the Apache License, Version 2.0 (the
  32894. * "License"); you may not use this file except in compliance
  32895. * with the License. You may obtain a copy of the License at
  32896. *
  32897. * http://www.apache.org/licenses/LICENSE-2.0
  32898. *
  32899. * Unless required by applicable law or agreed to in writing,
  32900. * software distributed under the License is distributed on an
  32901. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32902. * KIND, either express or implied. See the License for the
  32903. * specific language governing permissions and limitations
  32904. * under the License.
  32905. */
  32906. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  32907. // Encoding visual for all series include which is filtered for legend drawing
  32908. return {
  32909. seriesType: seriesType,
  32910. // For legend.
  32911. performRawSeries: true,
  32912. reset: function (seriesModel, ecModel, api) {
  32913. var data = seriesModel.getData();
  32914. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  32915. var symbolSize = seriesModel.get('symbolSize');
  32916. var keepAspect = seriesModel.get('symbolKeepAspect');
  32917. data.setVisual({
  32918. legendSymbol: legendSymbol || symbolType,
  32919. symbol: symbolType,
  32920. symbolSize: symbolSize,
  32921. symbolKeepAspect: keepAspect
  32922. });
  32923. // Only visible series has each data be visual encoded
  32924. if (ecModel.isSeriesFiltered(seriesModel)) {
  32925. return;
  32926. }
  32927. var hasCallback = typeof symbolSize === 'function';
  32928. function dataEach(data, idx) {
  32929. if (typeof symbolSize === 'function') {
  32930. var rawValue = seriesModel.getRawValue(idx);
  32931. // FIXME
  32932. var params = seriesModel.getDataParams(idx);
  32933. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  32934. }
  32935. if (data.hasItemOption) {
  32936. var itemModel = data.getItemModel(idx);
  32937. var itemSymbolType = itemModel.getShallow('symbol', true);
  32938. var itemSymbolSize = itemModel.getShallow('symbolSize',
  32939. true);
  32940. var itemSymbolKeepAspect
  32941. = itemModel.getShallow('symbolKeepAspect', true);
  32942. // If has item symbol
  32943. if (itemSymbolType != null) {
  32944. data.setItemVisual(idx, 'symbol', itemSymbolType);
  32945. }
  32946. if (itemSymbolSize != null) {
  32947. // PENDING Transform symbolSize ?
  32948. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  32949. }
  32950. if (itemSymbolKeepAspect != null) {
  32951. data.setItemVisual(idx, 'symbolKeepAspect',
  32952. itemSymbolKeepAspect);
  32953. }
  32954. }
  32955. }
  32956. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  32957. }
  32958. };
  32959. };
  32960. /*
  32961. * Licensed to the Apache Software Foundation (ASF) under one
  32962. * or more contributor license agreements. See the NOTICE file
  32963. * distributed with this work for additional information
  32964. * regarding copyright ownership. The ASF licenses this file
  32965. * to you under the Apache License, Version 2.0 (the
  32966. * "License"); you may not use this file except in compliance
  32967. * with the License. You may obtain a copy of the License at
  32968. *
  32969. * http://www.apache.org/licenses/LICENSE-2.0
  32970. *
  32971. * Unless required by applicable law or agreed to in writing,
  32972. * software distributed under the License is distributed on an
  32973. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32974. * KIND, either express or implied. See the License for the
  32975. * specific language governing permissions and limitations
  32976. * under the License.
  32977. */
  32978. /* global Float32Array */
  32979. var pointsLayout = function (seriesType) {
  32980. return {
  32981. seriesType: seriesType,
  32982. plan: createRenderPlanner(),
  32983. reset: function (seriesModel) {
  32984. var data = seriesModel.getData();
  32985. var coordSys = seriesModel.coordinateSystem;
  32986. var pipelineContext = seriesModel.pipelineContext;
  32987. var isLargeRender = pipelineContext.large;
  32988. if (!coordSys) {
  32989. return;
  32990. }
  32991. var dims = map(coordSys.dimensions, function (dim) {
  32992. return data.mapDimension(dim);
  32993. }).slice(0, 2);
  32994. var dimLen = dims.length;
  32995. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  32996. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  32997. dims[0] = stackResultDim;
  32998. }
  32999. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  33000. dims[1] = stackResultDim;
  33001. }
  33002. function progress(params, data) {
  33003. var segCount = params.end - params.start;
  33004. var points = isLargeRender && new Float32Array(segCount * dimLen);
  33005. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  33006. var point;
  33007. if (dimLen === 1) {
  33008. var x = data.get(dims[0], i);
  33009. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  33010. }
  33011. else {
  33012. var x = tmpIn[0] = data.get(dims[0], i);
  33013. var y = tmpIn[1] = data.get(dims[1], i);
  33014. // Also {Array.<number>}, not undefined to avoid if...else... statement
  33015. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  33016. }
  33017. if (isLargeRender) {
  33018. points[offset++] = point ? point[0] : NaN;
  33019. points[offset++] = point ? point[1] : NaN;
  33020. }
  33021. else {
  33022. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  33023. }
  33024. }
  33025. isLargeRender && data.setLayout('symbolPoints', points);
  33026. }
  33027. return dimLen && {progress: progress};
  33028. }
  33029. };
  33030. };
  33031. /*
  33032. * Licensed to the Apache Software Foundation (ASF) under one
  33033. * or more contributor license agreements. See the NOTICE file
  33034. * distributed with this work for additional information
  33035. * regarding copyright ownership. The ASF licenses this file
  33036. * to you under the Apache License, Version 2.0 (the
  33037. * "License"); you may not use this file except in compliance
  33038. * with the License. You may obtain a copy of the License at
  33039. *
  33040. * http://www.apache.org/licenses/LICENSE-2.0
  33041. *
  33042. * Unless required by applicable law or agreed to in writing,
  33043. * software distributed under the License is distributed on an
  33044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33045. * KIND, either express or implied. See the License for the
  33046. * specific language governing permissions and limitations
  33047. * under the License.
  33048. */
  33049. var samplers = {
  33050. average: function (frame) {
  33051. var sum = 0;
  33052. var count = 0;
  33053. for (var i = 0; i < frame.length; i++) {
  33054. if (!isNaN(frame[i])) {
  33055. sum += frame[i];
  33056. count++;
  33057. }
  33058. }
  33059. // Return NaN if count is 0
  33060. return count === 0 ? NaN : sum / count;
  33061. },
  33062. sum: function (frame) {
  33063. var sum = 0;
  33064. for (var i = 0; i < frame.length; i++) {
  33065. // Ignore NaN
  33066. sum += frame[i] || 0;
  33067. }
  33068. return sum;
  33069. },
  33070. max: function (frame) {
  33071. var max = -Infinity;
  33072. for (var i = 0; i < frame.length; i++) {
  33073. frame[i] > max && (max = frame[i]);
  33074. }
  33075. // NaN will cause illegal axis extent.
  33076. return isFinite(max) ? max : NaN;
  33077. },
  33078. min: function (frame) {
  33079. var min = Infinity;
  33080. for (var i = 0; i < frame.length; i++) {
  33081. frame[i] < min && (min = frame[i]);
  33082. }
  33083. // NaN will cause illegal axis extent.
  33084. return isFinite(min) ? min : NaN;
  33085. },
  33086. // TODO
  33087. // Median
  33088. nearest: function (frame) {
  33089. return frame[0];
  33090. }
  33091. };
  33092. var indexSampler = function (frame, value) {
  33093. return Math.round(frame.length / 2);
  33094. };
  33095. var dataSample = function (seriesType) {
  33096. return {
  33097. seriesType: seriesType,
  33098. modifyOutputEnd: true,
  33099. reset: function (seriesModel, ecModel, api) {
  33100. var data = seriesModel.getData();
  33101. var sampling = seriesModel.get('sampling');
  33102. var coordSys = seriesModel.coordinateSystem;
  33103. // Only cartesian2d support down sampling
  33104. if (coordSys.type === 'cartesian2d' && sampling) {
  33105. var baseAxis = coordSys.getBaseAxis();
  33106. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33107. var extent = baseAxis.getExtent();
  33108. // Coordinste system has been resized
  33109. var size = extent[1] - extent[0];
  33110. var rate = Math.round(data.count() / size);
  33111. if (rate > 1) {
  33112. var sampler;
  33113. if (typeof sampling === 'string') {
  33114. sampler = samplers[sampling];
  33115. }
  33116. else if (typeof sampling === 'function') {
  33117. sampler = sampling;
  33118. }
  33119. if (sampler) {
  33120. // Only support sample the first dim mapped from value axis.
  33121. seriesModel.setData(data.downSample(
  33122. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  33123. ));
  33124. }
  33125. }
  33126. }
  33127. }
  33128. };
  33129. };
  33130. /*
  33131. * Licensed to the Apache Software Foundation (ASF) under one
  33132. * or more contributor license agreements. See the NOTICE file
  33133. * distributed with this work for additional information
  33134. * regarding copyright ownership. The ASF licenses this file
  33135. * to you under the Apache License, Version 2.0 (the
  33136. * "License"); you may not use this file except in compliance
  33137. * with the License. You may obtain a copy of the License at
  33138. *
  33139. * http://www.apache.org/licenses/LICENSE-2.0
  33140. *
  33141. * Unless required by applicable law or agreed to in writing,
  33142. * software distributed under the License is distributed on an
  33143. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33144. * KIND, either express or implied. See the License for the
  33145. * specific language governing permissions and limitations
  33146. * under the License.
  33147. */
  33148. /**
  33149. * Cartesian coordinate system
  33150. * @module echarts/coord/Cartesian
  33151. *
  33152. */
  33153. function dimAxisMapper(dim) {
  33154. return this._axes[dim];
  33155. }
  33156. /**
  33157. * @alias module:echarts/coord/Cartesian
  33158. * @constructor
  33159. */
  33160. var Cartesian = function (name) {
  33161. this._axes = {};
  33162. this._dimList = [];
  33163. /**
  33164. * @type {string}
  33165. */
  33166. this.name = name || '';
  33167. };
  33168. Cartesian.prototype = {
  33169. constructor: Cartesian,
  33170. type: 'cartesian',
  33171. /**
  33172. * Get axis
  33173. * @param {number|string} dim
  33174. * @return {module:echarts/coord/Cartesian~Axis}
  33175. */
  33176. getAxis: function (dim) {
  33177. return this._axes[dim];
  33178. },
  33179. /**
  33180. * Get axes list
  33181. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  33182. */
  33183. getAxes: function () {
  33184. return map(this._dimList, dimAxisMapper, this);
  33185. },
  33186. /**
  33187. * Get axes list by given scale type
  33188. */
  33189. getAxesByScale: function (scaleType) {
  33190. scaleType = scaleType.toLowerCase();
  33191. return filter(
  33192. this.getAxes(),
  33193. function (axis) {
  33194. return axis.scale.type === scaleType;
  33195. }
  33196. );
  33197. },
  33198. /**
  33199. * Add axis
  33200. * @param {module:echarts/coord/Cartesian.Axis}
  33201. */
  33202. addAxis: function (axis) {
  33203. var dim = axis.dim;
  33204. this._axes[dim] = axis;
  33205. this._dimList.push(dim);
  33206. },
  33207. /**
  33208. * Convert data to coord in nd space
  33209. * @param {Array.<number>|Object.<string, number>} val
  33210. * @return {Array.<number>|Object.<string, number>}
  33211. */
  33212. dataToCoord: function (val) {
  33213. return this._dataCoordConvert(val, 'dataToCoord');
  33214. },
  33215. /**
  33216. * Convert coord in nd space to data
  33217. * @param {Array.<number>|Object.<string, number>} val
  33218. * @return {Array.<number>|Object.<string, number>}
  33219. */
  33220. coordToData: function (val) {
  33221. return this._dataCoordConvert(val, 'coordToData');
  33222. },
  33223. _dataCoordConvert: function (input, method) {
  33224. var dimList = this._dimList;
  33225. var output = input instanceof Array ? [] : {};
  33226. for (var i = 0; i < dimList.length; i++) {
  33227. var dim = dimList[i];
  33228. var axis = this._axes[dim];
  33229. output[dim] = axis[method](input[dim]);
  33230. }
  33231. return output;
  33232. }
  33233. };
  33234. /*
  33235. * Licensed to the Apache Software Foundation (ASF) under one
  33236. * or more contributor license agreements. See the NOTICE file
  33237. * distributed with this work for additional information
  33238. * regarding copyright ownership. The ASF licenses this file
  33239. * to you under the Apache License, Version 2.0 (the
  33240. * "License"); you may not use this file except in compliance
  33241. * with the License. You may obtain a copy of the License at
  33242. *
  33243. * http://www.apache.org/licenses/LICENSE-2.0
  33244. *
  33245. * Unless required by applicable law or agreed to in writing,
  33246. * software distributed under the License is distributed on an
  33247. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33248. * KIND, either express or implied. See the License for the
  33249. * specific language governing permissions and limitations
  33250. * under the License.
  33251. */
  33252. function Cartesian2D(name) {
  33253. Cartesian.call(this, name);
  33254. }
  33255. Cartesian2D.prototype = {
  33256. constructor: Cartesian2D,
  33257. type: 'cartesian2d',
  33258. /**
  33259. * @type {Array.<string>}
  33260. * @readOnly
  33261. */
  33262. dimensions: ['x', 'y'],
  33263. /**
  33264. * Base axis will be used on stacking.
  33265. *
  33266. * @return {module:echarts/coord/cartesian/Axis2D}
  33267. */
  33268. getBaseAxis: function () {
  33269. return this.getAxesByScale('ordinal')[0]
  33270. || this.getAxesByScale('time')[0]
  33271. || this.getAxis('x');
  33272. },
  33273. /**
  33274. * If contain point
  33275. * @param {Array.<number>} point
  33276. * @return {boolean}
  33277. */
  33278. containPoint: function (point) {
  33279. var axisX = this.getAxis('x');
  33280. var axisY = this.getAxis('y');
  33281. return axisX.contain(axisX.toLocalCoord(point[0]))
  33282. && axisY.contain(axisY.toLocalCoord(point[1]));
  33283. },
  33284. /**
  33285. * If contain data
  33286. * @param {Array.<number>} data
  33287. * @return {boolean}
  33288. */
  33289. containData: function (data) {
  33290. return this.getAxis('x').containData(data[0])
  33291. && this.getAxis('y').containData(data[1]);
  33292. },
  33293. /**
  33294. * @param {Array.<number>} data
  33295. * @param {Array.<number>} out
  33296. * @return {Array.<number>}
  33297. */
  33298. dataToPoint: function (data, reserved, out) {
  33299. var xAxis = this.getAxis('x');
  33300. var yAxis = this.getAxis('y');
  33301. out = out || [];
  33302. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  33303. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  33304. return out;
  33305. },
  33306. /**
  33307. * @param {Array.<number>} data
  33308. * @param {Array.<number>} out
  33309. * @return {Array.<number>}
  33310. */
  33311. clampData: function (data, out) {
  33312. var xScale = this.getAxis('x').scale;
  33313. var yScale = this.getAxis('y').scale;
  33314. var xAxisExtent = xScale.getExtent();
  33315. var yAxisExtent = yScale.getExtent();
  33316. var x = xScale.parse(data[0]);
  33317. var y = yScale.parse(data[1]);
  33318. out = out || [];
  33319. out[0] = Math.min(
  33320. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  33321. Math.max(xAxisExtent[0], xAxisExtent[1])
  33322. );
  33323. out[1] = Math.min(
  33324. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  33325. Math.max(yAxisExtent[0], yAxisExtent[1])
  33326. );
  33327. return out;
  33328. },
  33329. /**
  33330. * @param {Array.<number>} point
  33331. * @param {Array.<number>} out
  33332. * @return {Array.<number>}
  33333. */
  33334. pointToData: function (point, out) {
  33335. var xAxis = this.getAxis('x');
  33336. var yAxis = this.getAxis('y');
  33337. out = out || [];
  33338. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  33339. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  33340. return out;
  33341. },
  33342. /**
  33343. * Get other axis
  33344. * @param {module:echarts/coord/cartesian/Axis2D} axis
  33345. */
  33346. getOtherAxis: function (axis) {
  33347. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  33348. }
  33349. };
  33350. inherits(Cartesian2D, Cartesian);
  33351. /*
  33352. * Licensed to the Apache Software Foundation (ASF) under one
  33353. * or more contributor license agreements. See the NOTICE file
  33354. * distributed with this work for additional information
  33355. * regarding copyright ownership. The ASF licenses this file
  33356. * to you under the Apache License, Version 2.0 (the
  33357. * "License"); you may not use this file except in compliance
  33358. * with the License. You may obtain a copy of the License at
  33359. *
  33360. * http://www.apache.org/licenses/LICENSE-2.0
  33361. *
  33362. * Unless required by applicable law or agreed to in writing,
  33363. * software distributed under the License is distributed on an
  33364. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33365. * KIND, either express or implied. See the License for the
  33366. * specific language governing permissions and limitations
  33367. * under the License.
  33368. */
  33369. /**
  33370. * Extend axis 2d
  33371. * @constructor module:echarts/coord/cartesian/Axis2D
  33372. * @extends {module:echarts/coord/cartesian/Axis}
  33373. * @param {string} dim
  33374. * @param {*} scale
  33375. * @param {Array.<number>} coordExtent
  33376. * @param {string} axisType
  33377. * @param {string} position
  33378. */
  33379. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  33380. Axis.call(this, dim, scale, coordExtent);
  33381. /**
  33382. * Axis type
  33383. * - 'category'
  33384. * - 'value'
  33385. * - 'time'
  33386. * - 'log'
  33387. * @type {string}
  33388. */
  33389. this.type = axisType || 'value';
  33390. /**
  33391. * Axis position
  33392. * - 'top'
  33393. * - 'bottom'
  33394. * - 'left'
  33395. * - 'right'
  33396. */
  33397. this.position = position || 'bottom';
  33398. };
  33399. Axis2D.prototype = {
  33400. constructor: Axis2D,
  33401. /**
  33402. * Index of axis, can be used as key
  33403. */
  33404. index: 0,
  33405. /**
  33406. * Implemented in <module:echarts/coord/cartesian/Grid>.
  33407. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  33408. * If not on zero of other axis, return null/undefined.
  33409. * If no axes, return an empty array.
  33410. */
  33411. getAxesOnZeroOf: null,
  33412. /**
  33413. * Axis model
  33414. * @param {module:echarts/coord/cartesian/AxisModel}
  33415. */
  33416. model: null,
  33417. isHorizontal: function () {
  33418. var position = this.position;
  33419. return position === 'top' || position === 'bottom';
  33420. },
  33421. /**
  33422. * Each item cooresponds to this.getExtent(), which
  33423. * means globalExtent[0] may greater than globalExtent[1],
  33424. * unless `asc` is input.
  33425. *
  33426. * @param {boolean} [asc]
  33427. * @return {Array.<number>}
  33428. */
  33429. getGlobalExtent: function (asc) {
  33430. var ret = this.getExtent();
  33431. ret[0] = this.toGlobalCoord(ret[0]);
  33432. ret[1] = this.toGlobalCoord(ret[1]);
  33433. asc && ret[0] > ret[1] && ret.reverse();
  33434. return ret;
  33435. },
  33436. getOtherAxis: function () {
  33437. this.grid.getOtherAxis();
  33438. },
  33439. /**
  33440. * @override
  33441. */
  33442. pointToData: function (point, clamp) {
  33443. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  33444. },
  33445. /**
  33446. * Transform global coord to local coord,
  33447. * i.e. var localCoord = axis.toLocalCoord(80);
  33448. * designate by module:echarts/coord/cartesian/Grid.
  33449. * @type {Function}
  33450. */
  33451. toLocalCoord: null,
  33452. /**
  33453. * Transform global coord to local coord,
  33454. * i.e. var globalCoord = axis.toLocalCoord(40);
  33455. * designate by module:echarts/coord/cartesian/Grid.
  33456. * @type {Function}
  33457. */
  33458. toGlobalCoord: null
  33459. };
  33460. inherits(Axis2D, Axis);
  33461. /*
  33462. * Licensed to the Apache Software Foundation (ASF) under one
  33463. * or more contributor license agreements. See the NOTICE file
  33464. * distributed with this work for additional information
  33465. * regarding copyright ownership. The ASF licenses this file
  33466. * to you under the Apache License, Version 2.0 (the
  33467. * "License"); you may not use this file except in compliance
  33468. * with the License. You may obtain a copy of the License at
  33469. *
  33470. * http://www.apache.org/licenses/LICENSE-2.0
  33471. *
  33472. * Unless required by applicable law or agreed to in writing,
  33473. * software distributed under the License is distributed on an
  33474. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33475. * KIND, either express or implied. See the License for the
  33476. * specific language governing permissions and limitations
  33477. * under the License.
  33478. */
  33479. var defaultOption = {
  33480. show: true,
  33481. zlevel: 0,
  33482. z: 0,
  33483. // Inverse the axis.
  33484. inverse: false,
  33485. // Axis name displayed.
  33486. name: '',
  33487. // 'start' | 'middle' | 'end'
  33488. nameLocation: 'end',
  33489. // By degree. By defualt auto rotate by nameLocation.
  33490. nameRotate: null,
  33491. nameTruncate: {
  33492. maxWidth: null,
  33493. ellipsis: '...',
  33494. placeholder: '.'
  33495. },
  33496. // Use global text style by default.
  33497. nameTextStyle: {},
  33498. // The gap between axisName and axisLine.
  33499. nameGap: 15,
  33500. // Default `false` to support tooltip.
  33501. silent: false,
  33502. // Default `false` to avoid legacy user event listener fail.
  33503. triggerEvent: false,
  33504. tooltip: {
  33505. show: false
  33506. },
  33507. axisPointer: {},
  33508. axisLine: {
  33509. show: true,
  33510. onZero: true,
  33511. onZeroAxisIndex: null,
  33512. lineStyle: {
  33513. color: '#333',
  33514. width: 1,
  33515. type: 'solid'
  33516. },
  33517. // The arrow at both ends the the axis.
  33518. symbol: ['none', 'none'],
  33519. symbolSize: [10, 15]
  33520. },
  33521. axisTick: {
  33522. show: true,
  33523. // Whether axisTick is inside the grid or outside the grid.
  33524. inside: false,
  33525. // The length of axisTick.
  33526. length: 5,
  33527. lineStyle: {
  33528. width: 1
  33529. }
  33530. },
  33531. axisLabel: {
  33532. show: true,
  33533. // Whether axisLabel is inside the grid or outside the grid.
  33534. inside: false,
  33535. rotate: 0,
  33536. // true | false | null/undefined (auto)
  33537. showMinLabel: null,
  33538. // true | false | null/undefined (auto)
  33539. showMaxLabel: null,
  33540. margin: 8,
  33541. // formatter: null,
  33542. fontSize: 12
  33543. },
  33544. splitLine: {
  33545. show: true,
  33546. lineStyle: {
  33547. color: ['#ccc'],
  33548. width: 1,
  33549. type: 'solid'
  33550. }
  33551. },
  33552. splitArea: {
  33553. show: false,
  33554. areaStyle: {
  33555. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  33556. }
  33557. }
  33558. };
  33559. var axisDefault = {};
  33560. axisDefault.categoryAxis = merge({
  33561. // The gap at both ends of the axis. For categoryAxis, boolean.
  33562. boundaryGap: true,
  33563. // Set false to faster category collection.
  33564. // Only usefull in the case like: category is
  33565. // ['2012-01-01', '2012-01-02', ...], where the input
  33566. // data has been ensured not duplicate and is large data.
  33567. // null means "auto":
  33568. // if axis.data provided, do not deduplication,
  33569. // else do deduplication.
  33570. deduplication: null,
  33571. // splitArea: {
  33572. // show: false
  33573. // },
  33574. splitLine: {
  33575. show: false
  33576. },
  33577. axisTick: {
  33578. // If tick is align with label when boundaryGap is true
  33579. alignWithLabel: false,
  33580. interval: 'auto'
  33581. },
  33582. axisLabel: {
  33583. interval: 'auto'
  33584. }
  33585. }, defaultOption);
  33586. axisDefault.valueAxis = merge({
  33587. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  33588. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  33589. boundaryGap: [0, 0],
  33590. // TODO
  33591. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  33592. // Min value of the axis. can be:
  33593. // + a number
  33594. // + 'dataMin': use the min value in data.
  33595. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  33596. // min: null,
  33597. // Max value of the axis. can be:
  33598. // + a number
  33599. // + 'dataMax': use the max value in data.
  33600. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  33601. // max: null,
  33602. // Readonly prop, specifies start value of the range when using data zoom.
  33603. // rangeStart: null
  33604. // Readonly prop, specifies end value of the range when using data zoom.
  33605. // rangeEnd: null
  33606. // Optional value can be:
  33607. // + `false`: always include value 0.
  33608. // + `true`: the extent do not consider value 0.
  33609. // scale: false,
  33610. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  33611. splitNumber: 5
  33612. // Interval specifies the span of the ticks is mandatorily.
  33613. // interval: null
  33614. // Specify min interval when auto calculate tick interval.
  33615. // minInterval: null
  33616. // Specify max interval when auto calculate tick interval.
  33617. // maxInterval: null
  33618. }, defaultOption);
  33619. axisDefault.timeAxis = defaults({
  33620. scale: true,
  33621. min: 'dataMin',
  33622. max: 'dataMax'
  33623. }, axisDefault.valueAxis);
  33624. axisDefault.logAxis = defaults({
  33625. scale: true,
  33626. logBase: 10
  33627. }, axisDefault.valueAxis);
  33628. /*
  33629. * Licensed to the Apache Software Foundation (ASF) under one
  33630. * or more contributor license agreements. See the NOTICE file
  33631. * distributed with this work for additional information
  33632. * regarding copyright ownership. The ASF licenses this file
  33633. * to you under the Apache License, Version 2.0 (the
  33634. * "License"); you may not use this file except in compliance
  33635. * with the License. You may obtain a copy of the License at
  33636. *
  33637. * http://www.apache.org/licenses/LICENSE-2.0
  33638. *
  33639. * Unless required by applicable law or agreed to in writing,
  33640. * software distributed under the License is distributed on an
  33641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33642. * KIND, either express or implied. See the License for the
  33643. * specific language governing permissions and limitations
  33644. * under the License.
  33645. */
  33646. // FIXME axisType is fixed ?
  33647. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  33648. /**
  33649. * Generate sub axis model class
  33650. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  33651. * @param {module:echarts/model/Component} BaseAxisModelClass
  33652. * @param {Function} axisTypeDefaulter
  33653. * @param {Object} [extraDefaultOption]
  33654. */
  33655. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  33656. each$1(AXIS_TYPES, function (axisType) {
  33657. BaseAxisModelClass.extend({
  33658. /**
  33659. * @readOnly
  33660. */
  33661. type: axisName + 'Axis.' + axisType,
  33662. mergeDefaultAndTheme: function (option, ecModel) {
  33663. var layoutMode = this.layoutMode;
  33664. var inputPositionParams = layoutMode
  33665. ? getLayoutParams(option) : {};
  33666. var themeModel = ecModel.getTheme();
  33667. merge(option, themeModel.get(axisType + 'Axis'));
  33668. merge(option, this.getDefaultOption());
  33669. option.type = axisTypeDefaulter(axisName, option);
  33670. if (layoutMode) {
  33671. mergeLayoutParam(option, inputPositionParams, layoutMode);
  33672. }
  33673. },
  33674. /**
  33675. * @override
  33676. */
  33677. optionUpdated: function () {
  33678. var thisOption = this.option;
  33679. if (thisOption.type === 'category') {
  33680. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  33681. }
  33682. },
  33683. /**
  33684. * Should not be called before all of 'getInitailData' finished.
  33685. * Because categories are collected during initializing data.
  33686. */
  33687. getCategories: function (rawData) {
  33688. var option = this.option;
  33689. // FIXME
  33690. // warning if called before all of 'getInitailData' finished.
  33691. if (option.type === 'category') {
  33692. if (rawData) {
  33693. return option.data;
  33694. }
  33695. return this.__ordinalMeta.categories;
  33696. }
  33697. },
  33698. getOrdinalMeta: function () {
  33699. return this.__ordinalMeta;
  33700. },
  33701. defaultOption: mergeAll(
  33702. [
  33703. {},
  33704. axisDefault[axisType + 'Axis'],
  33705. extraDefaultOption
  33706. ],
  33707. true
  33708. )
  33709. });
  33710. });
  33711. ComponentModel.registerSubTypeDefaulter(
  33712. axisName + 'Axis',
  33713. curry(axisTypeDefaulter, axisName)
  33714. );
  33715. };
  33716. /*
  33717. * Licensed to the Apache Software Foundation (ASF) under one
  33718. * or more contributor license agreements. See the NOTICE file
  33719. * distributed with this work for additional information
  33720. * regarding copyright ownership. The ASF licenses this file
  33721. * to you under the Apache License, Version 2.0 (the
  33722. * "License"); you may not use this file except in compliance
  33723. * with the License. You may obtain a copy of the License at
  33724. *
  33725. * http://www.apache.org/licenses/LICENSE-2.0
  33726. *
  33727. * Unless required by applicable law or agreed to in writing,
  33728. * software distributed under the License is distributed on an
  33729. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33730. * KIND, either express or implied. See the License for the
  33731. * specific language governing permissions and limitations
  33732. * under the License.
  33733. */
  33734. var AxisModel = ComponentModel.extend({
  33735. type: 'cartesian2dAxis',
  33736. /**
  33737. * @type {module:echarts/coord/cartesian/Axis2D}
  33738. */
  33739. axis: null,
  33740. /**
  33741. * @override
  33742. */
  33743. init: function () {
  33744. AxisModel.superApply(this, 'init', arguments);
  33745. this.resetRange();
  33746. },
  33747. /**
  33748. * @override
  33749. */
  33750. mergeOption: function () {
  33751. AxisModel.superApply(this, 'mergeOption', arguments);
  33752. this.resetRange();
  33753. },
  33754. /**
  33755. * @override
  33756. */
  33757. restoreData: function () {
  33758. AxisModel.superApply(this, 'restoreData', arguments);
  33759. this.resetRange();
  33760. },
  33761. /**
  33762. * @override
  33763. * @return {module:echarts/model/Component}
  33764. */
  33765. getCoordSysModel: function () {
  33766. return this.ecModel.queryComponents({
  33767. mainType: 'grid',
  33768. index: this.option.gridIndex,
  33769. id: this.option.gridId
  33770. })[0];
  33771. }
  33772. });
  33773. function getAxisType(axisDim, option) {
  33774. // Default axis with data is category axis
  33775. return option.type || (option.data ? 'category' : 'value');
  33776. }
  33777. merge(AxisModel.prototype, axisModelCommonMixin);
  33778. var extraOption = {
  33779. // gridIndex: 0,
  33780. // gridId: '',
  33781. // Offset is for multiple axis on the same position
  33782. offset: 0
  33783. };
  33784. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  33785. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  33786. /*
  33787. * Licensed to the Apache Software Foundation (ASF) under one
  33788. * or more contributor license agreements. See the NOTICE file
  33789. * distributed with this work for additional information
  33790. * regarding copyright ownership. The ASF licenses this file
  33791. * to you under the Apache License, Version 2.0 (the
  33792. * "License"); you may not use this file except in compliance
  33793. * with the License. You may obtain a copy of the License at
  33794. *
  33795. * http://www.apache.org/licenses/LICENSE-2.0
  33796. *
  33797. * Unless required by applicable law or agreed to in writing,
  33798. * software distributed under the License is distributed on an
  33799. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33800. * KIND, either express or implied. See the License for the
  33801. * specific language governing permissions and limitations
  33802. * under the License.
  33803. */
  33804. // Grid 是在有直角坐标系的时候必须要存在的
  33805. // 所以这里也要被 Cartesian2D 依赖
  33806. ComponentModel.extend({
  33807. type: 'grid',
  33808. dependencies: ['xAxis', 'yAxis'],
  33809. layoutMode: 'box',
  33810. /**
  33811. * @type {module:echarts/coord/cartesian/Grid}
  33812. */
  33813. coordinateSystem: null,
  33814. defaultOption: {
  33815. show: false,
  33816. zlevel: 0,
  33817. z: 0,
  33818. left: '10%',
  33819. top: 60,
  33820. right: '10%',
  33821. bottom: 60,
  33822. // If grid size contain label
  33823. containLabel: false,
  33824. // width: {totalWidth} - left - right,
  33825. // height: {totalHeight} - top - bottom,
  33826. backgroundColor: 'rgba(0,0,0,0)',
  33827. borderWidth: 1,
  33828. borderColor: '#ccc'
  33829. }
  33830. });
  33831. /*
  33832. * Licensed to the Apache Software Foundation (ASF) under one
  33833. * or more contributor license agreements. See the NOTICE file
  33834. * distributed with this work for additional information
  33835. * regarding copyright ownership. The ASF licenses this file
  33836. * to you under the Apache License, Version 2.0 (the
  33837. * "License"); you may not use this file except in compliance
  33838. * with the License. You may obtain a copy of the License at
  33839. *
  33840. * http://www.apache.org/licenses/LICENSE-2.0
  33841. *
  33842. * Unless required by applicable law or agreed to in writing,
  33843. * software distributed under the License is distributed on an
  33844. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33845. * KIND, either express or implied. See the License for the
  33846. * specific language governing permissions and limitations
  33847. * under the License.
  33848. */
  33849. /**
  33850. * Grid is a region which contains at most 4 cartesian systems
  33851. *
  33852. * TODO Default cartesian
  33853. */
  33854. // Depends on GridModel, AxisModel, which performs preprocess.
  33855. /**
  33856. * Check if the axis is used in the specified grid
  33857. * @inner
  33858. */
  33859. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  33860. return axisModel.getCoordSysModel() === gridModel;
  33861. }
  33862. function Grid(gridModel, ecModel, api) {
  33863. /**
  33864. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  33865. * @private
  33866. */
  33867. this._coordsMap = {};
  33868. /**
  33869. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  33870. * @private
  33871. */
  33872. this._coordsList = [];
  33873. /**
  33874. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  33875. * @private
  33876. */
  33877. this._axesMap = {};
  33878. /**
  33879. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  33880. * @private
  33881. */
  33882. this._axesList = [];
  33883. this._initCartesian(gridModel, ecModel, api);
  33884. this.model = gridModel;
  33885. }
  33886. var gridProto = Grid.prototype;
  33887. gridProto.type = 'grid';
  33888. gridProto.axisPointerEnabled = true;
  33889. gridProto.getRect = function () {
  33890. return this._rect;
  33891. };
  33892. gridProto.update = function (ecModel, api) {
  33893. var axesMap = this._axesMap;
  33894. this._updateScale(ecModel, this.model);
  33895. each$1(axesMap.x, function (xAxis) {
  33896. niceScaleExtent(xAxis.scale, xAxis.model);
  33897. });
  33898. each$1(axesMap.y, function (yAxis) {
  33899. niceScaleExtent(yAxis.scale, yAxis.model);
  33900. });
  33901. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  33902. var onZeroRecords = {};
  33903. each$1(axesMap.x, function (xAxis) {
  33904. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  33905. });
  33906. each$1(axesMap.y, function (yAxis) {
  33907. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  33908. });
  33909. // Resize again if containLabel is enabled
  33910. // FIXME It may cause getting wrong grid size in data processing stage
  33911. this.resize(this.model, api);
  33912. };
  33913. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  33914. axis.getAxesOnZeroOf = function () {
  33915. // TODO: onZero of multiple axes.
  33916. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  33917. };
  33918. // onZero can not be enabled in these two situations:
  33919. // 1. When any other axis is a category axis.
  33920. // 2. When no axis is cross 0 point.
  33921. var otherAxes = axesMap[otherAxisDim];
  33922. var otherAxisOnZeroOf;
  33923. var axisModel = axis.model;
  33924. var onZero = axisModel.get('axisLine.onZero');
  33925. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  33926. if (!onZero) {
  33927. return;
  33928. }
  33929. // If target axis is specified.
  33930. if (onZeroAxisIndex != null) {
  33931. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  33932. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  33933. }
  33934. }
  33935. else {
  33936. // Find the first available other axis.
  33937. for (var idx in otherAxes) {
  33938. if (otherAxes.hasOwnProperty(idx)
  33939. && canOnZeroToAxis(otherAxes[idx])
  33940. // Consider that two Y axes on one value axis,
  33941. // if both onZero, the two Y axes overlap.
  33942. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  33943. ) {
  33944. otherAxisOnZeroOf = otherAxes[idx];
  33945. break;
  33946. }
  33947. }
  33948. }
  33949. if (otherAxisOnZeroOf) {
  33950. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  33951. }
  33952. function getOnZeroRecordKey(axis) {
  33953. return axis.dim + '_' + axis.index;
  33954. }
  33955. }
  33956. function canOnZeroToAxis(axis) {
  33957. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  33958. }
  33959. /**
  33960. * Resize the grid
  33961. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33962. * @param {module:echarts/ExtensionAPI} api
  33963. */
  33964. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  33965. var gridRect = getLayoutRect(
  33966. gridModel.getBoxLayoutParams(), {
  33967. width: api.getWidth(),
  33968. height: api.getHeight()
  33969. });
  33970. this._rect = gridRect;
  33971. var axesList = this._axesList;
  33972. adjustAxes();
  33973. // Minus label size
  33974. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  33975. each$1(axesList, function (axis) {
  33976. if (!axis.model.get('axisLabel.inside')) {
  33977. var labelUnionRect = estimateLabelUnionRect(axis);
  33978. if (labelUnionRect) {
  33979. var dim = axis.isHorizontal() ? 'height' : 'width';
  33980. var margin = axis.model.get('axisLabel.margin');
  33981. gridRect[dim] -= labelUnionRect[dim] + margin;
  33982. if (axis.position === 'top') {
  33983. gridRect.y += labelUnionRect.height + margin;
  33984. }
  33985. else if (axis.position === 'left') {
  33986. gridRect.x += labelUnionRect.width + margin;
  33987. }
  33988. }
  33989. }
  33990. });
  33991. adjustAxes();
  33992. }
  33993. function adjustAxes() {
  33994. each$1(axesList, function (axis) {
  33995. var isHorizontal = axis.isHorizontal();
  33996. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  33997. var idx = axis.inverse ? 1 : 0;
  33998. axis.setExtent(extent[idx], extent[1 - idx]);
  33999. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  34000. });
  34001. }
  34002. };
  34003. /**
  34004. * @param {string} axisType
  34005. * @param {number} [axisIndex]
  34006. */
  34007. gridProto.getAxis = function (axisType, axisIndex) {
  34008. var axesMapOnDim = this._axesMap[axisType];
  34009. if (axesMapOnDim != null) {
  34010. if (axisIndex == null) {
  34011. // Find first axis
  34012. for (var name in axesMapOnDim) {
  34013. if (axesMapOnDim.hasOwnProperty(name)) {
  34014. return axesMapOnDim[name];
  34015. }
  34016. }
  34017. }
  34018. return axesMapOnDim[axisIndex];
  34019. }
  34020. };
  34021. /**
  34022. * @return {Array.<module:echarts/coord/Axis>}
  34023. */
  34024. gridProto.getAxes = function () {
  34025. return this._axesList.slice();
  34026. };
  34027. /**
  34028. * Usage:
  34029. * grid.getCartesian(xAxisIndex, yAxisIndex);
  34030. * grid.getCartesian(xAxisIndex);
  34031. * grid.getCartesian(null, yAxisIndex);
  34032. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  34033. *
  34034. * @param {number|Object} [xAxisIndex]
  34035. * @param {number} [yAxisIndex]
  34036. */
  34037. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  34038. if (xAxisIndex != null && yAxisIndex != null) {
  34039. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34040. return this._coordsMap[key];
  34041. }
  34042. if (isObject$1(xAxisIndex)) {
  34043. yAxisIndex = xAxisIndex.yAxisIndex;
  34044. xAxisIndex = xAxisIndex.xAxisIndex;
  34045. }
  34046. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  34047. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  34048. if (coordList[i].getAxis('x').index === xAxisIndex
  34049. || coordList[i].getAxis('y').index === yAxisIndex
  34050. ) {
  34051. return coordList[i];
  34052. }
  34053. }
  34054. };
  34055. gridProto.getCartesians = function () {
  34056. return this._coordsList.slice();
  34057. };
  34058. /**
  34059. * @implements
  34060. * see {module:echarts/CoodinateSystem}
  34061. */
  34062. gridProto.convertToPixel = function (ecModel, finder, value) {
  34063. var target = this._findConvertTarget(ecModel, finder);
  34064. return target.cartesian
  34065. ? target.cartesian.dataToPoint(value)
  34066. : target.axis
  34067. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  34068. : null;
  34069. };
  34070. /**
  34071. * @implements
  34072. * see {module:echarts/CoodinateSystem}
  34073. */
  34074. gridProto.convertFromPixel = function (ecModel, finder, value) {
  34075. var target = this._findConvertTarget(ecModel, finder);
  34076. return target.cartesian
  34077. ? target.cartesian.pointToData(value)
  34078. : target.axis
  34079. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  34080. : null;
  34081. };
  34082. /**
  34083. * @inner
  34084. */
  34085. gridProto._findConvertTarget = function (ecModel, finder) {
  34086. var seriesModel = finder.seriesModel;
  34087. var xAxisModel = finder.xAxisModel
  34088. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  34089. var yAxisModel = finder.yAxisModel
  34090. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  34091. var gridModel = finder.gridModel;
  34092. var coordsList = this._coordsList;
  34093. var cartesian;
  34094. var axis;
  34095. if (seriesModel) {
  34096. cartesian = seriesModel.coordinateSystem;
  34097. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  34098. }
  34099. else if (xAxisModel && yAxisModel) {
  34100. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  34101. }
  34102. else if (xAxisModel) {
  34103. axis = this.getAxis('x', xAxisModel.componentIndex);
  34104. }
  34105. else if (yAxisModel) {
  34106. axis = this.getAxis('y', yAxisModel.componentIndex);
  34107. }
  34108. // Lowest priority.
  34109. else if (gridModel) {
  34110. var grid = gridModel.coordinateSystem;
  34111. if (grid === this) {
  34112. cartesian = this._coordsList[0];
  34113. }
  34114. }
  34115. return {cartesian: cartesian, axis: axis};
  34116. };
  34117. /**
  34118. * @implements
  34119. * see {module:echarts/CoodinateSystem}
  34120. */
  34121. gridProto.containPoint = function (point) {
  34122. var coord = this._coordsList[0];
  34123. if (coord) {
  34124. return coord.containPoint(point);
  34125. }
  34126. };
  34127. /**
  34128. * Initialize cartesian coordinate systems
  34129. * @private
  34130. */
  34131. gridProto._initCartesian = function (gridModel, ecModel, api) {
  34132. var axisPositionUsed = {
  34133. left: false,
  34134. right: false,
  34135. top: false,
  34136. bottom: false
  34137. };
  34138. var axesMap = {
  34139. x: {},
  34140. y: {}
  34141. };
  34142. var axesCount = {
  34143. x: 0,
  34144. y: 0
  34145. };
  34146. /// Create axis
  34147. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  34148. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  34149. if (!axesCount.x || !axesCount.y) {
  34150. // Roll back when there no either x or y axis
  34151. this._axesMap = {};
  34152. this._axesList = [];
  34153. return;
  34154. }
  34155. this._axesMap = axesMap;
  34156. /// Create cartesian2d
  34157. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  34158. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  34159. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34160. var cartesian = new Cartesian2D(key);
  34161. cartesian.grid = this;
  34162. cartesian.model = gridModel;
  34163. this._coordsMap[key] = cartesian;
  34164. this._coordsList.push(cartesian);
  34165. cartesian.addAxis(xAxis);
  34166. cartesian.addAxis(yAxis);
  34167. }, this);
  34168. }, this);
  34169. function createAxisCreator(axisType) {
  34170. return function (axisModel, idx) {
  34171. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  34172. return;
  34173. }
  34174. var axisPosition = axisModel.get('position');
  34175. if (axisType === 'x') {
  34176. // Fix position
  34177. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  34178. // Default bottom of X
  34179. axisPosition = 'bottom';
  34180. if (axisPositionUsed[axisPosition]) {
  34181. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  34182. }
  34183. }
  34184. }
  34185. else {
  34186. // Fix position
  34187. if (axisPosition !== 'left' && axisPosition !== 'right') {
  34188. // Default left of Y
  34189. axisPosition = 'left';
  34190. if (axisPositionUsed[axisPosition]) {
  34191. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  34192. }
  34193. }
  34194. }
  34195. axisPositionUsed[axisPosition] = true;
  34196. var axis = new Axis2D(
  34197. axisType, createScaleByModel(axisModel),
  34198. [0, 0],
  34199. axisModel.get('type'),
  34200. axisPosition
  34201. );
  34202. var isCategory = axis.type === 'category';
  34203. axis.onBand = isCategory && axisModel.get('boundaryGap');
  34204. axis.inverse = axisModel.get('inverse');
  34205. // Inject axis into axisModel
  34206. axisModel.axis = axis;
  34207. // Inject axisModel into axis
  34208. axis.model = axisModel;
  34209. // Inject grid info axis
  34210. axis.grid = this;
  34211. // Index of axis, can be used as key
  34212. axis.index = idx;
  34213. this._axesList.push(axis);
  34214. axesMap[axisType][idx] = axis;
  34215. axesCount[axisType]++;
  34216. };
  34217. }
  34218. };
  34219. /**
  34220. * Update cartesian properties from series
  34221. * @param {module:echarts/model/Option} option
  34222. * @private
  34223. */
  34224. gridProto._updateScale = function (ecModel, gridModel) {
  34225. // Reset scale
  34226. each$1(this._axesList, function (axis) {
  34227. axis.scale.setExtent(Infinity, -Infinity);
  34228. });
  34229. ecModel.eachSeries(function (seriesModel) {
  34230. if (isCartesian2D(seriesModel)) {
  34231. var axesModels = findAxesModels(seriesModel, ecModel);
  34232. var xAxisModel = axesModels[0];
  34233. var yAxisModel = axesModels[1];
  34234. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  34235. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  34236. ) {
  34237. return;
  34238. }
  34239. var cartesian = this.getCartesian(
  34240. xAxisModel.componentIndex, yAxisModel.componentIndex
  34241. );
  34242. var data = seriesModel.getData();
  34243. var xAxis = cartesian.getAxis('x');
  34244. var yAxis = cartesian.getAxis('y');
  34245. if (data.type === 'list') {
  34246. unionExtent(data, xAxis, seriesModel);
  34247. unionExtent(data, yAxis, seriesModel);
  34248. }
  34249. }
  34250. }, this);
  34251. function unionExtent(data, axis, seriesModel) {
  34252. each$1(data.mapDimension(axis.dim, true), function (dim) {
  34253. axis.scale.unionExtentFromData(
  34254. // For example, the extent of the orginal dimension
  34255. // is [0.1, 0.5], the extent of the `stackResultDimension`
  34256. // is [7, 9], the final extent should not include [0.1, 0.5].
  34257. data, getStackedDimension(data, dim)
  34258. );
  34259. });
  34260. }
  34261. };
  34262. /**
  34263. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  34264. * @return {Object} {baseAxes: [], otherAxes: []}
  34265. */
  34266. gridProto.getTooltipAxes = function (dim) {
  34267. var baseAxes = [];
  34268. var otherAxes = [];
  34269. each$1(this.getCartesians(), function (cartesian) {
  34270. var baseAxis = (dim != null && dim !== 'auto')
  34271. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  34272. var otherAxis = cartesian.getOtherAxis(baseAxis);
  34273. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  34274. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  34275. });
  34276. return {baseAxes: baseAxes, otherAxes: otherAxes};
  34277. };
  34278. /**
  34279. * @inner
  34280. */
  34281. function updateAxisTransform(axis, coordBase) {
  34282. var axisExtent = axis.getExtent();
  34283. var axisExtentSum = axisExtent[0] + axisExtent[1];
  34284. // Fast transform
  34285. axis.toGlobalCoord = axis.dim === 'x'
  34286. ? function (coord) {
  34287. return coord + coordBase;
  34288. }
  34289. : function (coord) {
  34290. return axisExtentSum - coord + coordBase;
  34291. };
  34292. axis.toLocalCoord = axis.dim === 'x'
  34293. ? function (coord) {
  34294. return coord - coordBase;
  34295. }
  34296. : function (coord) {
  34297. return axisExtentSum - coord + coordBase;
  34298. };
  34299. }
  34300. var axesTypes = ['xAxis', 'yAxis'];
  34301. /**
  34302. * @inner
  34303. */
  34304. function findAxesModels(seriesModel, ecModel) {
  34305. return map(axesTypes, function (axisType) {
  34306. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  34307. if (__DEV__) {
  34308. if (!axisModel) {
  34309. throw new Error(axisType + ' "' + retrieve(
  34310. seriesModel.get(axisType + 'Index'),
  34311. seriesModel.get(axisType + 'Id'),
  34312. 0
  34313. ) + '" not found');
  34314. }
  34315. }
  34316. return axisModel;
  34317. });
  34318. }
  34319. /**
  34320. * @inner
  34321. */
  34322. function isCartesian2D(seriesModel) {
  34323. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  34324. }
  34325. Grid.create = function (ecModel, api) {
  34326. var grids = [];
  34327. ecModel.eachComponent('grid', function (gridModel, idx) {
  34328. var grid = new Grid(gridModel, ecModel, api);
  34329. grid.name = 'grid_' + idx;
  34330. // dataSampling requires axis extent, so resize
  34331. // should be performed in create stage.
  34332. grid.resize(gridModel, api, true);
  34333. gridModel.coordinateSystem = grid;
  34334. grids.push(grid);
  34335. });
  34336. // Inject the coordinateSystems into seriesModel
  34337. ecModel.eachSeries(function (seriesModel) {
  34338. if (!isCartesian2D(seriesModel)) {
  34339. return;
  34340. }
  34341. var axesModels = findAxesModels(seriesModel, ecModel);
  34342. var xAxisModel = axesModels[0];
  34343. var yAxisModel = axesModels[1];
  34344. var gridModel = xAxisModel.getCoordSysModel();
  34345. if (__DEV__) {
  34346. if (!gridModel) {
  34347. throw new Error(
  34348. 'Grid "' + retrieve(
  34349. xAxisModel.get('gridIndex'),
  34350. xAxisModel.get('gridId'),
  34351. 0
  34352. ) + '" not found'
  34353. );
  34354. }
  34355. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  34356. throw new Error('xAxis and yAxis must use the same grid');
  34357. }
  34358. }
  34359. var grid = gridModel.coordinateSystem;
  34360. seriesModel.coordinateSystem = grid.getCartesian(
  34361. xAxisModel.componentIndex, yAxisModel.componentIndex
  34362. );
  34363. });
  34364. return grids;
  34365. };
  34366. // For deciding which dimensions to use when creating list data
  34367. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  34368. CoordinateSystemManager.register('cartesian2d', Grid);
  34369. /*
  34370. * Licensed to the Apache Software Foundation (ASF) under one
  34371. * or more contributor license agreements. See the NOTICE file
  34372. * distributed with this work for additional information
  34373. * regarding copyright ownership. The ASF licenses this file
  34374. * to you under the Apache License, Version 2.0 (the
  34375. * "License"); you may not use this file except in compliance
  34376. * with the License. You may obtain a copy of the License at
  34377. *
  34378. * http://www.apache.org/licenses/LICENSE-2.0
  34379. *
  34380. * Unless required by applicable law or agreed to in writing,
  34381. * software distributed under the License is distributed on an
  34382. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34383. * KIND, either express or implied. See the License for the
  34384. * specific language governing permissions and limitations
  34385. * under the License.
  34386. */
  34387. var PI$2 = Math.PI;
  34388. function makeAxisEventDataBase(axisModel) {
  34389. var eventData = {
  34390. componentType: axisModel.mainType,
  34391. componentIndex: axisModel.componentIndex
  34392. };
  34393. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  34394. return eventData;
  34395. }
  34396. /**
  34397. * A final axis is translated and rotated from a "standard axis".
  34398. * So opt.position and opt.rotation is required.
  34399. *
  34400. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  34401. * for example: (0, 0) ------------> (0, 50)
  34402. *
  34403. * nameDirection or tickDirection or labelDirection is 1 means tick
  34404. * or label is below the standard axis, whereas is -1 means above
  34405. * the standard axis. labelOffset means offset between label and axis,
  34406. * which is useful when 'onZero', where axisLabel is in the grid and
  34407. * label in outside grid.
  34408. *
  34409. * Tips: like always,
  34410. * positive rotation represents anticlockwise, and negative rotation
  34411. * represents clockwise.
  34412. * The direction of position coordinate is the same as the direction
  34413. * of screen coordinate.
  34414. *
  34415. * Do not need to consider axis 'inverse', which is auto processed by
  34416. * axis extent.
  34417. *
  34418. * @param {module:zrender/container/Group} group
  34419. * @param {Object} axisModel
  34420. * @param {Object} opt Standard axis parameters.
  34421. * @param {Array.<number>} opt.position [x, y]
  34422. * @param {number} opt.rotation by radian
  34423. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  34424. * @param {number} [opt.tickDirection=1] 1 or -1
  34425. * @param {number} [opt.labelDirection=1] 1 or -1
  34426. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  34427. * @param {string} [opt.axisLabelShow] default get from axisModel.
  34428. * @param {string} [opt.axisName] default get from axisModel.
  34429. * @param {number} [opt.axisNameAvailableWidth]
  34430. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  34431. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  34432. * @param {number} [opt.nameTruncateMaxWidth]
  34433. */
  34434. var AxisBuilder = function (axisModel, opt) {
  34435. /**
  34436. * @readOnly
  34437. */
  34438. this.opt = opt;
  34439. /**
  34440. * @readOnly
  34441. */
  34442. this.axisModel = axisModel;
  34443. // Default value
  34444. defaults(
  34445. opt,
  34446. {
  34447. labelOffset: 0,
  34448. nameDirection: 1,
  34449. tickDirection: 1,
  34450. labelDirection: 1,
  34451. silent: true
  34452. }
  34453. );
  34454. /**
  34455. * @readOnly
  34456. */
  34457. this.group = new Group();
  34458. // FIXME Not use a seperate text group?
  34459. var dumbGroup = new Group({
  34460. position: opt.position.slice(),
  34461. rotation: opt.rotation
  34462. });
  34463. // this.group.add(dumbGroup);
  34464. // this._dumbGroup = dumbGroup;
  34465. dumbGroup.updateTransform();
  34466. this._transform = dumbGroup.transform;
  34467. this._dumbGroup = dumbGroup;
  34468. };
  34469. AxisBuilder.prototype = {
  34470. constructor: AxisBuilder,
  34471. hasBuilder: function (name) {
  34472. return !!builders[name];
  34473. },
  34474. add: function (name) {
  34475. builders[name].call(this);
  34476. },
  34477. getGroup: function () {
  34478. return this.group;
  34479. }
  34480. };
  34481. var builders = {
  34482. /**
  34483. * @private
  34484. */
  34485. axisLine: function () {
  34486. var opt = this.opt;
  34487. var axisModel = this.axisModel;
  34488. if (!axisModel.get('axisLine.show')) {
  34489. return;
  34490. }
  34491. var extent = this.axisModel.axis.getExtent();
  34492. var matrix = this._transform;
  34493. var pt1 = [extent[0], 0];
  34494. var pt2 = [extent[1], 0];
  34495. if (matrix) {
  34496. applyTransform(pt1, pt1, matrix);
  34497. applyTransform(pt2, pt2, matrix);
  34498. }
  34499. var lineStyle = extend(
  34500. {
  34501. lineCap: 'round'
  34502. },
  34503. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  34504. );
  34505. this.group.add(new Line(subPixelOptimizeLine({
  34506. // Id for animation
  34507. anid: 'line',
  34508. shape: {
  34509. x1: pt1[0],
  34510. y1: pt1[1],
  34511. x2: pt2[0],
  34512. y2: pt2[1]
  34513. },
  34514. style: lineStyle,
  34515. strokeContainThreshold: opt.strokeContainThreshold || 5,
  34516. silent: true,
  34517. z2: 1
  34518. })));
  34519. var arrows = axisModel.get('axisLine.symbol');
  34520. var arrowSize = axisModel.get('axisLine.symbolSize');
  34521. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  34522. if (typeof arrowOffset === 'number') {
  34523. arrowOffset = [arrowOffset, arrowOffset];
  34524. }
  34525. if (arrows != null) {
  34526. if (typeof arrows === 'string') {
  34527. // Use the same arrow for start and end point
  34528. arrows = [arrows, arrows];
  34529. }
  34530. if (typeof arrowSize === 'string'
  34531. || typeof arrowSize === 'number'
  34532. ) {
  34533. // Use the same size for width and height
  34534. arrowSize = [arrowSize, arrowSize];
  34535. }
  34536. var symbolWidth = arrowSize[0];
  34537. var symbolHeight = arrowSize[1];
  34538. each$1([{
  34539. rotate: opt.rotation + Math.PI / 2,
  34540. offset: arrowOffset[0],
  34541. r: 0
  34542. }, {
  34543. rotate: opt.rotation - Math.PI / 2,
  34544. offset: arrowOffset[1],
  34545. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  34546. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  34547. }], function (point, index) {
  34548. if (arrows[index] !== 'none' && arrows[index] != null) {
  34549. var symbol = createSymbol(
  34550. arrows[index],
  34551. -symbolWidth / 2,
  34552. -symbolHeight / 2,
  34553. symbolWidth,
  34554. symbolHeight,
  34555. lineStyle.stroke,
  34556. true
  34557. );
  34558. // Calculate arrow position with offset
  34559. var r = point.r + point.offset;
  34560. var pos = [
  34561. pt1[0] + r * Math.cos(opt.rotation),
  34562. pt1[1] - r * Math.sin(opt.rotation)
  34563. ];
  34564. symbol.attr({
  34565. rotation: point.rotate,
  34566. position: pos,
  34567. silent: true,
  34568. z2: 11
  34569. });
  34570. this.group.add(symbol);
  34571. }
  34572. }, this);
  34573. }
  34574. },
  34575. /**
  34576. * @private
  34577. */
  34578. axisTickLabel: function () {
  34579. var axisModel = this.axisModel;
  34580. var opt = this.opt;
  34581. var tickEls = buildAxisTick(this, axisModel, opt);
  34582. var labelEls = buildAxisLabel(this, axisModel, opt);
  34583. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  34584. },
  34585. /**
  34586. * @private
  34587. */
  34588. axisName: function () {
  34589. var opt = this.opt;
  34590. var axisModel = this.axisModel;
  34591. var name = retrieve(opt.axisName, axisModel.get('name'));
  34592. if (!name) {
  34593. return;
  34594. }
  34595. var nameLocation = axisModel.get('nameLocation');
  34596. var nameDirection = opt.nameDirection;
  34597. var textStyleModel = axisModel.getModel('nameTextStyle');
  34598. var gap = axisModel.get('nameGap') || 0;
  34599. var extent = this.axisModel.axis.getExtent();
  34600. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  34601. var pos = [
  34602. nameLocation === 'start'
  34603. ? extent[0] - gapSignal * gap
  34604. : nameLocation === 'end'
  34605. ? extent[1] + gapSignal * gap
  34606. : (extent[0] + extent[1]) / 2, // 'middle'
  34607. // Reuse labelOffset.
  34608. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  34609. ];
  34610. var labelLayout;
  34611. var nameRotation = axisModel.get('nameRotate');
  34612. if (nameRotation != null) {
  34613. nameRotation = nameRotation * PI$2 / 180; // To radian.
  34614. }
  34615. var axisNameAvailableWidth;
  34616. if (isNameLocationCenter(nameLocation)) {
  34617. labelLayout = innerTextLayout(
  34618. opt.rotation,
  34619. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  34620. nameDirection
  34621. );
  34622. }
  34623. else {
  34624. labelLayout = endTextLayout(
  34625. opt, nameLocation, nameRotation || 0, extent
  34626. );
  34627. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  34628. if (axisNameAvailableWidth != null) {
  34629. axisNameAvailableWidth = Math.abs(
  34630. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  34631. );
  34632. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  34633. }
  34634. }
  34635. var textFont = textStyleModel.getFont();
  34636. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  34637. var ellipsis = truncateOpt.ellipsis;
  34638. var maxWidth = retrieve(
  34639. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  34640. );
  34641. // FIXME
  34642. // truncate rich text? (consider performance)
  34643. var truncatedText = (ellipsis != null && maxWidth != null)
  34644. ? truncateText$1(
  34645. name, maxWidth, textFont, ellipsis,
  34646. {minChar: 2, placeholder: truncateOpt.placeholder}
  34647. )
  34648. : name;
  34649. var tooltipOpt = axisModel.get('tooltip', true);
  34650. var mainType = axisModel.mainType;
  34651. var formatterParams = {
  34652. componentType: mainType,
  34653. name: name,
  34654. $vars: ['name']
  34655. };
  34656. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  34657. var textEl = new Text({
  34658. // Id for animation
  34659. anid: 'name',
  34660. __fullText: name,
  34661. __truncatedText: truncatedText,
  34662. position: pos,
  34663. rotation: labelLayout.rotation,
  34664. silent: isSilent(axisModel),
  34665. z2: 1,
  34666. tooltip: (tooltipOpt && tooltipOpt.show)
  34667. ? extend({
  34668. content: name,
  34669. formatter: function () {
  34670. return name;
  34671. },
  34672. formatterParams: formatterParams
  34673. }, tooltipOpt)
  34674. : null
  34675. });
  34676. setTextStyle(textEl.style, textStyleModel, {
  34677. text: truncatedText,
  34678. textFont: textFont,
  34679. textFill: textStyleModel.getTextColor()
  34680. || axisModel.get('axisLine.lineStyle.color'),
  34681. textAlign: labelLayout.textAlign,
  34682. textVerticalAlign: labelLayout.textVerticalAlign
  34683. });
  34684. if (axisModel.get('triggerEvent')) {
  34685. textEl.eventData = makeAxisEventDataBase(axisModel);
  34686. textEl.eventData.targetType = 'axisName';
  34687. textEl.eventData.name = name;
  34688. }
  34689. // FIXME
  34690. this._dumbGroup.add(textEl);
  34691. textEl.updateTransform();
  34692. this.group.add(textEl);
  34693. textEl.decomposeTransform();
  34694. }
  34695. };
  34696. /**
  34697. * @public
  34698. * @static
  34699. * @param {Object} opt
  34700. * @param {number} axisRotation in radian
  34701. * @param {number} textRotation in radian
  34702. * @param {number} direction
  34703. * @return {Object} {
  34704. * rotation, // according to axis
  34705. * textAlign,
  34706. * textVerticalAlign
  34707. * }
  34708. */
  34709. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  34710. var rotationDiff = remRadian(textRotation - axisRotation);
  34711. var textAlign;
  34712. var textVerticalAlign;
  34713. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  34714. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  34715. textAlign = 'center';
  34716. }
  34717. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  34718. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  34719. textAlign = 'center';
  34720. }
  34721. else {
  34722. textVerticalAlign = 'middle';
  34723. if (rotationDiff > 0 && rotationDiff < PI$2) {
  34724. textAlign = direction > 0 ? 'right' : 'left';
  34725. }
  34726. else {
  34727. textAlign = direction > 0 ? 'left' : 'right';
  34728. }
  34729. }
  34730. return {
  34731. rotation: rotationDiff,
  34732. textAlign: textAlign,
  34733. textVerticalAlign: textVerticalAlign
  34734. };
  34735. };
  34736. function endTextLayout(opt, textPosition, textRotate, extent) {
  34737. var rotationDiff = remRadian(textRotate - opt.rotation);
  34738. var textAlign;
  34739. var textVerticalAlign;
  34740. var inverse = extent[0] > extent[1];
  34741. var onLeft = (textPosition === 'start' && !inverse)
  34742. || (textPosition !== 'start' && inverse);
  34743. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  34744. textVerticalAlign = onLeft ? 'bottom' : 'top';
  34745. textAlign = 'center';
  34746. }
  34747. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  34748. textVerticalAlign = onLeft ? 'top' : 'bottom';
  34749. textAlign = 'center';
  34750. }
  34751. else {
  34752. textVerticalAlign = 'middle';
  34753. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  34754. textAlign = onLeft ? 'left' : 'right';
  34755. }
  34756. else {
  34757. textAlign = onLeft ? 'right' : 'left';
  34758. }
  34759. }
  34760. return {
  34761. rotation: rotationDiff,
  34762. textAlign: textAlign,
  34763. textVerticalAlign: textVerticalAlign
  34764. };
  34765. }
  34766. function isSilent(axisModel) {
  34767. var tooltipOpt = axisModel.get('tooltip');
  34768. return axisModel.get('silent')
  34769. // Consider mouse cursor, add these restrictions.
  34770. || !(
  34771. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  34772. );
  34773. }
  34774. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  34775. if (shouldShowAllLabels(axisModel.axis)) {
  34776. return;
  34777. }
  34778. // If min or max are user set, we need to check
  34779. // If the tick on min(max) are overlap on their neighbour tick
  34780. // If they are overlapped, we need to hide the min(max) tick label
  34781. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  34782. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  34783. // FIXME
  34784. // Have not consider onBand yet, where tick els is more than label els.
  34785. labelEls = labelEls || [];
  34786. tickEls = tickEls || [];
  34787. var firstLabel = labelEls[0];
  34788. var nextLabel = labelEls[1];
  34789. var lastLabel = labelEls[labelEls.length - 1];
  34790. var prevLabel = labelEls[labelEls.length - 2];
  34791. var firstTick = tickEls[0];
  34792. var nextTick = tickEls[1];
  34793. var lastTick = tickEls[tickEls.length - 1];
  34794. var prevTick = tickEls[tickEls.length - 2];
  34795. if (showMinLabel === false) {
  34796. ignoreEl(firstLabel);
  34797. ignoreEl(firstTick);
  34798. }
  34799. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  34800. if (showMinLabel) {
  34801. ignoreEl(nextLabel);
  34802. ignoreEl(nextTick);
  34803. }
  34804. else {
  34805. ignoreEl(firstLabel);
  34806. ignoreEl(firstTick);
  34807. }
  34808. }
  34809. if (showMaxLabel === false) {
  34810. ignoreEl(lastLabel);
  34811. ignoreEl(lastTick);
  34812. }
  34813. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  34814. if (showMaxLabel) {
  34815. ignoreEl(prevLabel);
  34816. ignoreEl(prevTick);
  34817. }
  34818. else {
  34819. ignoreEl(lastLabel);
  34820. ignoreEl(lastTick);
  34821. }
  34822. }
  34823. }
  34824. function ignoreEl(el) {
  34825. el && (el.ignore = true);
  34826. }
  34827. function isTwoLabelOverlapped(current, next, labelLayout) {
  34828. // current and next has the same rotation.
  34829. var firstRect = current && current.getBoundingRect().clone();
  34830. var nextRect = next && next.getBoundingRect().clone();
  34831. if (!firstRect || !nextRect) {
  34832. return;
  34833. }
  34834. // When checking intersect of two rotated labels, we use mRotationBack
  34835. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  34836. var mRotationBack = identity([]);
  34837. rotate(mRotationBack, mRotationBack, -current.rotation);
  34838. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  34839. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  34840. return firstRect.intersect(nextRect);
  34841. }
  34842. function isNameLocationCenter(nameLocation) {
  34843. return nameLocation === 'middle' || nameLocation === 'center';
  34844. }
  34845. function buildAxisTick(axisBuilder, axisModel, opt) {
  34846. var axis = axisModel.axis;
  34847. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  34848. return;
  34849. }
  34850. var tickModel = axisModel.getModel('axisTick');
  34851. var lineStyleModel = tickModel.getModel('lineStyle');
  34852. var tickLen = tickModel.get('length');
  34853. var ticksCoords = axis.getTicksCoords();
  34854. var pt1 = [];
  34855. var pt2 = [];
  34856. var matrix = axisBuilder._transform;
  34857. var tickEls = [];
  34858. for (var i = 0; i < ticksCoords.length; i++) {
  34859. var tickCoord = ticksCoords[i].coord;
  34860. pt1[0] = tickCoord;
  34861. pt1[1] = 0;
  34862. pt2[0] = tickCoord;
  34863. pt2[1] = opt.tickDirection * tickLen;
  34864. if (matrix) {
  34865. applyTransform(pt1, pt1, matrix);
  34866. applyTransform(pt2, pt2, matrix);
  34867. }
  34868. // Tick line, Not use group transform to have better line draw
  34869. var tickEl = new Line(subPixelOptimizeLine({
  34870. // Id for animation
  34871. anid: 'tick_' + ticksCoords[i].tickValue,
  34872. shape: {
  34873. x1: pt1[0],
  34874. y1: pt1[1],
  34875. x2: pt2[0],
  34876. y2: pt2[1]
  34877. },
  34878. style: defaults(
  34879. lineStyleModel.getLineStyle(),
  34880. {
  34881. stroke: axisModel.get('axisLine.lineStyle.color')
  34882. }
  34883. ),
  34884. z2: 2,
  34885. silent: true
  34886. }));
  34887. axisBuilder.group.add(tickEl);
  34888. tickEls.push(tickEl);
  34889. }
  34890. return tickEls;
  34891. }
  34892. function buildAxisLabel(axisBuilder, axisModel, opt) {
  34893. var axis = axisModel.axis;
  34894. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  34895. if (!show || axis.scale.isBlank()) {
  34896. return;
  34897. }
  34898. var labelModel = axisModel.getModel('axisLabel');
  34899. var labelMargin = labelModel.get('margin');
  34900. var labels = axis.getViewLabels();
  34901. // Special label rotate.
  34902. var labelRotation = (
  34903. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  34904. ) * PI$2 / 180;
  34905. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  34906. var rawCategoryData = axisModel.getCategories(true);
  34907. var labelEls = [];
  34908. var silent = isSilent(axisModel);
  34909. var triggerEvent = axisModel.get('triggerEvent');
  34910. each$1(labels, function (labelItem, index) {
  34911. var tickValue = labelItem.tickValue;
  34912. var formattedLabel = labelItem.formattedLabel;
  34913. var rawLabel = labelItem.rawLabel;
  34914. var itemLabelModel = labelModel;
  34915. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  34916. itemLabelModel = new Model(
  34917. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  34918. );
  34919. }
  34920. var textColor = itemLabelModel.getTextColor()
  34921. || axisModel.get('axisLine.lineStyle.color');
  34922. var tickCoord = axis.dataToCoord(tickValue);
  34923. var pos = [
  34924. tickCoord,
  34925. opt.labelOffset + opt.labelDirection * labelMargin
  34926. ];
  34927. var textEl = new Text({
  34928. // Id for animation
  34929. anid: 'label_' + tickValue,
  34930. position: pos,
  34931. rotation: labelLayout.rotation,
  34932. silent: silent,
  34933. z2: 10
  34934. });
  34935. setTextStyle(textEl.style, itemLabelModel, {
  34936. text: formattedLabel,
  34937. textAlign: itemLabelModel.getShallow('align', true)
  34938. || labelLayout.textAlign,
  34939. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  34940. || itemLabelModel.getShallow('baseline', true)
  34941. || labelLayout.textVerticalAlign,
  34942. textFill: typeof textColor === 'function'
  34943. ? textColor(
  34944. // (1) In category axis with data zoom, tick is not the original
  34945. // index of axis.data. So tick should not be exposed to user
  34946. // in category axis.
  34947. // (2) Compatible with previous version, which always use formatted label as
  34948. // input. But in interval scale the formatted label is like '223,445', which
  34949. // maked user repalce ','. So we modify it to return original val but remain
  34950. // it as 'string' to avoid error in replacing.
  34951. axis.type === 'category'
  34952. ? rawLabel
  34953. : axis.type === 'value'
  34954. ? tickValue + ''
  34955. : tickValue,
  34956. index
  34957. )
  34958. : textColor
  34959. });
  34960. // Pack data for mouse event
  34961. if (triggerEvent) {
  34962. textEl.eventData = makeAxisEventDataBase(axisModel);
  34963. textEl.eventData.targetType = 'axisLabel';
  34964. textEl.eventData.value = rawLabel;
  34965. }
  34966. // FIXME
  34967. axisBuilder._dumbGroup.add(textEl);
  34968. textEl.updateTransform();
  34969. labelEls.push(textEl);
  34970. axisBuilder.group.add(textEl);
  34971. textEl.decomposeTransform();
  34972. });
  34973. return labelEls;
  34974. }
  34975. /*
  34976. * Licensed to the Apache Software Foundation (ASF) under one
  34977. * or more contributor license agreements. See the NOTICE file
  34978. * distributed with this work for additional information
  34979. * regarding copyright ownership. The ASF licenses this file
  34980. * to you under the Apache License, Version 2.0 (the
  34981. * "License"); you may not use this file except in compliance
  34982. * with the License. You may obtain a copy of the License at
  34983. *
  34984. * http://www.apache.org/licenses/LICENSE-2.0
  34985. *
  34986. * Unless required by applicable law or agreed to in writing,
  34987. * software distributed under the License is distributed on an
  34988. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34989. * KIND, either express or implied. See the License for the
  34990. * specific language governing permissions and limitations
  34991. * under the License.
  34992. */
  34993. var each$6 = each$1;
  34994. var curry$1 = curry;
  34995. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  34996. // allAxesInfo should be updated when setOption performed.
  34997. function collect(ecModel, api) {
  34998. var result = {
  34999. /**
  35000. * key: makeKey(axis.model)
  35001. * value: {
  35002. * axis,
  35003. * coordSys,
  35004. * axisPointerModel,
  35005. * triggerTooltip,
  35006. * involveSeries,
  35007. * snap,
  35008. * seriesModels,
  35009. * seriesDataCount
  35010. * }
  35011. */
  35012. axesInfo: {},
  35013. seriesInvolved: false,
  35014. /**
  35015. * key: makeKey(coordSys.model)
  35016. * value: Object: key makeKey(axis.model), value: axisInfo
  35017. */
  35018. coordSysAxesInfo: {},
  35019. coordSysMap: {}
  35020. };
  35021. collectAxesInfo(result, ecModel, api);
  35022. // Check seriesInvolved for performance, in case too many series in some chart.
  35023. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  35024. return result;
  35025. }
  35026. function collectAxesInfo(result, ecModel, api) {
  35027. var globalTooltipModel = ecModel.getComponent('tooltip');
  35028. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  35029. // links can only be set on global.
  35030. var linksOption = globalAxisPointerModel.get('link', true) || [];
  35031. var linkGroups = [];
  35032. // Collect axes info.
  35033. each$6(api.getCoordinateSystems(), function (coordSys) {
  35034. // Some coordinate system do not support axes, like geo.
  35035. if (!coordSys.axisPointerEnabled) {
  35036. return;
  35037. }
  35038. var coordSysKey = makeKey(coordSys.model);
  35039. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  35040. result.coordSysMap[coordSysKey] = coordSys;
  35041. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  35042. // for user. So we enable seting tooltip on coordSys model.
  35043. var coordSysModel = coordSys.model;
  35044. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  35045. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  35046. // If axis tooltip used, choose tooltip axis for each coordSys.
  35047. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  35048. if (coordSys.getTooltipAxes
  35049. && globalTooltipModel
  35050. // If tooltip.showContent is set as false, tooltip will not
  35051. // show but axisPointer will show as normal.
  35052. && baseTooltipModel.get('show')
  35053. ) {
  35054. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  35055. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  35056. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  35057. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  35058. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  35059. if (triggerAxis || cross) {
  35060. each$6(tooltipAxes.baseAxes, curry$1(
  35061. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  35062. ));
  35063. }
  35064. if (cross) {
  35065. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  35066. }
  35067. }
  35068. // fromTooltip: true | false | 'cross'
  35069. // triggerTooltip: true | false | null
  35070. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  35071. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  35072. var axisPointerShow = axisPointerModel.get('show');
  35073. if (!axisPointerShow || (
  35074. axisPointerShow === 'auto'
  35075. && !fromTooltip
  35076. && !isHandleTrigger(axisPointerModel)
  35077. )) {
  35078. return;
  35079. }
  35080. if (triggerTooltip == null) {
  35081. triggerTooltip = axisPointerModel.get('triggerTooltip');
  35082. }
  35083. axisPointerModel = fromTooltip
  35084. ? makeAxisPointerModel(
  35085. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  35086. fromTooltip, triggerTooltip
  35087. )
  35088. : axisPointerModel;
  35089. var snap = axisPointerModel.get('snap');
  35090. var key = makeKey(axis.model);
  35091. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  35092. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  35093. var axisInfo = result.axesInfo[key] = {
  35094. key: key,
  35095. axis: axis,
  35096. coordSys: coordSys,
  35097. axisPointerModel: axisPointerModel,
  35098. triggerTooltip: triggerTooltip,
  35099. involveSeries: involveSeries,
  35100. snap: snap,
  35101. useHandle: isHandleTrigger(axisPointerModel),
  35102. seriesModels: []
  35103. };
  35104. axesInfoInCoordSys[key] = axisInfo;
  35105. result.seriesInvolved |= involveSeries;
  35106. var groupIndex = getLinkGroupIndex(linksOption, axis);
  35107. if (groupIndex != null) {
  35108. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  35109. linkGroup.axesInfo[key] = axisInfo;
  35110. linkGroup.mapper = linksOption[groupIndex].mapper;
  35111. axisInfo.linkGroup = linkGroup;
  35112. }
  35113. }
  35114. });
  35115. }
  35116. function makeAxisPointerModel(
  35117. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  35118. ) {
  35119. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  35120. var volatileOption = {};
  35121. each$6(
  35122. [
  35123. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  35124. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  35125. ],
  35126. function (field) {
  35127. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  35128. }
  35129. );
  35130. // category axis do not auto snap, otherwise some tick that do not
  35131. // has value can not be hovered. value/time/log axis default snap if
  35132. // triggered from tooltip and trigger tooltip.
  35133. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  35134. // Compatibel with previous behavior, tooltip axis do not show label by default.
  35135. // Only these properties can be overrided from tooltip to axisPointer.
  35136. if (tooltipAxisPointerModel.get('type') === 'cross') {
  35137. volatileOption.type = 'line';
  35138. }
  35139. var labelOption = volatileOption.label || (volatileOption.label = {});
  35140. // Follow the convention, do not show label when triggered by tooltip by default.
  35141. labelOption.show == null && (labelOption.show = false);
  35142. if (fromTooltip === 'cross') {
  35143. // When 'cross', both axes show labels.
  35144. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  35145. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  35146. // If triggerTooltip, this is a base axis, which should better not use cross style
  35147. // (cross style is dashed by default)
  35148. if (!triggerTooltip) {
  35149. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  35150. crossStyle && defaults(labelOption, crossStyle.textStyle);
  35151. }
  35152. }
  35153. return axis.model.getModel(
  35154. 'axisPointer',
  35155. new Model(volatileOption, globalAxisPointerModel, ecModel)
  35156. );
  35157. }
  35158. function collectSeriesInfo(result, ecModel) {
  35159. // Prepare data for axis trigger
  35160. ecModel.eachSeries(function (seriesModel) {
  35161. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  35162. var coordSys = seriesModel.coordinateSystem;
  35163. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  35164. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  35165. if (!coordSys
  35166. || seriesTooltipTrigger === 'none'
  35167. || seriesTooltipTrigger === false
  35168. || seriesTooltipTrigger === 'item'
  35169. || seriesTooltipShow === false
  35170. || seriesModel.get('axisPointer.show', true) === false
  35171. ) {
  35172. return;
  35173. }
  35174. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  35175. var axis = axisInfo.axis;
  35176. if (coordSys.getAxis(axis.dim) === axis) {
  35177. axisInfo.seriesModels.push(seriesModel);
  35178. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  35179. axisInfo.seriesDataCount += seriesModel.getData().count();
  35180. }
  35181. });
  35182. }, this);
  35183. }
  35184. /**
  35185. * For example:
  35186. * {
  35187. * axisPointer: {
  35188. * links: [{
  35189. * xAxisIndex: [2, 4],
  35190. * yAxisIndex: 'all'
  35191. * }, {
  35192. * xAxisId: ['a5', 'a7'],
  35193. * xAxisName: 'xxx'
  35194. * }]
  35195. * }
  35196. * }
  35197. */
  35198. function getLinkGroupIndex(linksOption, axis) {
  35199. var axisModel = axis.model;
  35200. var dim = axis.dim;
  35201. for (var i = 0; i < linksOption.length; i++) {
  35202. var linkOption = linksOption[i] || {};
  35203. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  35204. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  35205. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  35206. ) {
  35207. return i;
  35208. }
  35209. }
  35210. }
  35211. function checkPropInLink(linkPropValue, axisPropValue) {
  35212. return linkPropValue === 'all'
  35213. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  35214. || linkPropValue === axisPropValue;
  35215. }
  35216. function fixValue(axisModel) {
  35217. var axisInfo = getAxisInfo(axisModel);
  35218. if (!axisInfo) {
  35219. return;
  35220. }
  35221. var axisPointerModel = axisInfo.axisPointerModel;
  35222. var scale = axisInfo.axis.scale;
  35223. var option = axisPointerModel.option;
  35224. var status = axisPointerModel.get('status');
  35225. var value = axisPointerModel.get('value');
  35226. // Parse init value for category and time axis.
  35227. if (value != null) {
  35228. value = scale.parse(value);
  35229. }
  35230. var useHandle = isHandleTrigger(axisPointerModel);
  35231. // If `handle` used, `axisPointer` will always be displayed, so value
  35232. // and status should be initialized.
  35233. if (status == null) {
  35234. option.status = useHandle ? 'show' : 'hide';
  35235. }
  35236. var extent = scale.getExtent().slice();
  35237. extent[0] > extent[1] && extent.reverse();
  35238. if (// Pick a value on axis when initializing.
  35239. value == null
  35240. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  35241. // where we should re-pick a value to keep `handle` displaying normally.
  35242. || value > extent[1]
  35243. ) {
  35244. // Make handle displayed on the end of the axis when init, which looks better.
  35245. value = extent[1];
  35246. }
  35247. if (value < extent[0]) {
  35248. value = extent[0];
  35249. }
  35250. option.value = value;
  35251. if (useHandle) {
  35252. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  35253. }
  35254. }
  35255. function getAxisInfo(axisModel) {
  35256. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  35257. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  35258. }
  35259. function getAxisPointerModel(axisModel) {
  35260. var axisInfo = getAxisInfo(axisModel);
  35261. return axisInfo && axisInfo.axisPointerModel;
  35262. }
  35263. function isHandleTrigger(axisPointerModel) {
  35264. return !!axisPointerModel.get('handle.show');
  35265. }
  35266. /**
  35267. * @param {module:echarts/model/Model} model
  35268. * @return {string} unique key
  35269. */
  35270. function makeKey(model) {
  35271. return model.type + '||' + model.id;
  35272. }
  35273. /*
  35274. * Licensed to the Apache Software Foundation (ASF) under one
  35275. * or more contributor license agreements. See the NOTICE file
  35276. * distributed with this work for additional information
  35277. * regarding copyright ownership. The ASF licenses this file
  35278. * to you under the Apache License, Version 2.0 (the
  35279. * "License"); you may not use this file except in compliance
  35280. * with the License. You may obtain a copy of the License at
  35281. *
  35282. * http://www.apache.org/licenses/LICENSE-2.0
  35283. *
  35284. * Unless required by applicable law or agreed to in writing,
  35285. * software distributed under the License is distributed on an
  35286. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35287. * KIND, either express or implied. See the License for the
  35288. * specific language governing permissions and limitations
  35289. * under the License.
  35290. */
  35291. /**
  35292. * Base class of AxisView.
  35293. */
  35294. var AxisView = extendComponentView({
  35295. type: 'axis',
  35296. /**
  35297. * @private
  35298. */
  35299. _axisPointer: null,
  35300. /**
  35301. * @protected
  35302. * @type {string}
  35303. */
  35304. axisPointerClass: null,
  35305. /**
  35306. * @override
  35307. */
  35308. render: function (axisModel, ecModel, api, payload) {
  35309. // FIXME
  35310. // This process should proformed after coordinate systems updated
  35311. // (axis scale updated), and should be performed each time update.
  35312. // So put it here temporarily, although it is not appropriate to
  35313. // put a model-writing procedure in `view`.
  35314. this.axisPointerClass && fixValue(axisModel);
  35315. AxisView.superApply(this, 'render', arguments);
  35316. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  35317. },
  35318. /**
  35319. * Action handler.
  35320. * @public
  35321. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35322. * @param {module:echarts/model/Global} ecModel
  35323. * @param {module:echarts/ExtensionAPI} api
  35324. * @param {Object} payload
  35325. */
  35326. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  35327. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  35328. },
  35329. /**
  35330. * @override
  35331. */
  35332. remove: function (ecModel, api) {
  35333. var axisPointer = this._axisPointer;
  35334. axisPointer && axisPointer.remove(api);
  35335. AxisView.superApply(this, 'remove', arguments);
  35336. },
  35337. /**
  35338. * @override
  35339. */
  35340. dispose: function (ecModel, api) {
  35341. disposeAxisPointer(this, api);
  35342. AxisView.superApply(this, 'dispose', arguments);
  35343. }
  35344. });
  35345. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  35346. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  35347. if (!Clazz) {
  35348. return;
  35349. }
  35350. var axisPointerModel = getAxisPointerModel(axisModel);
  35351. axisPointerModel
  35352. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  35353. .render(axisModel, axisPointerModel, api, forceRender)
  35354. : disposeAxisPointer(axisView, api);
  35355. }
  35356. function disposeAxisPointer(axisView, ecModel, api) {
  35357. var axisPointer = axisView._axisPointer;
  35358. axisPointer && axisPointer.dispose(ecModel, api);
  35359. axisView._axisPointer = null;
  35360. }
  35361. var axisPointerClazz = [];
  35362. AxisView.registerAxisPointerClass = function (type, clazz) {
  35363. if (__DEV__) {
  35364. if (axisPointerClazz[type]) {
  35365. throw new Error('axisPointer ' + type + ' exists');
  35366. }
  35367. }
  35368. axisPointerClazz[type] = clazz;
  35369. };
  35370. AxisView.getAxisPointerClass = function (type) {
  35371. return type && axisPointerClazz[type];
  35372. };
  35373. /*
  35374. * Licensed to the Apache Software Foundation (ASF) under one
  35375. * or more contributor license agreements. See the NOTICE file
  35376. * distributed with this work for additional information
  35377. * regarding copyright ownership. The ASF licenses this file
  35378. * to you under the Apache License, Version 2.0 (the
  35379. * "License"); you may not use this file except in compliance
  35380. * with the License. You may obtain a copy of the License at
  35381. *
  35382. * http://www.apache.org/licenses/LICENSE-2.0
  35383. *
  35384. * Unless required by applicable law or agreed to in writing,
  35385. * software distributed under the License is distributed on an
  35386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35387. * KIND, either express or implied. See the License for the
  35388. * specific language governing permissions and limitations
  35389. * under the License.
  35390. */
  35391. /**
  35392. * Can only be called after coordinate system creation stage.
  35393. * (Can be called before coordinate system update stage).
  35394. *
  35395. * @param {Object} opt {labelInside}
  35396. * @return {Object} {
  35397. * position, rotation, labelDirection, labelOffset,
  35398. * tickDirection, labelRotate, z2
  35399. * }
  35400. */
  35401. function layout$1(gridModel, axisModel, opt) {
  35402. opt = opt || {};
  35403. var grid = gridModel.coordinateSystem;
  35404. var axis = axisModel.axis;
  35405. var layout = {};
  35406. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  35407. var rawAxisPosition = axis.position;
  35408. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  35409. var axisDim = axis.dim;
  35410. var rect = grid.getRect();
  35411. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  35412. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  35413. var axisOffset = axisModel.get('offset') || 0;
  35414. var posBound = axisDim === 'x'
  35415. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  35416. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  35417. if (otherAxisOnZeroOf) {
  35418. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  35419. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  35420. }
  35421. // Axis position
  35422. layout.position = [
  35423. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  35424. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  35425. ];
  35426. // Axis rotation
  35427. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  35428. // Tick and label direction, x y is axisDim
  35429. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  35430. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  35431. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  35432. if (axisModel.get('axisTick.inside')) {
  35433. layout.tickDirection = -layout.tickDirection;
  35434. }
  35435. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  35436. layout.labelDirection = -layout.labelDirection;
  35437. }
  35438. // Special label rotation
  35439. var labelRotate = axisModel.get('axisLabel.rotate');
  35440. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  35441. // Over splitLine and splitArea
  35442. layout.z2 = 1;
  35443. return layout;
  35444. }
  35445. /*
  35446. * Licensed to the Apache Software Foundation (ASF) under one
  35447. * or more contributor license agreements. See the NOTICE file
  35448. * distributed with this work for additional information
  35449. * regarding copyright ownership. The ASF licenses this file
  35450. * to you under the Apache License, Version 2.0 (the
  35451. * "License"); you may not use this file except in compliance
  35452. * with the License. You may obtain a copy of the License at
  35453. *
  35454. * http://www.apache.org/licenses/LICENSE-2.0
  35455. *
  35456. * Unless required by applicable law or agreed to in writing,
  35457. * software distributed under the License is distributed on an
  35458. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35459. * KIND, either express or implied. See the License for the
  35460. * specific language governing permissions and limitations
  35461. * under the License.
  35462. */
  35463. var axisBuilderAttrs = [
  35464. 'axisLine', 'axisTickLabel', 'axisName'
  35465. ];
  35466. var selfBuilderAttrs = [
  35467. 'splitArea', 'splitLine'
  35468. ];
  35469. // function getAlignWithLabel(model, axisModel) {
  35470. // var alignWithLabel = model.get('alignWithLabel');
  35471. // if (alignWithLabel === 'auto') {
  35472. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  35473. // }
  35474. // return alignWithLabel;
  35475. // }
  35476. var CartesianAxisView = AxisView.extend({
  35477. type: 'cartesianAxis',
  35478. axisPointerClass: 'CartesianAxisPointer',
  35479. /**
  35480. * @override
  35481. */
  35482. render: function (axisModel, ecModel, api, payload) {
  35483. this.group.removeAll();
  35484. var oldAxisGroup = this._axisGroup;
  35485. this._axisGroup = new Group();
  35486. this.group.add(this._axisGroup);
  35487. if (!axisModel.get('show')) {
  35488. return;
  35489. }
  35490. var gridModel = axisModel.getCoordSysModel();
  35491. var layout = layout$1(gridModel, axisModel);
  35492. var axisBuilder = new AxisBuilder(axisModel, layout);
  35493. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  35494. this._axisGroup.add(axisBuilder.getGroup());
  35495. each$1(selfBuilderAttrs, function (name) {
  35496. if (axisModel.get(name + '.show')) {
  35497. this['_' + name](axisModel, gridModel);
  35498. }
  35499. }, this);
  35500. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  35501. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  35502. },
  35503. remove: function () {
  35504. this._splitAreaColors = null;
  35505. },
  35506. /**
  35507. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35508. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35509. * @private
  35510. */
  35511. _splitLine: function (axisModel, gridModel) {
  35512. var axis = axisModel.axis;
  35513. if (axis.scale.isBlank()) {
  35514. return;
  35515. }
  35516. var splitLineModel = axisModel.getModel('splitLine');
  35517. var lineStyleModel = splitLineModel.getModel('lineStyle');
  35518. var lineColors = lineStyleModel.get('color');
  35519. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  35520. var gridRect = gridModel.coordinateSystem.getRect();
  35521. var isHorizontal = axis.isHorizontal();
  35522. var lineCount = 0;
  35523. var ticksCoords = axis.getTicksCoords({
  35524. tickModel: splitLineModel
  35525. });
  35526. var p1 = [];
  35527. var p2 = [];
  35528. // Simple optimization
  35529. // Batching the lines if color are the same
  35530. var lineStyle = lineStyleModel.getLineStyle();
  35531. for (var i = 0; i < ticksCoords.length; i++) {
  35532. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35533. if (isHorizontal) {
  35534. p1[0] = tickCoord;
  35535. p1[1] = gridRect.y;
  35536. p2[0] = tickCoord;
  35537. p2[1] = gridRect.y + gridRect.height;
  35538. }
  35539. else {
  35540. p1[0] = gridRect.x;
  35541. p1[1] = tickCoord;
  35542. p2[0] = gridRect.x + gridRect.width;
  35543. p2[1] = tickCoord;
  35544. }
  35545. var colorIndex = (lineCount++) % lineColors.length;
  35546. var tickValue = ticksCoords[i].tickValue;
  35547. this._axisGroup.add(new Line(subPixelOptimizeLine({
  35548. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  35549. shape: {
  35550. x1: p1[0],
  35551. y1: p1[1],
  35552. x2: p2[0],
  35553. y2: p2[1]
  35554. },
  35555. style: defaults({
  35556. stroke: lineColors[colorIndex]
  35557. }, lineStyle),
  35558. silent: true
  35559. })));
  35560. }
  35561. },
  35562. /**
  35563. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35564. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35565. * @private
  35566. */
  35567. _splitArea: function (axisModel, gridModel) {
  35568. var axis = axisModel.axis;
  35569. if (axis.scale.isBlank()) {
  35570. return;
  35571. }
  35572. var splitAreaModel = axisModel.getModel('splitArea');
  35573. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  35574. var areaColors = areaStyleModel.get('color');
  35575. var gridRect = gridModel.coordinateSystem.getRect();
  35576. var ticksCoords = axis.getTicksCoords({
  35577. tickModel: splitAreaModel,
  35578. clamp: true
  35579. });
  35580. if (!ticksCoords.length) {
  35581. return;
  35582. }
  35583. // For Making appropriate splitArea animation, the color and anid
  35584. // should be corresponding to previous one if possible.
  35585. var areaColorsLen = areaColors.length;
  35586. var lastSplitAreaColors = this._splitAreaColors;
  35587. var newSplitAreaColors = createHashMap();
  35588. var colorIndex = 0;
  35589. if (lastSplitAreaColors) {
  35590. for (var i = 0; i < ticksCoords.length; i++) {
  35591. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  35592. if (cIndex != null) {
  35593. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  35594. break;
  35595. }
  35596. }
  35597. }
  35598. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  35599. var areaStyle = areaStyleModel.getAreaStyle();
  35600. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  35601. for (var i = 1; i < ticksCoords.length; i++) {
  35602. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35603. var x;
  35604. var y;
  35605. var width;
  35606. var height;
  35607. if (axis.isHorizontal()) {
  35608. x = prev;
  35609. y = gridRect.y;
  35610. width = tickCoord - x;
  35611. height = gridRect.height;
  35612. prev = x + width;
  35613. }
  35614. else {
  35615. x = gridRect.x;
  35616. y = prev;
  35617. width = gridRect.width;
  35618. height = tickCoord - y;
  35619. prev = y + height;
  35620. }
  35621. var tickValue = ticksCoords[i - 1].tickValue;
  35622. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  35623. this._axisGroup.add(new Rect({
  35624. anid: tickValue != null ? 'area_' + tickValue : null,
  35625. shape: {
  35626. x: x,
  35627. y: y,
  35628. width: width,
  35629. height: height
  35630. },
  35631. style: defaults({
  35632. fill: areaColors[colorIndex]
  35633. }, areaStyle),
  35634. silent: true
  35635. }));
  35636. colorIndex = (colorIndex + 1) % areaColorsLen;
  35637. }
  35638. this._splitAreaColors = newSplitAreaColors;
  35639. }
  35640. });
  35641. CartesianAxisView.extend({
  35642. type: 'xAxis'
  35643. });
  35644. CartesianAxisView.extend({
  35645. type: 'yAxis'
  35646. });
  35647. /*
  35648. * Licensed to the Apache Software Foundation (ASF) under one
  35649. * or more contributor license agreements. See the NOTICE file
  35650. * distributed with this work for additional information
  35651. * regarding copyright ownership. The ASF licenses this file
  35652. * to you under the Apache License, Version 2.0 (the
  35653. * "License"); you may not use this file except in compliance
  35654. * with the License. You may obtain a copy of the License at
  35655. *
  35656. * http://www.apache.org/licenses/LICENSE-2.0
  35657. *
  35658. * Unless required by applicable law or agreed to in writing,
  35659. * software distributed under the License is distributed on an
  35660. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35661. * KIND, either express or implied. See the License for the
  35662. * specific language governing permissions and limitations
  35663. * under the License.
  35664. */
  35665. /*
  35666. * Licensed to the Apache Software Foundation (ASF) under one
  35667. * or more contributor license agreements. See the NOTICE file
  35668. * distributed with this work for additional information
  35669. * regarding copyright ownership. The ASF licenses this file
  35670. * to you under the Apache License, Version 2.0 (the
  35671. * "License"); you may not use this file except in compliance
  35672. * with the License. You may obtain a copy of the License at
  35673. *
  35674. * http://www.apache.org/licenses/LICENSE-2.0
  35675. *
  35676. * Unless required by applicable law or agreed to in writing,
  35677. * software distributed under the License is distributed on an
  35678. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35679. * KIND, either express or implied. See the License for the
  35680. * specific language governing permissions and limitations
  35681. * under the License.
  35682. */
  35683. // Grid view
  35684. extendComponentView({
  35685. type: 'grid',
  35686. render: function (gridModel, ecModel) {
  35687. this.group.removeAll();
  35688. if (gridModel.get('show')) {
  35689. this.group.add(new Rect({
  35690. shape: gridModel.coordinateSystem.getRect(),
  35691. style: defaults({
  35692. fill: gridModel.get('backgroundColor')
  35693. }, gridModel.getItemStyle()),
  35694. silent: true,
  35695. z2: -1
  35696. }));
  35697. }
  35698. }
  35699. });
  35700. registerPreprocessor(function (option) {
  35701. // Only create grid when need
  35702. if (option.xAxis && option.yAxis && !option.grid) {
  35703. option.grid = {};
  35704. }
  35705. });
  35706. /*
  35707. * Licensed to the Apache Software Foundation (ASF) under one
  35708. * or more contributor license agreements. See the NOTICE file
  35709. * distributed with this work for additional information
  35710. * regarding copyright ownership. The ASF licenses this file
  35711. * to you under the Apache License, Version 2.0 (the
  35712. * "License"); you may not use this file except in compliance
  35713. * with the License. You may obtain a copy of the License at
  35714. *
  35715. * http://www.apache.org/licenses/LICENSE-2.0
  35716. *
  35717. * Unless required by applicable law or agreed to in writing,
  35718. * software distributed under the License is distributed on an
  35719. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35720. * KIND, either express or implied. See the License for the
  35721. * specific language governing permissions and limitations
  35722. * under the License.
  35723. */
  35724. // In case developer forget to include grid component
  35725. registerVisual(visualSymbol('line', 'circle', 'line'));
  35726. registerLayout(pointsLayout('line'));
  35727. // Down sample after filter
  35728. registerProcessor(
  35729. PRIORITY.PROCESSOR.STATISTIC,
  35730. dataSample('line')
  35731. );
  35732. /*
  35733. * Licensed to the Apache Software Foundation (ASF) under one
  35734. * or more contributor license agreements. See the NOTICE file
  35735. * distributed with this work for additional information
  35736. * regarding copyright ownership. The ASF licenses this file
  35737. * to you under the Apache License, Version 2.0 (the
  35738. * "License"); you may not use this file except in compliance
  35739. * with the License. You may obtain a copy of the License at
  35740. *
  35741. * http://www.apache.org/licenses/LICENSE-2.0
  35742. *
  35743. * Unless required by applicable law or agreed to in writing,
  35744. * software distributed under the License is distributed on an
  35745. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35746. * KIND, either express or implied. See the License for the
  35747. * specific language governing permissions and limitations
  35748. * under the License.
  35749. */
  35750. var BaseBarSeries = SeriesModel.extend({
  35751. type: 'series.__base_bar__',
  35752. getInitialData: function (option, ecModel) {
  35753. return createListFromArray(this.getSource(), this);
  35754. },
  35755. getMarkerPosition: function (value) {
  35756. var coordSys = this.coordinateSystem;
  35757. if (coordSys) {
  35758. // PENDING if clamp ?
  35759. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  35760. var data = this.getData();
  35761. var offset = data.getLayout('offset');
  35762. var size = data.getLayout('size');
  35763. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  35764. pt[offsetIndex] += offset + size / 2;
  35765. return pt;
  35766. }
  35767. return [NaN, NaN];
  35768. },
  35769. defaultOption: {
  35770. zlevel: 0, // 一级层叠
  35771. z: 2, // 二级层叠
  35772. coordinateSystem: 'cartesian2d',
  35773. legendHoverLink: true,
  35774. // stack: null
  35775. // Cartesian coordinate system
  35776. // xAxisIndex: 0,
  35777. // yAxisIndex: 0,
  35778. // 最小高度改为0
  35779. barMinHeight: 0,
  35780. // 最小角度为0,仅对极坐标系下的柱状图有效
  35781. barMinAngle: 0,
  35782. // cursor: null,
  35783. large: false,
  35784. largeThreshold: 400,
  35785. progressive: 3e3,
  35786. progressiveChunkMode: 'mod',
  35787. // barMaxWidth: null,
  35788. // 默认自适应
  35789. // barWidth: null,
  35790. // 柱间距离,默认为柱形宽度的30%,可设固定值
  35791. // barGap: '30%',
  35792. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  35793. // barCategoryGap: '20%',
  35794. // label: {
  35795. // show: false
  35796. // },
  35797. itemStyle: {},
  35798. emphasis: {}
  35799. }
  35800. });
  35801. /*
  35802. * Licensed to the Apache Software Foundation (ASF) under one
  35803. * or more contributor license agreements. See the NOTICE file
  35804. * distributed with this work for additional information
  35805. * regarding copyright ownership. The ASF licenses this file
  35806. * to you under the Apache License, Version 2.0 (the
  35807. * "License"); you may not use this file except in compliance
  35808. * with the License. You may obtain a copy of the License at
  35809. *
  35810. * http://www.apache.org/licenses/LICENSE-2.0
  35811. *
  35812. * Unless required by applicable law or agreed to in writing,
  35813. * software distributed under the License is distributed on an
  35814. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35815. * KIND, either express or implied. See the License for the
  35816. * specific language governing permissions and limitations
  35817. * under the License.
  35818. */
  35819. BaseBarSeries.extend({
  35820. type: 'series.bar',
  35821. dependencies: ['grid', 'polar'],
  35822. brushSelector: 'rect',
  35823. /**
  35824. * @override
  35825. */
  35826. getProgressive: function () {
  35827. // Do not support progressive in normal mode.
  35828. return this.get('large')
  35829. ? this.get('progressive')
  35830. : false;
  35831. },
  35832. /**
  35833. * @override
  35834. */
  35835. getProgressiveThreshold: function () {
  35836. // Do not support progressive in normal mode.
  35837. var progressiveThreshold = this.get('progressiveThreshold');
  35838. var largeThreshold = this.get('largeThreshold');
  35839. if (largeThreshold > progressiveThreshold) {
  35840. progressiveThreshold = largeThreshold;
  35841. }
  35842. return progressiveThreshold;
  35843. }
  35844. });
  35845. /*
  35846. * Licensed to the Apache Software Foundation (ASF) under one
  35847. * or more contributor license agreements. See the NOTICE file
  35848. * distributed with this work for additional information
  35849. * regarding copyright ownership. The ASF licenses this file
  35850. * to you under the Apache License, Version 2.0 (the
  35851. * "License"); you may not use this file except in compliance
  35852. * with the License. You may obtain a copy of the License at
  35853. *
  35854. * http://www.apache.org/licenses/LICENSE-2.0
  35855. *
  35856. * Unless required by applicable law or agreed to in writing,
  35857. * software distributed under the License is distributed on an
  35858. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35859. * KIND, either express or implied. See the License for the
  35860. * specific language governing permissions and limitations
  35861. * under the License.
  35862. */
  35863. function setLabel(
  35864. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  35865. ) {
  35866. var labelModel = itemModel.getModel('label');
  35867. var hoverLabelModel = itemModel.getModel('emphasis.label');
  35868. setLabelStyle(
  35869. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  35870. {
  35871. labelFetcher: seriesModel,
  35872. labelDataIndex: dataIndex,
  35873. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  35874. isRectText: true,
  35875. autoColor: color
  35876. }
  35877. );
  35878. fixPosition(normalStyle);
  35879. fixPosition(hoverStyle);
  35880. }
  35881. function fixPosition(style, labelPositionOutside) {
  35882. if (style.textPosition === 'outside') {
  35883. style.textPosition = labelPositionOutside;
  35884. }
  35885. }
  35886. /*
  35887. * Licensed to the Apache Software Foundation (ASF) under one
  35888. * or more contributor license agreements. See the NOTICE file
  35889. * distributed with this work for additional information
  35890. * regarding copyright ownership. The ASF licenses this file
  35891. * to you under the Apache License, Version 2.0 (the
  35892. * "License"); you may not use this file except in compliance
  35893. * with the License. You may obtain a copy of the License at
  35894. *
  35895. * http://www.apache.org/licenses/LICENSE-2.0
  35896. *
  35897. * Unless required by applicable law or agreed to in writing,
  35898. * software distributed under the License is distributed on an
  35899. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35900. * KIND, either express or implied. See the License for the
  35901. * specific language governing permissions and limitations
  35902. * under the License.
  35903. */
  35904. var getBarItemStyle = makeStyleMapper(
  35905. [
  35906. ['fill', 'color'],
  35907. ['stroke', 'borderColor'],
  35908. ['lineWidth', 'borderWidth'],
  35909. // Compatitable with 2
  35910. ['stroke', 'barBorderColor'],
  35911. ['lineWidth', 'barBorderWidth'],
  35912. ['opacity'],
  35913. ['shadowBlur'],
  35914. ['shadowOffsetX'],
  35915. ['shadowOffsetY'],
  35916. ['shadowColor']
  35917. ]
  35918. );
  35919. var barItemStyle = {
  35920. getBarItemStyle: function (excludes) {
  35921. var style = getBarItemStyle(this, excludes);
  35922. if (this.getBorderLineDash) {
  35923. var lineDash = this.getBorderLineDash();
  35924. lineDash && (style.lineDash = lineDash);
  35925. }
  35926. return style;
  35927. }
  35928. };
  35929. /*
  35930. * Licensed to the Apache Software Foundation (ASF) under one
  35931. * or more contributor license agreements. See the NOTICE file
  35932. * distributed with this work for additional information
  35933. * regarding copyright ownership. The ASF licenses this file
  35934. * to you under the Apache License, Version 2.0 (the
  35935. * "License"); you may not use this file except in compliance
  35936. * with the License. You may obtain a copy of the License at
  35937. *
  35938. * http://www.apache.org/licenses/LICENSE-2.0
  35939. *
  35940. * Unless required by applicable law or agreed to in writing,
  35941. * software distributed under the License is distributed on an
  35942. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35943. * KIND, either express or implied. See the License for the
  35944. * specific language governing permissions and limitations
  35945. * under the License.
  35946. */
  35947. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  35948. // FIXME
  35949. // Just for compatible with ec2.
  35950. extend(Model.prototype, barItemStyle);
  35951. extendChartView({
  35952. type: 'bar',
  35953. render: function (seriesModel, ecModel, api) {
  35954. this._updateDrawMode(seriesModel);
  35955. var coordinateSystemType = seriesModel.get('coordinateSystem');
  35956. if (coordinateSystemType === 'cartesian2d'
  35957. || coordinateSystemType === 'polar'
  35958. ) {
  35959. this._isLargeDraw
  35960. ? this._renderLarge(seriesModel, ecModel, api)
  35961. : this._renderNormal(seriesModel, ecModel, api);
  35962. }
  35963. else if (__DEV__) {
  35964. console.warn('Only cartesian2d and polar supported for bar.');
  35965. }
  35966. return this.group;
  35967. },
  35968. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  35969. this._clear();
  35970. this._updateDrawMode(seriesModel);
  35971. },
  35972. incrementalRender: function (params, seriesModel, ecModel, api) {
  35973. // Do not support progressive in normal mode.
  35974. this._incrementalRenderLarge(params, seriesModel);
  35975. },
  35976. _updateDrawMode: function (seriesModel) {
  35977. var isLargeDraw = seriesModel.pipelineContext.large;
  35978. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  35979. this._isLargeDraw = isLargeDraw;
  35980. this._clear();
  35981. }
  35982. },
  35983. _renderNormal: function (seriesModel, ecModel, api) {
  35984. var group = this.group;
  35985. var data = seriesModel.getData();
  35986. var oldData = this._data;
  35987. var coord = seriesModel.coordinateSystem;
  35988. var baseAxis = coord.getBaseAxis();
  35989. var isHorizontalOrRadial;
  35990. if (coord.type === 'cartesian2d') {
  35991. isHorizontalOrRadial = baseAxis.isHorizontal();
  35992. }
  35993. else if (coord.type === 'polar') {
  35994. isHorizontalOrRadial = baseAxis.dim === 'angle';
  35995. }
  35996. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  35997. data.diff(oldData)
  35998. .add(function (dataIndex) {
  35999. if (!data.hasValue(dataIndex)) {
  36000. return;
  36001. }
  36002. var itemModel = data.getItemModel(dataIndex);
  36003. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  36004. var el = elementCreator[coord.type](
  36005. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  36006. );
  36007. data.setItemGraphicEl(dataIndex, el);
  36008. group.add(el);
  36009. updateStyle(
  36010. el, data, dataIndex, itemModel, layout,
  36011. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36012. );
  36013. })
  36014. .update(function (newIndex, oldIndex) {
  36015. var el = oldData.getItemGraphicEl(oldIndex);
  36016. if (!data.hasValue(newIndex)) {
  36017. group.remove(el);
  36018. return;
  36019. }
  36020. var itemModel = data.getItemModel(newIndex);
  36021. var layout = getLayout[coord.type](data, newIndex, itemModel);
  36022. if (el) {
  36023. updateProps(el, {shape: layout}, animationModel, newIndex);
  36024. }
  36025. else {
  36026. el = elementCreator[coord.type](
  36027. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  36028. );
  36029. }
  36030. data.setItemGraphicEl(newIndex, el);
  36031. // Add back
  36032. group.add(el);
  36033. updateStyle(
  36034. el, data, newIndex, itemModel, layout,
  36035. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36036. );
  36037. })
  36038. .remove(function (dataIndex) {
  36039. var el = oldData.getItemGraphicEl(dataIndex);
  36040. if (coord.type === 'cartesian2d') {
  36041. el && removeRect(dataIndex, animationModel, el);
  36042. }
  36043. else {
  36044. el && removeSector(dataIndex, animationModel, el);
  36045. }
  36046. })
  36047. .execute();
  36048. this._data = data;
  36049. },
  36050. _renderLarge: function (seriesModel, ecModel, api) {
  36051. this._clear();
  36052. createLarge(seriesModel, this.group);
  36053. },
  36054. _incrementalRenderLarge: function (params, seriesModel) {
  36055. createLarge(seriesModel, this.group, true);
  36056. },
  36057. dispose: noop,
  36058. remove: function (ecModel) {
  36059. this._clear(ecModel);
  36060. },
  36061. _clear: function (ecModel) {
  36062. var group = this.group;
  36063. var data = this._data;
  36064. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  36065. data.eachItemGraphicEl(function (el) {
  36066. if (el.type === 'sector') {
  36067. removeSector(el.dataIndex, ecModel, el);
  36068. }
  36069. else {
  36070. removeRect(el.dataIndex, ecModel, el);
  36071. }
  36072. });
  36073. }
  36074. else {
  36075. group.removeAll();
  36076. }
  36077. this._data = null;
  36078. }
  36079. });
  36080. var elementCreator = {
  36081. cartesian2d: function (
  36082. data, dataIndex, itemModel, layout, isHorizontal,
  36083. animationModel, isUpdate
  36084. ) {
  36085. var rect = new Rect({shape: extend({}, layout)});
  36086. // Animation
  36087. if (animationModel) {
  36088. var rectShape = rect.shape;
  36089. var animateProperty = isHorizontal ? 'height' : 'width';
  36090. var animateTarget = {};
  36091. rectShape[animateProperty] = 0;
  36092. animateTarget[animateProperty] = layout[animateProperty];
  36093. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  36094. shape: animateTarget
  36095. }, animationModel, dataIndex);
  36096. }
  36097. return rect;
  36098. },
  36099. polar: function (
  36100. data, dataIndex, itemModel, layout, isRadial,
  36101. animationModel, isUpdate
  36102. ) {
  36103. // Keep the same logic with bar in catesion: use end value to control
  36104. // direction. Notice that if clockwise is true (by default), the sector
  36105. // will always draw clockwisely, no matter whether endAngle is greater
  36106. // or less than startAngle.
  36107. var clockwise = layout.startAngle < layout.endAngle;
  36108. var sector = new Sector({
  36109. shape: defaults({clockwise: clockwise}, layout)
  36110. });
  36111. // Animation
  36112. if (animationModel) {
  36113. var sectorShape = sector.shape;
  36114. var animateProperty = isRadial ? 'r' : 'endAngle';
  36115. var animateTarget = {};
  36116. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  36117. animateTarget[animateProperty] = layout[animateProperty];
  36118. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  36119. shape: animateTarget
  36120. }, animationModel, dataIndex);
  36121. }
  36122. return sector;
  36123. }
  36124. };
  36125. function removeRect(dataIndex, animationModel, el) {
  36126. // Not show text when animating
  36127. el.style.text = null;
  36128. updateProps(el, {
  36129. shape: {
  36130. width: 0
  36131. }
  36132. }, animationModel, dataIndex, function () {
  36133. el.parent && el.parent.remove(el);
  36134. });
  36135. }
  36136. function removeSector(dataIndex, animationModel, el) {
  36137. // Not show text when animating
  36138. el.style.text = null;
  36139. updateProps(el, {
  36140. shape: {
  36141. r: el.shape.r0
  36142. }
  36143. }, animationModel, dataIndex, function () {
  36144. el.parent && el.parent.remove(el);
  36145. });
  36146. }
  36147. var getLayout = {
  36148. cartesian2d: function (data, dataIndex, itemModel) {
  36149. var layout = data.getItemLayout(dataIndex);
  36150. var fixedLineWidth = getLineWidth(itemModel, layout);
  36151. // fix layout with lineWidth
  36152. var signX = layout.width > 0 ? 1 : -1;
  36153. var signY = layout.height > 0 ? 1 : -1;
  36154. return {
  36155. x: layout.x + signX * fixedLineWidth / 2,
  36156. y: layout.y + signY * fixedLineWidth / 2,
  36157. width: layout.width - signX * fixedLineWidth,
  36158. height: layout.height - signY * fixedLineWidth
  36159. };
  36160. },
  36161. polar: function (data, dataIndex, itemModel) {
  36162. var layout = data.getItemLayout(dataIndex);
  36163. return {
  36164. cx: layout.cx,
  36165. cy: layout.cy,
  36166. r0: layout.r0,
  36167. r: layout.r,
  36168. startAngle: layout.startAngle,
  36169. endAngle: layout.endAngle
  36170. };
  36171. }
  36172. };
  36173. function updateStyle(
  36174. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  36175. ) {
  36176. var color = data.getItemVisual(dataIndex, 'color');
  36177. var opacity = data.getItemVisual(dataIndex, 'opacity');
  36178. var itemStyleModel = itemModel.getModel('itemStyle');
  36179. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  36180. if (!isPolar) {
  36181. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  36182. }
  36183. el.useStyle(defaults(
  36184. {
  36185. fill: color,
  36186. opacity: opacity
  36187. },
  36188. itemStyleModel.getBarItemStyle()
  36189. ));
  36190. var cursorStyle = itemModel.getShallow('cursor');
  36191. cursorStyle && el.attr('cursor', cursorStyle);
  36192. var labelPositionOutside = isHorizontal
  36193. ? (layout.height > 0 ? 'bottom' : 'top')
  36194. : (layout.width > 0 ? 'left' : 'right');
  36195. if (!isPolar) {
  36196. setLabel(
  36197. el.style, hoverStyle, itemModel, color,
  36198. seriesModel, dataIndex, labelPositionOutside
  36199. );
  36200. }
  36201. setHoverStyle(el, hoverStyle);
  36202. }
  36203. // In case width or height are too small.
  36204. function getLineWidth(itemModel, rawLayout) {
  36205. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  36206. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  36207. }
  36208. var LargePath = Path.extend({
  36209. type: 'largeBar',
  36210. shape: {points: []},
  36211. buildPath: function (ctx, shape) {
  36212. // Drawing lines is more efficient than drawing
  36213. // a whole line or drawing rects.
  36214. var points = shape.points;
  36215. var startPoint = this.__startPoint;
  36216. var valueIdx = this.__valueIdx;
  36217. for (var i = 0; i < points.length; i += 2) {
  36218. startPoint[this.__valueIdx] = points[i + valueIdx];
  36219. ctx.moveTo(startPoint[0], startPoint[1]);
  36220. ctx.lineTo(points[i], points[i + 1]);
  36221. }
  36222. }
  36223. });
  36224. function createLarge(seriesModel, group, incremental) {
  36225. // TODO support polar
  36226. var data = seriesModel.getData();
  36227. var startPoint = [];
  36228. var valueIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  36229. startPoint[1 - valueIdx] = data.getLayout('valueAxisStart');
  36230. var el = new LargePath({
  36231. shape: {points: data.getLayout('largePoints')},
  36232. incremental: !!incremental,
  36233. __startPoint: startPoint,
  36234. __valueIdx: valueIdx
  36235. });
  36236. group.add(el);
  36237. setLargeStyle(el, seriesModel, data);
  36238. }
  36239. function setLargeStyle(el, seriesModel, data) {
  36240. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  36241. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  36242. el.useStyle(itemStyle);
  36243. el.style.fill = null;
  36244. el.style.stroke = borderColor;
  36245. el.style.lineWidth = data.getLayout('barWidth');
  36246. }
  36247. /*
  36248. * Licensed to the Apache Software Foundation (ASF) under one
  36249. * or more contributor license agreements. See the NOTICE file
  36250. * distributed with this work for additional information
  36251. * regarding copyright ownership. The ASF licenses this file
  36252. * to you under the Apache License, Version 2.0 (the
  36253. * "License"); you may not use this file except in compliance
  36254. * with the License. You may obtain a copy of the License at
  36255. *
  36256. * http://www.apache.org/licenses/LICENSE-2.0
  36257. *
  36258. * Unless required by applicable law or agreed to in writing,
  36259. * software distributed under the License is distributed on an
  36260. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36261. * KIND, either express or implied. See the License for the
  36262. * specific language governing permissions and limitations
  36263. * under the License.
  36264. */
  36265. // In case developer forget to include grid component
  36266. registerLayout(curry(layout, 'bar'));
  36267. // Should after normal bar layout, otherwise it is blocked by normal bar layout.
  36268. registerLayout(largeLayout);
  36269. registerVisual({
  36270. seriesType: 'bar',
  36271. reset: function (seriesModel) {
  36272. // Visual coding for legend
  36273. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  36274. }
  36275. });
  36276. /*
  36277. * Licensed to the Apache Software Foundation (ASF) under one
  36278. * or more contributor license agreements. See the NOTICE file
  36279. * distributed with this work for additional information
  36280. * regarding copyright ownership. The ASF licenses this file
  36281. * to you under the Apache License, Version 2.0 (the
  36282. * "License"); you may not use this file except in compliance
  36283. * with the License. You may obtain a copy of the License at
  36284. *
  36285. * http://www.apache.org/licenses/LICENSE-2.0
  36286. *
  36287. * Unless required by applicable law or agreed to in writing,
  36288. * software distributed under the License is distributed on an
  36289. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36290. * KIND, either express or implied. See the License for the
  36291. * specific language governing permissions and limitations
  36292. * under the License.
  36293. */
  36294. /**
  36295. * [Usage]:
  36296. * (1)
  36297. * createListSimply(seriesModel, ['value']);
  36298. * (2)
  36299. * createListSimply(seriesModel, {
  36300. * coordDimensions: ['value'],
  36301. * dimensionsCount: 5
  36302. * });
  36303. *
  36304. * @param {module:echarts/model/Series} seriesModel
  36305. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  36306. * The options in opt, see `echarts/data/helper/createDimensions`
  36307. * @param {Array.<string>} [nameList]
  36308. * @return {module:echarts/data/List}
  36309. */
  36310. var createListSimply = function (seriesModel, opt, nameList) {
  36311. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  36312. var source = seriesModel.getSource();
  36313. var dimensionsInfo = createDimensions(source, opt);
  36314. var list = new List(dimensionsInfo, seriesModel);
  36315. list.initData(source, nameList);
  36316. return list;
  36317. };
  36318. /*
  36319. * Licensed to the Apache Software Foundation (ASF) under one
  36320. * or more contributor license agreements. See the NOTICE file
  36321. * distributed with this work for additional information
  36322. * regarding copyright ownership. The ASF licenses this file
  36323. * to you under the Apache License, Version 2.0 (the
  36324. * "License"); you may not use this file except in compliance
  36325. * with the License. You may obtain a copy of the License at
  36326. *
  36327. * http://www.apache.org/licenses/LICENSE-2.0
  36328. *
  36329. * Unless required by applicable law or agreed to in writing,
  36330. * software distributed under the License is distributed on an
  36331. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36332. * KIND, either express or implied. See the License for the
  36333. * specific language governing permissions and limitations
  36334. * under the License.
  36335. */
  36336. /**
  36337. * Data selectable mixin for chart series.
  36338. * To eanble data select, option of series must have `selectedMode`.
  36339. * And each data item will use `selected` to toggle itself selected status
  36340. */
  36341. var dataSelectableMixin = {
  36342. /**
  36343. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  36344. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  36345. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  36346. */
  36347. updateSelectedMap: function (targetList) {
  36348. this._targetList = isArray(targetList) ? targetList.slice() : [];
  36349. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  36350. targetMap.set(target.name, target);
  36351. return targetMap;
  36352. }, createHashMap());
  36353. },
  36354. /**
  36355. * Either name or id should be passed as input here.
  36356. * If both of them are defined, id is used.
  36357. *
  36358. * @param {string|undefined} name name of data
  36359. * @param {number|undefined} id dataIndex of data
  36360. */
  36361. // PENGING If selectedMode is null ?
  36362. select: function (name, id) {
  36363. var target = id != null
  36364. ? this._targetList[id]
  36365. : this._selectTargetMap.get(name);
  36366. var selectedMode = this.get('selectedMode');
  36367. if (selectedMode === 'single') {
  36368. this._selectTargetMap.each(function (target) {
  36369. target.selected = false;
  36370. });
  36371. }
  36372. target && (target.selected = true);
  36373. },
  36374. /**
  36375. * Either name or id should be passed as input here.
  36376. * If both of them are defined, id is used.
  36377. *
  36378. * @param {string|undefined} name name of data
  36379. * @param {number|undefined} id dataIndex of data
  36380. */
  36381. unSelect: function (name, id) {
  36382. var target = id != null
  36383. ? this._targetList[id]
  36384. : this._selectTargetMap.get(name);
  36385. // var selectedMode = this.get('selectedMode');
  36386. // selectedMode !== 'single' && target && (target.selected = false);
  36387. target && (target.selected = false);
  36388. },
  36389. /**
  36390. * Either name or id should be passed as input here.
  36391. * If both of them are defined, id is used.
  36392. *
  36393. * @param {string|undefined} name name of data
  36394. * @param {number|undefined} id dataIndex of data
  36395. */
  36396. toggleSelected: function (name, id) {
  36397. var target = id != null
  36398. ? this._targetList[id]
  36399. : this._selectTargetMap.get(name);
  36400. if (target != null) {
  36401. this[target.selected ? 'unSelect' : 'select'](name, id);
  36402. return target.selected;
  36403. }
  36404. },
  36405. /**
  36406. * Either name or id should be passed as input here.
  36407. * If both of them are defined, id is used.
  36408. *
  36409. * @param {string|undefined} name name of data
  36410. * @param {number|undefined} id dataIndex of data
  36411. */
  36412. isSelected: function (name, id) {
  36413. var target = id != null
  36414. ? this._targetList[id]
  36415. : this._selectTargetMap.get(name);
  36416. return target && target.selected;
  36417. }
  36418. };
  36419. /*
  36420. * Licensed to the Apache Software Foundation (ASF) under one
  36421. * or more contributor license agreements. See the NOTICE file
  36422. * distributed with this work for additional information
  36423. * regarding copyright ownership. The ASF licenses this file
  36424. * to you under the Apache License, Version 2.0 (the
  36425. * "License"); you may not use this file except in compliance
  36426. * with the License. You may obtain a copy of the License at
  36427. *
  36428. * http://www.apache.org/licenses/LICENSE-2.0
  36429. *
  36430. * Unless required by applicable law or agreed to in writing,
  36431. * software distributed under the License is distributed on an
  36432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36433. * KIND, either express or implied. See the License for the
  36434. * specific language governing permissions and limitations
  36435. * under the License.
  36436. */
  36437. var PieSeries = extendSeriesModel({
  36438. type: 'series.pie',
  36439. // Overwrite
  36440. init: function (option) {
  36441. PieSeries.superApply(this, 'init', arguments);
  36442. // Enable legend selection for each data item
  36443. // Use a function instead of direct access because data reference may changed
  36444. this.legendDataProvider = function () {
  36445. return this.getRawData();
  36446. };
  36447. this.updateSelectedMap(this._createSelectableList());
  36448. this._defaultLabelLine(option);
  36449. },
  36450. // Overwrite
  36451. mergeOption: function (newOption) {
  36452. PieSeries.superCall(this, 'mergeOption', newOption);
  36453. this.updateSelectedMap(this._createSelectableList());
  36454. },
  36455. getInitialData: function (option, ecModel) {
  36456. return createListSimply(this, ['value']);
  36457. },
  36458. _createSelectableList: function () {
  36459. var data = this.getRawData();
  36460. var valueDim = data.mapDimension('value');
  36461. var targetList = [];
  36462. for (var i = 0, len = data.count(); i < len; i++) {
  36463. targetList.push({
  36464. name: data.getName(i),
  36465. value: data.get(valueDim, i),
  36466. selected: retrieveRawAttr(data, i, 'selected')
  36467. });
  36468. }
  36469. return targetList;
  36470. },
  36471. // Overwrite
  36472. getDataParams: function (dataIndex) {
  36473. var data = this.getData();
  36474. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  36475. // FIXME toFixed?
  36476. var valueList = [];
  36477. data.each(data.mapDimension('value'), function (value) {
  36478. valueList.push(value);
  36479. });
  36480. params.percent = getPercentWithPrecision(
  36481. valueList,
  36482. dataIndex,
  36483. data.hostModel.get('percentPrecision')
  36484. );
  36485. params.$vars.push('percent');
  36486. return params;
  36487. },
  36488. _defaultLabelLine: function (option) {
  36489. // Extend labelLine emphasis
  36490. defaultEmphasis(option, 'labelLine', ['show']);
  36491. var labelLineNormalOpt = option.labelLine;
  36492. var labelLineEmphasisOpt = option.emphasis.labelLine;
  36493. // Not show label line if `label.normal.show = false`
  36494. labelLineNormalOpt.show = labelLineNormalOpt.show
  36495. && option.label.show;
  36496. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  36497. && option.emphasis.label.show;
  36498. },
  36499. defaultOption: {
  36500. zlevel: 0,
  36501. z: 2,
  36502. legendHoverLink: true,
  36503. hoverAnimation: true,
  36504. // 默认全局居中
  36505. center: ['50%', '50%'],
  36506. radius: [0, '75%'],
  36507. // 默认顺时针
  36508. clockwise: true,
  36509. startAngle: 90,
  36510. // 最小角度改为0
  36511. minAngle: 0,
  36512. // 选中时扇区偏移量
  36513. selectedOffset: 10,
  36514. // 高亮扇区偏移量
  36515. hoverOffset: 10,
  36516. // If use strategy to avoid label overlapping
  36517. avoidLabelOverlap: true,
  36518. // 选择模式,默认关闭,可选single,multiple
  36519. // selectedMode: false,
  36520. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  36521. // roseType: null,
  36522. percentPrecision: 2,
  36523. // If still show when all data zero.
  36524. stillShowZeroSum: true,
  36525. // cursor: null,
  36526. label: {
  36527. // If rotate around circle
  36528. rotate: false,
  36529. show: true,
  36530. // 'outer', 'inside', 'center'
  36531. position: 'outer'
  36532. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  36533. // 默认使用全局文本样式,详见TEXTSTYLE
  36534. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  36535. },
  36536. // Enabled when label.normal.position is 'outer'
  36537. labelLine: {
  36538. show: true,
  36539. // 引导线两段中的第一段长度
  36540. length: 15,
  36541. // 引导线两段中的第二段长度
  36542. length2: 15,
  36543. smooth: false,
  36544. lineStyle: {
  36545. // color: 各异,
  36546. width: 1,
  36547. type: 'solid'
  36548. }
  36549. },
  36550. itemStyle: {
  36551. borderWidth: 1
  36552. },
  36553. // Animation type canbe expansion, scale
  36554. animationType: 'expansion',
  36555. animationEasing: 'cubicOut'
  36556. }
  36557. });
  36558. mixin(PieSeries, dataSelectableMixin);
  36559. /*
  36560. * Licensed to the Apache Software Foundation (ASF) under one
  36561. * or more contributor license agreements. See the NOTICE file
  36562. * distributed with this work for additional information
  36563. * regarding copyright ownership. The ASF licenses this file
  36564. * to you under the Apache License, Version 2.0 (the
  36565. * "License"); you may not use this file except in compliance
  36566. * with the License. You may obtain a copy of the License at
  36567. *
  36568. * http://www.apache.org/licenses/LICENSE-2.0
  36569. *
  36570. * Unless required by applicable law or agreed to in writing,
  36571. * software distributed under the License is distributed on an
  36572. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36573. * KIND, either express or implied. See the License for the
  36574. * specific language governing permissions and limitations
  36575. * under the License.
  36576. */
  36577. /**
  36578. * @param {module:echarts/model/Series} seriesModel
  36579. * @param {boolean} hasAnimation
  36580. * @inner
  36581. */
  36582. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  36583. var data = seriesModel.getData();
  36584. var dataIndex = this.dataIndex;
  36585. var name = data.getName(dataIndex);
  36586. var selectedOffset = seriesModel.get('selectedOffset');
  36587. api.dispatchAction({
  36588. type: 'pieToggleSelect',
  36589. from: uid,
  36590. name: name,
  36591. seriesId: seriesModel.id
  36592. });
  36593. data.each(function (idx) {
  36594. toggleItemSelected(
  36595. data.getItemGraphicEl(idx),
  36596. data.getItemLayout(idx),
  36597. seriesModel.isSelected(data.getName(idx)),
  36598. selectedOffset,
  36599. hasAnimation
  36600. );
  36601. });
  36602. }
  36603. /**
  36604. * @param {module:zrender/graphic/Sector} el
  36605. * @param {Object} layout
  36606. * @param {boolean} isSelected
  36607. * @param {number} selectedOffset
  36608. * @param {boolean} hasAnimation
  36609. * @inner
  36610. */
  36611. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  36612. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  36613. var dx = Math.cos(midAngle);
  36614. var dy = Math.sin(midAngle);
  36615. var offset = isSelected ? selectedOffset : 0;
  36616. var position = [dx * offset, dy * offset];
  36617. hasAnimation
  36618. // animateTo will stop revious animation like update transition
  36619. ? el.animate()
  36620. .when(200, {
  36621. position: position
  36622. })
  36623. .start('bounceOut')
  36624. : el.attr('position', position);
  36625. }
  36626. /**
  36627. * Piece of pie including Sector, Label, LabelLine
  36628. * @constructor
  36629. * @extends {module:zrender/graphic/Group}
  36630. */
  36631. function PiePiece(data, idx) {
  36632. Group.call(this);
  36633. var sector = new Sector({
  36634. z2: 2
  36635. });
  36636. var polyline = new Polyline();
  36637. var text = new Text();
  36638. this.add(sector);
  36639. this.add(polyline);
  36640. this.add(text);
  36641. this.updateData(data, idx, true);
  36642. // Hover to change label and labelLine
  36643. function onEmphasis() {
  36644. polyline.ignore = polyline.hoverIgnore;
  36645. text.ignore = text.hoverIgnore;
  36646. }
  36647. function onNormal() {
  36648. polyline.ignore = polyline.normalIgnore;
  36649. text.ignore = text.normalIgnore;
  36650. }
  36651. this.on('emphasis', onEmphasis)
  36652. .on('normal', onNormal)
  36653. .on('mouseover', onEmphasis)
  36654. .on('mouseout', onNormal);
  36655. }
  36656. var piePieceProto = PiePiece.prototype;
  36657. piePieceProto.updateData = function (data, idx, firstCreate) {
  36658. var sector = this.childAt(0);
  36659. var seriesModel = data.hostModel;
  36660. var itemModel = data.getItemModel(idx);
  36661. var layout = data.getItemLayout(idx);
  36662. var sectorShape = extend({}, layout);
  36663. sectorShape.label = null;
  36664. if (firstCreate) {
  36665. sector.setShape(sectorShape);
  36666. var animationType = seriesModel.getShallow('animationType');
  36667. if (animationType === 'scale') {
  36668. sector.shape.r = layout.r0;
  36669. initProps(sector, {
  36670. shape: {
  36671. r: layout.r
  36672. }
  36673. }, seriesModel, idx);
  36674. }
  36675. // Expansion
  36676. else {
  36677. sector.shape.endAngle = layout.startAngle;
  36678. updateProps(sector, {
  36679. shape: {
  36680. endAngle: layout.endAngle
  36681. }
  36682. }, seriesModel, idx);
  36683. }
  36684. }
  36685. else {
  36686. updateProps(sector, {
  36687. shape: sectorShape
  36688. }, seriesModel, idx);
  36689. }
  36690. // Update common style
  36691. var visualColor = data.getItemVisual(idx, 'color');
  36692. sector.useStyle(
  36693. defaults(
  36694. {
  36695. lineJoin: 'bevel',
  36696. fill: visualColor
  36697. },
  36698. itemModel.getModel('itemStyle').getItemStyle()
  36699. )
  36700. );
  36701. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36702. var cursorStyle = itemModel.getShallow('cursor');
  36703. cursorStyle && sector.attr('cursor', cursorStyle);
  36704. // Toggle selected
  36705. toggleItemSelected(
  36706. this,
  36707. data.getItemLayout(idx),
  36708. seriesModel.isSelected(null, idx),
  36709. seriesModel.get('selectedOffset'),
  36710. seriesModel.get('animation')
  36711. );
  36712. function onEmphasis() {
  36713. // Sector may has animation of updating data. Force to move to the last frame
  36714. // Or it may stopped on the wrong shape
  36715. sector.stopAnimation(true);
  36716. sector.animateTo({
  36717. shape: {
  36718. r: layout.r + seriesModel.get('hoverOffset')
  36719. }
  36720. }, 300, 'elasticOut');
  36721. }
  36722. function onNormal() {
  36723. sector.stopAnimation(true);
  36724. sector.animateTo({
  36725. shape: {
  36726. r: layout.r
  36727. }
  36728. }, 300, 'elasticOut');
  36729. }
  36730. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  36731. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  36732. sector
  36733. .on('mouseover', onEmphasis)
  36734. .on('mouseout', onNormal)
  36735. .on('emphasis', onEmphasis)
  36736. .on('normal', onNormal);
  36737. }
  36738. this._updateLabel(data, idx);
  36739. setHoverStyle(this);
  36740. };
  36741. piePieceProto._updateLabel = function (data, idx) {
  36742. var labelLine = this.childAt(1);
  36743. var labelText = this.childAt(2);
  36744. var seriesModel = data.hostModel;
  36745. var itemModel = data.getItemModel(idx);
  36746. var layout = data.getItemLayout(idx);
  36747. var labelLayout = layout.label;
  36748. var visualColor = data.getItemVisual(idx, 'color');
  36749. updateProps(labelLine, {
  36750. shape: {
  36751. points: labelLayout.linePoints || [
  36752. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  36753. ]
  36754. }
  36755. }, seriesModel, idx);
  36756. updateProps(labelText, {
  36757. style: {
  36758. x: labelLayout.x,
  36759. y: labelLayout.y
  36760. }
  36761. }, seriesModel, idx);
  36762. labelText.attr({
  36763. rotation: labelLayout.rotation,
  36764. origin: [labelLayout.x, labelLayout.y],
  36765. z2: 10
  36766. });
  36767. var labelModel = itemModel.getModel('label');
  36768. var labelHoverModel = itemModel.getModel('emphasis.label');
  36769. var labelLineModel = itemModel.getModel('labelLine');
  36770. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  36771. var visualColor = data.getItemVisual(idx, 'color');
  36772. setLabelStyle(
  36773. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  36774. {
  36775. labelFetcher: data.hostModel,
  36776. labelDataIndex: idx,
  36777. defaultText: data.getName(idx),
  36778. autoColor: visualColor,
  36779. useInsideStyle: !!labelLayout.inside
  36780. },
  36781. {
  36782. textAlign: labelLayout.textAlign,
  36783. textVerticalAlign: labelLayout.verticalAlign,
  36784. opacity: data.getItemVisual(idx, 'opacity')
  36785. }
  36786. );
  36787. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  36788. labelText.hoverIgnore = !labelHoverModel.get('show');
  36789. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  36790. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  36791. // Default use item visual color
  36792. labelLine.setStyle({
  36793. stroke: visualColor,
  36794. opacity: data.getItemVisual(idx, 'opacity')
  36795. });
  36796. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  36797. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  36798. var smooth = labelLineModel.get('smooth');
  36799. if (smooth && smooth === true) {
  36800. smooth = 0.4;
  36801. }
  36802. labelLine.setShape({
  36803. smooth: smooth
  36804. });
  36805. };
  36806. inherits(PiePiece, Group);
  36807. // Pie view
  36808. var PieView = Chart.extend({
  36809. type: 'pie',
  36810. init: function () {
  36811. var sectorGroup = new Group();
  36812. this._sectorGroup = sectorGroup;
  36813. },
  36814. render: function (seriesModel, ecModel, api, payload) {
  36815. if (payload && (payload.from === this.uid)) {
  36816. return;
  36817. }
  36818. var data = seriesModel.getData();
  36819. var oldData = this._data;
  36820. var group = this.group;
  36821. var hasAnimation = ecModel.get('animation');
  36822. var isFirstRender = !oldData;
  36823. var animationType = seriesModel.get('animationType');
  36824. var onSectorClick = curry(
  36825. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  36826. );
  36827. var selectedMode = seriesModel.get('selectedMode');
  36828. data.diff(oldData)
  36829. .add(function (idx) {
  36830. var piePiece = new PiePiece(data, idx);
  36831. // Default expansion animation
  36832. if (isFirstRender && animationType !== 'scale') {
  36833. piePiece.eachChild(function (child) {
  36834. child.stopAnimation(true);
  36835. });
  36836. }
  36837. selectedMode && piePiece.on('click', onSectorClick);
  36838. data.setItemGraphicEl(idx, piePiece);
  36839. group.add(piePiece);
  36840. })
  36841. .update(function (newIdx, oldIdx) {
  36842. var piePiece = oldData.getItemGraphicEl(oldIdx);
  36843. piePiece.updateData(data, newIdx);
  36844. piePiece.off('click');
  36845. selectedMode && piePiece.on('click', onSectorClick);
  36846. group.add(piePiece);
  36847. data.setItemGraphicEl(newIdx, piePiece);
  36848. })
  36849. .remove(function (idx) {
  36850. var piePiece = oldData.getItemGraphicEl(idx);
  36851. group.remove(piePiece);
  36852. })
  36853. .execute();
  36854. if (
  36855. hasAnimation && isFirstRender && data.count() > 0
  36856. // Default expansion animation
  36857. && animationType !== 'scale'
  36858. ) {
  36859. var shape = data.getItemLayout(0);
  36860. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  36861. var removeClipPath = bind(group.removeClipPath, group);
  36862. group.setClipPath(this._createClipPath(
  36863. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  36864. ));
  36865. }
  36866. else {
  36867. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  36868. group.removeClipPath();
  36869. }
  36870. this._data = data;
  36871. },
  36872. dispose: function () {},
  36873. _createClipPath: function (
  36874. cx, cy, r, startAngle, clockwise, cb, seriesModel
  36875. ) {
  36876. var clipPath = new Sector({
  36877. shape: {
  36878. cx: cx,
  36879. cy: cy,
  36880. r0: 0,
  36881. r: r,
  36882. startAngle: startAngle,
  36883. endAngle: startAngle,
  36884. clockwise: clockwise
  36885. }
  36886. });
  36887. initProps(clipPath, {
  36888. shape: {
  36889. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  36890. }
  36891. }, seriesModel, cb);
  36892. return clipPath;
  36893. },
  36894. /**
  36895. * @implement
  36896. */
  36897. containPoint: function (point, seriesModel) {
  36898. var data = seriesModel.getData();
  36899. var itemLayout = data.getItemLayout(0);
  36900. if (itemLayout) {
  36901. var dx = point[0] - itemLayout.cx;
  36902. var dy = point[1] - itemLayout.cy;
  36903. var radius = Math.sqrt(dx * dx + dy * dy);
  36904. return radius <= itemLayout.r && radius >= itemLayout.r0;
  36905. }
  36906. }
  36907. });
  36908. /*
  36909. * Licensed to the Apache Software Foundation (ASF) under one
  36910. * or more contributor license agreements. See the NOTICE file
  36911. * distributed with this work for additional information
  36912. * regarding copyright ownership. The ASF licenses this file
  36913. * to you under the Apache License, Version 2.0 (the
  36914. * "License"); you may not use this file except in compliance
  36915. * with the License. You may obtain a copy of the License at
  36916. *
  36917. * http://www.apache.org/licenses/LICENSE-2.0
  36918. *
  36919. * Unless required by applicable law or agreed to in writing,
  36920. * software distributed under the License is distributed on an
  36921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36922. * KIND, either express or implied. See the License for the
  36923. * specific language governing permissions and limitations
  36924. * under the License.
  36925. */
  36926. var createDataSelectAction = function (seriesType, actionInfos) {
  36927. each$1(actionInfos, function (actionInfo) {
  36928. actionInfo.update = 'updateView';
  36929. /**
  36930. * @payload
  36931. * @property {string} seriesName
  36932. * @property {string} name
  36933. */
  36934. registerAction(actionInfo, function (payload, ecModel) {
  36935. var selected = {};
  36936. ecModel.eachComponent(
  36937. {mainType: 'series', subType: seriesType, query: payload},
  36938. function (seriesModel) {
  36939. if (seriesModel[actionInfo.method]) {
  36940. seriesModel[actionInfo.method](
  36941. payload.name,
  36942. payload.dataIndex
  36943. );
  36944. }
  36945. var data = seriesModel.getData();
  36946. // Create selected map
  36947. data.each(function (idx) {
  36948. var name = data.getName(idx);
  36949. selected[name] = seriesModel.isSelected(name)
  36950. || false;
  36951. });
  36952. }
  36953. );
  36954. return {
  36955. name: payload.name,
  36956. selected: selected
  36957. };
  36958. });
  36959. });
  36960. };
  36961. /*
  36962. * Licensed to the Apache Software Foundation (ASF) under one
  36963. * or more contributor license agreements. See the NOTICE file
  36964. * distributed with this work for additional information
  36965. * regarding copyright ownership. The ASF licenses this file
  36966. * to you under the Apache License, Version 2.0 (the
  36967. * "License"); you may not use this file except in compliance
  36968. * with the License. You may obtain a copy of the License at
  36969. *
  36970. * http://www.apache.org/licenses/LICENSE-2.0
  36971. *
  36972. * Unless required by applicable law or agreed to in writing,
  36973. * software distributed under the License is distributed on an
  36974. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36975. * KIND, either express or implied. See the License for the
  36976. * specific language governing permissions and limitations
  36977. * under the License.
  36978. */
  36979. // Pick color from palette for each data item.
  36980. // Applicable for charts that require applying color palette
  36981. // in data level (like pie, funnel, chord).
  36982. var dataColor = function (seriesType) {
  36983. return {
  36984. getTargetSeries: function (ecModel) {
  36985. // Pie and funnel may use diferrent scope
  36986. var paletteScope = {};
  36987. var seiresModelMap = createHashMap();
  36988. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  36989. seriesModel.__paletteScope = paletteScope;
  36990. seiresModelMap.set(seriesModel.uid, seriesModel);
  36991. });
  36992. return seiresModelMap;
  36993. },
  36994. reset: function (seriesModel, ecModel) {
  36995. var dataAll = seriesModel.getRawData();
  36996. var idxMap = {};
  36997. var data = seriesModel.getData();
  36998. data.each(function (idx) {
  36999. var rawIdx = data.getRawIndex(idx);
  37000. idxMap[rawIdx] = idx;
  37001. });
  37002. dataAll.each(function (rawIdx) {
  37003. var filteredIdx = idxMap[rawIdx];
  37004. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  37005. var singleDataColor = filteredIdx != null
  37006. && data.getItemVisual(filteredIdx, 'color', true);
  37007. if (!singleDataColor) {
  37008. // FIXME Performance
  37009. var itemModel = dataAll.getItemModel(rawIdx);
  37010. var color = itemModel.get('itemStyle.color')
  37011. || seriesModel.getColorFromPalette(
  37012. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  37013. dataAll.count()
  37014. );
  37015. // Legend may use the visual info in data before processed
  37016. dataAll.setItemVisual(rawIdx, 'color', color);
  37017. // Data is not filtered
  37018. if (filteredIdx != null) {
  37019. data.setItemVisual(filteredIdx, 'color', color);
  37020. }
  37021. }
  37022. else {
  37023. // Set data all color for legend
  37024. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  37025. }
  37026. });
  37027. }
  37028. };
  37029. };
  37030. /*
  37031. * Licensed to the Apache Software Foundation (ASF) under one
  37032. * or more contributor license agreements. See the NOTICE file
  37033. * distributed with this work for additional information
  37034. * regarding copyright ownership. The ASF licenses this file
  37035. * to you under the Apache License, Version 2.0 (the
  37036. * "License"); you may not use this file except in compliance
  37037. * with the License. You may obtain a copy of the License at
  37038. *
  37039. * http://www.apache.org/licenses/LICENSE-2.0
  37040. *
  37041. * Unless required by applicable law or agreed to in writing,
  37042. * software distributed under the License is distributed on an
  37043. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37044. * KIND, either express or implied. See the License for the
  37045. * specific language governing permissions and limitations
  37046. * under the License.
  37047. */
  37048. // FIXME emphasis label position is not same with normal label position
  37049. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  37050. list.sort(function (a, b) {
  37051. return a.y - b.y;
  37052. });
  37053. function shiftDown(start, end, delta, dir) {
  37054. for (var j = start; j < end; j++) {
  37055. list[j].y += delta;
  37056. if (j > start
  37057. && j + 1 < end
  37058. && list[j + 1].y > list[j].y + list[j].height
  37059. ) {
  37060. shiftUp(j, delta / 2);
  37061. return;
  37062. }
  37063. }
  37064. shiftUp(end - 1, delta / 2);
  37065. }
  37066. function shiftUp(end, delta) {
  37067. for (var j = end; j >= 0; j--) {
  37068. list[j].y -= delta;
  37069. if (j > 0
  37070. && list[j].y > list[j - 1].y + list[j - 1].height
  37071. ) {
  37072. break;
  37073. }
  37074. }
  37075. }
  37076. function changeX(list, isDownList, cx, cy, r, dir) {
  37077. var lastDeltaX = dir > 0
  37078. ? isDownList // right-side
  37079. ? Number.MAX_VALUE // down
  37080. : 0 // up
  37081. : isDownList // left-side
  37082. ? Number.MAX_VALUE // down
  37083. : 0; // up
  37084. for (var i = 0, l = list.length; i < l; i++) {
  37085. var deltaY = Math.abs(list[i].y - cy);
  37086. var length = list[i].len;
  37087. var length2 = list[i].len2;
  37088. var deltaX = (deltaY < r + length)
  37089. ? Math.sqrt(
  37090. (r + length + length2) * (r + length + length2)
  37091. - deltaY * deltaY
  37092. )
  37093. : Math.abs(list[i].x - cx);
  37094. if (isDownList && deltaX >= lastDeltaX) {
  37095. // right-down, left-down
  37096. deltaX = lastDeltaX - 10;
  37097. }
  37098. if (!isDownList && deltaX <= lastDeltaX) {
  37099. // right-up, left-up
  37100. deltaX = lastDeltaX + 10;
  37101. }
  37102. list[i].x = cx + deltaX * dir;
  37103. lastDeltaX = deltaX;
  37104. }
  37105. }
  37106. var lastY = 0;
  37107. var delta;
  37108. var len = list.length;
  37109. var upList = [];
  37110. var downList = [];
  37111. for (var i = 0; i < len; i++) {
  37112. delta = list[i].y - lastY;
  37113. if (delta < 0) {
  37114. shiftDown(i, len, -delta, dir);
  37115. }
  37116. lastY = list[i].y + list[i].height;
  37117. }
  37118. if (viewHeight - lastY < 0) {
  37119. shiftUp(len - 1, lastY - viewHeight);
  37120. }
  37121. for (var i = 0; i < len; i++) {
  37122. if (list[i].y >= cy) {
  37123. downList.push(list[i]);
  37124. }
  37125. else {
  37126. upList.push(list[i]);
  37127. }
  37128. }
  37129. changeX(upList, false, cx, cy, r, dir);
  37130. changeX(downList, true, cx, cy, r, dir);
  37131. }
  37132. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  37133. var leftList = [];
  37134. var rightList = [];
  37135. for (var i = 0; i < labelLayoutList.length; i++) {
  37136. if (isPositionCenter(labelLayoutList[i])) {
  37137. continue;
  37138. }
  37139. if (labelLayoutList[i].x < cx) {
  37140. leftList.push(labelLayoutList[i]);
  37141. }
  37142. else {
  37143. rightList.push(labelLayoutList[i]);
  37144. }
  37145. }
  37146. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  37147. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  37148. for (var i = 0; i < labelLayoutList.length; i++) {
  37149. if (isPositionCenter(labelLayoutList[i])) {
  37150. continue;
  37151. }
  37152. var linePoints = labelLayoutList[i].linePoints;
  37153. if (linePoints) {
  37154. var dist = linePoints[1][0] - linePoints[2][0];
  37155. if (labelLayoutList[i].x < cx) {
  37156. linePoints[2][0] = labelLayoutList[i].x + 3;
  37157. }
  37158. else {
  37159. linePoints[2][0] = labelLayoutList[i].x - 3;
  37160. }
  37161. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  37162. linePoints[1][0] = linePoints[2][0] + dist;
  37163. }
  37164. }
  37165. }
  37166. function isPositionCenter(layout) {
  37167. // Not change x for center label
  37168. return layout.position === 'center';
  37169. }
  37170. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  37171. var data = seriesModel.getData();
  37172. var labelLayoutList = [];
  37173. var cx;
  37174. var cy;
  37175. var hasLabelRotate = false;
  37176. data.each(function (idx) {
  37177. var layout = data.getItemLayout(idx);
  37178. var itemModel = data.getItemModel(idx);
  37179. var labelModel = itemModel.getModel('label');
  37180. // Use position in normal or emphasis
  37181. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  37182. var labelLineModel = itemModel.getModel('labelLine');
  37183. var labelLineLen = labelLineModel.get('length');
  37184. var labelLineLen2 = labelLineModel.get('length2');
  37185. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  37186. var dx = Math.cos(midAngle);
  37187. var dy = Math.sin(midAngle);
  37188. var textX;
  37189. var textY;
  37190. var linePoints;
  37191. var textAlign;
  37192. cx = layout.cx;
  37193. cy = layout.cy;
  37194. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  37195. if (labelPosition === 'center') {
  37196. textX = layout.cx;
  37197. textY = layout.cy;
  37198. textAlign = 'center';
  37199. }
  37200. else {
  37201. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  37202. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  37203. textX = x1 + dx * 3;
  37204. textY = y1 + dy * 3;
  37205. if (!isLabelInside) {
  37206. // For roseType
  37207. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  37208. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  37209. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  37210. var y3 = y2;
  37211. textX = x3 + (dx < 0 ? -5 : 5);
  37212. textY = y3;
  37213. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  37214. }
  37215. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  37216. }
  37217. var font = labelModel.getFont();
  37218. var labelRotate = labelModel.get('rotate')
  37219. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  37220. var text = seriesModel.getFormattedLabel(idx, 'normal')
  37221. || data.getName(idx);
  37222. var textRect = getBoundingRect(
  37223. text, font, textAlign, 'top'
  37224. );
  37225. hasLabelRotate = !!labelRotate;
  37226. layout.label = {
  37227. x: textX,
  37228. y: textY,
  37229. position: labelPosition,
  37230. height: textRect.height,
  37231. len: labelLineLen,
  37232. len2: labelLineLen2,
  37233. linePoints: linePoints,
  37234. textAlign: textAlign,
  37235. verticalAlign: 'middle',
  37236. rotation: labelRotate,
  37237. inside: isLabelInside
  37238. };
  37239. // Not layout the inside label
  37240. if (!isLabelInside) {
  37241. labelLayoutList.push(layout.label);
  37242. }
  37243. });
  37244. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  37245. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  37246. }
  37247. };
  37248. /*
  37249. * Licensed to the Apache Software Foundation (ASF) under one
  37250. * or more contributor license agreements. See the NOTICE file
  37251. * distributed with this work for additional information
  37252. * regarding copyright ownership. The ASF licenses this file
  37253. * to you under the Apache License, Version 2.0 (the
  37254. * "License"); you may not use this file except in compliance
  37255. * with the License. You may obtain a copy of the License at
  37256. *
  37257. * http://www.apache.org/licenses/LICENSE-2.0
  37258. *
  37259. * Unless required by applicable law or agreed to in writing,
  37260. * software distributed under the License is distributed on an
  37261. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37262. * KIND, either express or implied. See the License for the
  37263. * specific language governing permissions and limitations
  37264. * under the License.
  37265. */
  37266. var PI2$4 = Math.PI * 2;
  37267. var RADIAN = Math.PI / 180;
  37268. var pieLayout = function (seriesType, ecModel, api, payload) {
  37269. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37270. var data = seriesModel.getData();
  37271. var valueDim = data.mapDimension('value');
  37272. var center = seriesModel.get('center');
  37273. var radius = seriesModel.get('radius');
  37274. if (!isArray(radius)) {
  37275. radius = [0, radius];
  37276. }
  37277. if (!isArray(center)) {
  37278. center = [center, center];
  37279. }
  37280. var width = api.getWidth();
  37281. var height = api.getHeight();
  37282. var size = Math.min(width, height);
  37283. var cx = parsePercent$1(center[0], width);
  37284. var cy = parsePercent$1(center[1], height);
  37285. var r0 = parsePercent$1(radius[0], size / 2);
  37286. var r = parsePercent$1(radius[1], size / 2);
  37287. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  37288. var minAngle = seriesModel.get('minAngle') * RADIAN;
  37289. var validDataCount = 0;
  37290. data.each(valueDim, function (value) {
  37291. !isNaN(value) && validDataCount++;
  37292. });
  37293. var sum = data.getSum(valueDim);
  37294. // Sum may be 0
  37295. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  37296. var clockwise = seriesModel.get('clockwise');
  37297. var roseType = seriesModel.get('roseType');
  37298. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  37299. // [0...max]
  37300. var extent = data.getDataExtent(valueDim);
  37301. extent[0] = 0;
  37302. // In the case some sector angle is smaller than minAngle
  37303. var restAngle = PI2$4;
  37304. var valueSumLargerThanMinAngle = 0;
  37305. var currentAngle = startAngle;
  37306. var dir = clockwise ? 1 : -1;
  37307. data.each(valueDim, function (value, idx) {
  37308. var angle;
  37309. if (isNaN(value)) {
  37310. data.setItemLayout(idx, {
  37311. angle: NaN,
  37312. startAngle: NaN,
  37313. endAngle: NaN,
  37314. clockwise: clockwise,
  37315. cx: cx,
  37316. cy: cy,
  37317. r0: r0,
  37318. r: roseType
  37319. ? NaN
  37320. : r
  37321. });
  37322. return;
  37323. }
  37324. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  37325. if (roseType !== 'area') {
  37326. angle = (sum === 0 && stillShowZeroSum)
  37327. ? unitRadian : (value * unitRadian);
  37328. }
  37329. else {
  37330. angle = PI2$4 / validDataCount;
  37331. }
  37332. if (angle < minAngle) {
  37333. angle = minAngle;
  37334. restAngle -= minAngle;
  37335. }
  37336. else {
  37337. valueSumLargerThanMinAngle += value;
  37338. }
  37339. var endAngle = currentAngle + dir * angle;
  37340. data.setItemLayout(idx, {
  37341. angle: angle,
  37342. startAngle: currentAngle,
  37343. endAngle: endAngle,
  37344. clockwise: clockwise,
  37345. cx: cx,
  37346. cy: cy,
  37347. r0: r0,
  37348. r: roseType
  37349. ? linearMap(value, extent, [r0, r])
  37350. : r
  37351. });
  37352. currentAngle = endAngle;
  37353. });
  37354. // Some sector is constrained by minAngle
  37355. // Rest sectors needs recalculate angle
  37356. if (restAngle < PI2$4 && validDataCount) {
  37357. // Average the angle if rest angle is not enough after all angles is
  37358. // Constrained by minAngle
  37359. if (restAngle <= 1e-3) {
  37360. var angle = PI2$4 / validDataCount;
  37361. data.each(valueDim, function (value, idx) {
  37362. if (!isNaN(value)) {
  37363. var layout = data.getItemLayout(idx);
  37364. layout.angle = angle;
  37365. layout.startAngle = startAngle + dir * idx * angle;
  37366. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  37367. }
  37368. });
  37369. }
  37370. else {
  37371. unitRadian = restAngle / valueSumLargerThanMinAngle;
  37372. currentAngle = startAngle;
  37373. data.each(valueDim, function (value, idx) {
  37374. if (!isNaN(value)) {
  37375. var layout = data.getItemLayout(idx);
  37376. var angle = layout.angle === minAngle
  37377. ? minAngle : value * unitRadian;
  37378. layout.startAngle = currentAngle;
  37379. layout.endAngle = currentAngle + dir * angle;
  37380. currentAngle += dir * angle;
  37381. }
  37382. });
  37383. }
  37384. }
  37385. labelLayout(seriesModel, r, width, height);
  37386. });
  37387. };
  37388. /*
  37389. * Licensed to the Apache Software Foundation (ASF) under one
  37390. * or more contributor license agreements. See the NOTICE file
  37391. * distributed with this work for additional information
  37392. * regarding copyright ownership. The ASF licenses this file
  37393. * to you under the Apache License, Version 2.0 (the
  37394. * "License"); you may not use this file except in compliance
  37395. * with the License. You may obtain a copy of the License at
  37396. *
  37397. * http://www.apache.org/licenses/LICENSE-2.0
  37398. *
  37399. * Unless required by applicable law or agreed to in writing,
  37400. * software distributed under the License is distributed on an
  37401. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37402. * KIND, either express or implied. See the License for the
  37403. * specific language governing permissions and limitations
  37404. * under the License.
  37405. */
  37406. var dataFilter = function (seriesType) {
  37407. return {
  37408. seriesType: seriesType,
  37409. reset: function (seriesModel, ecModel) {
  37410. var legendModels = ecModel.findComponents({
  37411. mainType: 'legend'
  37412. });
  37413. if (!legendModels || !legendModels.length) {
  37414. return;
  37415. }
  37416. var data = seriesModel.getData();
  37417. data.filterSelf(function (idx) {
  37418. var name = data.getName(idx);
  37419. // If in any legend component the status is not selected.
  37420. for (var i = 0; i < legendModels.length; i++) {
  37421. if (!legendModels[i].isSelected(name)) {
  37422. return false;
  37423. }
  37424. }
  37425. return true;
  37426. });
  37427. }
  37428. };
  37429. };
  37430. /*
  37431. * Licensed to the Apache Software Foundation (ASF) under one
  37432. * or more contributor license agreements. See the NOTICE file
  37433. * distributed with this work for additional information
  37434. * regarding copyright ownership. The ASF licenses this file
  37435. * to you under the Apache License, Version 2.0 (the
  37436. * "License"); you may not use this file except in compliance
  37437. * with the License. You may obtain a copy of the License at
  37438. *
  37439. * http://www.apache.org/licenses/LICENSE-2.0
  37440. *
  37441. * Unless required by applicable law or agreed to in writing,
  37442. * software distributed under the License is distributed on an
  37443. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37444. * KIND, either express or implied. See the License for the
  37445. * specific language governing permissions and limitations
  37446. * under the License.
  37447. */
  37448. createDataSelectAction('pie', [{
  37449. type: 'pieToggleSelect',
  37450. event: 'pieselectchanged',
  37451. method: 'toggleSelected'
  37452. }, {
  37453. type: 'pieSelect',
  37454. event: 'pieselected',
  37455. method: 'select'
  37456. }, {
  37457. type: 'pieUnSelect',
  37458. event: 'pieunselected',
  37459. method: 'unSelect'
  37460. }]);
  37461. registerVisual(dataColor('pie'));
  37462. registerLayout(curry(pieLayout, 'pie'));
  37463. registerProcessor(dataFilter('pie'));
  37464. /*
  37465. * Licensed to the Apache Software Foundation (ASF) under one
  37466. * or more contributor license agreements. See the NOTICE file
  37467. * distributed with this work for additional information
  37468. * regarding copyright ownership. The ASF licenses this file
  37469. * to you under the Apache License, Version 2.0 (the
  37470. * "License"); you may not use this file except in compliance
  37471. * with the License. You may obtain a copy of the License at
  37472. *
  37473. * http://www.apache.org/licenses/LICENSE-2.0
  37474. *
  37475. * Unless required by applicable law or agreed to in writing,
  37476. * software distributed under the License is distributed on an
  37477. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37478. * KIND, either express or implied. See the License for the
  37479. * specific language governing permissions and limitations
  37480. * under the License.
  37481. */
  37482. SeriesModel.extend({
  37483. type: 'series.scatter',
  37484. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  37485. getInitialData: function (option, ecModel) {
  37486. return createListFromArray(this.getSource(), this);
  37487. },
  37488. brushSelector: 'point',
  37489. getProgressive: function () {
  37490. var progressive = this.option.progressive;
  37491. if (progressive == null) {
  37492. // PENDING
  37493. return this.option.large ? 5e3 : this.get('progressive');
  37494. }
  37495. return progressive;
  37496. },
  37497. getProgressiveThreshold: function () {
  37498. var progressiveThreshold = this.option.progressiveThreshold;
  37499. if (progressiveThreshold == null) {
  37500. // PENDING
  37501. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  37502. }
  37503. return progressiveThreshold;
  37504. },
  37505. defaultOption: {
  37506. coordinateSystem: 'cartesian2d',
  37507. zlevel: 0,
  37508. z: 2,
  37509. legendHoverLink: true,
  37510. hoverAnimation: true,
  37511. // Cartesian coordinate system
  37512. // xAxisIndex: 0,
  37513. // yAxisIndex: 0,
  37514. // Polar coordinate system
  37515. // polarIndex: 0,
  37516. // Geo coordinate system
  37517. // geoIndex: 0,
  37518. // symbol: null, // 图形类型
  37519. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  37520. // symbolRotate: null, // 图形旋转控制
  37521. large: false,
  37522. // Available when large is true
  37523. largeThreshold: 2000,
  37524. // cursor: null,
  37525. // label: {
  37526. // show: false
  37527. // distance: 5,
  37528. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  37529. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  37530. // 'inside'|'left'|'right'|'top'|'bottom'
  37531. // 默认使用全局文本样式,详见TEXTSTYLE
  37532. // },
  37533. itemStyle: {
  37534. opacity: 0.8
  37535. // color: 各异
  37536. }
  37537. // progressive: null
  37538. }
  37539. });
  37540. /*
  37541. * Licensed to the Apache Software Foundation (ASF) under one
  37542. * or more contributor license agreements. See the NOTICE file
  37543. * distributed with this work for additional information
  37544. * regarding copyright ownership. The ASF licenses this file
  37545. * to you under the Apache License, Version 2.0 (the
  37546. * "License"); you may not use this file except in compliance
  37547. * with the License. You may obtain a copy of the License at
  37548. *
  37549. * http://www.apache.org/licenses/LICENSE-2.0
  37550. *
  37551. * Unless required by applicable law or agreed to in writing,
  37552. * software distributed under the License is distributed on an
  37553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37554. * KIND, either express or implied. See the License for the
  37555. * specific language governing permissions and limitations
  37556. * under the License.
  37557. */
  37558. /* global Float32Array */
  37559. // TODO Batch by color
  37560. var BOOST_SIZE_THRESHOLD = 4;
  37561. var LargeSymbolPath = extendShape({
  37562. shape: {
  37563. points: null
  37564. },
  37565. symbolProxy: null,
  37566. buildPath: function (path, shape) {
  37567. var points = shape.points;
  37568. var size = shape.size;
  37569. var symbolProxy = this.symbolProxy;
  37570. var symbolProxyShape = symbolProxy.shape;
  37571. var ctx = path.getContext ? path.getContext() : path;
  37572. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  37573. // Do draw in afterBrush.
  37574. if (canBoost) {
  37575. return;
  37576. }
  37577. for (var i = 0; i < points.length;) {
  37578. var x = points[i++];
  37579. var y = points[i++];
  37580. if (isNaN(x) || isNaN(y)) {
  37581. continue;
  37582. }
  37583. symbolProxyShape.x = x - size[0] / 2;
  37584. symbolProxyShape.y = y - size[1] / 2;
  37585. symbolProxyShape.width = size[0];
  37586. symbolProxyShape.height = size[1];
  37587. symbolProxy.buildPath(path, symbolProxyShape, true);
  37588. }
  37589. },
  37590. afterBrush: function (ctx) {
  37591. var shape = this.shape;
  37592. var points = shape.points;
  37593. var size = shape.size;
  37594. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  37595. if (!canBoost) {
  37596. return;
  37597. }
  37598. this.setTransform(ctx);
  37599. // PENDING If style or other canvas status changed?
  37600. for (var i = 0; i < points.length;) {
  37601. var x = points[i++];
  37602. var y = points[i++];
  37603. if (isNaN(x) || isNaN(y)) {
  37604. continue;
  37605. }
  37606. // fillRect is faster than building a rect path and draw.
  37607. // And it support light globalCompositeOperation.
  37608. ctx.fillRect(
  37609. x - size[0] / 2, y - size[1] / 2,
  37610. size[0], size[1]
  37611. );
  37612. }
  37613. this.restoreTransform(ctx);
  37614. },
  37615. findDataIndex: function (x, y) {
  37616. // TODO ???
  37617. // Consider transform
  37618. var shape = this.shape;
  37619. var points = shape.points;
  37620. var size = shape.size;
  37621. var w = Math.max(size[0], 4);
  37622. var h = Math.max(size[1], 4);
  37623. // Not consider transform
  37624. // Treat each element as a rect
  37625. // top down traverse
  37626. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  37627. var i = idx * 2;
  37628. var x0 = points[i] - w / 2;
  37629. var y0 = points[i + 1] - h / 2;
  37630. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  37631. return idx;
  37632. }
  37633. }
  37634. return -1;
  37635. }
  37636. });
  37637. function LargeSymbolDraw() {
  37638. this.group = new Group();
  37639. }
  37640. var largeSymbolProto = LargeSymbolDraw.prototype;
  37641. largeSymbolProto.isPersistent = function () {
  37642. return !this._incremental;
  37643. };
  37644. /**
  37645. * Update symbols draw by new data
  37646. * @param {module:echarts/data/List} data
  37647. */
  37648. largeSymbolProto.updateData = function (data) {
  37649. this.group.removeAll();
  37650. var symbolEl = new LargeSymbolPath({
  37651. rectHover: true,
  37652. cursor: 'default'
  37653. });
  37654. symbolEl.setShape({
  37655. points: data.getLayout('symbolPoints')
  37656. });
  37657. this._setCommon(symbolEl, data);
  37658. this.group.add(symbolEl);
  37659. this._incremental = null;
  37660. };
  37661. largeSymbolProto.updateLayout = function (data) {
  37662. if (this._incremental) {
  37663. return;
  37664. }
  37665. var points = data.getLayout('symbolPoints');
  37666. this.group.eachChild(function (child) {
  37667. if (child.startIndex != null) {
  37668. var len = (child.endIndex - child.startIndex) * 2;
  37669. var byteOffset = child.startIndex * 4 * 2;
  37670. points = new Float32Array(points.buffer, byteOffset, len);
  37671. }
  37672. child.setShape('points', points);
  37673. });
  37674. };
  37675. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  37676. this.group.removeAll();
  37677. this._clearIncremental();
  37678. // Only use incremental displayables when data amount is larger than 2 million.
  37679. // PENDING Incremental data?
  37680. if (data.count() > 2e6) {
  37681. if (!this._incremental) {
  37682. this._incremental = new IncrementalDisplayble({
  37683. silent: true
  37684. });
  37685. }
  37686. this.group.add(this._incremental);
  37687. }
  37688. else {
  37689. this._incremental = null;
  37690. }
  37691. };
  37692. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  37693. var symbolEl;
  37694. if (this._incremental) {
  37695. symbolEl = new LargeSymbolPath();
  37696. this._incremental.addDisplayable(symbolEl, true);
  37697. }
  37698. else {
  37699. symbolEl = new LargeSymbolPath({
  37700. rectHover: true,
  37701. cursor: 'default',
  37702. startIndex: taskParams.start,
  37703. endIndex: taskParams.end
  37704. });
  37705. symbolEl.incremental = true;
  37706. this.group.add(symbolEl);
  37707. }
  37708. symbolEl.setShape({
  37709. points: data.getLayout('symbolPoints')
  37710. });
  37711. this._setCommon(symbolEl, data, !!this._incremental);
  37712. };
  37713. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  37714. var hostModel = data.hostModel;
  37715. // TODO
  37716. // if (data.hasItemVisual.symbolSize) {
  37717. // // TODO typed array?
  37718. // symbolEl.setShape('sizes', data.mapArray(
  37719. // function (idx) {
  37720. // var size = data.getItemVisual(idx, 'symbolSize');
  37721. // return (size instanceof Array) ? size : [size, size];
  37722. // }
  37723. // ));
  37724. // }
  37725. // else {
  37726. var size = data.getVisual('symbolSize');
  37727. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  37728. // }
  37729. // Create symbolProxy to build path for each data
  37730. symbolEl.symbolProxy = createSymbol(
  37731. data.getVisual('symbol'), 0, 0, 0, 0
  37732. );
  37733. // Use symbolProxy setColor method
  37734. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  37735. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  37736. symbolEl.useStyle(
  37737. // Draw shadow when doing fillRect is extremely slow.
  37738. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  37739. );
  37740. var visualColor = data.getVisual('color');
  37741. if (visualColor) {
  37742. symbolEl.setColor(visualColor);
  37743. }
  37744. if (!isIncremental) {
  37745. // Enable tooltip
  37746. // PENDING May have performance issue when path is extremely large
  37747. symbolEl.seriesIndex = hostModel.seriesIndex;
  37748. symbolEl.on('mousemove', function (e) {
  37749. symbolEl.dataIndex = null;
  37750. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  37751. if (dataIndex >= 0) {
  37752. // Provide dataIndex for tooltip
  37753. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  37754. }
  37755. });
  37756. }
  37757. };
  37758. largeSymbolProto.remove = function () {
  37759. this._clearIncremental();
  37760. this._incremental = null;
  37761. this.group.removeAll();
  37762. };
  37763. largeSymbolProto._clearIncremental = function () {
  37764. var incremental = this._incremental;
  37765. if (incremental) {
  37766. incremental.clearDisplaybles();
  37767. }
  37768. };
  37769. /*
  37770. * Licensed to the Apache Software Foundation (ASF) under one
  37771. * or more contributor license agreements. See the NOTICE file
  37772. * distributed with this work for additional information
  37773. * regarding copyright ownership. The ASF licenses this file
  37774. * to you under the Apache License, Version 2.0 (the
  37775. * "License"); you may not use this file except in compliance
  37776. * with the License. You may obtain a copy of the License at
  37777. *
  37778. * http://www.apache.org/licenses/LICENSE-2.0
  37779. *
  37780. * Unless required by applicable law or agreed to in writing,
  37781. * software distributed under the License is distributed on an
  37782. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37783. * KIND, either express or implied. See the License for the
  37784. * specific language governing permissions and limitations
  37785. * under the License.
  37786. */
  37787. extendChartView({
  37788. type: 'scatter',
  37789. render: function (seriesModel, ecModel, api) {
  37790. var data = seriesModel.getData();
  37791. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  37792. symbolDraw.updateData(data);
  37793. this._finished = true;
  37794. },
  37795. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37796. var data = seriesModel.getData();
  37797. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  37798. symbolDraw.incrementalPrepareUpdate(data);
  37799. this._finished = false;
  37800. },
  37801. incrementalRender: function (taskParams, seriesModel, ecModel) {
  37802. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  37803. this._finished = taskParams.end === seriesModel.getData().count();
  37804. },
  37805. updateTransform: function (seriesModel, ecModel, api) {
  37806. var data = seriesModel.getData();
  37807. // Must mark group dirty and make sure the incremental layer will be cleared
  37808. // PENDING
  37809. this.group.dirty();
  37810. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  37811. return {
  37812. update: true
  37813. };
  37814. }
  37815. else {
  37816. var res = pointsLayout().reset(seriesModel);
  37817. if (res.progress) {
  37818. res.progress({ start: 0, end: data.count() }, data);
  37819. }
  37820. this._symbolDraw.updateLayout(data);
  37821. }
  37822. },
  37823. _updateSymbolDraw: function (data, seriesModel) {
  37824. var symbolDraw = this._symbolDraw;
  37825. var pipelineContext = seriesModel.pipelineContext;
  37826. var isLargeDraw = pipelineContext.large;
  37827. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  37828. symbolDraw && symbolDraw.remove();
  37829. symbolDraw = this._symbolDraw = isLargeDraw
  37830. ? new LargeSymbolDraw()
  37831. : new SymbolDraw();
  37832. this._isLargeDraw = isLargeDraw;
  37833. this.group.removeAll();
  37834. }
  37835. this.group.add(symbolDraw.group);
  37836. return symbolDraw;
  37837. },
  37838. remove: function (ecModel, api) {
  37839. this._symbolDraw && this._symbolDraw.remove(true);
  37840. this._symbolDraw = null;
  37841. },
  37842. dispose: function () {}
  37843. });
  37844. /*
  37845. * Licensed to the Apache Software Foundation (ASF) under one
  37846. * or more contributor license agreements. See the NOTICE file
  37847. * distributed with this work for additional information
  37848. * regarding copyright ownership. The ASF licenses this file
  37849. * to you under the Apache License, Version 2.0 (the
  37850. * "License"); you may not use this file except in compliance
  37851. * with the License. You may obtain a copy of the License at
  37852. *
  37853. * http://www.apache.org/licenses/LICENSE-2.0
  37854. *
  37855. * Unless required by applicable law or agreed to in writing,
  37856. * software distributed under the License is distributed on an
  37857. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37858. * KIND, either express or implied. See the License for the
  37859. * specific language governing permissions and limitations
  37860. * under the License.
  37861. */
  37862. // import * as zrUtil from 'zrender/src/core/util';
  37863. // In case developer forget to include grid component
  37864. registerVisual(visualSymbol('scatter', 'circle'));
  37865. registerLayout(pointsLayout('scatter'));
  37866. // echarts.registerProcessor(function (ecModel, api) {
  37867. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  37868. // var data = seriesModel.getData();
  37869. // var coordSys = seriesModel.coordinateSystem;
  37870. // if (coordSys.type !== 'geo') {
  37871. // return;
  37872. // }
  37873. // var startPt = coordSys.pointToData([0, 0]);
  37874. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  37875. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  37876. // return data.mapDimension(dim);
  37877. // });
  37878. // var range = {};
  37879. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  37880. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  37881. // data.selectRange(range);
  37882. // });
  37883. // });
  37884. /*
  37885. * Licensed to the Apache Software Foundation (ASF) under one
  37886. * or more contributor license agreements. See the NOTICE file
  37887. * distributed with this work for additional information
  37888. * regarding copyright ownership. The ASF licenses this file
  37889. * to you under the Apache License, Version 2.0 (the
  37890. * "License"); you may not use this file except in compliance
  37891. * with the License. You may obtain a copy of the License at
  37892. *
  37893. * http://www.apache.org/licenses/LICENSE-2.0
  37894. *
  37895. * Unless required by applicable law or agreed to in writing,
  37896. * software distributed under the License is distributed on an
  37897. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37898. * KIND, either express or implied. See the License for the
  37899. * specific language governing permissions and limitations
  37900. * under the License.
  37901. */
  37902. // -------------
  37903. // Preprocessor
  37904. // -------------
  37905. registerPreprocessor(function (option) {
  37906. var graphicOption = option.graphic;
  37907. // Convert
  37908. // {graphic: [{left: 10, type: 'circle'}, ...]}
  37909. // or
  37910. // {graphic: {left: 10, type: 'circle'}}
  37911. // to
  37912. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  37913. if (isArray(graphicOption)) {
  37914. if (!graphicOption[0] || !graphicOption[0].elements) {
  37915. option.graphic = [{elements: graphicOption}];
  37916. }
  37917. else {
  37918. // Only one graphic instance can be instantiated. (We dont
  37919. // want that too many views are created in echarts._viewMap)
  37920. option.graphic = [option.graphic[0]];
  37921. }
  37922. }
  37923. else if (graphicOption && !graphicOption.elements) {
  37924. option.graphic = [{elements: [graphicOption]}];
  37925. }
  37926. });
  37927. // ------
  37928. // Model
  37929. // ------
  37930. var GraphicModel = extendComponentModel({
  37931. type: 'graphic',
  37932. defaultOption: {
  37933. // Extra properties for each elements:
  37934. //
  37935. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  37936. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  37937. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  37938. // This mechanism is useful when you want to position a group/element
  37939. // against the right side or the center of this container.
  37940. //
  37941. // width/height: (can only be pixel value, default 0)
  37942. // Only be used to specify contianer(group) size, if needed. And
  37943. // can not be percentage value (like '33%'). See the reason in the
  37944. // layout algorithm below.
  37945. //
  37946. // bounding: (enum: 'all' (default) | 'raw')
  37947. // Specify how to calculate boundingRect when locating.
  37948. // 'all': Get uioned and transformed boundingRect
  37949. // from both itself and its descendants.
  37950. // This mode simplies confining a group of elements in the bounding
  37951. // of their ancester container (e.g., using 'right: 0').
  37952. // 'raw': Only use the boundingRect of itself and before transformed.
  37953. // This mode is similar to css behavior, which is useful when you
  37954. // want an element to be able to overflow its container. (Consider
  37955. // a rotated circle needs to be located in a corner.)
  37956. // info: custom info. enables user to mount some info on elements and use them
  37957. // in event handlers. Update them only when user specified, otherwise, remain.
  37958. // Note: elements is always behind its ancestors in this elements array.
  37959. elements: [],
  37960. parentId: null
  37961. },
  37962. /**
  37963. * Save el options for the sake of the performance (only update modified graphics).
  37964. * The order is the same as those in option. (ancesters -> descendants)
  37965. *
  37966. * @private
  37967. * @type {Array.<Object>}
  37968. */
  37969. _elOptionsToUpdate: null,
  37970. /**
  37971. * @override
  37972. */
  37973. mergeOption: function (option) {
  37974. // Prevent default merge to elements
  37975. var elements = this.option.elements;
  37976. this.option.elements = null;
  37977. GraphicModel.superApply(this, 'mergeOption', arguments);
  37978. this.option.elements = elements;
  37979. },
  37980. /**
  37981. * @override
  37982. */
  37983. optionUpdated: function (newOption, isInit) {
  37984. var thisOption = this.option;
  37985. var newList = (isInit ? thisOption : newOption).elements;
  37986. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  37987. var flattenedList = [];
  37988. this._flatten(newList, flattenedList);
  37989. var mappingResult = mappingToExists(existList, flattenedList);
  37990. makeIdAndName(mappingResult);
  37991. // Clear elOptionsToUpdate
  37992. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  37993. each$1(mappingResult, function (resultItem, index) {
  37994. var newElOption = resultItem.option;
  37995. if (__DEV__) {
  37996. assert$1(
  37997. isObject$1(newElOption) || resultItem.exist,
  37998. 'Empty graphic option definition'
  37999. );
  38000. }
  38001. if (!newElOption) {
  38002. return;
  38003. }
  38004. elOptionsToUpdate.push(newElOption);
  38005. setKeyInfoToNewElOption(resultItem, newElOption);
  38006. mergeNewElOptionToExist(existList, index, newElOption);
  38007. setLayoutInfoToExist(existList[index], newElOption);
  38008. }, this);
  38009. // Clean
  38010. for (var i = existList.length - 1; i >= 0; i--) {
  38011. if (existList[i] == null) {
  38012. existList.splice(i, 1);
  38013. }
  38014. else {
  38015. // $action should be volatile, otherwise option gotten from
  38016. // `getOption` will contain unexpected $action.
  38017. delete existList[i].$action;
  38018. }
  38019. }
  38020. },
  38021. /**
  38022. * Convert
  38023. * [{
  38024. * type: 'group',
  38025. * id: 'xx',
  38026. * children: [{type: 'circle'}, {type: 'polygon'}]
  38027. * }]
  38028. * to
  38029. * [
  38030. * {type: 'group', id: 'xx'},
  38031. * {type: 'circle', parentId: 'xx'},
  38032. * {type: 'polygon', parentId: 'xx'}
  38033. * ]
  38034. *
  38035. * @private
  38036. * @param {Array.<Object>} optionList option list
  38037. * @param {Array.<Object>} result result of flatten
  38038. * @param {Object} parentOption parent option
  38039. */
  38040. _flatten: function (optionList, result, parentOption) {
  38041. each$1(optionList, function (option) {
  38042. if (!option) {
  38043. return;
  38044. }
  38045. if (parentOption) {
  38046. option.parentOption = parentOption;
  38047. }
  38048. result.push(option);
  38049. var children = option.children;
  38050. if (option.type === 'group' && children) {
  38051. this._flatten(children, result, option);
  38052. }
  38053. // Deleting for JSON output, and for not affecting group creation.
  38054. delete option.children;
  38055. }, this);
  38056. },
  38057. // FIXME
  38058. // Pass to view using payload? setOption has a payload?
  38059. useElOptionsToUpdate: function () {
  38060. var els = this._elOptionsToUpdate;
  38061. // Clear to avoid render duplicately when zooming.
  38062. this._elOptionsToUpdate = null;
  38063. return els;
  38064. }
  38065. });
  38066. // -----
  38067. // View
  38068. // -----
  38069. extendComponentView({
  38070. type: 'graphic',
  38071. /**
  38072. * @override
  38073. */
  38074. init: function (ecModel, api) {
  38075. /**
  38076. * @private
  38077. * @type {module:zrender/core/util.HashMap}
  38078. */
  38079. this._elMap = createHashMap();
  38080. /**
  38081. * @private
  38082. * @type {module:echarts/graphic/GraphicModel}
  38083. */
  38084. this._lastGraphicModel;
  38085. },
  38086. /**
  38087. * @override
  38088. */
  38089. render: function (graphicModel, ecModel, api) {
  38090. // Having leveraged between use cases and algorithm complexity, a very
  38091. // simple layout mechanism is used:
  38092. // The size(width/height) can be determined by itself or its parent (not
  38093. // implemented yet), but can not by its children. (Top-down travel)
  38094. // The location(x/y) can be determined by the bounding rect of itself
  38095. // (can including its descendants or not) and the size of its parent.
  38096. // (Bottom-up travel)
  38097. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  38098. // view will be reused.
  38099. if (graphicModel !== this._lastGraphicModel) {
  38100. this._clear();
  38101. }
  38102. this._lastGraphicModel = graphicModel;
  38103. this._updateElements(graphicModel);
  38104. this._relocate(graphicModel, api);
  38105. },
  38106. /**
  38107. * Update graphic elements.
  38108. *
  38109. * @private
  38110. * @param {Object} graphicModel graphic model
  38111. */
  38112. _updateElements: function (graphicModel) {
  38113. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  38114. if (!elOptionsToUpdate) {
  38115. return;
  38116. }
  38117. var elMap = this._elMap;
  38118. var rootGroup = this.group;
  38119. // Top-down tranverse to assign graphic settings to each elements.
  38120. each$1(elOptionsToUpdate, function (elOption) {
  38121. var $action = elOption.$action;
  38122. var id = elOption.id;
  38123. var existEl = elMap.get(id);
  38124. var parentId = elOption.parentId;
  38125. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  38126. var elOptionStyle = elOption.style;
  38127. if (elOption.type === 'text' && elOptionStyle) {
  38128. // In top/bottom mode, textVerticalAlign should not be used, which cause
  38129. // inaccurately locating.
  38130. if (elOption.hv && elOption.hv[1]) {
  38131. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  38132. }
  38133. // Compatible with previous setting: both support fill and textFill,
  38134. // stroke and textStroke.
  38135. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  38136. elOptionStyle.textFill = elOptionStyle.fill
  38137. );
  38138. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  38139. elOptionStyle.textStroke = elOptionStyle.stroke
  38140. );
  38141. }
  38142. // Remove unnecessary props to avoid potential problems.
  38143. var elOptionCleaned = getCleanedElOption(elOption);
  38144. // For simple, do not support parent change, otherwise reorder is needed.
  38145. if (__DEV__) {
  38146. existEl && assert$1(
  38147. targetElParent === existEl.parent,
  38148. 'Changing parent is not supported.'
  38149. );
  38150. }
  38151. if (!$action || $action === 'merge') {
  38152. existEl
  38153. ? existEl.attr(elOptionCleaned)
  38154. : createEl(id, targetElParent, elOptionCleaned, elMap);
  38155. }
  38156. else if ($action === 'replace') {
  38157. removeEl(existEl, elMap);
  38158. createEl(id, targetElParent, elOptionCleaned, elMap);
  38159. }
  38160. else if ($action === 'remove') {
  38161. removeEl(existEl, elMap);
  38162. }
  38163. var el = elMap.get(id);
  38164. if (el) {
  38165. el.__ecGraphicWidth = elOption.width;
  38166. el.__ecGraphicHeight = elOption.height;
  38167. setEventData(el, graphicModel, elOption);
  38168. }
  38169. });
  38170. },
  38171. /**
  38172. * Locate graphic elements.
  38173. *
  38174. * @private
  38175. * @param {Object} graphicModel graphic model
  38176. * @param {module:echarts/ExtensionAPI} api extension API
  38177. */
  38178. _relocate: function (graphicModel, api) {
  38179. var elOptions = graphicModel.option.elements;
  38180. var rootGroup = this.group;
  38181. var elMap = this._elMap;
  38182. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  38183. for (var i = elOptions.length - 1; i >= 0; i--) {
  38184. var elOption = elOptions[i];
  38185. var el = elMap.get(elOption.id);
  38186. if (!el) {
  38187. continue;
  38188. }
  38189. var parentEl = el.parent;
  38190. var containerInfo = parentEl === rootGroup
  38191. ? {
  38192. width: api.getWidth(),
  38193. height: api.getHeight()
  38194. }
  38195. : { // Like 'position:absolut' in css, default 0.
  38196. width: parentEl.__ecGraphicWidth || 0,
  38197. height: parentEl.__ecGraphicHeight || 0
  38198. };
  38199. positionElement(
  38200. el, elOption, containerInfo, null,
  38201. {hv: elOption.hv, boundingMode: elOption.bounding}
  38202. );
  38203. }
  38204. },
  38205. /**
  38206. * Clear all elements.
  38207. *
  38208. * @private
  38209. */
  38210. _clear: function () {
  38211. var elMap = this._elMap;
  38212. elMap.each(function (el) {
  38213. removeEl(el, elMap);
  38214. });
  38215. this._elMap = createHashMap();
  38216. },
  38217. /**
  38218. * @override
  38219. */
  38220. dispose: function () {
  38221. this._clear();
  38222. }
  38223. });
  38224. function createEl(id, targetElParent, elOption, elMap) {
  38225. var graphicType = elOption.type;
  38226. if (__DEV__) {
  38227. assert$1(graphicType, 'graphic type MUST be set');
  38228. }
  38229. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  38230. if (__DEV__) {
  38231. assert$1(Clz, 'graphic type can not be found');
  38232. }
  38233. var el = new Clz(elOption);
  38234. targetElParent.add(el);
  38235. elMap.set(id, el);
  38236. el.__ecGraphicId = id;
  38237. }
  38238. function removeEl(existEl, elMap) {
  38239. var existElParent = existEl && existEl.parent;
  38240. if (existElParent) {
  38241. existEl.type === 'group' && existEl.traverse(function (el) {
  38242. removeEl(el, elMap);
  38243. });
  38244. elMap.removeKey(existEl.__ecGraphicId);
  38245. existElParent.remove(existEl);
  38246. }
  38247. }
  38248. // Remove unnecessary props to avoid potential problems.
  38249. function getCleanedElOption(elOption) {
  38250. elOption = extend({}, elOption);
  38251. each$1(
  38252. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  38253. function (name) {
  38254. delete elOption[name];
  38255. }
  38256. );
  38257. return elOption;
  38258. }
  38259. function isSetLoc(obj, props) {
  38260. var isSet;
  38261. each$1(props, function (prop) {
  38262. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  38263. });
  38264. return isSet;
  38265. }
  38266. function setKeyInfoToNewElOption(resultItem, newElOption) {
  38267. var existElOption = resultItem.exist;
  38268. // Set id and type after id assigned.
  38269. newElOption.id = resultItem.keyInfo.id;
  38270. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  38271. // Set parent id if not specified
  38272. if (newElOption.parentId == null) {
  38273. var newElParentOption = newElOption.parentOption;
  38274. if (newElParentOption) {
  38275. newElOption.parentId = newElParentOption.id;
  38276. }
  38277. else if (existElOption) {
  38278. newElOption.parentId = existElOption.parentId;
  38279. }
  38280. }
  38281. // Clear
  38282. newElOption.parentOption = null;
  38283. }
  38284. function mergeNewElOptionToExist(existList, index, newElOption) {
  38285. // Update existing options, for `getOption` feature.
  38286. var newElOptCopy = extend({}, newElOption);
  38287. var existElOption = existList[index];
  38288. var $action = newElOption.$action || 'merge';
  38289. if ($action === 'merge') {
  38290. if (existElOption) {
  38291. if (__DEV__) {
  38292. var newType = newElOption.type;
  38293. assert$1(
  38294. !newType || existElOption.type === newType,
  38295. 'Please set $action: "replace" to change `type`'
  38296. );
  38297. }
  38298. // We can ensure that newElOptCopy and existElOption are not
  38299. // the same object, so `merge` will not change newElOptCopy.
  38300. merge(existElOption, newElOptCopy, true);
  38301. // Rigid body, use ignoreSize.
  38302. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  38303. // Will be used in render.
  38304. copyLayoutParams(newElOption, existElOption);
  38305. }
  38306. else {
  38307. existList[index] = newElOptCopy;
  38308. }
  38309. }
  38310. else if ($action === 'replace') {
  38311. existList[index] = newElOptCopy;
  38312. }
  38313. else if ($action === 'remove') {
  38314. // null will be cleaned later.
  38315. existElOption && (existList[index] = null);
  38316. }
  38317. }
  38318. function setLayoutInfoToExist(existItem, newElOption) {
  38319. if (!existItem) {
  38320. return;
  38321. }
  38322. existItem.hv = newElOption.hv = [
  38323. // Rigid body, dont care `width`.
  38324. isSetLoc(newElOption, ['left', 'right']),
  38325. // Rigid body, dont care `height`.
  38326. isSetLoc(newElOption, ['top', 'bottom'])
  38327. ];
  38328. // Give default group size. Otherwise layout error may occur.
  38329. if (existItem.type === 'group') {
  38330. existItem.width == null && (existItem.width = newElOption.width = 0);
  38331. existItem.height == null && (existItem.height = newElOption.height = 0);
  38332. }
  38333. }
  38334. function setEventData(el, graphicModel, elOption) {
  38335. var eventData = el.eventData;
  38336. // Simple optimize for large amount of elements that no need event.
  38337. if (!el.silent && !el.ignore && !eventData) {
  38338. eventData = el.eventData = {
  38339. componentType: 'graphic',
  38340. componentIndex: graphicModel.componentIndex,
  38341. name: el.name
  38342. };
  38343. }
  38344. // `elOption.info` enables user to mount some info on
  38345. // elements and use them in event handlers.
  38346. if (eventData) {
  38347. eventData.info = el.info;
  38348. }
  38349. }
  38350. /*
  38351. * Licensed to the Apache Software Foundation (ASF) under one
  38352. * or more contributor license agreements. See the NOTICE file
  38353. * distributed with this work for additional information
  38354. * regarding copyright ownership. The ASF licenses this file
  38355. * to you under the Apache License, Version 2.0 (the
  38356. * "License"); you may not use this file except in compliance
  38357. * with the License. You may obtain a copy of the License at
  38358. *
  38359. * http://www.apache.org/licenses/LICENSE-2.0
  38360. *
  38361. * Unless required by applicable law or agreed to in writing,
  38362. * software distributed under the License is distributed on an
  38363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38364. * KIND, either express or implied. See the License for the
  38365. * specific language governing permissions and limitations
  38366. * under the License.
  38367. */
  38368. /**
  38369. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  38370. * @param {module:echarts/model/Global} ecModel
  38371. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  38372. */
  38373. var findPointFromSeries = function (finder, ecModel) {
  38374. var point = [];
  38375. var seriesIndex = finder.seriesIndex;
  38376. var seriesModel;
  38377. if (seriesIndex == null || !(
  38378. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  38379. )) {
  38380. return {point: []};
  38381. }
  38382. var data = seriesModel.getData();
  38383. var dataIndex = queryDataIndex(data, finder);
  38384. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  38385. return {point: []};
  38386. }
  38387. var el = data.getItemGraphicEl(dataIndex);
  38388. var coordSys = seriesModel.coordinateSystem;
  38389. if (seriesModel.getTooltipPosition) {
  38390. point = seriesModel.getTooltipPosition(dataIndex) || [];
  38391. }
  38392. else if (coordSys && coordSys.dataToPoint) {
  38393. point = coordSys.dataToPoint(
  38394. data.getValues(
  38395. map(coordSys.dimensions, function (dim) {
  38396. return data.mapDimension(dim);
  38397. }), dataIndex, true
  38398. )
  38399. ) || [];
  38400. }
  38401. else if (el) {
  38402. // Use graphic bounding rect
  38403. var rect = el.getBoundingRect().clone();
  38404. rect.applyTransform(el.transform);
  38405. point = [
  38406. rect.x + rect.width / 2,
  38407. rect.y + rect.height / 2
  38408. ];
  38409. }
  38410. return {point: point, el: el};
  38411. };
  38412. /*
  38413. * Licensed to the Apache Software Foundation (ASF) under one
  38414. * or more contributor license agreements. See the NOTICE file
  38415. * distributed with this work for additional information
  38416. * regarding copyright ownership. The ASF licenses this file
  38417. * to you under the Apache License, Version 2.0 (the
  38418. * "License"); you may not use this file except in compliance
  38419. * with the License. You may obtain a copy of the License at
  38420. *
  38421. * http://www.apache.org/licenses/LICENSE-2.0
  38422. *
  38423. * Unless required by applicable law or agreed to in writing,
  38424. * software distributed under the License is distributed on an
  38425. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38426. * KIND, either express or implied. See the License for the
  38427. * specific language governing permissions and limitations
  38428. * under the License.
  38429. */
  38430. var each$7 = each$1;
  38431. var curry$2 = curry;
  38432. var inner$7 = makeInner();
  38433. /**
  38434. * Basic logic: check all axis, if they do not demand show/highlight,
  38435. * then hide/downplay them.
  38436. *
  38437. * @param {Object} coordSysAxesInfo
  38438. * @param {Object} payload
  38439. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  38440. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  38441. * trigger axisPointer and tooltip.
  38442. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  38443. * trigger axisPointer and tooltip.
  38444. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  38445. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  38446. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  38447. * [{
  38448. * axisDim: 'x'|'y'|'angle'|...,
  38449. * axisIndex: ...,
  38450. * value: ...
  38451. * }, ...]
  38452. * @param {Function} [payload.dispatchAction]
  38453. * @param {Object} [payload.tooltipOption]
  38454. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  38455. * which can be specified in dispatchAction
  38456. * @param {module:echarts/model/Global} ecModel
  38457. * @param {module:echarts/ExtensionAPI} api
  38458. * @return {Object} content of event obj for echarts.connect.
  38459. */
  38460. var axisTrigger = function (payload, ecModel, api) {
  38461. var currTrigger = payload.currTrigger;
  38462. var point = [payload.x, payload.y];
  38463. var finder = payload;
  38464. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  38465. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  38466. // Pending
  38467. // See #6121. But we are not able to reproduce it yet.
  38468. if (!coordSysAxesInfo) {
  38469. return;
  38470. }
  38471. if (illegalPoint(point)) {
  38472. // Used in the default behavior of `connection`: use the sample seriesIndex
  38473. // and dataIndex. And also used in the tooltipView trigger.
  38474. point = findPointFromSeries({
  38475. seriesIndex: finder.seriesIndex,
  38476. // Do not use dataIndexInside from other ec instance.
  38477. // FIXME: auto detect it?
  38478. dataIndex: finder.dataIndex
  38479. }, ecModel).point;
  38480. }
  38481. var isIllegalPoint = illegalPoint(point);
  38482. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  38483. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  38484. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  38485. // and dataIndex.
  38486. var inputAxesInfo = finder.axesInfo;
  38487. var axesInfo = coordSysAxesInfo.axesInfo;
  38488. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  38489. var outputFinder = {};
  38490. var showValueMap = {};
  38491. var dataByCoordSys = {list: [], map: {}};
  38492. var updaters = {
  38493. showPointer: curry$2(showPointer, showValueMap),
  38494. showTooltip: curry$2(showTooltip, dataByCoordSys)
  38495. };
  38496. // Process for triggered axes.
  38497. each$7(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  38498. // If a point given, it must be contained by the coordinate system.
  38499. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  38500. each$7(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  38501. var axis = axisInfo.axis;
  38502. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  38503. // If no inputAxesInfo, no axis is restricted.
  38504. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  38505. var val = inputAxisInfo && inputAxisInfo.value;
  38506. if (val == null && !isIllegalPoint) {
  38507. val = axis.pointToData(point);
  38508. }
  38509. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  38510. }
  38511. });
  38512. });
  38513. // Process for linked axes.
  38514. var linkTriggers = {};
  38515. each$7(axesInfo, function (tarAxisInfo, tarKey) {
  38516. var linkGroup = tarAxisInfo.linkGroup;
  38517. // If axis has been triggered in the previous stage, it should not be triggered by link.
  38518. if (linkGroup && !showValueMap[tarKey]) {
  38519. each$7(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  38520. var srcValItem = showValueMap[srcKey];
  38521. // If srcValItem exist, source axis is triggered, so link to target axis.
  38522. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  38523. var val = srcValItem.value;
  38524. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  38525. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  38526. )));
  38527. linkTriggers[tarAxisInfo.key] = val;
  38528. }
  38529. });
  38530. }
  38531. });
  38532. each$7(linkTriggers, function (val, tarKey) {
  38533. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  38534. });
  38535. updateModelActually(showValueMap, axesInfo, outputFinder);
  38536. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  38537. dispatchHighDownActually(axesInfo, dispatchAction, api);
  38538. return outputFinder;
  38539. };
  38540. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  38541. var axis = axisInfo.axis;
  38542. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  38543. return;
  38544. }
  38545. if (!axisInfo.involveSeries) {
  38546. updaters.showPointer(axisInfo, newValue);
  38547. return;
  38548. }
  38549. // Heavy calculation. So put it after axis.containData checking.
  38550. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  38551. var payloadBatch = payloadInfo.payloadBatch;
  38552. var snapToValue = payloadInfo.snapToValue;
  38553. // Fill content of event obj for echarts.connect.
  38554. // By defualt use the first involved series data as a sample to connect.
  38555. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  38556. extend(outputFinder, payloadBatch[0]);
  38557. }
  38558. // If no linkSource input, this process is for collecting link
  38559. // target, where snap should not be accepted.
  38560. if (!dontSnap && axisInfo.snap) {
  38561. if (axis.containData(snapToValue) && snapToValue != null) {
  38562. newValue = snapToValue;
  38563. }
  38564. }
  38565. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  38566. // Tooltip should always be snapToValue, otherwise there will be
  38567. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  38568. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  38569. }
  38570. function buildPayloadsBySeries(value, axisInfo) {
  38571. var axis = axisInfo.axis;
  38572. var dim = axis.dim;
  38573. var snapToValue = value;
  38574. var payloadBatch = [];
  38575. var minDist = Number.MAX_VALUE;
  38576. var minDiff = -1;
  38577. each$7(axisInfo.seriesModels, function (series, idx) {
  38578. var dataDim = series.getData().mapDimension(dim, true);
  38579. var seriesNestestValue;
  38580. var dataIndices;
  38581. if (series.getAxisTooltipData) {
  38582. var result = series.getAxisTooltipData(dataDim, value, axis);
  38583. dataIndices = result.dataIndices;
  38584. seriesNestestValue = result.nestestValue;
  38585. }
  38586. else {
  38587. dataIndices = series.getData().indicesOfNearest(
  38588. dataDim[0],
  38589. value,
  38590. // Add a threshold to avoid find the wrong dataIndex
  38591. // when data length is not same.
  38592. // false,
  38593. axis.type === 'category' ? 0.5 : null
  38594. );
  38595. if (!dataIndices.length) {
  38596. return;
  38597. }
  38598. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  38599. }
  38600. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  38601. return;
  38602. }
  38603. var diff = value - seriesNestestValue;
  38604. var dist = Math.abs(diff);
  38605. // Consider category case
  38606. if (dist <= minDist) {
  38607. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  38608. minDist = dist;
  38609. minDiff = diff;
  38610. snapToValue = seriesNestestValue;
  38611. payloadBatch.length = 0;
  38612. }
  38613. each$7(dataIndices, function (dataIndex) {
  38614. payloadBatch.push({
  38615. seriesIndex: series.seriesIndex,
  38616. dataIndexInside: dataIndex,
  38617. dataIndex: series.getData().getRawIndex(dataIndex)
  38618. });
  38619. });
  38620. }
  38621. });
  38622. return {
  38623. payloadBatch: payloadBatch,
  38624. snapToValue: snapToValue
  38625. };
  38626. }
  38627. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  38628. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  38629. }
  38630. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  38631. var payloadBatch = payloadInfo.payloadBatch;
  38632. var axis = axisInfo.axis;
  38633. var axisModel = axis.model;
  38634. var axisPointerModel = axisInfo.axisPointerModel;
  38635. // If no data, do not create anything in dataByCoordSys,
  38636. // whose length will be used to judge whether dispatch action.
  38637. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  38638. return;
  38639. }
  38640. var coordSysModel = axisInfo.coordSys.model;
  38641. var coordSysKey = makeKey(coordSysModel);
  38642. var coordSysItem = dataByCoordSys.map[coordSysKey];
  38643. if (!coordSysItem) {
  38644. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  38645. coordSysId: coordSysModel.id,
  38646. coordSysIndex: coordSysModel.componentIndex,
  38647. coordSysType: coordSysModel.type,
  38648. coordSysMainType: coordSysModel.mainType,
  38649. dataByAxis: []
  38650. };
  38651. dataByCoordSys.list.push(coordSysItem);
  38652. }
  38653. coordSysItem.dataByAxis.push({
  38654. axisDim: axis.dim,
  38655. axisIndex: axisModel.componentIndex,
  38656. axisType: axisModel.type,
  38657. axisId: axisModel.id,
  38658. value: value,
  38659. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  38660. // depends that all models have been updated. So it should not be performed
  38661. // here. Considering axisPointerModel used here is volatile, which is hard
  38662. // to be retrieve in TooltipView, we prepare parameters here.
  38663. valueLabelOpt: {
  38664. precision: axisPointerModel.get('label.precision'),
  38665. formatter: axisPointerModel.get('label.formatter')
  38666. },
  38667. seriesDataIndices: payloadBatch.slice()
  38668. });
  38669. }
  38670. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  38671. var outputAxesInfo = outputFinder.axesInfo = [];
  38672. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  38673. each$7(axesInfo, function (axisInfo, key) {
  38674. var option = axisInfo.axisPointerModel.option;
  38675. var valItem = showValueMap[key];
  38676. if (valItem) {
  38677. !axisInfo.useHandle && (option.status = 'show');
  38678. option.value = valItem.value;
  38679. // For label formatter param and highlight.
  38680. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  38681. }
  38682. // When always show (e.g., handle used), remain
  38683. // original value and status.
  38684. else {
  38685. // If hide, value still need to be set, consider
  38686. // click legend to toggle axis blank.
  38687. !axisInfo.useHandle && (option.status = 'hide');
  38688. }
  38689. // If status is 'hide', should be no info in payload.
  38690. option.status === 'show' && outputAxesInfo.push({
  38691. axisDim: axisInfo.axis.dim,
  38692. axisIndex: axisInfo.axis.model.componentIndex,
  38693. value: option.value
  38694. });
  38695. });
  38696. }
  38697. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  38698. // Basic logic: If no showTip required, hideTip will be dispatched.
  38699. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  38700. dispatchAction({type: 'hideTip'});
  38701. return;
  38702. }
  38703. // In most case only one axis (or event one series is used). It is
  38704. // convinient to fetch payload.seriesIndex and payload.dataIndex
  38705. // dirtectly. So put the first seriesIndex and dataIndex of the first
  38706. // axis on the payload.
  38707. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  38708. dispatchAction({
  38709. type: 'showTip',
  38710. escapeConnect: true,
  38711. x: point[0],
  38712. y: point[1],
  38713. tooltipOption: payload.tooltipOption,
  38714. position: payload.position,
  38715. dataIndexInside: sampleItem.dataIndexInside,
  38716. dataIndex: sampleItem.dataIndex,
  38717. seriesIndex: sampleItem.seriesIndex,
  38718. dataByCoordSys: dataByCoordSys.list
  38719. });
  38720. }
  38721. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  38722. // FIXME
  38723. // highlight status modification shoule be a stage of main process?
  38724. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  38725. var zr = api.getZr();
  38726. var highDownKey = 'axisPointerLastHighlights';
  38727. var lastHighlights = inner$7(zr)[highDownKey] || {};
  38728. var newHighlights = inner$7(zr)[highDownKey] = {};
  38729. // Update highlight/downplay status according to axisPointer model.
  38730. // Build hash map and remove duplicate incidentally.
  38731. each$7(axesInfo, function (axisInfo, key) {
  38732. var option = axisInfo.axisPointerModel.option;
  38733. option.status === 'show' && each$7(option.seriesDataIndices, function (batchItem) {
  38734. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  38735. newHighlights[key] = batchItem;
  38736. });
  38737. });
  38738. // Diff.
  38739. var toHighlight = [];
  38740. var toDownplay = [];
  38741. each$1(lastHighlights, function (batchItem, key) {
  38742. !newHighlights[key] && toDownplay.push(batchItem);
  38743. });
  38744. each$1(newHighlights, function (batchItem, key) {
  38745. !lastHighlights[key] && toHighlight.push(batchItem);
  38746. });
  38747. toDownplay.length && api.dispatchAction({
  38748. type: 'downplay', escapeConnect: true, batch: toDownplay
  38749. });
  38750. toHighlight.length && api.dispatchAction({
  38751. type: 'highlight', escapeConnect: true, batch: toHighlight
  38752. });
  38753. }
  38754. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  38755. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  38756. var inputAxisInfo = inputAxesInfo[i];
  38757. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  38758. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  38759. ) {
  38760. return inputAxisInfo;
  38761. }
  38762. }
  38763. }
  38764. function makeMapperParam(axisInfo) {
  38765. var axisModel = axisInfo.axis.model;
  38766. var item = {};
  38767. var dim = item.axisDim = axisInfo.axis.dim;
  38768. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  38769. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  38770. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  38771. return item;
  38772. }
  38773. function illegalPoint(point) {
  38774. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  38775. }
  38776. /*
  38777. * Licensed to the Apache Software Foundation (ASF) under one
  38778. * or more contributor license agreements. See the NOTICE file
  38779. * distributed with this work for additional information
  38780. * regarding copyright ownership. The ASF licenses this file
  38781. * to you under the Apache License, Version 2.0 (the
  38782. * "License"); you may not use this file except in compliance
  38783. * with the License. You may obtain a copy of the License at
  38784. *
  38785. * http://www.apache.org/licenses/LICENSE-2.0
  38786. *
  38787. * Unless required by applicable law or agreed to in writing,
  38788. * software distributed under the License is distributed on an
  38789. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38790. * KIND, either express or implied. See the License for the
  38791. * specific language governing permissions and limitations
  38792. * under the License.
  38793. */
  38794. var AxisPointerModel = extendComponentModel({
  38795. type: 'axisPointer',
  38796. coordSysAxesInfo: null,
  38797. defaultOption: {
  38798. // 'auto' means that show when triggered by tooltip or handle.
  38799. show: 'auto',
  38800. // 'click' | 'mousemove' | 'none'
  38801. triggerOn: null, // set default in AxisPonterView.js
  38802. zlevel: 0,
  38803. z: 50,
  38804. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  38805. // axispointer triggered by tootip determine snap automatically,
  38806. // see `modelHelper`.
  38807. snap: false,
  38808. triggerTooltip: true,
  38809. value: null,
  38810. status: null, // Init value depends on whether handle is used.
  38811. // [group0, group1, ...]
  38812. // Each group can be: {
  38813. // mapper: function () {},
  38814. // singleTooltip: 'multiple', // 'multiple' or 'single'
  38815. // xAxisId: ...,
  38816. // yAxisName: ...,
  38817. // angleAxisIndex: ...
  38818. // }
  38819. // mapper: can be ignored.
  38820. // input: {axisInfo, value}
  38821. // output: {axisInfo, value}
  38822. link: [],
  38823. // Do not set 'auto' here, otherwise global animation: false
  38824. // will not effect at this axispointer.
  38825. animation: null,
  38826. animationDurationUpdate: 200,
  38827. lineStyle: {
  38828. color: '#aaa',
  38829. width: 1,
  38830. type: 'solid'
  38831. },
  38832. shadowStyle: {
  38833. color: 'rgba(150,150,150,0.3)'
  38834. },
  38835. label: {
  38836. show: true,
  38837. formatter: null, // string | Function
  38838. precision: 'auto', // Or a number like 0, 1, 2 ...
  38839. margin: 3,
  38840. color: '#fff',
  38841. padding: [5, 7, 5, 7],
  38842. backgroundColor: 'auto', // default: axis line color
  38843. borderColor: null,
  38844. borderWidth: 0,
  38845. shadowBlur: 3,
  38846. shadowColor: '#aaa'
  38847. // Considering applicability, common style should
  38848. // better not have shadowOffset.
  38849. // shadowOffsetX: 0,
  38850. // shadowOffsetY: 2
  38851. },
  38852. handle: {
  38853. show: false,
  38854. /* eslint-disable */
  38855. icon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
  38856. /* eslint-enable */
  38857. size: 45,
  38858. // handle margin is from symbol center to axis, which is stable when circular move.
  38859. margin: 50,
  38860. // color: '#1b8bbd'
  38861. // color: '#2f4554'
  38862. color: '#333',
  38863. shadowBlur: 3,
  38864. shadowColor: '#aaa',
  38865. shadowOffsetX: 0,
  38866. shadowOffsetY: 2,
  38867. // For mobile performance
  38868. throttle: 40
  38869. }
  38870. }
  38871. });
  38872. /*
  38873. * Licensed to the Apache Software Foundation (ASF) under one
  38874. * or more contributor license agreements. See the NOTICE file
  38875. * distributed with this work for additional information
  38876. * regarding copyright ownership. The ASF licenses this file
  38877. * to you under the Apache License, Version 2.0 (the
  38878. * "License"); you may not use this file except in compliance
  38879. * with the License. You may obtain a copy of the License at
  38880. *
  38881. * http://www.apache.org/licenses/LICENSE-2.0
  38882. *
  38883. * Unless required by applicable law or agreed to in writing,
  38884. * software distributed under the License is distributed on an
  38885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38886. * KIND, either express or implied. See the License for the
  38887. * specific language governing permissions and limitations
  38888. * under the License.
  38889. */
  38890. var inner$8 = makeInner();
  38891. var each$8 = each$1;
  38892. /**
  38893. * @param {string} key
  38894. * @param {module:echarts/ExtensionAPI} api
  38895. * @param {Function} handler
  38896. * param: {string} currTrigger
  38897. * param: {Array.<number>} point
  38898. */
  38899. function register(key, api, handler) {
  38900. if (env$1.node) {
  38901. return;
  38902. }
  38903. var zr = api.getZr();
  38904. inner$8(zr).records || (inner$8(zr).records = {});
  38905. initGlobalListeners(zr, api);
  38906. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  38907. record.handler = handler;
  38908. }
  38909. function initGlobalListeners(zr, api) {
  38910. if (inner$8(zr).initialized) {
  38911. return;
  38912. }
  38913. inner$8(zr).initialized = true;
  38914. useHandler('click', curry(doEnter, 'click'));
  38915. useHandler('mousemove', curry(doEnter, 'mousemove'));
  38916. // useHandler('mouseout', onLeave);
  38917. useHandler('globalout', onLeave);
  38918. function useHandler(eventType, cb) {
  38919. zr.on(eventType, function (e) {
  38920. var dis = makeDispatchAction(api);
  38921. each$8(inner$8(zr).records, function (record) {
  38922. record && cb(record, e, dis.dispatchAction);
  38923. });
  38924. dispatchTooltipFinally(dis.pendings, api);
  38925. });
  38926. }
  38927. }
  38928. function dispatchTooltipFinally(pendings, api) {
  38929. var showLen = pendings.showTip.length;
  38930. var hideLen = pendings.hideTip.length;
  38931. var actuallyPayload;
  38932. if (showLen) {
  38933. actuallyPayload = pendings.showTip[showLen - 1];
  38934. }
  38935. else if (hideLen) {
  38936. actuallyPayload = pendings.hideTip[hideLen - 1];
  38937. }
  38938. if (actuallyPayload) {
  38939. actuallyPayload.dispatchAction = null;
  38940. api.dispatchAction(actuallyPayload);
  38941. }
  38942. }
  38943. function onLeave(record, e, dispatchAction) {
  38944. record.handler('leave', null, dispatchAction);
  38945. }
  38946. function doEnter(currTrigger, record, e, dispatchAction) {
  38947. record.handler(currTrigger, e, dispatchAction);
  38948. }
  38949. function makeDispatchAction(api) {
  38950. var pendings = {
  38951. showTip: [],
  38952. hideTip: []
  38953. };
  38954. // FIXME
  38955. // better approach?
  38956. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  38957. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  38958. // So we have to add "final stage" to merge those dispatched actions.
  38959. var dispatchAction = function (payload) {
  38960. var pendingList = pendings[payload.type];
  38961. if (pendingList) {
  38962. pendingList.push(payload);
  38963. }
  38964. else {
  38965. payload.dispatchAction = dispatchAction;
  38966. api.dispatchAction(payload);
  38967. }
  38968. };
  38969. return {
  38970. dispatchAction: dispatchAction,
  38971. pendings: pendings
  38972. };
  38973. }
  38974. /**
  38975. * @param {string} key
  38976. * @param {module:echarts/ExtensionAPI} api
  38977. */
  38978. function unregister(key, api) {
  38979. if (env$1.node) {
  38980. return;
  38981. }
  38982. var zr = api.getZr();
  38983. var record = (inner$8(zr).records || {})[key];
  38984. if (record) {
  38985. inner$8(zr).records[key] = null;
  38986. }
  38987. }
  38988. /*
  38989. * Licensed to the Apache Software Foundation (ASF) under one
  38990. * or more contributor license agreements. See the NOTICE file
  38991. * distributed with this work for additional information
  38992. * regarding copyright ownership. The ASF licenses this file
  38993. * to you under the Apache License, Version 2.0 (the
  38994. * "License"); you may not use this file except in compliance
  38995. * with the License. You may obtain a copy of the License at
  38996. *
  38997. * http://www.apache.org/licenses/LICENSE-2.0
  38998. *
  38999. * Unless required by applicable law or agreed to in writing,
  39000. * software distributed under the License is distributed on an
  39001. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39002. * KIND, either express or implied. See the License for the
  39003. * specific language governing permissions and limitations
  39004. * under the License.
  39005. */
  39006. var AxisPointerView = extendComponentView({
  39007. type: 'axisPointer',
  39008. render: function (globalAxisPointerModel, ecModel, api) {
  39009. var globalTooltipModel = ecModel.getComponent('tooltip');
  39010. var triggerOn = globalAxisPointerModel.get('triggerOn')
  39011. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  39012. // Register global listener in AxisPointerView to enable
  39013. // AxisPointerView to be independent to Tooltip.
  39014. register(
  39015. 'axisPointer',
  39016. api,
  39017. function (currTrigger, e, dispatchAction) {
  39018. // If 'none', it is not controlled by mouse totally.
  39019. if (triggerOn !== 'none'
  39020. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  39021. ) {
  39022. dispatchAction({
  39023. type: 'updateAxisPointer',
  39024. currTrigger: currTrigger,
  39025. x: e && e.offsetX,
  39026. y: e && e.offsetY
  39027. });
  39028. }
  39029. }
  39030. );
  39031. },
  39032. /**
  39033. * @override
  39034. */
  39035. remove: function (ecModel, api) {
  39036. unregister(api.getZr(), 'axisPointer');
  39037. AxisPointerView.superApply(this._model, 'remove', arguments);
  39038. },
  39039. /**
  39040. * @override
  39041. */
  39042. dispose: function (ecModel, api) {
  39043. unregister('axisPointer', api);
  39044. AxisPointerView.superApply(this._model, 'dispose', arguments);
  39045. }
  39046. });
  39047. /*
  39048. * Licensed to the Apache Software Foundation (ASF) under one
  39049. * or more contributor license agreements. See the NOTICE file
  39050. * distributed with this work for additional information
  39051. * regarding copyright ownership. The ASF licenses this file
  39052. * to you under the Apache License, Version 2.0 (the
  39053. * "License"); you may not use this file except in compliance
  39054. * with the License. You may obtain a copy of the License at
  39055. *
  39056. * http://www.apache.org/licenses/LICENSE-2.0
  39057. *
  39058. * Unless required by applicable law or agreed to in writing,
  39059. * software distributed under the License is distributed on an
  39060. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39061. * KIND, either express or implied. See the License for the
  39062. * specific language governing permissions and limitations
  39063. * under the License.
  39064. */
  39065. var inner$9 = makeInner();
  39066. var clone$4 = clone;
  39067. var bind$1 = bind;
  39068. /**
  39069. * Base axis pointer class in 2D.
  39070. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  39071. */
  39072. function BaseAxisPointer() {
  39073. }
  39074. BaseAxisPointer.prototype = {
  39075. /**
  39076. * @private
  39077. */
  39078. _group: null,
  39079. /**
  39080. * @private
  39081. */
  39082. _lastGraphicKey: null,
  39083. /**
  39084. * @private
  39085. */
  39086. _handle: null,
  39087. /**
  39088. * @private
  39089. */
  39090. _dragging: false,
  39091. /**
  39092. * @private
  39093. */
  39094. _lastValue: null,
  39095. /**
  39096. * @private
  39097. */
  39098. _lastStatus: null,
  39099. /**
  39100. * @private
  39101. */
  39102. _payloadInfo: null,
  39103. /**
  39104. * In px, arbitrary value. Do not set too small,
  39105. * no animation is ok for most cases.
  39106. * @protected
  39107. */
  39108. animationThreshold: 15,
  39109. /**
  39110. * @implement
  39111. */
  39112. render: function (axisModel, axisPointerModel, api, forceRender) {
  39113. var value = axisPointerModel.get('value');
  39114. var status = axisPointerModel.get('status');
  39115. // Bind them to `this`, not in closure, otherwise they will not
  39116. // be replaced when user calling setOption in not merge mode.
  39117. this._axisModel = axisModel;
  39118. this._axisPointerModel = axisPointerModel;
  39119. this._api = api;
  39120. // Optimize: `render` will be called repeatly during mouse move.
  39121. // So it is power consuming if performing `render` each time,
  39122. // especially on mobile device.
  39123. if (!forceRender
  39124. && this._lastValue === value
  39125. && this._lastStatus === status
  39126. ) {
  39127. return;
  39128. }
  39129. this._lastValue = value;
  39130. this._lastStatus = status;
  39131. var group = this._group;
  39132. var handle = this._handle;
  39133. if (!status || status === 'hide') {
  39134. // Do not clear here, for animation better.
  39135. group && group.hide();
  39136. handle && handle.hide();
  39137. return;
  39138. }
  39139. group && group.show();
  39140. handle && handle.show();
  39141. // Otherwise status is 'show'
  39142. var elOption = {};
  39143. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  39144. // Enable change axis pointer type.
  39145. var graphicKey = elOption.graphicKey;
  39146. if (graphicKey !== this._lastGraphicKey) {
  39147. this.clear(api);
  39148. }
  39149. this._lastGraphicKey = graphicKey;
  39150. var moveAnimation = this._moveAnimation
  39151. = this.determineAnimation(axisModel, axisPointerModel);
  39152. if (!group) {
  39153. group = this._group = new Group();
  39154. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  39155. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  39156. api.getZr().add(group);
  39157. }
  39158. else {
  39159. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  39160. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  39161. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  39162. }
  39163. updateMandatoryProps(group, axisPointerModel, true);
  39164. this._renderHandle(value);
  39165. },
  39166. /**
  39167. * @implement
  39168. */
  39169. remove: function (api) {
  39170. this.clear(api);
  39171. },
  39172. /**
  39173. * @implement
  39174. */
  39175. dispose: function (api) {
  39176. this.clear(api);
  39177. },
  39178. /**
  39179. * @protected
  39180. */
  39181. determineAnimation: function (axisModel, axisPointerModel) {
  39182. var animation = axisPointerModel.get('animation');
  39183. var axis = axisModel.axis;
  39184. var isCategoryAxis = axis.type === 'category';
  39185. var useSnap = axisPointerModel.get('snap');
  39186. // Value axis without snap always do not snap.
  39187. if (!useSnap && !isCategoryAxis) {
  39188. return false;
  39189. }
  39190. if (animation === 'auto' || animation == null) {
  39191. var animationThreshold = this.animationThreshold;
  39192. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  39193. return true;
  39194. }
  39195. // It is important to auto animation when snap used. Consider if there is
  39196. // a dataZoom, animation will be disabled when too many points exist, while
  39197. // it will be enabled for better visual effect when little points exist.
  39198. if (useSnap) {
  39199. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  39200. var axisExtent = axis.getExtent();
  39201. // Approximate band width
  39202. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  39203. }
  39204. return false;
  39205. }
  39206. return animation === true;
  39207. },
  39208. /**
  39209. * add {pointer, label, graphicKey} to elOption
  39210. * @protected
  39211. */
  39212. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  39213. // Shoule be implemenented by sub-class.
  39214. },
  39215. /**
  39216. * @protected
  39217. */
  39218. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  39219. var pointerOption = elOption.pointer;
  39220. if (pointerOption) {
  39221. var pointerEl = inner$9(group).pointerEl = new graphic[pointerOption.type](
  39222. clone$4(elOption.pointer)
  39223. );
  39224. group.add(pointerEl);
  39225. }
  39226. },
  39227. /**
  39228. * @protected
  39229. */
  39230. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  39231. if (elOption.label) {
  39232. var labelEl = inner$9(group).labelEl = new Rect(
  39233. clone$4(elOption.label)
  39234. );
  39235. group.add(labelEl);
  39236. updateLabelShowHide(labelEl, axisPointerModel);
  39237. }
  39238. },
  39239. /**
  39240. * @protected
  39241. */
  39242. updatePointerEl: function (group, elOption, updateProps$$1) {
  39243. var pointerEl = inner$9(group).pointerEl;
  39244. if (pointerEl) {
  39245. pointerEl.setStyle(elOption.pointer.style);
  39246. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  39247. }
  39248. },
  39249. /**
  39250. * @protected
  39251. */
  39252. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  39253. var labelEl = inner$9(group).labelEl;
  39254. if (labelEl) {
  39255. labelEl.setStyle(elOption.label.style);
  39256. updateProps$$1(labelEl, {
  39257. // Consider text length change in vertical axis, animation should
  39258. // be used on shape, otherwise the effect will be weird.
  39259. shape: elOption.label.shape,
  39260. position: elOption.label.position
  39261. });
  39262. updateLabelShowHide(labelEl, axisPointerModel);
  39263. }
  39264. },
  39265. /**
  39266. * @private
  39267. */
  39268. _renderHandle: function (value) {
  39269. if (this._dragging || !this.updateHandleTransform) {
  39270. return;
  39271. }
  39272. var axisPointerModel = this._axisPointerModel;
  39273. var zr = this._api.getZr();
  39274. var handle = this._handle;
  39275. var handleModel = axisPointerModel.getModel('handle');
  39276. var status = axisPointerModel.get('status');
  39277. if (!handleModel.get('show') || !status || status === 'hide') {
  39278. handle && zr.remove(handle);
  39279. this._handle = null;
  39280. return;
  39281. }
  39282. var isInit;
  39283. if (!this._handle) {
  39284. isInit = true;
  39285. handle = this._handle = createIcon(
  39286. handleModel.get('icon'),
  39287. {
  39288. cursor: 'move',
  39289. draggable: true,
  39290. onmousemove: function (e) {
  39291. // Fot mobile devicem, prevent screen slider on the button.
  39292. stop(e.event);
  39293. },
  39294. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  39295. drift: bind$1(this._onHandleDragMove, this),
  39296. ondragend: bind$1(this._onHandleDragEnd, this)
  39297. }
  39298. );
  39299. zr.add(handle);
  39300. }
  39301. updateMandatoryProps(handle, axisPointerModel, false);
  39302. // update style
  39303. var includeStyles = [
  39304. 'color', 'borderColor', 'borderWidth', 'opacity',
  39305. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  39306. ];
  39307. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  39308. // update position
  39309. var handleSize = handleModel.get('size');
  39310. if (!isArray(handleSize)) {
  39311. handleSize = [handleSize, handleSize];
  39312. }
  39313. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  39314. createOrUpdate(
  39315. this,
  39316. '_doDispatchAxisPointer',
  39317. handleModel.get('throttle') || 0,
  39318. 'fixRate'
  39319. );
  39320. this._moveHandleToValue(value, isInit);
  39321. },
  39322. /**
  39323. * @private
  39324. */
  39325. _moveHandleToValue: function (value, isInit) {
  39326. updateProps$1(
  39327. this._axisPointerModel,
  39328. !isInit && this._moveAnimation,
  39329. this._handle,
  39330. getHandleTransProps(this.getHandleTransform(
  39331. value, this._axisModel, this._axisPointerModel
  39332. ))
  39333. );
  39334. },
  39335. /**
  39336. * @private
  39337. */
  39338. _onHandleDragMove: function (dx, dy) {
  39339. var handle = this._handle;
  39340. if (!handle) {
  39341. return;
  39342. }
  39343. this._dragging = true;
  39344. // Persistent for throttle.
  39345. var trans = this.updateHandleTransform(
  39346. getHandleTransProps(handle),
  39347. [dx, dy],
  39348. this._axisModel,
  39349. this._axisPointerModel
  39350. );
  39351. this._payloadInfo = trans;
  39352. handle.stopAnimation();
  39353. handle.attr(getHandleTransProps(trans));
  39354. inner$9(handle).lastProp = null;
  39355. this._doDispatchAxisPointer();
  39356. },
  39357. /**
  39358. * Throttled method.
  39359. * @private
  39360. */
  39361. _doDispatchAxisPointer: function () {
  39362. var handle = this._handle;
  39363. if (!handle) {
  39364. return;
  39365. }
  39366. var payloadInfo = this._payloadInfo;
  39367. var axisModel = this._axisModel;
  39368. this._api.dispatchAction({
  39369. type: 'updateAxisPointer',
  39370. x: payloadInfo.cursorPoint[0],
  39371. y: payloadInfo.cursorPoint[1],
  39372. tooltipOption: payloadInfo.tooltipOption,
  39373. axesInfo: [{
  39374. axisDim: axisModel.axis.dim,
  39375. axisIndex: axisModel.componentIndex
  39376. }]
  39377. });
  39378. },
  39379. /**
  39380. * @private
  39381. */
  39382. _onHandleDragEnd: function (moveAnimation) {
  39383. this._dragging = false;
  39384. var handle = this._handle;
  39385. if (!handle) {
  39386. return;
  39387. }
  39388. var value = this._axisPointerModel.get('value');
  39389. // Consider snap or categroy axis, handle may be not consistent with
  39390. // axisPointer. So move handle to align the exact value position when
  39391. // drag ended.
  39392. this._moveHandleToValue(value);
  39393. // For the effect: tooltip will be shown when finger holding on handle
  39394. // button, and will be hidden after finger left handle button.
  39395. this._api.dispatchAction({
  39396. type: 'hideTip'
  39397. });
  39398. },
  39399. /**
  39400. * Should be implemenented by sub-class if support `handle`.
  39401. * @protected
  39402. * @param {number} value
  39403. * @param {module:echarts/model/Model} axisModel
  39404. * @param {module:echarts/model/Model} axisPointerModel
  39405. * @return {Object} {position: [x, y], rotation: 0}
  39406. */
  39407. getHandleTransform: null,
  39408. /**
  39409. * * Should be implemenented by sub-class if support `handle`.
  39410. * @protected
  39411. * @param {Object} transform {position, rotation}
  39412. * @param {Array.<number>} delta [dx, dy]
  39413. * @param {module:echarts/model/Model} axisModel
  39414. * @param {module:echarts/model/Model} axisPointerModel
  39415. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  39416. */
  39417. updateHandleTransform: null,
  39418. /**
  39419. * @private
  39420. */
  39421. clear: function (api) {
  39422. this._lastValue = null;
  39423. this._lastStatus = null;
  39424. var zr = api.getZr();
  39425. var group = this._group;
  39426. var handle = this._handle;
  39427. if (zr && group) {
  39428. this._lastGraphicKey = null;
  39429. group && zr.remove(group);
  39430. handle && zr.remove(handle);
  39431. this._group = null;
  39432. this._handle = null;
  39433. this._payloadInfo = null;
  39434. }
  39435. },
  39436. /**
  39437. * @protected
  39438. */
  39439. doClear: function () {
  39440. // Implemented by sub-class if necessary.
  39441. },
  39442. /**
  39443. * @protected
  39444. * @param {Array.<number>} xy
  39445. * @param {Array.<number>} wh
  39446. * @param {number} [xDimIndex=0] or 1
  39447. */
  39448. buildLabel: function (xy, wh, xDimIndex) {
  39449. xDimIndex = xDimIndex || 0;
  39450. return {
  39451. x: xy[xDimIndex],
  39452. y: xy[1 - xDimIndex],
  39453. width: wh[xDimIndex],
  39454. height: wh[1 - xDimIndex]
  39455. };
  39456. }
  39457. };
  39458. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  39459. function updateProps$1(animationModel, moveAnimation, el, props) {
  39460. // Animation optimize.
  39461. if (!propsEqual(inner$9(el).lastProp, props)) {
  39462. inner$9(el).lastProp = props;
  39463. moveAnimation
  39464. ? updateProps(el, props, animationModel)
  39465. : (el.stopAnimation(), el.attr(props));
  39466. }
  39467. }
  39468. function propsEqual(lastProps, newProps) {
  39469. if (isObject$1(lastProps) && isObject$1(newProps)) {
  39470. var equals = true;
  39471. each$1(newProps, function (item, key) {
  39472. equals = equals && propsEqual(lastProps[key], item);
  39473. });
  39474. return !!equals;
  39475. }
  39476. else {
  39477. return lastProps === newProps;
  39478. }
  39479. }
  39480. function updateLabelShowHide(labelEl, axisPointerModel) {
  39481. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  39482. }
  39483. function getHandleTransProps(trans) {
  39484. return {
  39485. position: trans.position.slice(),
  39486. rotation: trans.rotation || 0
  39487. };
  39488. }
  39489. function updateMandatoryProps(group, axisPointerModel, silent) {
  39490. var z = axisPointerModel.get('z');
  39491. var zlevel = axisPointerModel.get('zlevel');
  39492. group && group.traverse(function (el) {
  39493. if (el.type !== 'group') {
  39494. z != null && (el.z = z);
  39495. zlevel != null && (el.zlevel = zlevel);
  39496. el.silent = silent;
  39497. }
  39498. });
  39499. }
  39500. enableClassExtend(BaseAxisPointer);
  39501. /*
  39502. * Licensed to the Apache Software Foundation (ASF) under one
  39503. * or more contributor license agreements. See the NOTICE file
  39504. * distributed with this work for additional information
  39505. * regarding copyright ownership. The ASF licenses this file
  39506. * to you under the Apache License, Version 2.0 (the
  39507. * "License"); you may not use this file except in compliance
  39508. * with the License. You may obtain a copy of the License at
  39509. *
  39510. * http://www.apache.org/licenses/LICENSE-2.0
  39511. *
  39512. * Unless required by applicable law or agreed to in writing,
  39513. * software distributed under the License is distributed on an
  39514. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39515. * KIND, either express or implied. See the License for the
  39516. * specific language governing permissions and limitations
  39517. * under the License.
  39518. */
  39519. /**
  39520. * @param {module:echarts/model/Model} axisPointerModel
  39521. */
  39522. function buildElStyle(axisPointerModel) {
  39523. var axisPointerType = axisPointerModel.get('type');
  39524. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  39525. var style;
  39526. if (axisPointerType === 'line') {
  39527. style = styleModel.getLineStyle();
  39528. style.fill = null;
  39529. }
  39530. else if (axisPointerType === 'shadow') {
  39531. style = styleModel.getAreaStyle();
  39532. style.stroke = null;
  39533. }
  39534. return style;
  39535. }
  39536. /**
  39537. * @param {Function} labelPos {align, verticalAlign, position}
  39538. */
  39539. function buildLabelElOption(
  39540. elOption, axisModel, axisPointerModel, api, labelPos
  39541. ) {
  39542. var value = axisPointerModel.get('value');
  39543. var text = getValueLabel(
  39544. value, axisModel.axis, axisModel.ecModel,
  39545. axisPointerModel.get('seriesDataIndices'),
  39546. {
  39547. precision: axisPointerModel.get('label.precision'),
  39548. formatter: axisPointerModel.get('label.formatter')
  39549. }
  39550. );
  39551. var labelModel = axisPointerModel.getModel('label');
  39552. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  39553. var font = labelModel.getFont();
  39554. var textRect = getBoundingRect(text, font);
  39555. var position = labelPos.position;
  39556. var width = textRect.width + paddings[1] + paddings[3];
  39557. var height = textRect.height + paddings[0] + paddings[2];
  39558. // Adjust by align.
  39559. var align = labelPos.align;
  39560. align === 'right' && (position[0] -= width);
  39561. align === 'center' && (position[0] -= width / 2);
  39562. var verticalAlign = labelPos.verticalAlign;
  39563. verticalAlign === 'bottom' && (position[1] -= height);
  39564. verticalAlign === 'middle' && (position[1] -= height / 2);
  39565. // Not overflow ec container
  39566. confineInContainer(position, width, height, api);
  39567. var bgColor = labelModel.get('backgroundColor');
  39568. if (!bgColor || bgColor === 'auto') {
  39569. bgColor = axisModel.get('axisLine.lineStyle.color');
  39570. }
  39571. elOption.label = {
  39572. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  39573. position: position.slice(),
  39574. // TODO: rich
  39575. style: {
  39576. text: text,
  39577. textFont: font,
  39578. textFill: labelModel.getTextColor(),
  39579. textPosition: 'inside',
  39580. fill: bgColor,
  39581. stroke: labelModel.get('borderColor') || 'transparent',
  39582. lineWidth: labelModel.get('borderWidth') || 0,
  39583. shadowBlur: labelModel.get('shadowBlur'),
  39584. shadowColor: labelModel.get('shadowColor'),
  39585. shadowOffsetX: labelModel.get('shadowOffsetX'),
  39586. shadowOffsetY: labelModel.get('shadowOffsetY')
  39587. },
  39588. // Lable should be over axisPointer.
  39589. z2: 10
  39590. };
  39591. }
  39592. // Do not overflow ec container
  39593. function confineInContainer(position, width, height, api) {
  39594. var viewWidth = api.getWidth();
  39595. var viewHeight = api.getHeight();
  39596. position[0] = Math.min(position[0] + width, viewWidth) - width;
  39597. position[1] = Math.min(position[1] + height, viewHeight) - height;
  39598. position[0] = Math.max(position[0], 0);
  39599. position[1] = Math.max(position[1], 0);
  39600. }
  39601. /**
  39602. * @param {number} value
  39603. * @param {module:echarts/coord/Axis} axis
  39604. * @param {module:echarts/model/Global} ecModel
  39605. * @param {Object} opt
  39606. * @param {Array.<Object>} seriesDataIndices
  39607. * @param {number|string} opt.precision 'auto' or a number
  39608. * @param {string|Function} opt.formatter label formatter
  39609. */
  39610. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  39611. value = axis.scale.parse(value);
  39612. var text = axis.scale.getLabel(
  39613. // If `precision` is set, width can be fixed (like '12.00500'), which
  39614. // helps to debounce when when moving label.
  39615. value, {precision: opt.precision}
  39616. );
  39617. var formatter = opt.formatter;
  39618. if (formatter) {
  39619. var params = {
  39620. value: getAxisRawValue(axis, value),
  39621. seriesData: []
  39622. };
  39623. each$1(seriesDataIndices, function (idxItem) {
  39624. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  39625. var dataIndex = idxItem.dataIndexInside;
  39626. var dataParams = series && series.getDataParams(dataIndex);
  39627. dataParams && params.seriesData.push(dataParams);
  39628. });
  39629. if (isString(formatter)) {
  39630. text = formatter.replace('{value}', text);
  39631. }
  39632. else if (isFunction$1(formatter)) {
  39633. text = formatter(params);
  39634. }
  39635. }
  39636. return text;
  39637. }
  39638. /**
  39639. * @param {module:echarts/coord/Axis} axis
  39640. * @param {number} value
  39641. * @param {Object} layoutInfo {
  39642. * rotation, position, labelOffset, labelDirection, labelMargin
  39643. * }
  39644. */
  39645. function getTransformedPosition(axis, value, layoutInfo) {
  39646. var transform = create$1();
  39647. rotate(transform, transform, layoutInfo.rotation);
  39648. translate(transform, transform, layoutInfo.position);
  39649. return applyTransform$1([
  39650. axis.dataToCoord(value),
  39651. (layoutInfo.labelOffset || 0)
  39652. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  39653. ], transform);
  39654. }
  39655. function buildCartesianSingleLabelElOption(
  39656. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  39657. ) {
  39658. var textLayout = AxisBuilder.innerTextLayout(
  39659. layoutInfo.rotation, 0, layoutInfo.labelDirection
  39660. );
  39661. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  39662. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  39663. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  39664. align: textLayout.textAlign,
  39665. verticalAlign: textLayout.textVerticalAlign
  39666. });
  39667. }
  39668. /**
  39669. * @param {Array.<number>} p1
  39670. * @param {Array.<number>} p2
  39671. * @param {number} [xDimIndex=0] or 1
  39672. */
  39673. function makeLineShape(p1, p2, xDimIndex) {
  39674. xDimIndex = xDimIndex || 0;
  39675. return {
  39676. x1: p1[xDimIndex],
  39677. y1: p1[1 - xDimIndex],
  39678. x2: p2[xDimIndex],
  39679. y2: p2[1 - xDimIndex]
  39680. };
  39681. }
  39682. /**
  39683. * @param {Array.<number>} xy
  39684. * @param {Array.<number>} wh
  39685. * @param {number} [xDimIndex=0] or 1
  39686. */
  39687. function makeRectShape(xy, wh, xDimIndex) {
  39688. xDimIndex = xDimIndex || 0;
  39689. return {
  39690. x: xy[xDimIndex],
  39691. y: xy[1 - xDimIndex],
  39692. width: wh[xDimIndex],
  39693. height: wh[1 - xDimIndex]
  39694. };
  39695. }
  39696. /*
  39697. * Licensed to the Apache Software Foundation (ASF) under one
  39698. * or more contributor license agreements. See the NOTICE file
  39699. * distributed with this work for additional information
  39700. * regarding copyright ownership. The ASF licenses this file
  39701. * to you under the Apache License, Version 2.0 (the
  39702. * "License"); you may not use this file except in compliance
  39703. * with the License. You may obtain a copy of the License at
  39704. *
  39705. * http://www.apache.org/licenses/LICENSE-2.0
  39706. *
  39707. * Unless required by applicable law or agreed to in writing,
  39708. * software distributed under the License is distributed on an
  39709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39710. * KIND, either express or implied. See the License for the
  39711. * specific language governing permissions and limitations
  39712. * under the License.
  39713. */
  39714. var CartesianAxisPointer = BaseAxisPointer.extend({
  39715. /**
  39716. * @override
  39717. */
  39718. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  39719. var axis = axisModel.axis;
  39720. var grid = axis.grid;
  39721. var axisPointerType = axisPointerModel.get('type');
  39722. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  39723. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  39724. if (axisPointerType && axisPointerType !== 'none') {
  39725. var elStyle = buildElStyle(axisPointerModel);
  39726. var pointerOption = pointerShapeBuilder[axisPointerType](
  39727. axis, pixelValue, otherExtent, elStyle
  39728. );
  39729. pointerOption.style = elStyle;
  39730. elOption.graphicKey = pointerOption.type;
  39731. elOption.pointer = pointerOption;
  39732. }
  39733. var layoutInfo = layout$1(grid.model, axisModel);
  39734. buildCartesianSingleLabelElOption(
  39735. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  39736. );
  39737. },
  39738. /**
  39739. * @override
  39740. */
  39741. getHandleTransform: function (value, axisModel, axisPointerModel) {
  39742. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  39743. labelInside: false
  39744. });
  39745. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  39746. return {
  39747. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  39748. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  39749. };
  39750. },
  39751. /**
  39752. * @override
  39753. */
  39754. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  39755. var axis = axisModel.axis;
  39756. var grid = axis.grid;
  39757. var axisExtent = axis.getGlobalExtent(true);
  39758. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  39759. var dimIndex = axis.dim === 'x' ? 0 : 1;
  39760. var currPosition = transform.position;
  39761. currPosition[dimIndex] += delta[dimIndex];
  39762. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  39763. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  39764. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  39765. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  39766. cursorPoint[dimIndex] = currPosition[dimIndex];
  39767. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  39768. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  39769. return {
  39770. position: currPosition,
  39771. rotation: transform.rotation,
  39772. cursorPoint: cursorPoint,
  39773. tooltipOption: tooltipOptions[dimIndex]
  39774. };
  39775. }
  39776. });
  39777. function getCartesian(grid, axis) {
  39778. var opt = {};
  39779. opt[axis.dim + 'AxisIndex'] = axis.index;
  39780. return grid.getCartesian(opt);
  39781. }
  39782. var pointerShapeBuilder = {
  39783. line: function (axis, pixelValue, otherExtent, elStyle) {
  39784. var targetShape = makeLineShape(
  39785. [pixelValue, otherExtent[0]],
  39786. [pixelValue, otherExtent[1]],
  39787. getAxisDimIndex(axis)
  39788. );
  39789. subPixelOptimizeLine({
  39790. shape: targetShape,
  39791. style: elStyle
  39792. });
  39793. return {
  39794. type: 'Line',
  39795. shape: targetShape
  39796. };
  39797. },
  39798. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  39799. var bandWidth = Math.max(1, axis.getBandWidth());
  39800. var span = otherExtent[1] - otherExtent[0];
  39801. return {
  39802. type: 'Rect',
  39803. shape: makeRectShape(
  39804. [pixelValue - bandWidth / 2, otherExtent[0]],
  39805. [bandWidth, span],
  39806. getAxisDimIndex(axis)
  39807. )
  39808. };
  39809. }
  39810. };
  39811. function getAxisDimIndex(axis) {
  39812. return axis.dim === 'x' ? 0 : 1;
  39813. }
  39814. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  39815. /*
  39816. * Licensed to the Apache Software Foundation (ASF) under one
  39817. * or more contributor license agreements. See the NOTICE file
  39818. * distributed with this work for additional information
  39819. * regarding copyright ownership. The ASF licenses this file
  39820. * to you under the Apache License, Version 2.0 (the
  39821. * "License"); you may not use this file except in compliance
  39822. * with the License. You may obtain a copy of the License at
  39823. *
  39824. * http://www.apache.org/licenses/LICENSE-2.0
  39825. *
  39826. * Unless required by applicable law or agreed to in writing,
  39827. * software distributed under the License is distributed on an
  39828. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39829. * KIND, either express or implied. See the License for the
  39830. * specific language governing permissions and limitations
  39831. * under the License.
  39832. */
  39833. // CartesianAxisPointer is not supposed to be required here. But consider
  39834. // echarts.simple.js and online build tooltip, which only require gridSimple,
  39835. // CartesianAxisPointer should be able to required somewhere.
  39836. registerPreprocessor(function (option) {
  39837. // Always has a global axisPointerModel for default setting.
  39838. if (option) {
  39839. (!option.axisPointer || option.axisPointer.length === 0)
  39840. && (option.axisPointer = {});
  39841. var link = option.axisPointer.link;
  39842. // Normalize to array to avoid object mergin. But if link
  39843. // is not set, remain null/undefined, otherwise it will
  39844. // override existent link setting.
  39845. if (link && !isArray(link)) {
  39846. option.axisPointer.link = [link];
  39847. }
  39848. }
  39849. });
  39850. // This process should proformed after coordinate systems created
  39851. // and series data processed. So put it on statistic processing stage.
  39852. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  39853. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  39854. // allAxesInfo should be updated when setOption performed.
  39855. ecModel.getComponent('axisPointer').coordSysAxesInfo
  39856. = collect(ecModel, api);
  39857. });
  39858. // Broadcast to all views.
  39859. registerAction({
  39860. type: 'updateAxisPointer',
  39861. event: 'updateAxisPointer',
  39862. update: ':updateAxisPointer'
  39863. }, axisTrigger);
  39864. /*
  39865. * Licensed to the Apache Software Foundation (ASF) under one
  39866. * or more contributor license agreements. See the NOTICE file
  39867. * distributed with this work for additional information
  39868. * regarding copyright ownership. The ASF licenses this file
  39869. * to you under the Apache License, Version 2.0 (the
  39870. * "License"); you may not use this file except in compliance
  39871. * with the License. You may obtain a copy of the License at
  39872. *
  39873. * http://www.apache.org/licenses/LICENSE-2.0
  39874. *
  39875. * Unless required by applicable law or agreed to in writing,
  39876. * software distributed under the License is distributed on an
  39877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39878. * KIND, either express or implied. See the License for the
  39879. * specific language governing permissions and limitations
  39880. * under the License.
  39881. */
  39882. extendComponentModel({
  39883. type: 'tooltip',
  39884. dependencies: ['axisPointer'],
  39885. defaultOption: {
  39886. zlevel: 0,
  39887. z: 60,
  39888. show: true,
  39889. // tooltip主体内容
  39890. showContent: true,
  39891. // 'trigger' only works on coordinate system.
  39892. // 'item' | 'axis' | 'none'
  39893. trigger: 'item',
  39894. // 'click' | 'mousemove' | 'none'
  39895. triggerOn: 'mousemove|click',
  39896. alwaysShowContent: false,
  39897. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  39898. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  39899. // 'auto': use html by default, and use non-html if `document` is not defined
  39900. // 'html': use html for tooltip
  39901. // 'richText': use canvas, svg, and etc. for tooltip
  39902. // 位置 {Array} | {Function}
  39903. // position: null
  39904. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  39905. // align: null,
  39906. // verticalAlign: null,
  39907. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  39908. confine: false,
  39909. // 内容格式器:{string}(Template) ¦ {Function}
  39910. // formatter: null
  39911. showDelay: 0,
  39912. // 隐藏延迟,单位ms
  39913. hideDelay: 100,
  39914. // 动画变换时间,单位s
  39915. transitionDuration: 0.4,
  39916. enterable: false,
  39917. // 提示背景颜色,默认为透明度为0.7的黑色
  39918. backgroundColor: 'rgba(50,50,50,0.7)',
  39919. // 提示边框颜色
  39920. borderColor: '#333',
  39921. // 提示边框圆角,单位px,默认为4
  39922. borderRadius: 4,
  39923. // 提示边框线宽,单位px,默认为0(无边框)
  39924. borderWidth: 0,
  39925. // 提示内边距,单位px,默认各方向内边距为5,
  39926. // 接受数组分别设定上右下左边距,同css
  39927. padding: 5,
  39928. // Extra css text
  39929. extraCssText: '',
  39930. // 坐标轴指示器,坐标轴触发有效
  39931. axisPointer: {
  39932. // 默认为直线
  39933. // 可选为:'line' | 'shadow' | 'cross'
  39934. type: 'line',
  39935. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  39936. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  39937. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  39938. // 极坐标系会默认选择 angle 轴
  39939. axis: 'auto',
  39940. animation: 'auto',
  39941. animationDurationUpdate: 200,
  39942. animationEasingUpdate: 'exponentialOut',
  39943. crossStyle: {
  39944. color: '#999',
  39945. width: 1,
  39946. type: 'dashed',
  39947. // TODO formatter
  39948. textStyle: {}
  39949. }
  39950. // lineStyle and shadowStyle should not be specified here,
  39951. // otherwise it will always override those styles on option.axisPointer.
  39952. },
  39953. textStyle: {
  39954. color: '#fff',
  39955. fontSize: 14
  39956. }
  39957. }
  39958. });
  39959. /*
  39960. * Licensed to the Apache Software Foundation (ASF) under one
  39961. * or more contributor license agreements. See the NOTICE file
  39962. * distributed with this work for additional information
  39963. * regarding copyright ownership. The ASF licenses this file
  39964. * to you under the Apache License, Version 2.0 (the
  39965. * "License"); you may not use this file except in compliance
  39966. * with the License. You may obtain a copy of the License at
  39967. *
  39968. * http://www.apache.org/licenses/LICENSE-2.0
  39969. *
  39970. * Unless required by applicable law or agreed to in writing,
  39971. * software distributed under the License is distributed on an
  39972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39973. * KIND, either express or implied. See the License for the
  39974. * specific language governing permissions and limitations
  39975. * under the License.
  39976. */
  39977. var each$10 = each$1;
  39978. var toCamelCase$1 = toCamelCase;
  39979. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  39980. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  39981. /**
  39982. * @param {number} duration
  39983. * @return {string}
  39984. * @inner
  39985. */
  39986. function assembleTransition(duration) {
  39987. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  39988. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  39989. + 'top ' + duration + 's ' + transitionCurve;
  39990. return map(vendors, function (vendorPrefix) {
  39991. return vendorPrefix + 'transition:' + transitionText;
  39992. }).join(';');
  39993. }
  39994. /**
  39995. * @param {Object} textStyle
  39996. * @return {string}
  39997. * @inner
  39998. */
  39999. function assembleFont(textStyleModel) {
  40000. var cssText = [];
  40001. var fontSize = textStyleModel.get('fontSize');
  40002. var color = textStyleModel.getTextColor();
  40003. color && cssText.push('color:' + color);
  40004. cssText.push('font:' + textStyleModel.getFont());
  40005. fontSize
  40006. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  40007. each$10(['decoration', 'align'], function (name) {
  40008. var val = textStyleModel.get(name);
  40009. val && cssText.push('text-' + name + ':' + val);
  40010. });
  40011. return cssText.join(';');
  40012. }
  40013. /**
  40014. * @param {Object} tooltipModel
  40015. * @return {string}
  40016. * @inner
  40017. */
  40018. function assembleCssText(tooltipModel) {
  40019. var cssText = [];
  40020. var transitionDuration = tooltipModel.get('transitionDuration');
  40021. var backgroundColor = tooltipModel.get('backgroundColor');
  40022. var textStyleModel = tooltipModel.getModel('textStyle');
  40023. var padding = tooltipModel.get('padding');
  40024. // Animation transition. Do not animate when transitionDuration is 0.
  40025. transitionDuration
  40026. && cssText.push(assembleTransition(transitionDuration));
  40027. if (backgroundColor) {
  40028. if (env$1.canvasSupported) {
  40029. cssText.push('background-Color:' + backgroundColor);
  40030. }
  40031. else {
  40032. // for ie
  40033. cssText.push(
  40034. 'background-Color:#' + toHex(backgroundColor)
  40035. );
  40036. cssText.push('filter:alpha(opacity=70)');
  40037. }
  40038. }
  40039. // Border style
  40040. each$10(['width', 'color', 'radius'], function (name) {
  40041. var borderName = 'border-' + name;
  40042. var camelCase = toCamelCase$1(borderName);
  40043. var val = tooltipModel.get(camelCase);
  40044. val != null
  40045. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  40046. });
  40047. // Text style
  40048. cssText.push(assembleFont(textStyleModel));
  40049. // Padding
  40050. if (padding != null) {
  40051. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  40052. }
  40053. return cssText.join(';') + ';';
  40054. }
  40055. /**
  40056. * @alias module:echarts/component/tooltip/TooltipContent
  40057. * @constructor
  40058. */
  40059. function TooltipContent(container, api) {
  40060. if (env$1.wxa) {
  40061. return null;
  40062. }
  40063. var el = document.createElement('div');
  40064. var zr = this._zr = api.getZr();
  40065. this.el = el;
  40066. this._x = api.getWidth() / 2;
  40067. this._y = api.getHeight() / 2;
  40068. container.appendChild(el);
  40069. this._container = container;
  40070. this._show = false;
  40071. /**
  40072. * @private
  40073. */
  40074. this._hideTimeout;
  40075. var self = this;
  40076. el.onmouseenter = function () {
  40077. // clear the timeout in hideLater and keep showing tooltip
  40078. if (self._enterable) {
  40079. clearTimeout(self._hideTimeout);
  40080. self._show = true;
  40081. }
  40082. self._inContent = true;
  40083. };
  40084. el.onmousemove = function (e) {
  40085. e = e || window.event;
  40086. if (!self._enterable) {
  40087. // Try trigger zrender event to avoid mouse
  40088. // in and out shape too frequently
  40089. var handler = zr.handler;
  40090. normalizeEvent(container, e, true);
  40091. handler.dispatch('mousemove', e);
  40092. }
  40093. };
  40094. el.onmouseleave = function () {
  40095. if (self._enterable) {
  40096. if (self._show) {
  40097. self.hideLater(self._hideDelay);
  40098. }
  40099. }
  40100. self._inContent = false;
  40101. };
  40102. }
  40103. TooltipContent.prototype = {
  40104. constructor: TooltipContent,
  40105. /**
  40106. * @private
  40107. * @type {boolean}
  40108. */
  40109. _enterable: true,
  40110. /**
  40111. * Update when tooltip is rendered
  40112. */
  40113. update: function () {
  40114. // FIXME
  40115. // Move this logic to ec main?
  40116. var container = this._container;
  40117. var stl = container.currentStyle
  40118. || document.defaultView.getComputedStyle(container);
  40119. var domStyle = container.style;
  40120. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  40121. domStyle.position = 'relative';
  40122. }
  40123. // Hide the tooltip
  40124. // PENDING
  40125. // this.hide();
  40126. },
  40127. show: function (tooltipModel) {
  40128. clearTimeout(this._hideTimeout);
  40129. var el = this.el;
  40130. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  40131. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  40132. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  40133. + (tooltipModel.get('extraCssText') || '');
  40134. el.style.display = el.innerHTML ? 'block' : 'none';
  40135. // If mouse occsionally move over the tooltip, a mouseout event will be
  40136. // triggered by canvas, and cuase some unexpectable result like dragging
  40137. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  40138. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  40139. // scenario.
  40140. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  40141. this._show = true;
  40142. },
  40143. setContent: function (content) {
  40144. this.el.innerHTML = content == null ? '' : content;
  40145. },
  40146. setEnterable: function (enterable) {
  40147. this._enterable = enterable;
  40148. },
  40149. getSize: function () {
  40150. var el = this.el;
  40151. return [el.clientWidth, el.clientHeight];
  40152. },
  40153. moveTo: function (x, y) {
  40154. // xy should be based on canvas root. But tooltipContent is
  40155. // the sibling of canvas root. So padding of ec container
  40156. // should be considered here.
  40157. var zr = this._zr;
  40158. var viewportRootOffset;
  40159. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  40160. x += viewportRootOffset.offsetLeft;
  40161. y += viewportRootOffset.offsetTop;
  40162. }
  40163. var style = this.el.style;
  40164. style.left = x + 'px';
  40165. style.top = y + 'px';
  40166. this._x = x;
  40167. this._y = y;
  40168. },
  40169. hide: function () {
  40170. this.el.style.display = 'none';
  40171. this._show = false;
  40172. },
  40173. hideLater: function (time) {
  40174. if (this._show && !(this._inContent && this._enterable)) {
  40175. if (time) {
  40176. this._hideDelay = time;
  40177. // Set show false to avoid invoke hideLater mutiple times
  40178. this._show = false;
  40179. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  40180. }
  40181. else {
  40182. this.hide();
  40183. }
  40184. }
  40185. },
  40186. isShow: function () {
  40187. return this._show;
  40188. },
  40189. getOuterSize: function () {
  40190. var width = this.el.clientWidth;
  40191. var height = this.el.clientHeight;
  40192. // Consider browser compatibility.
  40193. // IE8 does not support getComputedStyle.
  40194. if (document.defaultView && document.defaultView.getComputedStyle) {
  40195. var stl = document.defaultView.getComputedStyle(this.el);
  40196. if (stl) {
  40197. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  40198. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  40199. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  40200. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  40201. }
  40202. }
  40203. return {width: width, height: height};
  40204. }
  40205. };
  40206. /*
  40207. * Licensed to the Apache Software Foundation (ASF) under one
  40208. * or more contributor license agreements. See the NOTICE file
  40209. * distributed with this work for additional information
  40210. * regarding copyright ownership. The ASF licenses this file
  40211. * to you under the Apache License, Version 2.0 (the
  40212. * "License"); you may not use this file except in compliance
  40213. * with the License. You may obtain a copy of the License at
  40214. *
  40215. * http://www.apache.org/licenses/LICENSE-2.0
  40216. *
  40217. * Unless required by applicable law or agreed to in writing,
  40218. * software distributed under the License is distributed on an
  40219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40220. * KIND, either express or implied. See the License for the
  40221. * specific language governing permissions and limitations
  40222. * under the License.
  40223. */
  40224. // import Group from 'zrender/src/container/Group';
  40225. /**
  40226. * @alias module:echarts/component/tooltip/TooltipRichContent
  40227. * @constructor
  40228. */
  40229. function TooltipRichContent(api) {
  40230. this._zr = api.getZr();
  40231. this._show = false;
  40232. /**
  40233. * @private
  40234. */
  40235. this._hideTimeout;
  40236. }
  40237. TooltipRichContent.prototype = {
  40238. constructor: TooltipRichContent,
  40239. /**
  40240. * @private
  40241. * @type {boolean}
  40242. */
  40243. _enterable: true,
  40244. /**
  40245. * Update when tooltip is rendered
  40246. */
  40247. update: function () {
  40248. // noop
  40249. },
  40250. show: function (tooltipModel) {
  40251. if (this._hideTimeout) {
  40252. clearTimeout(this._hideTimeout);
  40253. }
  40254. this.el.attr('show', true);
  40255. this._show = true;
  40256. },
  40257. /**
  40258. * Set tooltip content
  40259. *
  40260. * @param {string} content rich text string of content
  40261. * @param {Object} markerRich rich text style
  40262. * @param {Object} tooltipModel tooltip model
  40263. */
  40264. setContent: function (content, markerRich, tooltipModel) {
  40265. if (this.el) {
  40266. this._zr.remove(this.el);
  40267. }
  40268. var markers = {};
  40269. var text = content;
  40270. var prefix = '{marker';
  40271. var suffix = '|}';
  40272. var startId = text.indexOf(prefix);
  40273. while (startId >= 0) {
  40274. var endId = text.indexOf(suffix);
  40275. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  40276. if (name.indexOf('sub') > -1) {
  40277. markers['marker' + name] = {
  40278. textWidth: 4,
  40279. textHeight: 4,
  40280. textBorderRadius: 2,
  40281. textBackgroundColor: markerRich[name],
  40282. // TODO: textOffset is not implemented for rich text
  40283. textOffset: [3, 0]
  40284. };
  40285. }
  40286. else {
  40287. markers['marker' + name] = {
  40288. textWidth: 10,
  40289. textHeight: 10,
  40290. textBorderRadius: 5,
  40291. textBackgroundColor: markerRich[name]
  40292. };
  40293. }
  40294. text = text.substr(endId + 1);
  40295. startId = text.indexOf('{marker');
  40296. }
  40297. this.el = new Text({
  40298. style: {
  40299. rich: markers,
  40300. text: content,
  40301. textLineHeight: 20,
  40302. textBackgroundColor: tooltipModel.get('backgroundColor'),
  40303. textBorderRadius: tooltipModel.get('borderRadius'),
  40304. textFill: tooltipModel.get('textStyle.color'),
  40305. textPadding: tooltipModel.get('padding')
  40306. },
  40307. z: tooltipModel.get('z')
  40308. });
  40309. this._zr.add(this.el);
  40310. var self = this;
  40311. this.el.on('mouseover', function () {
  40312. // clear the timeout in hideLater and keep showing tooltip
  40313. if (self._enterable) {
  40314. clearTimeout(self._hideTimeout);
  40315. self._show = true;
  40316. }
  40317. self._inContent = true;
  40318. });
  40319. this.el.on('mouseout', function () {
  40320. if (self._enterable) {
  40321. if (self._show) {
  40322. self.hideLater(self._hideDelay);
  40323. }
  40324. }
  40325. self._inContent = false;
  40326. });
  40327. },
  40328. setEnterable: function (enterable) {
  40329. this._enterable = enterable;
  40330. },
  40331. getSize: function () {
  40332. var bounding = this.el.getBoundingRect();
  40333. return [bounding.width, bounding.height];
  40334. },
  40335. moveTo: function (x, y) {
  40336. if (this.el) {
  40337. this.el.attr('position', [x, y]);
  40338. }
  40339. },
  40340. hide: function () {
  40341. this.el.hide();
  40342. this._show = false;
  40343. },
  40344. hideLater: function (time) {
  40345. if (this._show && !(this._inContent && this._enterable)) {
  40346. if (time) {
  40347. this._hideDelay = time;
  40348. // Set show false to avoid invoke hideLater mutiple times
  40349. this._show = false;
  40350. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  40351. }
  40352. else {
  40353. this.hide();
  40354. }
  40355. }
  40356. },
  40357. isShow: function () {
  40358. return this._show;
  40359. },
  40360. getOuterSize: function () {
  40361. return this.getSize();
  40362. }
  40363. };
  40364. /*
  40365. * Licensed to the Apache Software Foundation (ASF) under one
  40366. * or more contributor license agreements. See the NOTICE file
  40367. * distributed with this work for additional information
  40368. * regarding copyright ownership. The ASF licenses this file
  40369. * to you under the Apache License, Version 2.0 (the
  40370. * "License"); you may not use this file except in compliance
  40371. * with the License. You may obtain a copy of the License at
  40372. *
  40373. * http://www.apache.org/licenses/LICENSE-2.0
  40374. *
  40375. * Unless required by applicable law or agreed to in writing,
  40376. * software distributed under the License is distributed on an
  40377. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40378. * KIND, either express or implied. See the License for the
  40379. * specific language governing permissions and limitations
  40380. * under the License.
  40381. */
  40382. var bind$2 = bind;
  40383. var each$9 = each$1;
  40384. var parsePercent$2 = parsePercent$1;
  40385. var proxyRect = new Rect({
  40386. shape: {x: -1, y: -1, width: 2, height: 2}
  40387. });
  40388. extendComponentView({
  40389. type: 'tooltip',
  40390. init: function (ecModel, api) {
  40391. if (env$1.node) {
  40392. return;
  40393. }
  40394. var tooltipModel = ecModel.getComponent('tooltip');
  40395. var renderMode = tooltipModel.get('renderMode');
  40396. this._renderMode = getTooltipRenderMode(renderMode);
  40397. var tooltipContent;
  40398. if (this._renderMode === 'html') {
  40399. tooltipContent = new TooltipContent(api.getDom(), api);
  40400. this._newLine = '<br/>';
  40401. }
  40402. else {
  40403. tooltipContent = new TooltipRichContent(api);
  40404. this._newLine = '\n';
  40405. }
  40406. this._tooltipContent = tooltipContent;
  40407. },
  40408. render: function (tooltipModel, ecModel, api) {
  40409. if (env$1.node) {
  40410. return;
  40411. }
  40412. // Reset
  40413. this.group.removeAll();
  40414. /**
  40415. * @private
  40416. * @type {module:echarts/component/tooltip/TooltipModel}
  40417. */
  40418. this._tooltipModel = tooltipModel;
  40419. /**
  40420. * @private
  40421. * @type {module:echarts/model/Global}
  40422. */
  40423. this._ecModel = ecModel;
  40424. /**
  40425. * @private
  40426. * @type {module:echarts/ExtensionAPI}
  40427. */
  40428. this._api = api;
  40429. /**
  40430. * Should be cleaned when render.
  40431. * @private
  40432. * @type {Array.<Array.<Object>>}
  40433. */
  40434. this._lastDataByCoordSys = null;
  40435. /**
  40436. * @private
  40437. * @type {boolean}
  40438. */
  40439. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  40440. var tooltipContent = this._tooltipContent;
  40441. tooltipContent.update();
  40442. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  40443. this._initGlobalListener();
  40444. this._keepShow();
  40445. },
  40446. _initGlobalListener: function () {
  40447. var tooltipModel = this._tooltipModel;
  40448. var triggerOn = tooltipModel.get('triggerOn');
  40449. register(
  40450. 'itemTooltip',
  40451. this._api,
  40452. bind$2(function (currTrigger, e, dispatchAction) {
  40453. // If 'none', it is not controlled by mouse totally.
  40454. if (triggerOn !== 'none') {
  40455. if (triggerOn.indexOf(currTrigger) >= 0) {
  40456. this._tryShow(e, dispatchAction);
  40457. }
  40458. else if (currTrigger === 'leave') {
  40459. this._hide(dispatchAction);
  40460. }
  40461. }
  40462. }, this)
  40463. );
  40464. },
  40465. _keepShow: function () {
  40466. var tooltipModel = this._tooltipModel;
  40467. var ecModel = this._ecModel;
  40468. var api = this._api;
  40469. // Try to keep the tooltip show when refreshing
  40470. if (this._lastX != null
  40471. && this._lastY != null
  40472. // When user is willing to control tooltip totally using API,
  40473. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  40474. // which is not expected.
  40475. && tooltipModel.get('triggerOn') !== 'none'
  40476. ) {
  40477. var self = this;
  40478. clearTimeout(this._refreshUpdateTimeout);
  40479. this._refreshUpdateTimeout = setTimeout(function () {
  40480. // Show tip next tick after other charts are rendered
  40481. // In case highlight action has wrong result
  40482. // FIXME
  40483. self.manuallyShowTip(tooltipModel, ecModel, api, {
  40484. x: self._lastX,
  40485. y: self._lastY
  40486. });
  40487. });
  40488. }
  40489. },
  40490. /**
  40491. * Show tip manually by
  40492. * dispatchAction({
  40493. * type: 'showTip',
  40494. * x: 10,
  40495. * y: 10
  40496. * });
  40497. * Or
  40498. * dispatchAction({
  40499. * type: 'showTip',
  40500. * seriesIndex: 0,
  40501. * dataIndex or dataIndexInside or name
  40502. * });
  40503. *
  40504. * TODO Batch
  40505. */
  40506. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  40507. if (payload.from === this.uid || env$1.node) {
  40508. return;
  40509. }
  40510. var dispatchAction = makeDispatchAction$1(payload, api);
  40511. // Reset ticket
  40512. this._ticket = '';
  40513. // When triggered from axisPointer.
  40514. var dataByCoordSys = payload.dataByCoordSys;
  40515. if (payload.tooltip && payload.x != null && payload.y != null) {
  40516. var el = proxyRect;
  40517. el.position = [payload.x, payload.y];
  40518. el.update();
  40519. el.tooltip = payload.tooltip;
  40520. // Manually show tooltip while view is not using zrender elements.
  40521. this._tryShow({
  40522. offsetX: payload.x,
  40523. offsetY: payload.y,
  40524. target: el
  40525. }, dispatchAction);
  40526. }
  40527. else if (dataByCoordSys) {
  40528. this._tryShow({
  40529. offsetX: payload.x,
  40530. offsetY: payload.y,
  40531. position: payload.position,
  40532. event: {},
  40533. dataByCoordSys: payload.dataByCoordSys,
  40534. tooltipOption: payload.tooltipOption
  40535. }, dispatchAction);
  40536. }
  40537. else if (payload.seriesIndex != null) {
  40538. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  40539. return;
  40540. }
  40541. var pointInfo = findPointFromSeries(payload, ecModel);
  40542. var cx = pointInfo.point[0];
  40543. var cy = pointInfo.point[1];
  40544. if (cx != null && cy != null) {
  40545. this._tryShow({
  40546. offsetX: cx,
  40547. offsetY: cy,
  40548. position: payload.position,
  40549. target: pointInfo.el,
  40550. event: {}
  40551. }, dispatchAction);
  40552. }
  40553. }
  40554. else if (payload.x != null && payload.y != null) {
  40555. // FIXME
  40556. // should wrap dispatchAction like `axisPointer/globalListener` ?
  40557. api.dispatchAction({
  40558. type: 'updateAxisPointer',
  40559. x: payload.x,
  40560. y: payload.y
  40561. });
  40562. this._tryShow({
  40563. offsetX: payload.x,
  40564. offsetY: payload.y,
  40565. position: payload.position,
  40566. target: api.getZr().findHover(payload.x, payload.y).target,
  40567. event: {}
  40568. }, dispatchAction);
  40569. }
  40570. },
  40571. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  40572. var tooltipContent = this._tooltipContent;
  40573. if (!this._alwaysShowContent && this._tooltipModel) {
  40574. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  40575. }
  40576. this._lastX = this._lastY = null;
  40577. if (payload.from !== this.uid) {
  40578. this._hide(makeDispatchAction$1(payload, api));
  40579. }
  40580. },
  40581. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  40582. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  40583. // and tooltip.
  40584. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  40585. var seriesIndex = payload.seriesIndex;
  40586. var dataIndex = payload.dataIndex;
  40587. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  40588. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  40589. return;
  40590. }
  40591. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  40592. if (!seriesModel) {
  40593. return;
  40594. }
  40595. var data = seriesModel.getData();
  40596. var tooltipModel = buildTooltipModel([
  40597. data.getItemModel(dataIndex),
  40598. seriesModel,
  40599. (seriesModel.coordinateSystem || {}).model,
  40600. tooltipModel
  40601. ]);
  40602. if (tooltipModel.get('trigger') !== 'axis') {
  40603. return;
  40604. }
  40605. api.dispatchAction({
  40606. type: 'updateAxisPointer',
  40607. seriesIndex: seriesIndex,
  40608. dataIndex: dataIndex,
  40609. position: payload.position
  40610. });
  40611. return true;
  40612. },
  40613. _tryShow: function (e, dispatchAction) {
  40614. var el = e.target;
  40615. var tooltipModel = this._tooltipModel;
  40616. if (!tooltipModel) {
  40617. return;
  40618. }
  40619. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  40620. this._lastX = e.offsetX;
  40621. this._lastY = e.offsetY;
  40622. var dataByCoordSys = e.dataByCoordSys;
  40623. if (dataByCoordSys && dataByCoordSys.length) {
  40624. this._showAxisTooltip(dataByCoordSys, e);
  40625. }
  40626. // Always show item tooltip if mouse is on the element with dataIndex
  40627. else if (el && el.dataIndex != null) {
  40628. this._lastDataByCoordSys = null;
  40629. this._showSeriesItemTooltip(e, el, dispatchAction);
  40630. }
  40631. // Tooltip provided directly. Like legend.
  40632. else if (el && el.tooltip) {
  40633. this._lastDataByCoordSys = null;
  40634. this._showComponentItemTooltip(e, el, dispatchAction);
  40635. }
  40636. else {
  40637. this._lastDataByCoordSys = null;
  40638. this._hide(dispatchAction);
  40639. }
  40640. },
  40641. _showOrMove: function (tooltipModel, cb) {
  40642. // showDelay is used in this case: tooltip.enterable is set
  40643. // as true. User intent to move mouse into tooltip and click
  40644. // something. `showDelay` makes it easyer to enter the content
  40645. // but tooltip do not move immediately.
  40646. var delay = tooltipModel.get('showDelay');
  40647. cb = bind(cb, this);
  40648. clearTimeout(this._showTimout);
  40649. delay > 0
  40650. ? (this._showTimout = setTimeout(cb, delay))
  40651. : cb();
  40652. },
  40653. _showAxisTooltip: function (dataByCoordSys, e) {
  40654. var ecModel = this._ecModel;
  40655. var globalTooltipModel = this._tooltipModel;
  40656. var point = [e.offsetX, e.offsetY];
  40657. var singleDefaultHTML = [];
  40658. var singleParamsList = [];
  40659. var singleTooltipModel = buildTooltipModel([
  40660. e.tooltipOption,
  40661. globalTooltipModel
  40662. ]);
  40663. var renderMode = this._renderMode;
  40664. var newLine = this._newLine;
  40665. var markers = {};
  40666. each$9(dataByCoordSys, function (itemCoordSys) {
  40667. // var coordParamList = [];
  40668. // var coordDefaultHTML = [];
  40669. // var coordTooltipModel = buildTooltipModel([
  40670. // e.tooltipOption,
  40671. // itemCoordSys.tooltipOption,
  40672. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  40673. // globalTooltipModel
  40674. // ]);
  40675. // var displayMode = coordTooltipModel.get('displayMode');
  40676. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  40677. each$9(itemCoordSys.dataByAxis, function (item) {
  40678. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  40679. var axisValue = item.value;
  40680. var seriesDefaultHTML = [];
  40681. if (!axisModel || axisValue == null) {
  40682. return;
  40683. }
  40684. var valueLabel = getValueLabel(
  40685. axisValue, axisModel.axis, ecModel,
  40686. item.seriesDataIndices,
  40687. item.valueLabelOpt
  40688. );
  40689. each$1(item.seriesDataIndices, function (idxItem) {
  40690. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  40691. var dataIndex = idxItem.dataIndexInside;
  40692. var dataParams = series && series.getDataParams(dataIndex);
  40693. dataParams.axisDim = item.axisDim;
  40694. dataParams.axisIndex = item.axisIndex;
  40695. dataParams.axisType = item.axisType;
  40696. dataParams.axisId = item.axisId;
  40697. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  40698. dataParams.axisValueLabel = valueLabel;
  40699. if (dataParams) {
  40700. singleParamsList.push(dataParams);
  40701. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  40702. var html;
  40703. if (isObject$1(seriesTooltip)) {
  40704. html = seriesTooltip.html;
  40705. var newMarkers = seriesTooltip.markers;
  40706. merge(markers, newMarkers);
  40707. }
  40708. else {
  40709. html = seriesTooltip;
  40710. }
  40711. seriesDefaultHTML.push(html);
  40712. }
  40713. });
  40714. // Default tooltip content
  40715. // FIXME
  40716. // (1) shold be the first data which has name?
  40717. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  40718. var firstLine = valueLabel;
  40719. if (renderMode !== 'html') {
  40720. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  40721. }
  40722. else {
  40723. singleDefaultHTML.push(
  40724. (firstLine ? encodeHTML(firstLine) + newLine : '')
  40725. + seriesDefaultHTML.join(newLine)
  40726. );
  40727. }
  40728. });
  40729. }, this);
  40730. // In most case, the second axis is shown upper than the first one.
  40731. singleDefaultHTML.reverse();
  40732. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  40733. var positionExpr = e.position;
  40734. this._showOrMove(singleTooltipModel, function () {
  40735. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  40736. this._updatePosition(
  40737. singleTooltipModel,
  40738. positionExpr,
  40739. point[0], point[1],
  40740. this._tooltipContent,
  40741. singleParamsList
  40742. );
  40743. }
  40744. else {
  40745. this._showTooltipContent(
  40746. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  40747. point[0], point[1], positionExpr, undefined, markers
  40748. );
  40749. }
  40750. });
  40751. // Do not trigger events here, because this branch only be entered
  40752. // from dispatchAction.
  40753. },
  40754. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  40755. var ecModel = this._ecModel;
  40756. // Use dataModel in element if possible
  40757. // Used when mouseover on a element like markPoint or edge
  40758. // In which case, the data is not main data in series.
  40759. var seriesIndex = el.seriesIndex;
  40760. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  40761. // For example, graph link.
  40762. var dataModel = el.dataModel || seriesModel;
  40763. var dataIndex = el.dataIndex;
  40764. var dataType = el.dataType;
  40765. var data = dataModel.getData();
  40766. var tooltipModel = buildTooltipModel([
  40767. data.getItemModel(dataIndex),
  40768. dataModel,
  40769. seriesModel && (seriesModel.coordinateSystem || {}).model,
  40770. this._tooltipModel
  40771. ]);
  40772. var tooltipTrigger = tooltipModel.get('trigger');
  40773. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  40774. return;
  40775. }
  40776. var params = dataModel.getDataParams(dataIndex, dataType);
  40777. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  40778. var defaultHtml;
  40779. var markers;
  40780. if (isObject$1(seriesTooltip)) {
  40781. defaultHtml = seriesTooltip.html;
  40782. markers = seriesTooltip.markers;
  40783. }
  40784. else {
  40785. defaultHtml = seriesTooltip;
  40786. markers = null;
  40787. }
  40788. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  40789. this._showOrMove(tooltipModel, function () {
  40790. this._showTooltipContent(
  40791. tooltipModel, defaultHtml, params, asyncTicket,
  40792. e.offsetX, e.offsetY, e.position, e.target, markers
  40793. );
  40794. });
  40795. // FIXME
  40796. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  40797. dispatchAction({
  40798. type: 'showTip',
  40799. dataIndexInside: dataIndex,
  40800. dataIndex: data.getRawIndex(dataIndex),
  40801. seriesIndex: seriesIndex,
  40802. from: this.uid
  40803. });
  40804. },
  40805. _showComponentItemTooltip: function (e, el, dispatchAction) {
  40806. var tooltipOpt = el.tooltip;
  40807. if (typeof tooltipOpt === 'string') {
  40808. var content = tooltipOpt;
  40809. tooltipOpt = {
  40810. content: content,
  40811. // Fixed formatter
  40812. formatter: content
  40813. };
  40814. }
  40815. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  40816. var defaultHtml = subTooltipModel.get('content');
  40817. var asyncTicket = Math.random();
  40818. // Do not check whether `trigger` is 'none' here, because `trigger`
  40819. // only works on cooridinate system. In fact, we have not found case
  40820. // that requires setting `trigger` nothing on component yet.
  40821. this._showOrMove(subTooltipModel, function () {
  40822. this._showTooltipContent(
  40823. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  40824. asyncTicket, e.offsetX, e.offsetY, e.position, el
  40825. );
  40826. });
  40827. // If not dispatch showTip, tip may be hide triggered by axis.
  40828. dispatchAction({
  40829. type: 'showTip',
  40830. from: this.uid
  40831. });
  40832. },
  40833. _showTooltipContent: function (
  40834. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  40835. ) {
  40836. // Reset ticket
  40837. this._ticket = '';
  40838. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  40839. return;
  40840. }
  40841. var tooltipContent = this._tooltipContent;
  40842. var formatter = tooltipModel.get('formatter');
  40843. positionExpr = positionExpr || tooltipModel.get('position');
  40844. var html = defaultHtml;
  40845. if (formatter && typeof formatter === 'string') {
  40846. html = formatTpl(formatter, params, true);
  40847. }
  40848. else if (typeof formatter === 'function') {
  40849. var callback = bind$2(function (cbTicket, html) {
  40850. if (cbTicket === this._ticket) {
  40851. tooltipContent.setContent(html, markers, tooltipModel);
  40852. this._updatePosition(
  40853. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  40854. );
  40855. }
  40856. }, this);
  40857. this._ticket = asyncTicket;
  40858. html = formatter(params, asyncTicket, callback);
  40859. }
  40860. tooltipContent.setContent(html, markers, tooltipModel);
  40861. tooltipContent.show(tooltipModel);
  40862. this._updatePosition(
  40863. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  40864. );
  40865. },
  40866. /**
  40867. * @param {string|Function|Array.<number>|Object} positionExpr
  40868. * @param {number} x Mouse x
  40869. * @param {number} y Mouse y
  40870. * @param {boolean} confine Whether confine tooltip content in view rect.
  40871. * @param {Object|<Array.<Object>} params
  40872. * @param {module:zrender/Element} el target element
  40873. * @param {module:echarts/ExtensionAPI} api
  40874. * @return {Array.<number>}
  40875. */
  40876. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  40877. var viewWidth = this._api.getWidth();
  40878. var viewHeight = this._api.getHeight();
  40879. positionExpr = positionExpr || tooltipModel.get('position');
  40880. var contentSize = content.getSize();
  40881. var align = tooltipModel.get('align');
  40882. var vAlign = tooltipModel.get('verticalAlign');
  40883. var rect = el && el.getBoundingRect().clone();
  40884. el && rect.applyTransform(el.transform);
  40885. if (typeof positionExpr === 'function') {
  40886. // Callback of position can be an array or a string specify the position
  40887. positionExpr = positionExpr([x, y], params, content.el, rect, {
  40888. viewSize: [viewWidth, viewHeight],
  40889. contentSize: contentSize.slice()
  40890. });
  40891. }
  40892. if (isArray(positionExpr)) {
  40893. x = parsePercent$2(positionExpr[0], viewWidth);
  40894. y = parsePercent$2(positionExpr[1], viewHeight);
  40895. }
  40896. else if (isObject$1(positionExpr)) {
  40897. positionExpr.width = contentSize[0];
  40898. positionExpr.height = contentSize[1];
  40899. var layoutRect = getLayoutRect(
  40900. positionExpr, {width: viewWidth, height: viewHeight}
  40901. );
  40902. x = layoutRect.x;
  40903. y = layoutRect.y;
  40904. align = null;
  40905. // When positionExpr is left/top/right/bottom,
  40906. // align and verticalAlign will not work.
  40907. vAlign = null;
  40908. }
  40909. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  40910. else if (typeof positionExpr === 'string' && el) {
  40911. var pos = calcTooltipPosition(
  40912. positionExpr, rect, contentSize
  40913. );
  40914. x = pos[0];
  40915. y = pos[1];
  40916. }
  40917. else {
  40918. var pos = refixTooltipPosition(
  40919. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  40920. );
  40921. x = pos[0];
  40922. y = pos[1];
  40923. }
  40924. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  40925. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  40926. if (tooltipModel.get('confine')) {
  40927. var pos = confineTooltipPosition(
  40928. x, y, content, viewWidth, viewHeight
  40929. );
  40930. x = pos[0];
  40931. y = pos[1];
  40932. }
  40933. content.moveTo(x, y);
  40934. },
  40935. // FIXME
  40936. // Should we remove this but leave this to user?
  40937. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  40938. var lastCoordSys = this._lastDataByCoordSys;
  40939. var contentNotChanged = !!lastCoordSys
  40940. && lastCoordSys.length === dataByCoordSys.length;
  40941. contentNotChanged && each$9(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  40942. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  40943. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  40944. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  40945. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  40946. contentNotChanged && each$9(lastDataByAxis, function (lastItem, indexAxis) {
  40947. var thisItem = thisDataByAxis[indexAxis] || {};
  40948. var lastIndices = lastItem.seriesDataIndices || [];
  40949. var newIndices = thisItem.seriesDataIndices || [];
  40950. contentNotChanged
  40951. &= lastItem.value === thisItem.value
  40952. && lastItem.axisType === thisItem.axisType
  40953. && lastItem.axisId === thisItem.axisId
  40954. && lastIndices.length === newIndices.length;
  40955. contentNotChanged && each$9(lastIndices, function (lastIdxItem, j) {
  40956. var newIdxItem = newIndices[j];
  40957. contentNotChanged
  40958. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  40959. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  40960. });
  40961. });
  40962. });
  40963. this._lastDataByCoordSys = dataByCoordSys;
  40964. return !!contentNotChanged;
  40965. },
  40966. _hide: function (dispatchAction) {
  40967. // Do not directly hideLater here, because this behavior may be prevented
  40968. // in dispatchAction when showTip is dispatched.
  40969. // FIXME
  40970. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  40971. this._lastDataByCoordSys = null;
  40972. dispatchAction({
  40973. type: 'hideTip',
  40974. from: this.uid
  40975. });
  40976. },
  40977. dispose: function (ecModel, api) {
  40978. if (env$1.node) {
  40979. return;
  40980. }
  40981. this._tooltipContent.hide();
  40982. unregister('itemTooltip', api);
  40983. }
  40984. });
  40985. /**
  40986. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  40987. * From top to bottom. (the last one should be globalTooltipModel);
  40988. */
  40989. function buildTooltipModel(modelCascade) {
  40990. var resultModel = modelCascade.pop();
  40991. while (modelCascade.length) {
  40992. var tooltipOpt = modelCascade.pop();
  40993. if (tooltipOpt) {
  40994. if (Model.isInstance(tooltipOpt)) {
  40995. tooltipOpt = tooltipOpt.get('tooltip', true);
  40996. }
  40997. // In each data item tooltip can be simply write:
  40998. // {
  40999. // value: 10,
  41000. // tooltip: 'Something you need to know'
  41001. // }
  41002. if (typeof tooltipOpt === 'string') {
  41003. tooltipOpt = {formatter: tooltipOpt};
  41004. }
  41005. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  41006. }
  41007. }
  41008. return resultModel;
  41009. }
  41010. function makeDispatchAction$1(payload, api) {
  41011. return payload.dispatchAction || bind(api.dispatchAction, api);
  41012. }
  41013. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  41014. var size = content.getOuterSize();
  41015. var width = size.width;
  41016. var height = size.height;
  41017. if (gapH != null) {
  41018. if (x + width + gapH > viewWidth) {
  41019. x -= width + gapH;
  41020. }
  41021. else {
  41022. x += gapH;
  41023. }
  41024. }
  41025. if (gapV != null) {
  41026. if (y + height + gapV > viewHeight) {
  41027. y -= height + gapV;
  41028. }
  41029. else {
  41030. y += gapV;
  41031. }
  41032. }
  41033. return [x, y];
  41034. }
  41035. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  41036. var size = content.getOuterSize();
  41037. var width = size.width;
  41038. var height = size.height;
  41039. x = Math.min(x + width, viewWidth) - width;
  41040. y = Math.min(y + height, viewHeight) - height;
  41041. x = Math.max(x, 0);
  41042. y = Math.max(y, 0);
  41043. return [x, y];
  41044. }
  41045. function calcTooltipPosition(position, rect, contentSize) {
  41046. var domWidth = contentSize[0];
  41047. var domHeight = contentSize[1];
  41048. var gap = 5;
  41049. var x = 0;
  41050. var y = 0;
  41051. var rectWidth = rect.width;
  41052. var rectHeight = rect.height;
  41053. switch (position) {
  41054. case 'inside':
  41055. x = rect.x + rectWidth / 2 - domWidth / 2;
  41056. y = rect.y + rectHeight / 2 - domHeight / 2;
  41057. break;
  41058. case 'top':
  41059. x = rect.x + rectWidth / 2 - domWidth / 2;
  41060. y = rect.y - domHeight - gap;
  41061. break;
  41062. case 'bottom':
  41063. x = rect.x + rectWidth / 2 - domWidth / 2;
  41064. y = rect.y + rectHeight + gap;
  41065. break;
  41066. case 'left':
  41067. x = rect.x - domWidth - gap;
  41068. y = rect.y + rectHeight / 2 - domHeight / 2;
  41069. break;
  41070. case 'right':
  41071. x = rect.x + rectWidth + gap;
  41072. y = rect.y + rectHeight / 2 - domHeight / 2;
  41073. }
  41074. return [x, y];
  41075. }
  41076. function isCenterAlign(align) {
  41077. return align === 'center' || align === 'middle';
  41078. }
  41079. /*
  41080. * Licensed to the Apache Software Foundation (ASF) under one
  41081. * or more contributor license agreements. See the NOTICE file
  41082. * distributed with this work for additional information
  41083. * regarding copyright ownership. The ASF licenses this file
  41084. * to you under the Apache License, Version 2.0 (the
  41085. * "License"); you may not use this file except in compliance
  41086. * with the License. You may obtain a copy of the License at
  41087. *
  41088. * http://www.apache.org/licenses/LICENSE-2.0
  41089. *
  41090. * Unless required by applicable law or agreed to in writing,
  41091. * software distributed under the License is distributed on an
  41092. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41093. * KIND, either express or implied. See the License for the
  41094. * specific language governing permissions and limitations
  41095. * under the License.
  41096. */
  41097. // FIXME Better way to pack data in graphic element
  41098. /**
  41099. * @action
  41100. * @property {string} type
  41101. * @property {number} seriesIndex
  41102. * @property {number} dataIndex
  41103. * @property {number} [x]
  41104. * @property {number} [y]
  41105. */
  41106. registerAction(
  41107. {
  41108. type: 'showTip',
  41109. event: 'showTip',
  41110. update: 'tooltip:manuallyShowTip'
  41111. },
  41112. // noop
  41113. function () {}
  41114. );
  41115. registerAction(
  41116. {
  41117. type: 'hideTip',
  41118. event: 'hideTip',
  41119. update: 'tooltip:manuallyHideTip'
  41120. },
  41121. // noop
  41122. function () {}
  41123. );
  41124. /*
  41125. * Licensed to the Apache Software Foundation (ASF) under one
  41126. * or more contributor license agreements. See the NOTICE file
  41127. * distributed with this work for additional information
  41128. * regarding copyright ownership. The ASF licenses this file
  41129. * to you under the Apache License, Version 2.0 (the
  41130. * "License"); you may not use this file except in compliance
  41131. * with the License. You may obtain a copy of the License at
  41132. *
  41133. * http://www.apache.org/licenses/LICENSE-2.0
  41134. *
  41135. * Unless required by applicable law or agreed to in writing,
  41136. * software distributed under the License is distributed on an
  41137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41138. * KIND, either express or implied. See the License for the
  41139. * specific language governing permissions and limitations
  41140. * under the License.
  41141. */
  41142. var LegendModel = extendComponentModel({
  41143. type: 'legend.plain',
  41144. dependencies: ['series'],
  41145. layoutMode: {
  41146. type: 'box',
  41147. // legend.width/height are maxWidth/maxHeight actually,
  41148. // whereas realy width/height is calculated by its content.
  41149. // (Setting {left: 10, right: 10} does not make sense).
  41150. // So consider the case:
  41151. // `setOption({legend: {left: 10});`
  41152. // then `setOption({legend: {right: 10});`
  41153. // The previous `left` should be cleared by setting `ignoreSize`.
  41154. ignoreSize: true
  41155. },
  41156. init: function (option, parentModel, ecModel) {
  41157. this.mergeDefaultAndTheme(option, ecModel);
  41158. option.selected = option.selected || {};
  41159. },
  41160. mergeOption: function (option) {
  41161. LegendModel.superCall(this, 'mergeOption', option);
  41162. },
  41163. optionUpdated: function () {
  41164. this._updateData(this.ecModel);
  41165. var legendData = this._data;
  41166. // If selectedMode is single, try to select one
  41167. if (legendData[0] && this.get('selectedMode') === 'single') {
  41168. var hasSelected = false;
  41169. // If has any selected in option.selected
  41170. for (var i = 0; i < legendData.length; i++) {
  41171. var name = legendData[i].get('name');
  41172. if (this.isSelected(name)) {
  41173. // Force to unselect others
  41174. this.select(name);
  41175. hasSelected = true;
  41176. break;
  41177. }
  41178. }
  41179. // Try select the first if selectedMode is single
  41180. !hasSelected && this.select(legendData[0].get('name'));
  41181. }
  41182. },
  41183. _updateData: function (ecModel) {
  41184. var potentialData = [];
  41185. var availableNames = [];
  41186. ecModel.eachRawSeries(function (seriesModel) {
  41187. var seriesName = seriesModel.name;
  41188. availableNames.push(seriesName);
  41189. var isPotential;
  41190. if (seriesModel.legendDataProvider) {
  41191. var data = seriesModel.legendDataProvider();
  41192. var names = data.mapArray(data.getName);
  41193. if (!ecModel.isSeriesFiltered(seriesModel)) {
  41194. availableNames = availableNames.concat(names);
  41195. }
  41196. if (names.length) {
  41197. potentialData = potentialData.concat(names);
  41198. }
  41199. else {
  41200. isPotential = true;
  41201. }
  41202. }
  41203. else {
  41204. isPotential = true;
  41205. }
  41206. if (isPotential && isNameSpecified(seriesModel)) {
  41207. potentialData.push(seriesModel.name);
  41208. }
  41209. });
  41210. /**
  41211. * @type {Array.<string>}
  41212. * @private
  41213. */
  41214. this._availableNames = availableNames;
  41215. // If legend.data not specified in option, use availableNames as data,
  41216. // which is convinient for user preparing option.
  41217. var rawData = this.get('data') || potentialData;
  41218. var legendData = map(rawData, function (dataItem) {
  41219. // Can be string or number
  41220. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  41221. dataItem = {
  41222. name: dataItem
  41223. };
  41224. }
  41225. return new Model(dataItem, this, this.ecModel);
  41226. }, this);
  41227. /**
  41228. * @type {Array.<module:echarts/model/Model>}
  41229. * @private
  41230. */
  41231. this._data = legendData;
  41232. },
  41233. /**
  41234. * @return {Array.<module:echarts/model/Model>}
  41235. */
  41236. getData: function () {
  41237. return this._data;
  41238. },
  41239. /**
  41240. * @param {string} name
  41241. */
  41242. select: function (name) {
  41243. var selected = this.option.selected;
  41244. var selectedMode = this.get('selectedMode');
  41245. if (selectedMode === 'single') {
  41246. var data = this._data;
  41247. each$1(data, function (dataItem) {
  41248. selected[dataItem.get('name')] = false;
  41249. });
  41250. }
  41251. selected[name] = true;
  41252. },
  41253. /**
  41254. * @param {string} name
  41255. */
  41256. unSelect: function (name) {
  41257. if (this.get('selectedMode') !== 'single') {
  41258. this.option.selected[name] = false;
  41259. }
  41260. },
  41261. /**
  41262. * @param {string} name
  41263. */
  41264. toggleSelected: function (name) {
  41265. var selected = this.option.selected;
  41266. // Default is true
  41267. if (!selected.hasOwnProperty(name)) {
  41268. selected[name] = true;
  41269. }
  41270. this[selected[name] ? 'unSelect' : 'select'](name);
  41271. },
  41272. /**
  41273. * @param {string} name
  41274. */
  41275. isSelected: function (name) {
  41276. var selected = this.option.selected;
  41277. return !(selected.hasOwnProperty(name) && !selected[name])
  41278. && indexOf(this._availableNames, name) >= 0;
  41279. },
  41280. defaultOption: {
  41281. // 一级层叠
  41282. zlevel: 0,
  41283. // 二级层叠
  41284. z: 4,
  41285. show: true,
  41286. // 布局方式,默认为水平布局,可选为:
  41287. // 'horizontal' | 'vertical'
  41288. orient: 'horizontal',
  41289. left: 'center',
  41290. // right: 'center',
  41291. top: 0,
  41292. // bottom: null,
  41293. // 水平对齐
  41294. // 'auto' | 'left' | 'right'
  41295. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  41296. align: 'auto',
  41297. backgroundColor: 'rgba(0,0,0,0)',
  41298. // 图例边框颜色
  41299. borderColor: '#ccc',
  41300. borderRadius: 0,
  41301. // 图例边框线宽,单位px,默认为0(无边框)
  41302. borderWidth: 0,
  41303. // 图例内边距,单位px,默认各方向内边距为5,
  41304. // 接受数组分别设定上右下左边距,同css
  41305. padding: 5,
  41306. // 各个item之间的间隔,单位px,默认为10,
  41307. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  41308. itemGap: 10,
  41309. // 图例图形宽度
  41310. itemWidth: 25,
  41311. // 图例图形高度
  41312. itemHeight: 14,
  41313. // 图例关闭时候的颜色
  41314. inactiveColor: '#ccc',
  41315. textStyle: {
  41316. // 图例文字颜色
  41317. color: '#333'
  41318. },
  41319. // formatter: '',
  41320. // 选择模式,默认开启图例开关
  41321. selectedMode: true,
  41322. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  41323. // selected: null,
  41324. // 图例内容(详见legend.data,数组中每一项代表一个item
  41325. // data: [],
  41326. // Tooltip 相关配置
  41327. tooltip: {
  41328. show: false
  41329. }
  41330. }
  41331. });
  41332. /*
  41333. * Licensed to the Apache Software Foundation (ASF) under one
  41334. * or more contributor license agreements. See the NOTICE file
  41335. * distributed with this work for additional information
  41336. * regarding copyright ownership. The ASF licenses this file
  41337. * to you under the Apache License, Version 2.0 (the
  41338. * "License"); you may not use this file except in compliance
  41339. * with the License. You may obtain a copy of the License at
  41340. *
  41341. * http://www.apache.org/licenses/LICENSE-2.0
  41342. *
  41343. * Unless required by applicable law or agreed to in writing,
  41344. * software distributed under the License is distributed on an
  41345. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41346. * KIND, either express or implied. See the License for the
  41347. * specific language governing permissions and limitations
  41348. * under the License.
  41349. */
  41350. function legendSelectActionHandler(methodName, payload, ecModel) {
  41351. var selectedMap = {};
  41352. var isToggleSelect = methodName === 'toggleSelected';
  41353. var isSelected;
  41354. // Update all legend components
  41355. ecModel.eachComponent('legend', function (legendModel) {
  41356. if (isToggleSelect && isSelected != null) {
  41357. // Force other legend has same selected status
  41358. // Or the first is toggled to true and other are toggled to false
  41359. // In the case one legend has some item unSelected in option. And if other legend
  41360. // doesn't has the item, they will assume it is selected.
  41361. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  41362. }
  41363. else {
  41364. legendModel[methodName](payload.name);
  41365. isSelected = legendModel.isSelected(payload.name);
  41366. }
  41367. var legendData = legendModel.getData();
  41368. each$1(legendData, function (model) {
  41369. var name = model.get('name');
  41370. // Wrap element
  41371. if (name === '\n' || name === '') {
  41372. return;
  41373. }
  41374. var isItemSelected = legendModel.isSelected(name);
  41375. if (selectedMap.hasOwnProperty(name)) {
  41376. // Unselected if any legend is unselected
  41377. selectedMap[name] = selectedMap[name] && isItemSelected;
  41378. }
  41379. else {
  41380. selectedMap[name] = isItemSelected;
  41381. }
  41382. });
  41383. });
  41384. // Return the event explicitly
  41385. return {
  41386. name: payload.name,
  41387. selected: selectedMap
  41388. };
  41389. }
  41390. /**
  41391. * @event legendToggleSelect
  41392. * @type {Object}
  41393. * @property {string} type 'legendToggleSelect'
  41394. * @property {string} [from]
  41395. * @property {string} name Series name or data item name
  41396. */
  41397. registerAction(
  41398. 'legendToggleSelect', 'legendselectchanged',
  41399. curry(legendSelectActionHandler, 'toggleSelected')
  41400. );
  41401. /**
  41402. * @event legendSelect
  41403. * @type {Object}
  41404. * @property {string} type 'legendSelect'
  41405. * @property {string} name Series name or data item name
  41406. */
  41407. registerAction(
  41408. 'legendSelect', 'legendselected',
  41409. curry(legendSelectActionHandler, 'select')
  41410. );
  41411. /**
  41412. * @event legendUnSelect
  41413. * @type {Object}
  41414. * @property {string} type 'legendUnSelect'
  41415. * @property {string} name Series name or data item name
  41416. */
  41417. registerAction(
  41418. 'legendUnSelect', 'legendunselected',
  41419. curry(legendSelectActionHandler, 'unSelect')
  41420. );
  41421. /*
  41422. * Licensed to the Apache Software Foundation (ASF) under one
  41423. * or more contributor license agreements. See the NOTICE file
  41424. * distributed with this work for additional information
  41425. * regarding copyright ownership. The ASF licenses this file
  41426. * to you under the Apache License, Version 2.0 (the
  41427. * "License"); you may not use this file except in compliance
  41428. * with the License. You may obtain a copy of the License at
  41429. *
  41430. * http://www.apache.org/licenses/LICENSE-2.0
  41431. *
  41432. * Unless required by applicable law or agreed to in writing,
  41433. * software distributed under the License is distributed on an
  41434. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41435. * KIND, either express or implied. See the License for the
  41436. * specific language governing permissions and limitations
  41437. * under the License.
  41438. */
  41439. /**
  41440. * Layout list like component.
  41441. * It will box layout each items in group of component and then position the whole group in the viewport
  41442. * @param {module:zrender/group/Group} group
  41443. * @param {module:echarts/model/Component} componentModel
  41444. * @param {module:echarts/ExtensionAPI}
  41445. */
  41446. function layout$2(group, componentModel, api) {
  41447. var boxLayoutParams = componentModel.getBoxLayoutParams();
  41448. var padding = componentModel.get('padding');
  41449. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  41450. var rect = getLayoutRect(
  41451. boxLayoutParams,
  41452. viewportSize,
  41453. padding
  41454. );
  41455. box(
  41456. componentModel.get('orient'),
  41457. group,
  41458. componentModel.get('itemGap'),
  41459. rect.width,
  41460. rect.height
  41461. );
  41462. positionElement(
  41463. group,
  41464. boxLayoutParams,
  41465. viewportSize,
  41466. padding
  41467. );
  41468. }
  41469. function makeBackground(rect, componentModel) {
  41470. var padding = normalizeCssArray$1(
  41471. componentModel.get('padding')
  41472. );
  41473. var style = componentModel.getItemStyle(['color', 'opacity']);
  41474. style.fill = componentModel.get('backgroundColor');
  41475. var rect = new Rect({
  41476. shape: {
  41477. x: rect.x - padding[3],
  41478. y: rect.y - padding[0],
  41479. width: rect.width + padding[1] + padding[3],
  41480. height: rect.height + padding[0] + padding[2],
  41481. r: componentModel.get('borderRadius')
  41482. },
  41483. style: style,
  41484. silent: true,
  41485. z2: -1
  41486. });
  41487. // FIXME
  41488. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  41489. // and background rect when setting like `left: 0`, `top: 0`.
  41490. // graphic.subPixelOptimizeRect(rect);
  41491. return rect;
  41492. }
  41493. /*
  41494. * Licensed to the Apache Software Foundation (ASF) under one
  41495. * or more contributor license agreements. See the NOTICE file
  41496. * distributed with this work for additional information
  41497. * regarding copyright ownership. The ASF licenses this file
  41498. * to you under the Apache License, Version 2.0 (the
  41499. * "License"); you may not use this file except in compliance
  41500. * with the License. You may obtain a copy of the License at
  41501. *
  41502. * http://www.apache.org/licenses/LICENSE-2.0
  41503. *
  41504. * Unless required by applicable law or agreed to in writing,
  41505. * software distributed under the License is distributed on an
  41506. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41507. * KIND, either express or implied. See the License for the
  41508. * specific language governing permissions and limitations
  41509. * under the License.
  41510. */
  41511. var curry$3 = curry;
  41512. var each$11 = each$1;
  41513. var Group$2 = Group;
  41514. var LegendView = extendComponentView({
  41515. type: 'legend.plain',
  41516. newlineDisabled: false,
  41517. /**
  41518. * @override
  41519. */
  41520. init: function () {
  41521. /**
  41522. * @private
  41523. * @type {module:zrender/container/Group}
  41524. */
  41525. this.group.add(this._contentGroup = new Group$2());
  41526. /**
  41527. * @private
  41528. * @type {module:zrender/Element}
  41529. */
  41530. this._backgroundEl;
  41531. /**
  41532. * If first rendering, `contentGroup.position` is [0, 0], which
  41533. * does not make sense and may cause unexepcted animation if adopted.
  41534. * @private
  41535. * @type {boolean}
  41536. */
  41537. this._isFirstRender = true;
  41538. },
  41539. /**
  41540. * @protected
  41541. */
  41542. getContentGroup: function () {
  41543. return this._contentGroup;
  41544. },
  41545. /**
  41546. * @override
  41547. */
  41548. render: function (legendModel, ecModel, api) {
  41549. var isFirstRender = this._isFirstRender;
  41550. this._isFirstRender = false;
  41551. this.resetInner();
  41552. if (!legendModel.get('show', true)) {
  41553. return;
  41554. }
  41555. var itemAlign = legendModel.get('align');
  41556. if (!itemAlign || itemAlign === 'auto') {
  41557. itemAlign = (
  41558. legendModel.get('left') === 'right'
  41559. && legendModel.get('orient') === 'vertical'
  41560. ) ? 'right' : 'left';
  41561. }
  41562. this.renderInner(itemAlign, legendModel, ecModel, api);
  41563. // Perform layout.
  41564. var positionInfo = legendModel.getBoxLayoutParams();
  41565. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  41566. var padding = legendModel.get('padding');
  41567. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  41568. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender);
  41569. // Place mainGroup, based on the calculated `mainRect`.
  41570. var layoutRect = getLayoutRect(
  41571. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  41572. viewportSize,
  41573. padding
  41574. );
  41575. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  41576. // Render background after group is layout.
  41577. this.group.add(
  41578. this._backgroundEl = makeBackground(mainRect, legendModel)
  41579. );
  41580. },
  41581. /**
  41582. * @protected
  41583. */
  41584. resetInner: function () {
  41585. this.getContentGroup().removeAll();
  41586. this._backgroundEl && this.group.remove(this._backgroundEl);
  41587. },
  41588. /**
  41589. * @protected
  41590. */
  41591. renderInner: function (itemAlign, legendModel, ecModel, api) {
  41592. var contentGroup = this.getContentGroup();
  41593. var legendDrawnMap = createHashMap();
  41594. var selectMode = legendModel.get('selectedMode');
  41595. var excludeSeriesId = [];
  41596. ecModel.eachRawSeries(function (seriesModel) {
  41597. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  41598. });
  41599. each$11(legendModel.getData(), function (itemModel, dataIndex) {
  41600. var name = itemModel.get('name');
  41601. // Use empty string or \n as a newline string
  41602. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  41603. contentGroup.add(new Group$2({
  41604. newline: true
  41605. }));
  41606. return;
  41607. }
  41608. // Representitive series.
  41609. var seriesModel = ecModel.getSeriesByName(name)[0];
  41610. if (legendDrawnMap.get(name)) {
  41611. // Have been drawed
  41612. return;
  41613. }
  41614. // Series legend
  41615. if (seriesModel) {
  41616. var data = seriesModel.getData();
  41617. var color = data.getVisual('color');
  41618. // If color is a callback function
  41619. if (typeof color === 'function') {
  41620. // Use the first data
  41621. color = color(seriesModel.getDataParams(0));
  41622. }
  41623. // Using rect symbol defaultly
  41624. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  41625. var symbolType = data.getVisual('symbol');
  41626. var itemGroup = this._createItem(
  41627. name, dataIndex, itemModel, legendModel,
  41628. legendSymbolType, symbolType,
  41629. itemAlign, color,
  41630. selectMode
  41631. );
  41632. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  41633. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  41634. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  41635. legendDrawnMap.set(name, true);
  41636. }
  41637. else {
  41638. // Data legend of pie, funnel
  41639. ecModel.eachRawSeries(function (seriesModel) {
  41640. // In case multiple series has same data name
  41641. if (legendDrawnMap.get(name)) {
  41642. return;
  41643. }
  41644. if (seriesModel.legendDataProvider) {
  41645. var data = seriesModel.legendDataProvider();
  41646. var idx = data.indexOfName(name);
  41647. if (idx < 0) {
  41648. return;
  41649. }
  41650. var color = data.getItemVisual(idx, 'color');
  41651. var legendSymbolType = 'roundRect';
  41652. var itemGroup = this._createItem(
  41653. name, dataIndex, itemModel, legendModel,
  41654. legendSymbolType, null,
  41655. itemAlign, color,
  41656. selectMode
  41657. );
  41658. // FIXME: consider different series has items with the same name.
  41659. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  41660. // Should not specify the series name, consider legend controls
  41661. // more than one pie series.
  41662. .on('mouseover', curry$3(dispatchHighlightAction, null, name, api, excludeSeriesId))
  41663. .on('mouseout', curry$3(dispatchDownplayAction, null, name, api, excludeSeriesId));
  41664. legendDrawnMap.set(name, true);
  41665. }
  41666. }, this);
  41667. }
  41668. if (__DEV__) {
  41669. if (!legendDrawnMap.get(name)) {
  41670. console.warn(
  41671. name + ' series not exists. Legend data should be same with series name or data name.'
  41672. );
  41673. }
  41674. }
  41675. }, this);
  41676. },
  41677. _createItem: function (
  41678. name, dataIndex, itemModel, legendModel,
  41679. legendSymbolType, symbolType,
  41680. itemAlign, color, selectMode
  41681. ) {
  41682. var itemWidth = legendModel.get('itemWidth');
  41683. var itemHeight = legendModel.get('itemHeight');
  41684. var inactiveColor = legendModel.get('inactiveColor');
  41685. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  41686. var isSelected = legendModel.isSelected(name);
  41687. var itemGroup = new Group$2();
  41688. var textStyleModel = itemModel.getModel('textStyle');
  41689. var itemIcon = itemModel.get('icon');
  41690. var tooltipModel = itemModel.getModel('tooltip');
  41691. var legendGlobalTooltipModel = tooltipModel.parentModel;
  41692. // Use user given icon first
  41693. legendSymbolType = itemIcon || legendSymbolType;
  41694. itemGroup.add(createSymbol(
  41695. legendSymbolType,
  41696. 0,
  41697. 0,
  41698. itemWidth,
  41699. itemHeight,
  41700. isSelected ? color : inactiveColor,
  41701. // symbolKeepAspect default true for legend
  41702. symbolKeepAspect == null ? true : symbolKeepAspect
  41703. ));
  41704. // Compose symbols
  41705. // PENDING
  41706. if (!itemIcon && symbolType
  41707. // At least show one symbol, can't be all none
  41708. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  41709. ) {
  41710. var size = itemHeight * 0.8;
  41711. if (symbolType === 'none') {
  41712. symbolType = 'circle';
  41713. }
  41714. // Put symbol in the center
  41715. itemGroup.add(createSymbol(
  41716. symbolType,
  41717. (itemWidth - size) / 2,
  41718. (itemHeight - size) / 2,
  41719. size,
  41720. size,
  41721. isSelected ? color : inactiveColor,
  41722. // symbolKeepAspect default true for legend
  41723. symbolKeepAspect == null ? true : symbolKeepAspect
  41724. ));
  41725. }
  41726. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  41727. var textAlign = itemAlign;
  41728. var formatter = legendModel.get('formatter');
  41729. var content = name;
  41730. if (typeof formatter === 'string' && formatter) {
  41731. content = formatter.replace('{name}', name != null ? name : '');
  41732. }
  41733. else if (typeof formatter === 'function') {
  41734. content = formatter(name);
  41735. }
  41736. itemGroup.add(new Text({
  41737. style: setTextStyle({}, textStyleModel, {
  41738. text: content,
  41739. x: textX,
  41740. y: itemHeight / 2,
  41741. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  41742. textAlign: textAlign,
  41743. textVerticalAlign: 'middle'
  41744. })
  41745. }));
  41746. // Add a invisible rect to increase the area of mouse hover
  41747. var hitRect = new Rect({
  41748. shape: itemGroup.getBoundingRect(),
  41749. invisible: true,
  41750. tooltip: tooltipModel.get('show') ? extend({
  41751. content: name,
  41752. // Defaul formatter
  41753. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  41754. return name;
  41755. },
  41756. formatterParams: {
  41757. componentType: 'legend',
  41758. legendIndex: legendModel.componentIndex,
  41759. name: name,
  41760. $vars: ['name']
  41761. }
  41762. }, tooltipModel.option) : null
  41763. });
  41764. itemGroup.add(hitRect);
  41765. itemGroup.eachChild(function (child) {
  41766. child.silent = true;
  41767. });
  41768. hitRect.silent = !selectMode;
  41769. this.getContentGroup().add(itemGroup);
  41770. setHoverStyle(itemGroup);
  41771. itemGroup.__legendDataIndex = dataIndex;
  41772. return itemGroup;
  41773. },
  41774. /**
  41775. * @protected
  41776. */
  41777. layoutInner: function (legendModel, itemAlign, maxSize) {
  41778. var contentGroup = this.getContentGroup();
  41779. // Place items in contentGroup.
  41780. box(
  41781. legendModel.get('orient'),
  41782. contentGroup,
  41783. legendModel.get('itemGap'),
  41784. maxSize.width,
  41785. maxSize.height
  41786. );
  41787. var contentRect = contentGroup.getBoundingRect();
  41788. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  41789. return this.group.getBoundingRect();
  41790. },
  41791. /**
  41792. * @protected
  41793. */
  41794. remove: function () {
  41795. this.getContentGroup().removeAll();
  41796. this._isFirstRender = true;
  41797. }
  41798. });
  41799. function dispatchSelectAction(name, api) {
  41800. api.dispatchAction({
  41801. type: 'legendToggleSelect',
  41802. name: name
  41803. });
  41804. }
  41805. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  41806. // If element hover will move to a hoverLayer.
  41807. var el = api.getZr().storage.getDisplayList()[0];
  41808. if (!(el && el.useHoverLayer)) {
  41809. api.dispatchAction({
  41810. type: 'highlight',
  41811. seriesName: seriesName,
  41812. name: dataName,
  41813. excludeSeriesId: excludeSeriesId
  41814. });
  41815. }
  41816. }
  41817. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  41818. // If element hover will move to a hoverLayer.
  41819. var el = api.getZr().storage.getDisplayList()[0];
  41820. if (!(el && el.useHoverLayer)) {
  41821. api.dispatchAction({
  41822. type: 'downplay',
  41823. seriesName: seriesName,
  41824. name: dataName,
  41825. excludeSeriesId: excludeSeriesId
  41826. });
  41827. }
  41828. }
  41829. /*
  41830. * Licensed to the Apache Software Foundation (ASF) under one
  41831. * or more contributor license agreements. See the NOTICE file
  41832. * distributed with this work for additional information
  41833. * regarding copyright ownership. The ASF licenses this file
  41834. * to you under the Apache License, Version 2.0 (the
  41835. * "License"); you may not use this file except in compliance
  41836. * with the License. You may obtain a copy of the License at
  41837. *
  41838. * http://www.apache.org/licenses/LICENSE-2.0
  41839. *
  41840. * Unless required by applicable law or agreed to in writing,
  41841. * software distributed under the License is distributed on an
  41842. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41843. * KIND, either express or implied. See the License for the
  41844. * specific language governing permissions and limitations
  41845. * under the License.
  41846. */
  41847. var legendFilter = function (ecModel) {
  41848. var legendModels = ecModel.findComponents({
  41849. mainType: 'legend'
  41850. });
  41851. if (legendModels && legendModels.length) {
  41852. ecModel.filterSeries(function (series) {
  41853. // If in any legend component the status is not selected.
  41854. // Because in legend series is assumed selected when it is not in the legend data.
  41855. for (var i = 0; i < legendModels.length; i++) {
  41856. if (!legendModels[i].isSelected(series.name)) {
  41857. return false;
  41858. }
  41859. }
  41860. return true;
  41861. });
  41862. }
  41863. };
  41864. /*
  41865. * Licensed to the Apache Software Foundation (ASF) under one
  41866. * or more contributor license agreements. See the NOTICE file
  41867. * distributed with this work for additional information
  41868. * regarding copyright ownership. The ASF licenses this file
  41869. * to you under the Apache License, Version 2.0 (the
  41870. * "License"); you may not use this file except in compliance
  41871. * with the License. You may obtain a copy of the License at
  41872. *
  41873. * http://www.apache.org/licenses/LICENSE-2.0
  41874. *
  41875. * Unless required by applicable law or agreed to in writing,
  41876. * software distributed under the License is distributed on an
  41877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41878. * KIND, either express or implied. See the License for the
  41879. * specific language governing permissions and limitations
  41880. * under the License.
  41881. */
  41882. // Do not contain scrollable legend, for sake of file size.
  41883. // Series Filter
  41884. registerProcessor(legendFilter);
  41885. ComponentModel.registerSubTypeDefaulter('legend', function () {
  41886. // Default 'plain' when no type specified.
  41887. return 'plain';
  41888. });
  41889. /*
  41890. * Licensed to the Apache Software Foundation (ASF) under one
  41891. * or more contributor license agreements. See the NOTICE file
  41892. * distributed with this work for additional information
  41893. * regarding copyright ownership. The ASF licenses this file
  41894. * to you under the Apache License, Version 2.0 (the
  41895. * "License"); you may not use this file except in compliance
  41896. * with the License. You may obtain a copy of the License at
  41897. *
  41898. * http://www.apache.org/licenses/LICENSE-2.0
  41899. *
  41900. * Unless required by applicable law or agreed to in writing,
  41901. * software distributed under the License is distributed on an
  41902. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41903. * KIND, either express or implied. See the License for the
  41904. * specific language governing permissions and limitations
  41905. * under the License.
  41906. */
  41907. var ScrollableLegendModel = LegendModel.extend({
  41908. type: 'legend.scroll',
  41909. /**
  41910. * @param {number} scrollDataIndex
  41911. */
  41912. setScrollDataIndex: function (scrollDataIndex) {
  41913. this.option.scrollDataIndex = scrollDataIndex;
  41914. },
  41915. defaultOption: {
  41916. scrollDataIndex: 0,
  41917. pageButtonItemGap: 5,
  41918. pageButtonGap: null,
  41919. pageButtonPosition: 'end', // 'start' or 'end'
  41920. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  41921. pageIcons: {
  41922. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  41923. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  41924. },
  41925. pageIconColor: '#2f4554',
  41926. pageIconInactiveColor: '#aaa',
  41927. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  41928. pageTextStyle: {
  41929. color: '#333'
  41930. },
  41931. animationDurationUpdate: 800
  41932. },
  41933. /**
  41934. * @override
  41935. */
  41936. init: function (option, parentModel, ecModel, extraOpt) {
  41937. var inputPositionParams = getLayoutParams(option);
  41938. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  41939. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  41940. },
  41941. /**
  41942. * @override
  41943. */
  41944. mergeOption: function (option, extraOpt) {
  41945. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  41946. mergeAndNormalizeLayoutParams(this, this.option, option);
  41947. },
  41948. getOrient: function () {
  41949. return this.get('orient') === 'vertical'
  41950. ? {index: 1, name: 'vertical'}
  41951. : {index: 0, name: 'horizontal'};
  41952. }
  41953. });
  41954. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  41955. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  41956. var orient = legendModel.getOrient();
  41957. var ignoreSize = [1, 1];
  41958. ignoreSize[orient.index] = 0;
  41959. mergeLayoutParam(target, raw, {
  41960. type: 'box', ignoreSize: ignoreSize
  41961. });
  41962. }
  41963. /*
  41964. * Licensed to the Apache Software Foundation (ASF) under one
  41965. * or more contributor license agreements. See the NOTICE file
  41966. * distributed with this work for additional information
  41967. * regarding copyright ownership. The ASF licenses this file
  41968. * to you under the Apache License, Version 2.0 (the
  41969. * "License"); you may not use this file except in compliance
  41970. * with the License. You may obtain a copy of the License at
  41971. *
  41972. * http://www.apache.org/licenses/LICENSE-2.0
  41973. *
  41974. * Unless required by applicable law or agreed to in writing,
  41975. * software distributed under the License is distributed on an
  41976. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41977. * KIND, either express or implied. See the License for the
  41978. * specific language governing permissions and limitations
  41979. * under the License.
  41980. */
  41981. /**
  41982. * Separate legend and scrollable legend to reduce package size.
  41983. */
  41984. var Group$3 = Group;
  41985. var WH = ['width', 'height'];
  41986. var XY = ['x', 'y'];
  41987. var ScrollableLegendView = LegendView.extend({
  41988. type: 'legend.scroll',
  41989. newlineDisabled: true,
  41990. init: function () {
  41991. ScrollableLegendView.superCall(this, 'init');
  41992. /**
  41993. * @private
  41994. * @type {number} For `scroll`.
  41995. */
  41996. this._currentIndex = 0;
  41997. /**
  41998. * @private
  41999. * @type {module:zrender/container/Group}
  42000. */
  42001. this.group.add(this._containerGroup = new Group$3());
  42002. this._containerGroup.add(this.getContentGroup());
  42003. /**
  42004. * @private
  42005. * @type {module:zrender/container/Group}
  42006. */
  42007. this.group.add(this._controllerGroup = new Group$3());
  42008. /**
  42009. *
  42010. * @private
  42011. */
  42012. this._showController;
  42013. },
  42014. /**
  42015. * @override
  42016. */
  42017. resetInner: function () {
  42018. ScrollableLegendView.superCall(this, 'resetInner');
  42019. this._controllerGroup.removeAll();
  42020. this._containerGroup.removeClipPath();
  42021. this._containerGroup.__rectSize = null;
  42022. },
  42023. /**
  42024. * @override
  42025. */
  42026. renderInner: function (itemAlign, legendModel, ecModel, api) {
  42027. var me = this;
  42028. // Render content items.
  42029. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  42030. var controllerGroup = this._controllerGroup;
  42031. // FIXME: support be 'auto' adapt to size number text length,
  42032. // e.g., '3/12345' should not overlap with the control arrow button.
  42033. var pageIconSize = legendModel.get('pageIconSize', true);
  42034. if (!isArray(pageIconSize)) {
  42035. pageIconSize = [pageIconSize, pageIconSize];
  42036. }
  42037. createPageButton('pagePrev', 0);
  42038. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  42039. controllerGroup.add(new Text({
  42040. name: 'pageText',
  42041. style: {
  42042. textFill: pageTextStyleModel.getTextColor(),
  42043. font: pageTextStyleModel.getFont(),
  42044. textVerticalAlign: 'middle',
  42045. textAlign: 'center'
  42046. },
  42047. silent: true
  42048. }));
  42049. createPageButton('pageNext', 1);
  42050. function createPageButton(name, iconIdx) {
  42051. var pageDataIndexName = name + 'DataIndex';
  42052. var icon = createIcon(
  42053. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  42054. {
  42055. // Buttons will be created in each render, so we do not need
  42056. // to worry about avoiding using legendModel kept in scope.
  42057. onclick: bind(
  42058. me._pageGo, me, pageDataIndexName, legendModel, api
  42059. )
  42060. },
  42061. {
  42062. x: -pageIconSize[0] / 2,
  42063. y: -pageIconSize[1] / 2,
  42064. width: pageIconSize[0],
  42065. height: pageIconSize[1]
  42066. }
  42067. );
  42068. icon.name = name;
  42069. controllerGroup.add(icon);
  42070. }
  42071. },
  42072. /**
  42073. * @override
  42074. */
  42075. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender) {
  42076. var contentGroup = this.getContentGroup();
  42077. var containerGroup = this._containerGroup;
  42078. var controllerGroup = this._controllerGroup;
  42079. var orientIdx = legendModel.getOrient().index;
  42080. var wh = WH[orientIdx];
  42081. var hw = WH[1 - orientIdx];
  42082. var yx = XY[1 - orientIdx];
  42083. // Place items in contentGroup.
  42084. box(
  42085. legendModel.get('orient'),
  42086. contentGroup,
  42087. legendModel.get('itemGap'),
  42088. !orientIdx ? null : maxSize.width,
  42089. orientIdx ? null : maxSize.height
  42090. );
  42091. box(
  42092. // Buttons in controller are layout always horizontally.
  42093. 'horizontal',
  42094. controllerGroup,
  42095. legendModel.get('pageButtonItemGap', true)
  42096. );
  42097. var contentRect = contentGroup.getBoundingRect();
  42098. var controllerRect = controllerGroup.getBoundingRect();
  42099. var showController = this._showController = contentRect[wh] > maxSize[wh];
  42100. var contentPos = [-contentRect.x, -contentRect.y];
  42101. // Remain contentPos when scroll animation perfroming.
  42102. // If first rendering, `contentGroup.position` is [0, 0], which
  42103. // does not make sense and may cause unexepcted animation if adopted.
  42104. if (!isFirstRender) {
  42105. contentPos[orientIdx] = contentGroup.position[orientIdx];
  42106. }
  42107. // Layout container group based on 0.
  42108. var containerPos = [0, 0];
  42109. var controllerPos = [-controllerRect.x, -controllerRect.y];
  42110. var pageButtonGap = retrieve2(
  42111. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  42112. );
  42113. // Place containerGroup and controllerGroup and contentGroup.
  42114. if (showController) {
  42115. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  42116. // controller is on the right / bottom.
  42117. if (pageButtonPosition === 'end') {
  42118. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  42119. }
  42120. // controller is on the left / top.
  42121. else {
  42122. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  42123. }
  42124. }
  42125. // Always align controller to content as 'middle'.
  42126. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  42127. contentGroup.attr('position', contentPos);
  42128. containerGroup.attr('position', containerPos);
  42129. controllerGroup.attr('position', controllerPos);
  42130. // Calculate `mainRect` and set `clipPath`.
  42131. // mainRect should not be calculated by `this.group.getBoundingRect()`
  42132. // for sake of the overflow.
  42133. var mainRect = this.group.getBoundingRect();
  42134. var mainRect = {x: 0, y: 0};
  42135. // Consider content may be overflow (should be clipped).
  42136. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  42137. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  42138. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  42139. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  42140. containerGroup.__rectSize = maxSize[wh];
  42141. if (showController) {
  42142. var clipShape = {x: 0, y: 0};
  42143. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  42144. clipShape[hw] = mainRect[hw];
  42145. containerGroup.setClipPath(new Rect({shape: clipShape}));
  42146. // Consider content may be larger than container, container rect
  42147. // can not be obtained from `containerGroup.getBoundingRect()`.
  42148. containerGroup.__rectSize = clipShape[wh];
  42149. }
  42150. else {
  42151. // Do not remove or ignore controller. Keep them set as place holders.
  42152. controllerGroup.eachChild(function (child) {
  42153. child.attr({invisible: true, silent: true});
  42154. });
  42155. }
  42156. // Content translate animation.
  42157. var pageInfo = this._getPageInfo(legendModel);
  42158. pageInfo.pageIndex != null && updateProps(
  42159. contentGroup,
  42160. {position: pageInfo.contentPosition},
  42161. // When switch from "show controller" to "not show controller", view should be
  42162. // updated immediately without animation, otherwise causes weird efffect.
  42163. showController ? legendModel : false
  42164. );
  42165. this._updatePageInfoView(legendModel, pageInfo);
  42166. return mainRect;
  42167. },
  42168. _pageGo: function (to, legendModel, api) {
  42169. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  42170. scrollDataIndex != null && api.dispatchAction({
  42171. type: 'legendScroll',
  42172. scrollDataIndex: scrollDataIndex,
  42173. legendId: legendModel.id
  42174. });
  42175. },
  42176. _updatePageInfoView: function (legendModel, pageInfo) {
  42177. var controllerGroup = this._controllerGroup;
  42178. each$1(['pagePrev', 'pageNext'], function (name) {
  42179. var canJump = pageInfo[name + 'DataIndex'] != null;
  42180. var icon = controllerGroup.childOfName(name);
  42181. if (icon) {
  42182. icon.setStyle(
  42183. 'fill',
  42184. canJump
  42185. ? legendModel.get('pageIconColor', true)
  42186. : legendModel.get('pageIconInactiveColor', true)
  42187. );
  42188. icon.cursor = canJump ? 'pointer' : 'default';
  42189. }
  42190. });
  42191. var pageText = controllerGroup.childOfName('pageText');
  42192. var pageFormatter = legendModel.get('pageFormatter');
  42193. var pageIndex = pageInfo.pageIndex;
  42194. var current = pageIndex != null ? pageIndex + 1 : 0;
  42195. var total = pageInfo.pageCount;
  42196. pageText && pageFormatter && pageText.setStyle(
  42197. 'text',
  42198. isString(pageFormatter)
  42199. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  42200. : pageFormatter({current: current, total: total})
  42201. );
  42202. },
  42203. /**
  42204. * @param {module:echarts/model/Model} legendModel
  42205. * @return {Object} {
  42206. * contentPosition: Array.<number>, null when data item not found.
  42207. * pageIndex: number, null when data item not found.
  42208. * pageCount: number, always be a number, can be 0.
  42209. * pagePrevDataIndex: number, null when no next page.
  42210. * pageNextDataIndex: number, null when no previous page.
  42211. * }
  42212. */
  42213. _getPageInfo: function (legendModel) {
  42214. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  42215. var contentGroup = this.getContentGroup();
  42216. var containerRectSize = this._containerGroup.__rectSize;
  42217. var orientIdx = legendModel.getOrient().index;
  42218. var wh = WH[orientIdx];
  42219. var xy = XY[orientIdx];
  42220. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  42221. var children = contentGroup.children();
  42222. var targetItem = children[targetItemIndex];
  42223. var itemCount = children.length;
  42224. var pCount = !itemCount ? 0 : 1;
  42225. var result = {
  42226. contentPosition: contentGroup.position.slice(),
  42227. pageCount: pCount,
  42228. pageIndex: pCount - 1,
  42229. pagePrevDataIndex: null,
  42230. pageNextDataIndex: null
  42231. };
  42232. if (!targetItem) {
  42233. return result;
  42234. }
  42235. var targetItemInfo = getItemInfo(targetItem);
  42236. result.contentPosition[orientIdx] = -targetItemInfo.s;
  42237. // Strategy:
  42238. // (1) Always align based on the left/top most item.
  42239. // (2) It is user-friendly that the last item shown in the
  42240. // current window is shown at the begining of next window.
  42241. // Otherwise if half of the last item is cut by the window,
  42242. // it will have no chance to display entirely.
  42243. // (3) Consider that item size probably be different, we
  42244. // have calculate pageIndex by size rather than item index,
  42245. // and we can not get page index directly by division.
  42246. // (4) The window is to narrow to contain more than
  42247. // one item, we should make sure that the page can be fliped.
  42248. for (var i = targetItemIndex + 1,
  42249. winStartItemInfo = targetItemInfo,
  42250. winEndItemInfo = targetItemInfo,
  42251. currItemInfo = null;
  42252. i <= itemCount;
  42253. ++i
  42254. ) {
  42255. currItemInfo = getItemInfo(children[i]);
  42256. if (
  42257. // Half of the last item is out of the window.
  42258. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  42259. // If the current item does not intersect with the window, the new page
  42260. // can be started at the current item or the last item.
  42261. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  42262. ) {
  42263. if (winEndItemInfo.i > winStartItemInfo.i) {
  42264. winStartItemInfo = winEndItemInfo;
  42265. }
  42266. else { // e.g., when page size is smaller than item size.
  42267. winStartItemInfo = currItemInfo;
  42268. }
  42269. if (winStartItemInfo) {
  42270. if (result.pageNextDataIndex == null) {
  42271. result.pageNextDataIndex = winStartItemInfo.i;
  42272. }
  42273. ++result.pageCount;
  42274. }
  42275. }
  42276. winEndItemInfo = currItemInfo;
  42277. }
  42278. for (var i = targetItemIndex - 1,
  42279. winStartItemInfo = targetItemInfo,
  42280. winEndItemInfo = targetItemInfo,
  42281. currItemInfo = null;
  42282. i >= -1;
  42283. --i
  42284. ) {
  42285. currItemInfo = getItemInfo(children[i]);
  42286. if (
  42287. // If the the end item does not intersect with the window started
  42288. // from the current item, a page can be settled.
  42289. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  42290. // e.g., when page size is smaller than item size.
  42291. && winStartItemInfo.i < winEndItemInfo.i
  42292. ) {
  42293. winEndItemInfo = winStartItemInfo;
  42294. if (result.pagePrevDataIndex == null) {
  42295. result.pagePrevDataIndex = winStartItemInfo.i;
  42296. }
  42297. ++result.pageCount;
  42298. ++result.pageIndex;
  42299. }
  42300. winStartItemInfo = currItemInfo;
  42301. }
  42302. return result;
  42303. function getItemInfo(el) {
  42304. if (el) {
  42305. var itemRect = el.getBoundingRect();
  42306. var start = itemRect[xy] + el.position[orientIdx];
  42307. return {
  42308. s: start,
  42309. e: start + itemRect[wh],
  42310. i: el.__legendDataIndex
  42311. };
  42312. }
  42313. }
  42314. function intersect(itemInfo, winStart) {
  42315. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  42316. }
  42317. },
  42318. _findTargetItemIndex: function (targetDataIndex) {
  42319. var index;
  42320. var contentGroup = this.getContentGroup();
  42321. if (this._showController) {
  42322. contentGroup.eachChild(function (child, idx) {
  42323. if (child.__legendDataIndex === targetDataIndex) {
  42324. index = idx;
  42325. }
  42326. });
  42327. }
  42328. else {
  42329. index = 0;
  42330. }
  42331. return index;
  42332. }
  42333. });
  42334. /*
  42335. * Licensed to the Apache Software Foundation (ASF) under one
  42336. * or more contributor license agreements. See the NOTICE file
  42337. * distributed with this work for additional information
  42338. * regarding copyright ownership. The ASF licenses this file
  42339. * to you under the Apache License, Version 2.0 (the
  42340. * "License"); you may not use this file except in compliance
  42341. * with the License. You may obtain a copy of the License at
  42342. *
  42343. * http://www.apache.org/licenses/LICENSE-2.0
  42344. *
  42345. * Unless required by applicable law or agreed to in writing,
  42346. * software distributed under the License is distributed on an
  42347. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42348. * KIND, either express or implied. See the License for the
  42349. * specific language governing permissions and limitations
  42350. * under the License.
  42351. */
  42352. /**
  42353. * @event legendScroll
  42354. * @type {Object}
  42355. * @property {string} type 'legendScroll'
  42356. * @property {string} scrollDataIndex
  42357. */
  42358. registerAction(
  42359. 'legendScroll', 'legendscroll',
  42360. function (payload, ecModel) {
  42361. var scrollDataIndex = payload.scrollDataIndex;
  42362. scrollDataIndex != null && ecModel.eachComponent(
  42363. {mainType: 'legend', subType: 'scroll', query: payload},
  42364. function (legendModel) {
  42365. legendModel.setScrollDataIndex(scrollDataIndex);
  42366. }
  42367. );
  42368. }
  42369. );
  42370. /*
  42371. * Licensed to the Apache Software Foundation (ASF) under one
  42372. * or more contributor license agreements. See the NOTICE file
  42373. * distributed with this work for additional information
  42374. * regarding copyright ownership. The ASF licenses this file
  42375. * to you under the Apache License, Version 2.0 (the
  42376. * "License"); you may not use this file except in compliance
  42377. * with the License. You may obtain a copy of the License at
  42378. *
  42379. * http://www.apache.org/licenses/LICENSE-2.0
  42380. *
  42381. * Unless required by applicable law or agreed to in writing,
  42382. * software distributed under the License is distributed on an
  42383. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42384. * KIND, either express or implied. See the License for the
  42385. * specific language governing permissions and limitations
  42386. * under the License.
  42387. */
  42388. /**
  42389. * Legend component entry file8
  42390. */
  42391. /*
  42392. * Licensed to the Apache Software Foundation (ASF) under one
  42393. * or more contributor license agreements. See the NOTICE file
  42394. * distributed with this work for additional information
  42395. * regarding copyright ownership. The ASF licenses this file
  42396. * to you under the Apache License, Version 2.0 (the
  42397. * "License"); you may not use this file except in compliance
  42398. * with the License. You may obtain a copy of the License at
  42399. *
  42400. * http://www.apache.org/licenses/LICENSE-2.0
  42401. *
  42402. * Unless required by applicable law or agreed to in writing,
  42403. * software distributed under the License is distributed on an
  42404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42405. * KIND, either express or implied. See the License for the
  42406. * specific language governing permissions and limitations
  42407. * under the License.
  42408. */
  42409. /*
  42410. * Licensed to the Apache Software Foundation (ASF) under one
  42411. * or more contributor license agreements. See the NOTICE file
  42412. * distributed with this work for additional information
  42413. * regarding copyright ownership. The ASF licenses this file
  42414. * to you under the Apache License, Version 2.0 (the
  42415. * "License"); you may not use this file except in compliance
  42416. * with the License. You may obtain a copy of the License at
  42417. *
  42418. * http://www.apache.org/licenses/LICENSE-2.0
  42419. *
  42420. * Unless required by applicable law or agreed to in writing,
  42421. * software distributed under the License is distributed on an
  42422. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42423. * KIND, either express or implied. See the License for the
  42424. * specific language governing permissions and limitations
  42425. * under the License.
  42426. */
  42427. // Model
  42428. extendComponentModel({
  42429. type: 'title',
  42430. layoutMode: {type: 'box', ignoreSize: true},
  42431. defaultOption: {
  42432. // 一级层叠
  42433. zlevel: 0,
  42434. // 二级层叠
  42435. z: 6,
  42436. show: true,
  42437. text: '',
  42438. // 超链接跳转
  42439. // link: null,
  42440. // 仅支持self | blank
  42441. target: 'blank',
  42442. subtext: '',
  42443. // 超链接跳转
  42444. // sublink: null,
  42445. // 仅支持self | blank
  42446. subtarget: 'blank',
  42447. // 'center' ¦ 'left' ¦ 'right'
  42448. // ¦ {number}(x坐标,单位px)
  42449. left: 0,
  42450. // 'top' ¦ 'bottom' ¦ 'center'
  42451. // ¦ {number}(y坐标,单位px)
  42452. top: 0,
  42453. // 水平对齐
  42454. // 'auto' | 'left' | 'right' | 'center'
  42455. // 默认根据 left 的位置判断是左对齐还是右对齐
  42456. // textAlign: null
  42457. //
  42458. // 垂直对齐
  42459. // 'auto' | 'top' | 'bottom' | 'middle'
  42460. // 默认根据 top 位置判断是上对齐还是下对齐
  42461. // textBaseline: null
  42462. backgroundColor: 'rgba(0,0,0,0)',
  42463. // 标题边框颜色
  42464. borderColor: '#ccc',
  42465. // 标题边框线宽,单位px,默认为0(无边框)
  42466. borderWidth: 0,
  42467. // 标题内边距,单位px,默认各方向内边距为5,
  42468. // 接受数组分别设定上右下左边距,同css
  42469. padding: 5,
  42470. // 主副标题纵向间隔,单位px,默认为10,
  42471. itemGap: 10,
  42472. textStyle: {
  42473. fontSize: 18,
  42474. fontWeight: 'bolder',
  42475. color: '#333'
  42476. },
  42477. subtextStyle: {
  42478. color: '#aaa'
  42479. }
  42480. }
  42481. });
  42482. // View
  42483. extendComponentView({
  42484. type: 'title',
  42485. render: function (titleModel, ecModel, api) {
  42486. this.group.removeAll();
  42487. if (!titleModel.get('show')) {
  42488. return;
  42489. }
  42490. var group = this.group;
  42491. var textStyleModel = titleModel.getModel('textStyle');
  42492. var subtextStyleModel = titleModel.getModel('subtextStyle');
  42493. var textAlign = titleModel.get('textAlign');
  42494. var textBaseline = titleModel.get('textBaseline');
  42495. var textEl = new Text({
  42496. style: setTextStyle({}, textStyleModel, {
  42497. text: titleModel.get('text'),
  42498. textFill: textStyleModel.getTextColor()
  42499. }, {disableBox: true}),
  42500. z2: 10
  42501. });
  42502. var textRect = textEl.getBoundingRect();
  42503. var subText = titleModel.get('subtext');
  42504. var subTextEl = new Text({
  42505. style: setTextStyle({}, subtextStyleModel, {
  42506. text: subText,
  42507. textFill: subtextStyleModel.getTextColor(),
  42508. y: textRect.height + titleModel.get('itemGap'),
  42509. textVerticalAlign: 'top'
  42510. }, {disableBox: true}),
  42511. z2: 10
  42512. });
  42513. var link = titleModel.get('link');
  42514. var sublink = titleModel.get('sublink');
  42515. var triggerEvent = titleModel.get('triggerEvent', true);
  42516. textEl.silent = !link && !triggerEvent;
  42517. subTextEl.silent = !sublink && !triggerEvent;
  42518. if (link) {
  42519. textEl.on('click', function () {
  42520. window.open(link, '_' + titleModel.get('target'));
  42521. });
  42522. }
  42523. if (sublink) {
  42524. subTextEl.on('click', function () {
  42525. window.open(sublink, '_' + titleModel.get('subtarget'));
  42526. });
  42527. }
  42528. textEl.eventData = subTextEl.eventData = triggerEvent
  42529. ? {
  42530. componentType: 'title',
  42531. componentIndex: titleModel.componentIndex
  42532. }
  42533. : null;
  42534. group.add(textEl);
  42535. subText && group.add(subTextEl);
  42536. // If no subText, but add subTextEl, there will be an empty line.
  42537. var groupRect = group.getBoundingRect();
  42538. var layoutOption = titleModel.getBoxLayoutParams();
  42539. layoutOption.width = groupRect.width;
  42540. layoutOption.height = groupRect.height;
  42541. var layoutRect = getLayoutRect(
  42542. layoutOption, {
  42543. width: api.getWidth(),
  42544. height: api.getHeight()
  42545. }, titleModel.get('padding')
  42546. );
  42547. // Adjust text align based on position
  42548. if (!textAlign) {
  42549. // Align left if title is on the left. center and right is same
  42550. textAlign = titleModel.get('left') || titleModel.get('right');
  42551. if (textAlign === 'middle') {
  42552. textAlign = 'center';
  42553. }
  42554. // Adjust layout by text align
  42555. if (textAlign === 'right') {
  42556. layoutRect.x += layoutRect.width;
  42557. }
  42558. else if (textAlign === 'center') {
  42559. layoutRect.x += layoutRect.width / 2;
  42560. }
  42561. }
  42562. if (!textBaseline) {
  42563. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  42564. if (textBaseline === 'center') {
  42565. textBaseline = 'middle';
  42566. }
  42567. if (textBaseline === 'bottom') {
  42568. layoutRect.y += layoutRect.height;
  42569. }
  42570. else if (textBaseline === 'middle') {
  42571. layoutRect.y += layoutRect.height / 2;
  42572. }
  42573. textBaseline = textBaseline || 'top';
  42574. }
  42575. group.attr('position', [layoutRect.x, layoutRect.y]);
  42576. var alignStyle = {
  42577. textAlign: textAlign,
  42578. textVerticalAlign: textBaseline
  42579. };
  42580. textEl.setStyle(alignStyle);
  42581. subTextEl.setStyle(alignStyle);
  42582. // Render background
  42583. // Get groupRect again because textAlign has been changed
  42584. groupRect = group.getBoundingRect();
  42585. var padding = layoutRect.margin;
  42586. var style = titleModel.getItemStyle(['color', 'opacity']);
  42587. style.fill = titleModel.get('backgroundColor');
  42588. var rect = new Rect({
  42589. shape: {
  42590. x: groupRect.x - padding[3],
  42591. y: groupRect.y - padding[0],
  42592. width: groupRect.width + padding[1] + padding[3],
  42593. height: groupRect.height + padding[0] + padding[2],
  42594. r: titleModel.get('borderRadius')
  42595. },
  42596. style: style,
  42597. silent: true
  42598. });
  42599. subPixelOptimizeRect(rect);
  42600. group.add(rect);
  42601. }
  42602. });
  42603. /*
  42604. * Licensed to the Apache Software Foundation (ASF) under one
  42605. * or more contributor license agreements. See the NOTICE file
  42606. * distributed with this work for additional information
  42607. * regarding copyright ownership. The ASF licenses this file
  42608. * to you under the Apache License, Version 2.0 (the
  42609. * "License"); you may not use this file except in compliance
  42610. * with the License. You may obtain a copy of the License at
  42611. *
  42612. * http://www.apache.org/licenses/LICENSE-2.0
  42613. *
  42614. * Unless required by applicable law or agreed to in writing,
  42615. * software distributed under the License is distributed on an
  42616. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42617. * KIND, either express or implied. See the License for the
  42618. * specific language governing permissions and limitations
  42619. * under the License.
  42620. */
  42621. var addCommas$1 = addCommas;
  42622. var encodeHTML$1 = encodeHTML;
  42623. function fillLabel(opt) {
  42624. defaultEmphasis(opt, 'label', ['show']);
  42625. }
  42626. var MarkerModel = extendComponentModel({
  42627. type: 'marker',
  42628. dependencies: ['series', 'grid', 'polar', 'geo'],
  42629. /**
  42630. * @overrite
  42631. */
  42632. init: function (option, parentModel, ecModel, extraOpt) {
  42633. if (__DEV__) {
  42634. if (this.type === 'marker') {
  42635. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  42636. }
  42637. }
  42638. this.mergeDefaultAndTheme(option, ecModel);
  42639. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  42640. },
  42641. /**
  42642. * @return {boolean}
  42643. */
  42644. isAnimationEnabled: function () {
  42645. if (env$1.node) {
  42646. return false;
  42647. }
  42648. var hostSeries = this.__hostSeries;
  42649. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  42650. },
  42651. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  42652. var MarkerModel = this.constructor;
  42653. var modelPropName = this.mainType + 'Model';
  42654. if (!createdBySelf) {
  42655. ecModel.eachSeries(function (seriesModel) {
  42656. var markerOpt = seriesModel.get(this.mainType, true);
  42657. var markerModel = seriesModel[modelPropName];
  42658. if (!markerOpt || !markerOpt.data) {
  42659. seriesModel[modelPropName] = null;
  42660. return;
  42661. }
  42662. if (!markerModel) {
  42663. if (isInit) {
  42664. // Default label emphasis `position` and `show`
  42665. fillLabel(markerOpt);
  42666. }
  42667. each$1(markerOpt.data, function (item) {
  42668. // FIXME Overwrite fillLabel method ?
  42669. if (item instanceof Array) {
  42670. fillLabel(item[0]);
  42671. fillLabel(item[1]);
  42672. }
  42673. else {
  42674. fillLabel(item);
  42675. }
  42676. });
  42677. markerModel = new MarkerModel(
  42678. markerOpt, this, ecModel
  42679. );
  42680. extend(markerModel, {
  42681. mainType: this.mainType,
  42682. // Use the same series index and name
  42683. seriesIndex: seriesModel.seriesIndex,
  42684. name: seriesModel.name,
  42685. createdBySelf: true
  42686. });
  42687. markerModel.__hostSeries = seriesModel;
  42688. }
  42689. else {
  42690. markerModel.mergeOption(markerOpt, ecModel, true);
  42691. }
  42692. seriesModel[modelPropName] = markerModel;
  42693. }, this);
  42694. }
  42695. },
  42696. formatTooltip: function (dataIndex) {
  42697. var data = this.getData();
  42698. var value = this.getRawValue(dataIndex);
  42699. var formattedValue = isArray(value)
  42700. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  42701. var name = data.getName(dataIndex);
  42702. var html = encodeHTML$1(this.name);
  42703. if (value != null || name) {
  42704. html += '<br />';
  42705. }
  42706. if (name) {
  42707. html += encodeHTML$1(name);
  42708. if (value != null) {
  42709. html += ' : ';
  42710. }
  42711. }
  42712. if (value != null) {
  42713. html += encodeHTML$1(formattedValue);
  42714. }
  42715. return html;
  42716. },
  42717. getData: function () {
  42718. return this._data;
  42719. },
  42720. setData: function (data) {
  42721. this._data = data;
  42722. }
  42723. });
  42724. mixin(MarkerModel, dataFormatMixin);
  42725. /*
  42726. * Licensed to the Apache Software Foundation (ASF) under one
  42727. * or more contributor license agreements. See the NOTICE file
  42728. * distributed with this work for additional information
  42729. * regarding copyright ownership. The ASF licenses this file
  42730. * to you under the Apache License, Version 2.0 (the
  42731. * "License"); you may not use this file except in compliance
  42732. * with the License. You may obtain a copy of the License at
  42733. *
  42734. * http://www.apache.org/licenses/LICENSE-2.0
  42735. *
  42736. * Unless required by applicable law or agreed to in writing,
  42737. * software distributed under the License is distributed on an
  42738. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42739. * KIND, either express or implied. See the License for the
  42740. * specific language governing permissions and limitations
  42741. * under the License.
  42742. */
  42743. MarkerModel.extend({
  42744. type: 'markPoint',
  42745. defaultOption: {
  42746. zlevel: 0,
  42747. z: 5,
  42748. symbol: 'pin',
  42749. symbolSize: 50,
  42750. //symbolRotate: 0,
  42751. //symbolOffset: [0, 0]
  42752. tooltip: {
  42753. trigger: 'item'
  42754. },
  42755. label: {
  42756. show: true,
  42757. position: 'inside'
  42758. },
  42759. itemStyle: {
  42760. borderWidth: 2
  42761. },
  42762. emphasis: {
  42763. label: {
  42764. show: true
  42765. }
  42766. }
  42767. }
  42768. });
  42769. /*
  42770. * Licensed to the Apache Software Foundation (ASF) under one
  42771. * or more contributor license agreements. See the NOTICE file
  42772. * distributed with this work for additional information
  42773. * regarding copyright ownership. The ASF licenses this file
  42774. * to you under the Apache License, Version 2.0 (the
  42775. * "License"); you may not use this file except in compliance
  42776. * with the License. You may obtain a copy of the License at
  42777. *
  42778. * http://www.apache.org/licenses/LICENSE-2.0
  42779. *
  42780. * Unless required by applicable law or agreed to in writing,
  42781. * software distributed under the License is distributed on an
  42782. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42783. * KIND, either express or implied. See the License for the
  42784. * specific language governing permissions and limitations
  42785. * under the License.
  42786. */
  42787. var indexOf$1 = indexOf;
  42788. function hasXOrY(item) {
  42789. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  42790. }
  42791. function hasXAndY(item) {
  42792. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  42793. }
  42794. // Make it simple, do not visit all stacked value to count precision.
  42795. // function getPrecision(data, valueAxisDim, dataIndex) {
  42796. // var precision = -1;
  42797. // var stackedDim = data.mapDimension(valueAxisDim);
  42798. // do {
  42799. // precision = Math.max(
  42800. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  42801. // precision
  42802. // );
  42803. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  42804. // if (stackedOnSeries) {
  42805. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  42806. // data = stackedOnSeries.getData();
  42807. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  42808. // stackedDim = data.getCalculationInfo('stackedDimension');
  42809. // }
  42810. // else {
  42811. // data = null;
  42812. // }
  42813. // } while (data);
  42814. // return precision;
  42815. // }
  42816. function markerTypeCalculatorWithExtent(
  42817. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  42818. ) {
  42819. var coordArr = [];
  42820. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  42821. var calcDataDim = stacked
  42822. ? data.getCalculationInfo('stackResultDimension')
  42823. : targetDataDim;
  42824. var value = numCalculate(data, calcDataDim, mlType);
  42825. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  42826. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  42827. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  42828. // Make it simple, do not visit all stacked value to count precision.
  42829. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  42830. precision = Math.min(precision, 20);
  42831. if (precision >= 0) {
  42832. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  42833. }
  42834. return coordArr;
  42835. }
  42836. var curry$4 = curry;
  42837. // TODO Specified percent
  42838. var markerTypeCalculator = {
  42839. /**
  42840. * @method
  42841. * @param {module:echarts/data/List} data
  42842. * @param {string} baseAxisDim
  42843. * @param {string} valueAxisDim
  42844. */
  42845. min: curry$4(markerTypeCalculatorWithExtent, 'min'),
  42846. /**
  42847. * @method
  42848. * @param {module:echarts/data/List} data
  42849. * @param {string} baseAxisDim
  42850. * @param {string} valueAxisDim
  42851. */
  42852. max: curry$4(markerTypeCalculatorWithExtent, 'max'),
  42853. /**
  42854. * @method
  42855. * @param {module:echarts/data/List} data
  42856. * @param {string} baseAxisDim
  42857. * @param {string} valueAxisDim
  42858. */
  42859. average: curry$4(markerTypeCalculatorWithExtent, 'average')
  42860. };
  42861. /**
  42862. * Transform markPoint data item to format used in List by do the following
  42863. * 1. Calculate statistic like `max`, `min`, `average`
  42864. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  42865. * @param {module:echarts/model/Series} seriesModel
  42866. * @param {module:echarts/coord/*} [coordSys]
  42867. * @param {Object} item
  42868. * @return {Object}
  42869. */
  42870. function dataTransform(seriesModel, item) {
  42871. var data = seriesModel.getData();
  42872. var coordSys = seriesModel.coordinateSystem;
  42873. // 1. If not specify the position with pixel directly
  42874. // 2. If `coord` is not a data array. Which uses `xAxis`,
  42875. // `yAxis` to specify the coord on each dimension
  42876. // parseFloat first because item.x and item.y can be percent string like '20%'
  42877. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  42878. var dims = coordSys.dimensions;
  42879. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  42880. // Clone the option
  42881. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  42882. item = clone(item);
  42883. if (item.type
  42884. && markerTypeCalculator[item.type]
  42885. && axisInfo.baseAxis && axisInfo.valueAxis
  42886. ) {
  42887. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  42888. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  42889. item.coord = markerTypeCalculator[item.type](
  42890. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  42891. otherCoordIndex, targetCoordIndex
  42892. );
  42893. // Force to use the value of calculated value.
  42894. item.value = item.coord[targetCoordIndex];
  42895. }
  42896. else {
  42897. // FIXME Only has one of xAxis and yAxis.
  42898. var coord = [
  42899. item.xAxis != null ? item.xAxis : item.radiusAxis,
  42900. item.yAxis != null ? item.yAxis : item.angleAxis
  42901. ];
  42902. // Each coord support max, min, average
  42903. for (var i = 0; i < 2; i++) {
  42904. if (markerTypeCalculator[coord[i]]) {
  42905. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  42906. }
  42907. }
  42908. item.coord = coord;
  42909. }
  42910. }
  42911. return item;
  42912. }
  42913. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  42914. var ret = {};
  42915. if (item.valueIndex != null || item.valueDim != null) {
  42916. ret.valueDataDim = item.valueIndex != null
  42917. ? data.getDimension(item.valueIndex) : item.valueDim;
  42918. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  42919. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  42920. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  42921. }
  42922. else {
  42923. ret.baseAxis = seriesModel.getBaseAxis();
  42924. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  42925. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  42926. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  42927. }
  42928. return ret;
  42929. }
  42930. function dataDimToCoordDim(seriesModel, dataDim) {
  42931. var data = seriesModel.getData();
  42932. var dimensions = data.dimensions;
  42933. dataDim = data.getDimension(dataDim);
  42934. for (var i = 0; i < dimensions.length; i++) {
  42935. var dimItem = data.getDimensionInfo(dimensions[i]);
  42936. if (dimItem.name === dataDim) {
  42937. return dimItem.coordDim;
  42938. }
  42939. }
  42940. }
  42941. /**
  42942. * Filter data which is out of coordinateSystem range
  42943. * [dataFilter description]
  42944. * @param {module:echarts/coord/*} [coordSys]
  42945. * @param {Object} item
  42946. * @return {boolean}
  42947. */
  42948. function dataFilter$1(coordSys, item) {
  42949. // Alwalys return true if there is no coordSys
  42950. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  42951. ? coordSys.containData(item.coord) : true;
  42952. }
  42953. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  42954. // x, y, radius, angle
  42955. if (dimIndex < 2) {
  42956. return item.coord && item.coord[dimIndex];
  42957. }
  42958. return item.value;
  42959. }
  42960. function numCalculate(data, valueDataDim, type) {
  42961. if (type === 'average') {
  42962. var sum = 0;
  42963. var count = 0;
  42964. data.each(valueDataDim, function (val, idx) {
  42965. if (!isNaN(val)) {
  42966. sum += val;
  42967. count++;
  42968. }
  42969. });
  42970. return sum / count;
  42971. }
  42972. else if (type === 'median') {
  42973. return data.getMedian(valueDataDim);
  42974. }
  42975. else {
  42976. // max & min
  42977. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  42978. }
  42979. }
  42980. /*
  42981. * Licensed to the Apache Software Foundation (ASF) under one
  42982. * or more contributor license agreements. See the NOTICE file
  42983. * distributed with this work for additional information
  42984. * regarding copyright ownership. The ASF licenses this file
  42985. * to you under the Apache License, Version 2.0 (the
  42986. * "License"); you may not use this file except in compliance
  42987. * with the License. You may obtain a copy of the License at
  42988. *
  42989. * http://www.apache.org/licenses/LICENSE-2.0
  42990. *
  42991. * Unless required by applicable law or agreed to in writing,
  42992. * software distributed under the License is distributed on an
  42993. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42994. * KIND, either express or implied. See the License for the
  42995. * specific language governing permissions and limitations
  42996. * under the License.
  42997. */
  42998. var MarkerView = extendComponentView({
  42999. type: 'marker',
  43000. init: function () {
  43001. /**
  43002. * Markline grouped by series
  43003. * @private
  43004. * @type {module:zrender/core/util.HashMap}
  43005. */
  43006. this.markerGroupMap = createHashMap();
  43007. },
  43008. render: function (markerModel, ecModel, api) {
  43009. var markerGroupMap = this.markerGroupMap;
  43010. markerGroupMap.each(function (item) {
  43011. item.__keep = false;
  43012. });
  43013. var markerModelKey = this.type + 'Model';
  43014. ecModel.eachSeries(function (seriesModel) {
  43015. var markerModel = seriesModel[markerModelKey];
  43016. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  43017. }, this);
  43018. markerGroupMap.each(function (item) {
  43019. !item.__keep && this.group.remove(item.group);
  43020. }, this);
  43021. },
  43022. renderSeries: function () {}
  43023. });
  43024. /*
  43025. * Licensed to the Apache Software Foundation (ASF) under one
  43026. * or more contributor license agreements. See the NOTICE file
  43027. * distributed with this work for additional information
  43028. * regarding copyright ownership. The ASF licenses this file
  43029. * to you under the Apache License, Version 2.0 (the
  43030. * "License"); you may not use this file except in compliance
  43031. * with the License. You may obtain a copy of the License at
  43032. *
  43033. * http://www.apache.org/licenses/LICENSE-2.0
  43034. *
  43035. * Unless required by applicable law or agreed to in writing,
  43036. * software distributed under the License is distributed on an
  43037. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43038. * KIND, either express or implied. See the License for the
  43039. * specific language governing permissions and limitations
  43040. * under the License.
  43041. */
  43042. function updateMarkerLayout(mpData, seriesModel, api) {
  43043. var coordSys = seriesModel.coordinateSystem;
  43044. mpData.each(function (idx) {
  43045. var itemModel = mpData.getItemModel(idx);
  43046. var point;
  43047. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  43048. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  43049. if (!isNaN(xPx) && !isNaN(yPx)) {
  43050. point = [xPx, yPx];
  43051. }
  43052. // Chart like bar may have there own marker positioning logic
  43053. else if (seriesModel.getMarkerPosition) {
  43054. // Use the getMarkerPoisition
  43055. point = seriesModel.getMarkerPosition(
  43056. mpData.getValues(mpData.dimensions, idx)
  43057. );
  43058. }
  43059. else if (coordSys) {
  43060. var x = mpData.get(coordSys.dimensions[0], idx);
  43061. var y = mpData.get(coordSys.dimensions[1], idx);
  43062. point = coordSys.dataToPoint([x, y]);
  43063. }
  43064. // Use x, y if has any
  43065. if (!isNaN(xPx)) {
  43066. point[0] = xPx;
  43067. }
  43068. if (!isNaN(yPx)) {
  43069. point[1] = yPx;
  43070. }
  43071. mpData.setItemLayout(idx, point);
  43072. });
  43073. }
  43074. MarkerView.extend({
  43075. type: 'markPoint',
  43076. // updateLayout: function (markPointModel, ecModel, api) {
  43077. // ecModel.eachSeries(function (seriesModel) {
  43078. // var mpModel = seriesModel.markPointModel;
  43079. // if (mpModel) {
  43080. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  43081. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  43082. // }
  43083. // }, this);
  43084. // },
  43085. updateTransform: function (markPointModel, ecModel, api) {
  43086. ecModel.eachSeries(function (seriesModel) {
  43087. var mpModel = seriesModel.markPointModel;
  43088. if (mpModel) {
  43089. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  43090. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  43091. }
  43092. }, this);
  43093. },
  43094. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  43095. var coordSys = seriesModel.coordinateSystem;
  43096. var seriesId = seriesModel.id;
  43097. var seriesData = seriesModel.getData();
  43098. var symbolDrawMap = this.markerGroupMap;
  43099. var symbolDraw = symbolDrawMap.get(seriesId)
  43100. || symbolDrawMap.set(seriesId, new SymbolDraw());
  43101. var mpData = createList$1(coordSys, seriesModel, mpModel);
  43102. // FIXME
  43103. mpModel.setData(mpData);
  43104. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  43105. mpData.each(function (idx) {
  43106. var itemModel = mpData.getItemModel(idx);
  43107. var symbolSize = itemModel.getShallow('symbolSize');
  43108. if (typeof symbolSize === 'function') {
  43109. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  43110. symbolSize = symbolSize(
  43111. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  43112. );
  43113. }
  43114. mpData.setItemVisual(idx, {
  43115. symbolSize: symbolSize,
  43116. color: itemModel.get('itemStyle.color')
  43117. || seriesData.getVisual('color'),
  43118. symbol: itemModel.getShallow('symbol')
  43119. });
  43120. });
  43121. // TODO Text are wrong
  43122. symbolDraw.updateData(mpData);
  43123. this.group.add(symbolDraw.group);
  43124. // Set host model for tooltip
  43125. // FIXME
  43126. mpData.eachItemGraphicEl(function (el) {
  43127. el.traverse(function (child) {
  43128. child.dataModel = mpModel;
  43129. });
  43130. });
  43131. symbolDraw.__keep = true;
  43132. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  43133. }
  43134. });
  43135. /**
  43136. * @inner
  43137. * @param {module:echarts/coord/*} [coordSys]
  43138. * @param {module:echarts/model/Series} seriesModel
  43139. * @param {module:echarts/model/Model} mpModel
  43140. */
  43141. function createList$1(coordSys, seriesModel, mpModel) {
  43142. var coordDimsInfos;
  43143. if (coordSys) {
  43144. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  43145. var info = seriesModel.getData().getDimensionInfo(
  43146. seriesModel.getData().mapDimension(coordDim)
  43147. ) || {};
  43148. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  43149. return defaults({name: coordDim}, info);
  43150. });
  43151. }
  43152. else {
  43153. coordDimsInfos = [{
  43154. name: 'value',
  43155. type: 'float'
  43156. }];
  43157. }
  43158. var mpData = new List(coordDimsInfos, mpModel);
  43159. var dataOpt = map(mpModel.get('data'), curry(
  43160. dataTransform, seriesModel
  43161. ));
  43162. if (coordSys) {
  43163. dataOpt = filter(
  43164. dataOpt, curry(dataFilter$1, coordSys)
  43165. );
  43166. }
  43167. mpData.initData(dataOpt, null,
  43168. coordSys ? dimValueGetter : function (item) {
  43169. return item.value;
  43170. }
  43171. );
  43172. return mpData;
  43173. }
  43174. /*
  43175. * Licensed to the Apache Software Foundation (ASF) under one
  43176. * or more contributor license agreements. See the NOTICE file
  43177. * distributed with this work for additional information
  43178. * regarding copyright ownership. The ASF licenses this file
  43179. * to you under the Apache License, Version 2.0 (the
  43180. * "License"); you may not use this file except in compliance
  43181. * with the License. You may obtain a copy of the License at
  43182. *
  43183. * http://www.apache.org/licenses/LICENSE-2.0
  43184. *
  43185. * Unless required by applicable law or agreed to in writing,
  43186. * software distributed under the License is distributed on an
  43187. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43188. * KIND, either express or implied. See the License for the
  43189. * specific language governing permissions and limitations
  43190. * under the License.
  43191. */
  43192. // HINT Markpoint can't be used too much
  43193. registerPreprocessor(function (opt) {
  43194. // Make sure markPoint component is enabled
  43195. opt.markPoint = opt.markPoint || {};
  43196. });
  43197. /*
  43198. * Licensed to the Apache Software Foundation (ASF) under one
  43199. * or more contributor license agreements. See the NOTICE file
  43200. * distributed with this work for additional information
  43201. * regarding copyright ownership. The ASF licenses this file
  43202. * to you under the Apache License, Version 2.0 (the
  43203. * "License"); you may not use this file except in compliance
  43204. * with the License. You may obtain a copy of the License at
  43205. *
  43206. * http://www.apache.org/licenses/LICENSE-2.0
  43207. *
  43208. * Unless required by applicable law or agreed to in writing,
  43209. * software distributed under the License is distributed on an
  43210. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43211. * KIND, either express or implied. See the License for the
  43212. * specific language governing permissions and limitations
  43213. * under the License.
  43214. */
  43215. MarkerModel.extend({
  43216. type: 'markLine',
  43217. defaultOption: {
  43218. zlevel: 0,
  43219. z: 5,
  43220. symbol: ['circle', 'arrow'],
  43221. symbolSize: [8, 16],
  43222. //symbolRotate: 0,
  43223. precision: 2,
  43224. tooltip: {
  43225. trigger: 'item'
  43226. },
  43227. label: {
  43228. show: true,
  43229. position: 'end'
  43230. },
  43231. lineStyle: {
  43232. type: 'dashed'
  43233. },
  43234. emphasis: {
  43235. label: {
  43236. show: true
  43237. },
  43238. lineStyle: {
  43239. width: 3
  43240. }
  43241. },
  43242. animationEasing: 'linear'
  43243. }
  43244. });
  43245. /*
  43246. * Licensed to the Apache Software Foundation (ASF) under one
  43247. * or more contributor license agreements. See the NOTICE file
  43248. * distributed with this work for additional information
  43249. * regarding copyright ownership. The ASF licenses this file
  43250. * to you under the Apache License, Version 2.0 (the
  43251. * "License"); you may not use this file except in compliance
  43252. * with the License. You may obtain a copy of the License at
  43253. *
  43254. * http://www.apache.org/licenses/LICENSE-2.0
  43255. *
  43256. * Unless required by applicable law or agreed to in writing,
  43257. * software distributed under the License is distributed on an
  43258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43259. * KIND, either express or implied. See the License for the
  43260. * specific language governing permissions and limitations
  43261. * under the License.
  43262. */
  43263. /**
  43264. * Line path for bezier and straight line draw
  43265. */
  43266. var straightLineProto = Line.prototype;
  43267. var bezierCurveProto = BezierCurve.prototype;
  43268. function isLine(shape) {
  43269. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  43270. }
  43271. var LinePath = extendShape({
  43272. type: 'ec-line',
  43273. style: {
  43274. stroke: '#000',
  43275. fill: null
  43276. },
  43277. shape: {
  43278. x1: 0,
  43279. y1: 0,
  43280. x2: 0,
  43281. y2: 0,
  43282. percent: 1,
  43283. cpx1: null,
  43284. cpy1: null
  43285. },
  43286. buildPath: function (ctx, shape) {
  43287. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  43288. },
  43289. pointAt: function (t) {
  43290. return isLine(this.shape)
  43291. ? straightLineProto.pointAt.call(this, t)
  43292. : bezierCurveProto.pointAt.call(this, t);
  43293. },
  43294. tangentAt: function (t) {
  43295. var shape = this.shape;
  43296. var p = isLine(shape)
  43297. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  43298. : bezierCurveProto.tangentAt.call(this, t);
  43299. return normalize(p, p);
  43300. }
  43301. });
  43302. /*
  43303. * Licensed to the Apache Software Foundation (ASF) under one
  43304. * or more contributor license agreements. See the NOTICE file
  43305. * distributed with this work for additional information
  43306. * regarding copyright ownership. The ASF licenses this file
  43307. * to you under the Apache License, Version 2.0 (the
  43308. * "License"); you may not use this file except in compliance
  43309. * with the License. You may obtain a copy of the License at
  43310. *
  43311. * http://www.apache.org/licenses/LICENSE-2.0
  43312. *
  43313. * Unless required by applicable law or agreed to in writing,
  43314. * software distributed under the License is distributed on an
  43315. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43316. * KIND, either express or implied. See the License for the
  43317. * specific language governing permissions and limitations
  43318. * under the License.
  43319. */
  43320. /**
  43321. * @module echarts/chart/helper/Line
  43322. */
  43323. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  43324. function makeSymbolTypeKey(symbolCategory) {
  43325. return '_' + symbolCategory + 'Type';
  43326. }
  43327. /**
  43328. * @inner
  43329. */
  43330. function createSymbol$1(name, lineData, idx) {
  43331. var color = lineData.getItemVisual(idx, 'color');
  43332. var symbolType = lineData.getItemVisual(idx, name);
  43333. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  43334. if (!symbolType || symbolType === 'none') {
  43335. return;
  43336. }
  43337. if (!isArray(symbolSize)) {
  43338. symbolSize = [symbolSize, symbolSize];
  43339. }
  43340. var symbolPath = createSymbol(
  43341. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  43342. symbolSize[0], symbolSize[1], color
  43343. );
  43344. symbolPath.name = name;
  43345. return symbolPath;
  43346. }
  43347. function createLine(points) {
  43348. var line = new LinePath({
  43349. name: 'line'
  43350. });
  43351. setLinePoints(line.shape, points);
  43352. return line;
  43353. }
  43354. function setLinePoints(targetShape, points) {
  43355. var p1 = points[0];
  43356. var p2 = points[1];
  43357. var cp1 = points[2];
  43358. targetShape.x1 = p1[0];
  43359. targetShape.y1 = p1[1];
  43360. targetShape.x2 = p2[0];
  43361. targetShape.y2 = p2[1];
  43362. targetShape.percent = 1;
  43363. if (cp1) {
  43364. targetShape.cpx1 = cp1[0];
  43365. targetShape.cpy1 = cp1[1];
  43366. }
  43367. else {
  43368. targetShape.cpx1 = NaN;
  43369. targetShape.cpy1 = NaN;
  43370. }
  43371. }
  43372. function updateSymbolAndLabelBeforeLineUpdate() {
  43373. var lineGroup = this;
  43374. var symbolFrom = lineGroup.childOfName('fromSymbol');
  43375. var symbolTo = lineGroup.childOfName('toSymbol');
  43376. var label = lineGroup.childOfName('label');
  43377. // Quick reject
  43378. if (!symbolFrom && !symbolTo && label.ignore) {
  43379. return;
  43380. }
  43381. var invScale = 1;
  43382. var parentNode = this.parent;
  43383. while (parentNode) {
  43384. if (parentNode.scale) {
  43385. invScale /= parentNode.scale[0];
  43386. }
  43387. parentNode = parentNode.parent;
  43388. }
  43389. var line = lineGroup.childOfName('line');
  43390. // If line not changed
  43391. // FIXME Parent scale changed
  43392. if (!this.__dirty && !line.__dirty) {
  43393. return;
  43394. }
  43395. var percent = line.shape.percent;
  43396. var fromPos = line.pointAt(0);
  43397. var toPos = line.pointAt(percent);
  43398. var d = sub([], toPos, fromPos);
  43399. normalize(d, d);
  43400. if (symbolFrom) {
  43401. symbolFrom.attr('position', fromPos);
  43402. var tangent = line.tangentAt(0);
  43403. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  43404. tangent[1], tangent[0]
  43405. ));
  43406. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  43407. }
  43408. if (symbolTo) {
  43409. symbolTo.attr('position', toPos);
  43410. var tangent = line.tangentAt(1);
  43411. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  43412. tangent[1], tangent[0]
  43413. ));
  43414. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  43415. }
  43416. if (!label.ignore) {
  43417. label.attr('position', toPos);
  43418. var textPosition;
  43419. var textAlign;
  43420. var textVerticalAlign;
  43421. var distance$$1 = 5 * invScale;
  43422. // End
  43423. if (label.__position === 'end') {
  43424. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  43425. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  43426. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  43427. }
  43428. // Middle
  43429. else if (label.__position === 'middle') {
  43430. var halfPercent = percent / 2;
  43431. var tangent = line.tangentAt(halfPercent);
  43432. var n = [tangent[1], -tangent[0]];
  43433. var cp = line.pointAt(halfPercent);
  43434. if (n[1] > 0) {
  43435. n[0] = -n[0];
  43436. n[1] = -n[1];
  43437. }
  43438. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  43439. textAlign = 'center';
  43440. textVerticalAlign = 'bottom';
  43441. var rotation = -Math.atan2(tangent[1], tangent[0]);
  43442. if (toPos[0] < fromPos[0]) {
  43443. rotation = Math.PI + rotation;
  43444. }
  43445. label.attr('rotation', rotation);
  43446. }
  43447. // Start
  43448. else {
  43449. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  43450. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  43451. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  43452. }
  43453. label.attr({
  43454. style: {
  43455. // Use the user specified text align and baseline first
  43456. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  43457. textAlign: label.__textAlign || textAlign
  43458. },
  43459. position: textPosition,
  43460. scale: [invScale, invScale]
  43461. });
  43462. }
  43463. }
  43464. /**
  43465. * @constructor
  43466. * @extends {module:zrender/graphic/Group}
  43467. * @alias {module:echarts/chart/helper/Line}
  43468. */
  43469. function Line$1(lineData, idx, seriesScope) {
  43470. Group.call(this);
  43471. this._createLine(lineData, idx, seriesScope);
  43472. }
  43473. var lineProto = Line$1.prototype;
  43474. // Update symbol position and rotation
  43475. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  43476. lineProto._createLine = function (lineData, idx, seriesScope) {
  43477. var seriesModel = lineData.hostModel;
  43478. var linePoints = lineData.getItemLayout(idx);
  43479. var line = createLine(linePoints);
  43480. line.shape.percent = 0;
  43481. initProps(line, {
  43482. shape: {
  43483. percent: 1
  43484. }
  43485. }, seriesModel, idx);
  43486. this.add(line);
  43487. var label = new Text({
  43488. name: 'label',
  43489. // FIXME
  43490. // Temporary solution for `focusNodeAdjacency`.
  43491. // line label do not use the opacity of lineStyle.
  43492. lineLabelOriginalOpacity: 1
  43493. });
  43494. this.add(label);
  43495. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  43496. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  43497. // symbols must added after line to make sure
  43498. // it will be updated after line#update.
  43499. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  43500. this.add(symbol);
  43501. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  43502. }, this);
  43503. this._updateCommonStl(lineData, idx, seriesScope);
  43504. };
  43505. lineProto.updateData = function (lineData, idx, seriesScope) {
  43506. var seriesModel = lineData.hostModel;
  43507. var line = this.childOfName('line');
  43508. var linePoints = lineData.getItemLayout(idx);
  43509. var target = {
  43510. shape: {}
  43511. };
  43512. setLinePoints(target.shape, linePoints);
  43513. updateProps(line, target, seriesModel, idx);
  43514. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  43515. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  43516. var key = makeSymbolTypeKey(symbolCategory);
  43517. // Symbol changed
  43518. if (this[key] !== symbolType) {
  43519. this.remove(this.childOfName(symbolCategory));
  43520. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  43521. this.add(symbol);
  43522. }
  43523. this[key] = symbolType;
  43524. }, this);
  43525. this._updateCommonStl(lineData, idx, seriesScope);
  43526. };
  43527. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  43528. var seriesModel = lineData.hostModel;
  43529. var line = this.childOfName('line');
  43530. var lineStyle = seriesScope && seriesScope.lineStyle;
  43531. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  43532. var labelModel = seriesScope && seriesScope.labelModel;
  43533. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  43534. // Optimization for large dataset
  43535. if (!seriesScope || lineData.hasItemOption) {
  43536. var itemModel = lineData.getItemModel(idx);
  43537. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  43538. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  43539. labelModel = itemModel.getModel('label');
  43540. hoverLabelModel = itemModel.getModel('emphasis.label');
  43541. }
  43542. var visualColor = lineData.getItemVisual(idx, 'color');
  43543. var visualOpacity = retrieve3(
  43544. lineData.getItemVisual(idx, 'opacity'),
  43545. lineStyle.opacity,
  43546. 1
  43547. );
  43548. line.useStyle(defaults(
  43549. {
  43550. strokeNoScale: true,
  43551. fill: 'none',
  43552. stroke: visualColor,
  43553. opacity: visualOpacity
  43554. },
  43555. lineStyle
  43556. ));
  43557. line.hoverStyle = hoverLineStyle;
  43558. // Update symbol
  43559. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  43560. var symbol = this.childOfName(symbolCategory);
  43561. if (symbol) {
  43562. symbol.setColor(visualColor);
  43563. symbol.setStyle({
  43564. opacity: visualOpacity
  43565. });
  43566. }
  43567. }, this);
  43568. var showLabel = labelModel.getShallow('show');
  43569. var hoverShowLabel = hoverLabelModel.getShallow('show');
  43570. var label = this.childOfName('label');
  43571. var defaultLabelColor;
  43572. var baseText;
  43573. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  43574. if (showLabel || hoverShowLabel) {
  43575. defaultLabelColor = visualColor || '#000';
  43576. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  43577. if (baseText == null) {
  43578. var rawVal = seriesModel.getRawValue(idx);
  43579. baseText = rawVal == null
  43580. ? lineData.getName(idx)
  43581. : isFinite(rawVal)
  43582. ? round$2(rawVal)
  43583. : rawVal;
  43584. }
  43585. }
  43586. var normalText = showLabel ? baseText : null;
  43587. var emphasisText = hoverShowLabel
  43588. ? retrieve2(
  43589. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  43590. baseText
  43591. )
  43592. : null;
  43593. var labelStyle = label.style;
  43594. // Always set `textStyle` even if `normalStyle.text` is null, because default
  43595. // values have to be set on `normalStyle`.
  43596. if (normalText != null || emphasisText != null) {
  43597. setTextStyle(label.style, labelModel, {
  43598. text: normalText
  43599. }, {
  43600. autoColor: defaultLabelColor
  43601. });
  43602. label.__textAlign = labelStyle.textAlign;
  43603. label.__verticalAlign = labelStyle.textVerticalAlign;
  43604. // 'start', 'middle', 'end'
  43605. label.__position = labelModel.get('position') || 'middle';
  43606. }
  43607. if (emphasisText != null) {
  43608. // Only these properties supported in this emphasis style here.
  43609. label.hoverStyle = {
  43610. text: emphasisText,
  43611. textFill: hoverLabelModel.getTextColor(true),
  43612. // For merging hover style to normal style, do not use
  43613. // `hoverLabelModel.getFont()` here.
  43614. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  43615. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  43616. fontSize: hoverLabelModel.getShallow('fontSize'),
  43617. fontFamily: hoverLabelModel.getShallow('fontFamily')
  43618. };
  43619. }
  43620. else {
  43621. label.hoverStyle = {
  43622. text: null
  43623. };
  43624. }
  43625. label.ignore = !showLabel && !hoverShowLabel;
  43626. setHoverStyle(this);
  43627. };
  43628. lineProto.highlight = function () {
  43629. this.trigger('emphasis');
  43630. };
  43631. lineProto.downplay = function () {
  43632. this.trigger('normal');
  43633. };
  43634. lineProto.updateLayout = function (lineData, idx) {
  43635. this.setLinePoints(lineData.getItemLayout(idx));
  43636. };
  43637. lineProto.setLinePoints = function (points) {
  43638. var linePath = this.childOfName('line');
  43639. setLinePoints(linePath.shape, points);
  43640. linePath.dirty();
  43641. };
  43642. inherits(Line$1, Group);
  43643. /*
  43644. * Licensed to the Apache Software Foundation (ASF) under one
  43645. * or more contributor license agreements. See the NOTICE file
  43646. * distributed with this work for additional information
  43647. * regarding copyright ownership. The ASF licenses this file
  43648. * to you under the Apache License, Version 2.0 (the
  43649. * "License"); you may not use this file except in compliance
  43650. * with the License. You may obtain a copy of the License at
  43651. *
  43652. * http://www.apache.org/licenses/LICENSE-2.0
  43653. *
  43654. * Unless required by applicable law or agreed to in writing,
  43655. * software distributed under the License is distributed on an
  43656. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43657. * KIND, either express or implied. See the License for the
  43658. * specific language governing permissions and limitations
  43659. * under the License.
  43660. */
  43661. /**
  43662. * @module echarts/chart/helper/LineDraw
  43663. */
  43664. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  43665. /**
  43666. * @alias module:echarts/component/marker/LineDraw
  43667. * @constructor
  43668. */
  43669. function LineDraw(ctor) {
  43670. this._ctor = ctor || Line$1;
  43671. this.group = new Group();
  43672. }
  43673. var lineDrawProto = LineDraw.prototype;
  43674. lineDrawProto.isPersistent = function () {
  43675. return true;
  43676. };
  43677. /**
  43678. * @param {module:echarts/data/List} lineData
  43679. */
  43680. lineDrawProto.updateData = function (lineData) {
  43681. var lineDraw = this;
  43682. var group = lineDraw.group;
  43683. var oldLineData = lineDraw._lineData;
  43684. lineDraw._lineData = lineData;
  43685. // There is no oldLineData only when first rendering or switching from
  43686. // stream mode to normal mode, where previous elements should be removed.
  43687. if (!oldLineData) {
  43688. group.removeAll();
  43689. }
  43690. var seriesScope = makeSeriesScope$1(lineData);
  43691. lineData.diff(oldLineData)
  43692. .add(function (idx) {
  43693. doAdd(lineDraw, lineData, idx, seriesScope);
  43694. })
  43695. .update(function (newIdx, oldIdx) {
  43696. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  43697. })
  43698. .remove(function (idx) {
  43699. group.remove(oldLineData.getItemGraphicEl(idx));
  43700. })
  43701. .execute();
  43702. };
  43703. function doAdd(lineDraw, lineData, idx, seriesScope) {
  43704. var itemLayout = lineData.getItemLayout(idx);
  43705. if (!lineNeedsDraw(itemLayout)) {
  43706. return;
  43707. }
  43708. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  43709. lineData.setItemGraphicEl(idx, el);
  43710. lineDraw.group.add(el);
  43711. }
  43712. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  43713. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  43714. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  43715. lineDraw.group.remove(itemEl);
  43716. return;
  43717. }
  43718. if (!itemEl) {
  43719. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  43720. }
  43721. else {
  43722. itemEl.updateData(newLineData, newIdx, seriesScope);
  43723. }
  43724. newLineData.setItemGraphicEl(newIdx, itemEl);
  43725. lineDraw.group.add(itemEl);
  43726. }
  43727. lineDrawProto.updateLayout = function () {
  43728. var lineData = this._lineData;
  43729. // Do not support update layout in incremental mode.
  43730. if (!lineData) {
  43731. return;
  43732. }
  43733. lineData.eachItemGraphicEl(function (el, idx) {
  43734. el.updateLayout(lineData, idx);
  43735. }, this);
  43736. };
  43737. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  43738. this._seriesScope = makeSeriesScope$1(lineData);
  43739. this._lineData = null;
  43740. this.group.removeAll();
  43741. };
  43742. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  43743. function updateIncrementalAndHover(el) {
  43744. if (!el.isGroup) {
  43745. el.incremental = el.useHoverLayer = true;
  43746. }
  43747. }
  43748. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  43749. var itemLayout = lineData.getItemLayout(idx);
  43750. if (lineNeedsDraw(itemLayout)) {
  43751. var el = new this._ctor(lineData, idx, this._seriesScope);
  43752. el.traverse(updateIncrementalAndHover);
  43753. this.group.add(el);
  43754. lineData.setItemGraphicEl(idx, el);
  43755. }
  43756. }
  43757. };
  43758. function makeSeriesScope$1(lineData) {
  43759. var hostModel = lineData.hostModel;
  43760. return {
  43761. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  43762. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  43763. labelModel: hostModel.getModel('label'),
  43764. hoverLabelModel: hostModel.getModel('emphasis.label')
  43765. };
  43766. }
  43767. lineDrawProto.remove = function () {
  43768. this._clearIncremental();
  43769. this._incremental = null;
  43770. this.group.removeAll();
  43771. };
  43772. lineDrawProto._clearIncremental = function () {
  43773. var incremental = this._incremental;
  43774. if (incremental) {
  43775. incremental.clearDisplaybles();
  43776. }
  43777. };
  43778. function isPointNaN(pt) {
  43779. return isNaN(pt[0]) || isNaN(pt[1]);
  43780. }
  43781. function lineNeedsDraw(pts) {
  43782. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  43783. }
  43784. /*
  43785. * Licensed to the Apache Software Foundation (ASF) under one
  43786. * or more contributor license agreements. See the NOTICE file
  43787. * distributed with this work for additional information
  43788. * regarding copyright ownership. The ASF licenses this file
  43789. * to you under the Apache License, Version 2.0 (the
  43790. * "License"); you may not use this file except in compliance
  43791. * with the License. You may obtain a copy of the License at
  43792. *
  43793. * http://www.apache.org/licenses/LICENSE-2.0
  43794. *
  43795. * Unless required by applicable law or agreed to in writing,
  43796. * software distributed under the License is distributed on an
  43797. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43798. * KIND, either express or implied. See the License for the
  43799. * specific language governing permissions and limitations
  43800. * under the License.
  43801. */
  43802. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  43803. var data = seriesModel.getData();
  43804. // Special type markLine like 'min', 'max', 'average', 'median'
  43805. var mlType = item.type;
  43806. if (!isArray(item)
  43807. && (
  43808. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  43809. // In case
  43810. // data: [{
  43811. // yAxis: 10
  43812. // }]
  43813. || (item.xAxis != null || item.yAxis != null)
  43814. )
  43815. ) {
  43816. var valueAxis;
  43817. var valueDataDim;
  43818. var value;
  43819. if (item.yAxis != null || item.xAxis != null) {
  43820. valueDataDim = item.yAxis != null ? 'y' : 'x';
  43821. valueAxis = coordSys.getAxis(valueDataDim);
  43822. value = retrieve(item.yAxis, item.xAxis);
  43823. }
  43824. else {
  43825. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  43826. valueDataDim = axisInfo.valueDataDim;
  43827. valueAxis = axisInfo.valueAxis;
  43828. value = numCalculate(data, valueDataDim, mlType);
  43829. }
  43830. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  43831. var baseIndex = 1 - valueIndex;
  43832. var mlFrom = clone(item);
  43833. var mlTo = {};
  43834. mlFrom.type = null;
  43835. mlFrom.coord = [];
  43836. mlTo.coord = [];
  43837. mlFrom.coord[baseIndex] = -Infinity;
  43838. mlTo.coord[baseIndex] = Infinity;
  43839. var precision = mlModel.get('precision');
  43840. if (precision >= 0 && typeof value === 'number') {
  43841. value = +value.toFixed(Math.min(precision, 20));
  43842. }
  43843. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  43844. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  43845. type: mlType,
  43846. valueIndex: item.valueIndex,
  43847. // Force to use the value of calculated value.
  43848. value: value
  43849. }];
  43850. }
  43851. item = [
  43852. dataTransform(seriesModel, item[0]),
  43853. dataTransform(seriesModel, item[1]),
  43854. extend({}, item[2])
  43855. ];
  43856. // Avoid line data type is extended by from(to) data type
  43857. item[2].type = item[2].type || '';
  43858. // Merge from option and to option into line option
  43859. merge(item[2], item[0]);
  43860. merge(item[2], item[1]);
  43861. return item;
  43862. };
  43863. function isInifinity(val) {
  43864. return !isNaN(val) && !isFinite(val);
  43865. }
  43866. // If a markLine has one dim
  43867. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  43868. var otherDimIndex = 1 - dimIndex;
  43869. var dimName = coordSys.dimensions[dimIndex];
  43870. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  43871. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  43872. }
  43873. function markLineFilter(coordSys, item) {
  43874. if (coordSys.type === 'cartesian2d') {
  43875. var fromCoord = item[0].coord;
  43876. var toCoord = item[1].coord;
  43877. // In case
  43878. // {
  43879. // markLine: {
  43880. // data: [{ yAxis: 2 }]
  43881. // }
  43882. // }
  43883. if (
  43884. fromCoord && toCoord
  43885. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  43886. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  43887. ) {
  43888. return true;
  43889. }
  43890. }
  43891. return dataFilter$1(coordSys, item[0])
  43892. && dataFilter$1(coordSys, item[1]);
  43893. }
  43894. function updateSingleMarkerEndLayout(
  43895. data, idx, isFrom, seriesModel, api
  43896. ) {
  43897. var coordSys = seriesModel.coordinateSystem;
  43898. var itemModel = data.getItemModel(idx);
  43899. var point;
  43900. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  43901. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  43902. if (!isNaN(xPx) && !isNaN(yPx)) {
  43903. point = [xPx, yPx];
  43904. }
  43905. else {
  43906. // Chart like bar may have there own marker positioning logic
  43907. if (seriesModel.getMarkerPosition) {
  43908. // Use the getMarkerPoisition
  43909. point = seriesModel.getMarkerPosition(
  43910. data.getValues(data.dimensions, idx)
  43911. );
  43912. }
  43913. else {
  43914. var dims = coordSys.dimensions;
  43915. var x = data.get(dims[0], idx);
  43916. var y = data.get(dims[1], idx);
  43917. point = coordSys.dataToPoint([x, y]);
  43918. }
  43919. // Expand line to the edge of grid if value on one axis is Inifnity
  43920. // In case
  43921. // markLine: {
  43922. // data: [{
  43923. // yAxis: 2
  43924. // // or
  43925. // type: 'average'
  43926. // }]
  43927. // }
  43928. if (coordSys.type === 'cartesian2d') {
  43929. var xAxis = coordSys.getAxis('x');
  43930. var yAxis = coordSys.getAxis('y');
  43931. var dims = coordSys.dimensions;
  43932. if (isInifinity(data.get(dims[0], idx))) {
  43933. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  43934. }
  43935. else if (isInifinity(data.get(dims[1], idx))) {
  43936. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  43937. }
  43938. }
  43939. // Use x, y if has any
  43940. if (!isNaN(xPx)) {
  43941. point[0] = xPx;
  43942. }
  43943. if (!isNaN(yPx)) {
  43944. point[1] = yPx;
  43945. }
  43946. }
  43947. data.setItemLayout(idx, point);
  43948. }
  43949. MarkerView.extend({
  43950. type: 'markLine',
  43951. // updateLayout: function (markLineModel, ecModel, api) {
  43952. // ecModel.eachSeries(function (seriesModel) {
  43953. // var mlModel = seriesModel.markLineModel;
  43954. // if (mlModel) {
  43955. // var mlData = mlModel.getData();
  43956. // var fromData = mlModel.__from;
  43957. // var toData = mlModel.__to;
  43958. // // Update visual and layout of from symbol and to symbol
  43959. // fromData.each(function (idx) {
  43960. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  43961. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  43962. // });
  43963. // // Update layout of line
  43964. // mlData.each(function (idx) {
  43965. // mlData.setItemLayout(idx, [
  43966. // fromData.getItemLayout(idx),
  43967. // toData.getItemLayout(idx)
  43968. // ]);
  43969. // });
  43970. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  43971. // }
  43972. // }, this);
  43973. // },
  43974. updateTransform: function (markLineModel, ecModel, api) {
  43975. ecModel.eachSeries(function (seriesModel) {
  43976. var mlModel = seriesModel.markLineModel;
  43977. if (mlModel) {
  43978. var mlData = mlModel.getData();
  43979. var fromData = mlModel.__from;
  43980. var toData = mlModel.__to;
  43981. // Update visual and layout of from symbol and to symbol
  43982. fromData.each(function (idx) {
  43983. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  43984. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  43985. });
  43986. // Update layout of line
  43987. mlData.each(function (idx) {
  43988. mlData.setItemLayout(idx, [
  43989. fromData.getItemLayout(idx),
  43990. toData.getItemLayout(idx)
  43991. ]);
  43992. });
  43993. this.markerGroupMap.get(seriesModel.id).updateLayout();
  43994. }
  43995. }, this);
  43996. },
  43997. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  43998. var coordSys = seriesModel.coordinateSystem;
  43999. var seriesId = seriesModel.id;
  44000. var seriesData = seriesModel.getData();
  44001. var lineDrawMap = this.markerGroupMap;
  44002. var lineDraw = lineDrawMap.get(seriesId)
  44003. || lineDrawMap.set(seriesId, new LineDraw());
  44004. this.group.add(lineDraw.group);
  44005. var mlData = createList$2(coordSys, seriesModel, mlModel);
  44006. var fromData = mlData.from;
  44007. var toData = mlData.to;
  44008. var lineData = mlData.line;
  44009. mlModel.__from = fromData;
  44010. mlModel.__to = toData;
  44011. // Line data for tooltip and formatter
  44012. mlModel.setData(lineData);
  44013. var symbolType = mlModel.get('symbol');
  44014. var symbolSize = mlModel.get('symbolSize');
  44015. if (!isArray(symbolType)) {
  44016. symbolType = [symbolType, symbolType];
  44017. }
  44018. if (typeof symbolSize === 'number') {
  44019. symbolSize = [symbolSize, symbolSize];
  44020. }
  44021. // Update visual and layout of from symbol and to symbol
  44022. mlData.from.each(function (idx) {
  44023. updateDataVisualAndLayout(fromData, idx, true);
  44024. updateDataVisualAndLayout(toData, idx, false);
  44025. });
  44026. // Update visual and layout of line
  44027. lineData.each(function (idx) {
  44028. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  44029. lineData.setItemVisual(idx, {
  44030. color: lineColor || fromData.getItemVisual(idx, 'color')
  44031. });
  44032. lineData.setItemLayout(idx, [
  44033. fromData.getItemLayout(idx),
  44034. toData.getItemLayout(idx)
  44035. ]);
  44036. lineData.setItemVisual(idx, {
  44037. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  44038. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  44039. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  44040. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  44041. });
  44042. });
  44043. lineDraw.updateData(lineData);
  44044. // Set host model for tooltip
  44045. // FIXME
  44046. mlData.line.eachItemGraphicEl(function (el, idx) {
  44047. el.traverse(function (child) {
  44048. child.dataModel = mlModel;
  44049. });
  44050. });
  44051. function updateDataVisualAndLayout(data, idx, isFrom) {
  44052. var itemModel = data.getItemModel(idx);
  44053. updateSingleMarkerEndLayout(
  44054. data, idx, isFrom, seriesModel, api
  44055. );
  44056. data.setItemVisual(idx, {
  44057. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  44058. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  44059. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  44060. });
  44061. }
  44062. lineDraw.__keep = true;
  44063. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  44064. }
  44065. });
  44066. /**
  44067. * @inner
  44068. * @param {module:echarts/coord/*} coordSys
  44069. * @param {module:echarts/model/Series} seriesModel
  44070. * @param {module:echarts/model/Model} mpModel
  44071. */
  44072. function createList$2(coordSys, seriesModel, mlModel) {
  44073. var coordDimsInfos;
  44074. if (coordSys) {
  44075. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  44076. var info = seriesModel.getData().getDimensionInfo(
  44077. seriesModel.getData().mapDimension(coordDim)
  44078. ) || {};
  44079. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  44080. return defaults({name: coordDim}, info);
  44081. });
  44082. }
  44083. else {
  44084. coordDimsInfos = [{
  44085. name: 'value',
  44086. type: 'float'
  44087. }];
  44088. }
  44089. var fromData = new List(coordDimsInfos, mlModel);
  44090. var toData = new List(coordDimsInfos, mlModel);
  44091. // No dimensions
  44092. var lineData = new List([], mlModel);
  44093. var optData = map(mlModel.get('data'), curry(
  44094. markLineTransform, seriesModel, coordSys, mlModel
  44095. ));
  44096. if (coordSys) {
  44097. optData = filter(
  44098. optData, curry(markLineFilter, coordSys)
  44099. );
  44100. }
  44101. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  44102. return item.value;
  44103. };
  44104. fromData.initData(
  44105. map(optData, function (item) {
  44106. return item[0];
  44107. }),
  44108. null,
  44109. dimValueGetter$$1
  44110. );
  44111. toData.initData(
  44112. map(optData, function (item) {
  44113. return item[1];
  44114. }),
  44115. null,
  44116. dimValueGetter$$1
  44117. );
  44118. lineData.initData(
  44119. map(optData, function (item) {
  44120. return item[2];
  44121. })
  44122. );
  44123. lineData.hasItemOption = true;
  44124. return {
  44125. from: fromData,
  44126. to: toData,
  44127. line: lineData
  44128. };
  44129. }
  44130. /*
  44131. * Licensed to the Apache Software Foundation (ASF) under one
  44132. * or more contributor license agreements. See the NOTICE file
  44133. * distributed with this work for additional information
  44134. * regarding copyright ownership. The ASF licenses this file
  44135. * to you under the Apache License, Version 2.0 (the
  44136. * "License"); you may not use this file except in compliance
  44137. * with the License. You may obtain a copy of the License at
  44138. *
  44139. * http://www.apache.org/licenses/LICENSE-2.0
  44140. *
  44141. * Unless required by applicable law or agreed to in writing,
  44142. * software distributed under the License is distributed on an
  44143. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44144. * KIND, either express or implied. See the License for the
  44145. * specific language governing permissions and limitations
  44146. * under the License.
  44147. */
  44148. registerPreprocessor(function (opt) {
  44149. // Make sure markLine component is enabled
  44150. opt.markLine = opt.markLine || {};
  44151. });
  44152. /*
  44153. * Licensed to the Apache Software Foundation (ASF) under one
  44154. * or more contributor license agreements. See the NOTICE file
  44155. * distributed with this work for additional information
  44156. * regarding copyright ownership. The ASF licenses this file
  44157. * to you under the Apache License, Version 2.0 (the
  44158. * "License"); you may not use this file except in compliance
  44159. * with the License. You may obtain a copy of the License at
  44160. *
  44161. * http://www.apache.org/licenses/LICENSE-2.0
  44162. *
  44163. * Unless required by applicable law or agreed to in writing,
  44164. * software distributed under the License is distributed on an
  44165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44166. * KIND, either express or implied. See the License for the
  44167. * specific language governing permissions and limitations
  44168. * under the License.
  44169. */
  44170. MarkerModel.extend({
  44171. type: 'markArea',
  44172. defaultOption: {
  44173. zlevel: 0,
  44174. // PENDING
  44175. z: 1,
  44176. tooltip: {
  44177. trigger: 'item'
  44178. },
  44179. // markArea should fixed on the coordinate system
  44180. animation: false,
  44181. label: {
  44182. show: true,
  44183. position: 'top'
  44184. },
  44185. itemStyle: {
  44186. // color and borderColor default to use color from series
  44187. // color: 'auto'
  44188. // borderColor: 'auto'
  44189. borderWidth: 0
  44190. },
  44191. emphasis: {
  44192. label: {
  44193. show: true,
  44194. position: 'top'
  44195. }
  44196. }
  44197. }
  44198. });
  44199. /*
  44200. * Licensed to the Apache Software Foundation (ASF) under one
  44201. * or more contributor license agreements. See the NOTICE file
  44202. * distributed with this work for additional information
  44203. * regarding copyright ownership. The ASF licenses this file
  44204. * to you under the Apache License, Version 2.0 (the
  44205. * "License"); you may not use this file except in compliance
  44206. * with the License. You may obtain a copy of the License at
  44207. *
  44208. * http://www.apache.org/licenses/LICENSE-2.0
  44209. *
  44210. * Unless required by applicable law or agreed to in writing,
  44211. * software distributed under the License is distributed on an
  44212. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44213. * KIND, either express or implied. See the License for the
  44214. * specific language governing permissions and limitations
  44215. * under the License.
  44216. */
  44217. // TODO Better on polar
  44218. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  44219. var lt = dataTransform(seriesModel, item[0]);
  44220. var rb = dataTransform(seriesModel, item[1]);
  44221. var retrieve$$1 = retrieve;
  44222. // FIXME make sure lt is less than rb
  44223. var ltCoord = lt.coord;
  44224. var rbCoord = rb.coord;
  44225. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  44226. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  44227. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  44228. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  44229. // Merge option into one
  44230. var result = mergeAll([{}, lt, rb]);
  44231. result.coord = [
  44232. lt.coord, rb.coord
  44233. ];
  44234. result.x0 = lt.x;
  44235. result.y0 = lt.y;
  44236. result.x1 = rb.x;
  44237. result.y1 = rb.y;
  44238. return result;
  44239. };
  44240. function isInifinity$1(val) {
  44241. return !isNaN(val) && !isFinite(val);
  44242. }
  44243. // If a markArea has one dim
  44244. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  44245. var otherDimIndex = 1 - dimIndex;
  44246. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  44247. }
  44248. function markAreaFilter(coordSys, item) {
  44249. var fromCoord = item.coord[0];
  44250. var toCoord = item.coord[1];
  44251. if (coordSys.type === 'cartesian2d') {
  44252. // In case
  44253. // {
  44254. // markArea: {
  44255. // data: [{ yAxis: 2 }]
  44256. // }
  44257. // }
  44258. if (
  44259. fromCoord && toCoord
  44260. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  44261. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  44262. ) {
  44263. return true;
  44264. }
  44265. }
  44266. return dataFilter$1(coordSys, {
  44267. coord: fromCoord,
  44268. x: item.x0,
  44269. y: item.y0
  44270. })
  44271. || dataFilter$1(coordSys, {
  44272. coord: toCoord,
  44273. x: item.x1,
  44274. y: item.y1
  44275. });
  44276. }
  44277. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  44278. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  44279. var coordSys = seriesModel.coordinateSystem;
  44280. var itemModel = data.getItemModel(idx);
  44281. var point;
  44282. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  44283. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  44284. if (!isNaN(xPx) && !isNaN(yPx)) {
  44285. point = [xPx, yPx];
  44286. }
  44287. else {
  44288. // Chart like bar may have there own marker positioning logic
  44289. if (seriesModel.getMarkerPosition) {
  44290. // Use the getMarkerPoisition
  44291. point = seriesModel.getMarkerPosition(
  44292. data.getValues(dims, idx)
  44293. );
  44294. }
  44295. else {
  44296. var x = data.get(dims[0], idx);
  44297. var y = data.get(dims[1], idx);
  44298. var pt = [x, y];
  44299. coordSys.clampData && coordSys.clampData(pt, pt);
  44300. point = coordSys.dataToPoint(pt, true);
  44301. }
  44302. if (coordSys.type === 'cartesian2d') {
  44303. var xAxis = coordSys.getAxis('x');
  44304. var yAxis = coordSys.getAxis('y');
  44305. var x = data.get(dims[0], idx);
  44306. var y = data.get(dims[1], idx);
  44307. if (isInifinity$1(x)) {
  44308. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  44309. }
  44310. else if (isInifinity$1(y)) {
  44311. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  44312. }
  44313. }
  44314. // Use x, y if has any
  44315. if (!isNaN(xPx)) {
  44316. point[0] = xPx;
  44317. }
  44318. if (!isNaN(yPx)) {
  44319. point[1] = yPx;
  44320. }
  44321. }
  44322. return point;
  44323. }
  44324. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  44325. MarkerView.extend({
  44326. type: 'markArea',
  44327. // updateLayout: function (markAreaModel, ecModel, api) {
  44328. // ecModel.eachSeries(function (seriesModel) {
  44329. // var maModel = seriesModel.markAreaModel;
  44330. // if (maModel) {
  44331. // var areaData = maModel.getData();
  44332. // areaData.each(function (idx) {
  44333. // var points = zrUtil.map(dimPermutations, function (dim) {
  44334. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  44335. // });
  44336. // // Layout
  44337. // areaData.setItemLayout(idx, points);
  44338. // var el = areaData.getItemGraphicEl(idx);
  44339. // el.setShape('points', points);
  44340. // });
  44341. // }
  44342. // }, this);
  44343. // },
  44344. updateTransform: function (markAreaModel, ecModel, api) {
  44345. ecModel.eachSeries(function (seriesModel) {
  44346. var maModel = seriesModel.markAreaModel;
  44347. if (maModel) {
  44348. var areaData = maModel.getData();
  44349. areaData.each(function (idx) {
  44350. var points = map(dimPermutations, function (dim) {
  44351. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  44352. });
  44353. // Layout
  44354. areaData.setItemLayout(idx, points);
  44355. var el = areaData.getItemGraphicEl(idx);
  44356. el.setShape('points', points);
  44357. });
  44358. }
  44359. }, this);
  44360. },
  44361. renderSeries: function (seriesModel, maModel, ecModel, api) {
  44362. var coordSys = seriesModel.coordinateSystem;
  44363. var seriesId = seriesModel.id;
  44364. var seriesData = seriesModel.getData();
  44365. var areaGroupMap = this.markerGroupMap;
  44366. var polygonGroup = areaGroupMap.get(seriesId)
  44367. || areaGroupMap.set(seriesId, {group: new Group()});
  44368. this.group.add(polygonGroup.group);
  44369. polygonGroup.__keep = true;
  44370. var areaData = createList$3(coordSys, seriesModel, maModel);
  44371. // Line data for tooltip and formatter
  44372. maModel.setData(areaData);
  44373. // Update visual and layout of line
  44374. areaData.each(function (idx) {
  44375. // Layout
  44376. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  44377. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  44378. }));
  44379. // Visual
  44380. areaData.setItemVisual(idx, {
  44381. color: seriesData.getVisual('color')
  44382. });
  44383. });
  44384. areaData.diff(polygonGroup.__data)
  44385. .add(function (idx) {
  44386. var polygon = new Polygon({
  44387. shape: {
  44388. points: areaData.getItemLayout(idx)
  44389. }
  44390. });
  44391. areaData.setItemGraphicEl(idx, polygon);
  44392. polygonGroup.group.add(polygon);
  44393. })
  44394. .update(function (newIdx, oldIdx) {
  44395. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  44396. updateProps(polygon, {
  44397. shape: {
  44398. points: areaData.getItemLayout(newIdx)
  44399. }
  44400. }, maModel, newIdx);
  44401. polygonGroup.group.add(polygon);
  44402. areaData.setItemGraphicEl(newIdx, polygon);
  44403. })
  44404. .remove(function (idx) {
  44405. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  44406. polygonGroup.group.remove(polygon);
  44407. })
  44408. .execute();
  44409. areaData.eachItemGraphicEl(function (polygon, idx) {
  44410. var itemModel = areaData.getItemModel(idx);
  44411. var labelModel = itemModel.getModel('label');
  44412. var labelHoverModel = itemModel.getModel('emphasis.label');
  44413. var color = areaData.getItemVisual(idx, 'color');
  44414. polygon.useStyle(
  44415. defaults(
  44416. itemModel.getModel('itemStyle').getItemStyle(),
  44417. {
  44418. fill: modifyAlpha(color, 0.4),
  44419. stroke: color
  44420. }
  44421. )
  44422. );
  44423. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  44424. setLabelStyle(
  44425. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  44426. {
  44427. labelFetcher: maModel,
  44428. labelDataIndex: idx,
  44429. defaultText: areaData.getName(idx) || '',
  44430. isRectText: true,
  44431. autoColor: color
  44432. }
  44433. );
  44434. setHoverStyle(polygon, {});
  44435. polygon.dataModel = maModel;
  44436. });
  44437. polygonGroup.__data = areaData;
  44438. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  44439. }
  44440. });
  44441. /**
  44442. * @inner
  44443. * @param {module:echarts/coord/*} coordSys
  44444. * @param {module:echarts/model/Series} seriesModel
  44445. * @param {module:echarts/model/Model} mpModel
  44446. */
  44447. function createList$3(coordSys, seriesModel, maModel) {
  44448. var coordDimsInfos;
  44449. var areaData;
  44450. var dims = ['x0', 'y0', 'x1', 'y1'];
  44451. if (coordSys) {
  44452. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  44453. var data = seriesModel.getData();
  44454. var info = data.getDimensionInfo(
  44455. data.mapDimension(coordDim)
  44456. ) || {};
  44457. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  44458. return defaults({name: coordDim}, info);
  44459. });
  44460. areaData = new List(map(dims, function (dim, idx) {
  44461. return {
  44462. name: dim,
  44463. type: coordDimsInfos[idx % 2].type
  44464. };
  44465. }), maModel);
  44466. }
  44467. else {
  44468. coordDimsInfos = [{
  44469. name: 'value',
  44470. type: 'float'
  44471. }];
  44472. areaData = new List(coordDimsInfos, maModel);
  44473. }
  44474. var optData = map(maModel.get('data'), curry(
  44475. markAreaTransform, seriesModel, coordSys, maModel
  44476. ));
  44477. if (coordSys) {
  44478. optData = filter(
  44479. optData, curry(markAreaFilter, coordSys)
  44480. );
  44481. }
  44482. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  44483. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  44484. } : function (item) {
  44485. return item.value;
  44486. };
  44487. areaData.initData(optData, null, dimValueGetter$$1);
  44488. areaData.hasItemOption = true;
  44489. return areaData;
  44490. }
  44491. /*
  44492. * Licensed to the Apache Software Foundation (ASF) under one
  44493. * or more contributor license agreements. See the NOTICE file
  44494. * distributed with this work for additional information
  44495. * regarding copyright ownership. The ASF licenses this file
  44496. * to you under the Apache License, Version 2.0 (the
  44497. * "License"); you may not use this file except in compliance
  44498. * with the License. You may obtain a copy of the License at
  44499. *
  44500. * http://www.apache.org/licenses/LICENSE-2.0
  44501. *
  44502. * Unless required by applicable law or agreed to in writing,
  44503. * software distributed under the License is distributed on an
  44504. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44505. * KIND, either express or implied. See the License for the
  44506. * specific language governing permissions and limitations
  44507. * under the License.
  44508. */
  44509. registerPreprocessor(function (opt) {
  44510. // Make sure markArea component is enabled
  44511. opt.markArea = opt.markArea || {};
  44512. });
  44513. /*
  44514. * Licensed to the Apache Software Foundation (ASF) under one
  44515. * or more contributor license agreements. See the NOTICE file
  44516. * distributed with this work for additional information
  44517. * regarding copyright ownership. The ASF licenses this file
  44518. * to you under the Apache License, Version 2.0 (the
  44519. * "License"); you may not use this file except in compliance
  44520. * with the License. You may obtain a copy of the License at
  44521. *
  44522. * http://www.apache.org/licenses/LICENSE-2.0
  44523. *
  44524. * Unless required by applicable law or agreed to in writing,
  44525. * software distributed under the License is distributed on an
  44526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44527. * KIND, either express or implied. See the License for the
  44528. * specific language governing permissions and limitations
  44529. * under the License.
  44530. */
  44531. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  44532. // Default 'slider' when no type specified.
  44533. return 'slider';
  44534. });
  44535. /*
  44536. * Licensed to the Apache Software Foundation (ASF) under one
  44537. * or more contributor license agreements. See the NOTICE file
  44538. * distributed with this work for additional information
  44539. * regarding copyright ownership. The ASF licenses this file
  44540. * to you under the Apache License, Version 2.0 (the
  44541. * "License"); you may not use this file except in compliance
  44542. * with the License. You may obtain a copy of the License at
  44543. *
  44544. * http://www.apache.org/licenses/LICENSE-2.0
  44545. *
  44546. * Unless required by applicable law or agreed to in writing,
  44547. * software distributed under the License is distributed on an
  44548. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44549. * KIND, either express or implied. See the License for the
  44550. * specific language governing permissions and limitations
  44551. * under the License.
  44552. */
  44553. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  44554. // Supported coords.
  44555. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  44556. /**
  44557. * @param {string} coordType
  44558. * @return {boolean}
  44559. */
  44560. function isCoordSupported(coordType) {
  44561. return indexOf(COORDS, coordType) >= 0;
  44562. }
  44563. /**
  44564. * Create "each" method to iterate names.
  44565. *
  44566. * @pubilc
  44567. * @param {Array.<string>} names
  44568. * @param {Array.<string>=} attrs
  44569. * @return {Function}
  44570. */
  44571. function createNameEach(names, attrs) {
  44572. names = names.slice();
  44573. var capitalNames = map(names, capitalFirst);
  44574. attrs = (attrs || []).slice();
  44575. var capitalAttrs = map(attrs, capitalFirst);
  44576. return function (callback, context) {
  44577. each$1(names, function (name, index) {
  44578. var nameObj = {name: name, capital: capitalNames[index]};
  44579. for (var j = 0; j < attrs.length; j++) {
  44580. nameObj[attrs[j]] = name + capitalAttrs[j];
  44581. }
  44582. callback.call(context, nameObj);
  44583. });
  44584. };
  44585. }
  44586. /**
  44587. * Iterate each dimension name.
  44588. *
  44589. * @public
  44590. * @param {Function} callback The parameter is like:
  44591. * {
  44592. * name: 'angle',
  44593. * capital: 'Angle',
  44594. * axis: 'angleAxis',
  44595. * axisIndex: 'angleAixs',
  44596. * index: 'angleIndex'
  44597. * }
  44598. * @param {Object} context
  44599. */
  44600. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  44601. /**
  44602. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  44603. * dataZoomModels and 'links' make up one or more graphics.
  44604. * This function finds the graphic where the source dataZoomModel is in.
  44605. *
  44606. * @public
  44607. * @param {Function} forEachNode Node iterator.
  44608. * @param {Function} forEachEdgeType edgeType iterator
  44609. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  44610. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  44611. */
  44612. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  44613. return function (sourceNode) {
  44614. var result = {
  44615. nodes: [],
  44616. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  44617. };
  44618. forEachEdgeType(function (edgeType) {
  44619. result.records[edgeType.name] = {};
  44620. });
  44621. if (!sourceNode) {
  44622. return result;
  44623. }
  44624. absorb(sourceNode, result);
  44625. var existsLink;
  44626. do {
  44627. existsLink = false;
  44628. forEachNode(processSingleNode);
  44629. }
  44630. while (existsLink);
  44631. function processSingleNode(node) {
  44632. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  44633. absorb(node, result);
  44634. existsLink = true;
  44635. }
  44636. }
  44637. return result;
  44638. };
  44639. function isNodeAbsorded(node, result) {
  44640. return indexOf(result.nodes, node) >= 0;
  44641. }
  44642. function isLinked(node, result) {
  44643. var hasLink = false;
  44644. forEachEdgeType(function (edgeType) {
  44645. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  44646. result.records[edgeType.name][edgeId] && (hasLink = true);
  44647. });
  44648. });
  44649. return hasLink;
  44650. }
  44651. function absorb(node, result) {
  44652. result.nodes.push(node);
  44653. forEachEdgeType(function (edgeType) {
  44654. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  44655. result.records[edgeType.name][edgeId] = true;
  44656. });
  44657. });
  44658. }
  44659. }
  44660. /*
  44661. * Licensed to the Apache Software Foundation (ASF) under one
  44662. * or more contributor license agreements. See the NOTICE file
  44663. * distributed with this work for additional information
  44664. * regarding copyright ownership. The ASF licenses this file
  44665. * to you under the Apache License, Version 2.0 (the
  44666. * "License"); you may not use this file except in compliance
  44667. * with the License. You may obtain a copy of the License at
  44668. *
  44669. * http://www.apache.org/licenses/LICENSE-2.0
  44670. *
  44671. * Unless required by applicable law or agreed to in writing,
  44672. * software distributed under the License is distributed on an
  44673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44674. * KIND, either express or implied. See the License for the
  44675. * specific language governing permissions and limitations
  44676. * under the License.
  44677. */
  44678. var each$13 = each$1;
  44679. var asc$1 = asc;
  44680. /**
  44681. * Operate single axis.
  44682. * One axis can only operated by one axis operator.
  44683. * Different dataZoomModels may be defined to operate the same axis.
  44684. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  44685. * So dataZoomModels share one axisProxy in that case.
  44686. *
  44687. * @class
  44688. */
  44689. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  44690. /**
  44691. * @private
  44692. * @type {string}
  44693. */
  44694. this._dimName = dimName;
  44695. /**
  44696. * @private
  44697. */
  44698. this._axisIndex = axisIndex;
  44699. /**
  44700. * @private
  44701. * @type {Array.<number>}
  44702. */
  44703. this._valueWindow;
  44704. /**
  44705. * @private
  44706. * @type {Array.<number>}
  44707. */
  44708. this._percentWindow;
  44709. /**
  44710. * @private
  44711. * @type {Array.<number>}
  44712. */
  44713. this._dataExtent;
  44714. /**
  44715. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  44716. * @private
  44717. * @type {Object}
  44718. */
  44719. this._minMaxSpan;
  44720. /**
  44721. * @readOnly
  44722. * @type {module: echarts/model/Global}
  44723. */
  44724. this.ecModel = ecModel;
  44725. /**
  44726. * @private
  44727. * @type {module: echarts/component/dataZoom/DataZoomModel}
  44728. */
  44729. this._dataZoomModel = dataZoomModel;
  44730. // /**
  44731. // * @readOnly
  44732. // * @private
  44733. // */
  44734. // this.hasSeriesStacked;
  44735. };
  44736. AxisProxy.prototype = {
  44737. constructor: AxisProxy,
  44738. /**
  44739. * Whether the axisProxy is hosted by dataZoomModel.
  44740. *
  44741. * @public
  44742. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  44743. * @return {boolean}
  44744. */
  44745. hostedBy: function (dataZoomModel) {
  44746. return this._dataZoomModel === dataZoomModel;
  44747. },
  44748. /**
  44749. * @return {Array.<number>} Value can only be NaN or finite value.
  44750. */
  44751. getDataValueWindow: function () {
  44752. return this._valueWindow.slice();
  44753. },
  44754. /**
  44755. * @return {Array.<number>}
  44756. */
  44757. getDataPercentWindow: function () {
  44758. return this._percentWindow.slice();
  44759. },
  44760. /**
  44761. * @public
  44762. * @param {number} axisIndex
  44763. * @return {Array} seriesModels
  44764. */
  44765. getTargetSeriesModels: function () {
  44766. var seriesModels = [];
  44767. var ecModel = this.ecModel;
  44768. ecModel.eachSeries(function (seriesModel) {
  44769. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  44770. var dimName = this._dimName;
  44771. var axisModel = ecModel.queryComponents({
  44772. mainType: dimName + 'Axis',
  44773. index: seriesModel.get(dimName + 'AxisIndex'),
  44774. id: seriesModel.get(dimName + 'AxisId')
  44775. })[0];
  44776. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  44777. seriesModels.push(seriesModel);
  44778. }
  44779. }
  44780. }, this);
  44781. return seriesModels;
  44782. },
  44783. getAxisModel: function () {
  44784. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  44785. },
  44786. getOtherAxisModel: function () {
  44787. var axisDim = this._dimName;
  44788. var ecModel = this.ecModel;
  44789. var axisModel = this.getAxisModel();
  44790. var isCartesian = axisDim === 'x' || axisDim === 'y';
  44791. var otherAxisDim;
  44792. var coordSysIndexName;
  44793. if (isCartesian) {
  44794. coordSysIndexName = 'gridIndex';
  44795. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  44796. }
  44797. else {
  44798. coordSysIndexName = 'polarIndex';
  44799. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  44800. }
  44801. var foundOtherAxisModel;
  44802. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  44803. if ((otherAxisModel.get(coordSysIndexName) || 0)
  44804. === (axisModel.get(coordSysIndexName) || 0)
  44805. ) {
  44806. foundOtherAxisModel = otherAxisModel;
  44807. }
  44808. });
  44809. return foundOtherAxisModel;
  44810. },
  44811. getMinMaxSpan: function () {
  44812. return clone(this._minMaxSpan);
  44813. },
  44814. /**
  44815. * Only calculate by given range and this._dataExtent, do not change anything.
  44816. *
  44817. * @param {Object} opt
  44818. * @param {number} [opt.start]
  44819. * @param {number} [opt.end]
  44820. * @param {number} [opt.startValue]
  44821. * @param {number} [opt.endValue]
  44822. */
  44823. calculateDataWindow: function (opt) {
  44824. var dataExtent = this._dataExtent;
  44825. var axisModel = this.getAxisModel();
  44826. var scale = axisModel.axis.scale;
  44827. var rangePropMode = this._dataZoomModel.getRangePropMode();
  44828. var percentExtent = [0, 100];
  44829. var percentWindow = [
  44830. opt.start,
  44831. opt.end
  44832. ];
  44833. var valueWindow = [];
  44834. each$13(['startValue', 'endValue'], function (prop) {
  44835. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  44836. });
  44837. // Normalize bound.
  44838. each$13([0, 1], function (idx) {
  44839. var boundValue = valueWindow[idx];
  44840. var boundPercent = percentWindow[idx];
  44841. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  44842. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  44843. // for cases that a dataZoom component controls multiple axes with different
  44844. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  44845. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  44846. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  44847. // accurately (because all of values that are overflow the `dataExtent` will
  44848. // be calculated to percent '100%'). So we have to use
  44849. // `dataZoom.getRangePropMode()` to mark which prop is used.
  44850. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  44851. // it remains its original value.
  44852. if (rangePropMode[idx] === 'percent') {
  44853. if (boundPercent == null) {
  44854. boundPercent = percentExtent[idx];
  44855. }
  44856. // Use scale.parse to math round for category or time axis.
  44857. boundValue = scale.parse(linearMap(
  44858. boundPercent, percentExtent, dataExtent, true
  44859. ));
  44860. }
  44861. else {
  44862. // Calculating `percent` from `value` may be not accurate, because
  44863. // This calculation can not be inversed, because all of values that
  44864. // are overflow the `dataExtent` will be calculated to percent '100%'
  44865. boundPercent = linearMap(
  44866. boundValue, dataExtent, percentExtent, true
  44867. );
  44868. }
  44869. // valueWindow[idx] = round(boundValue);
  44870. // percentWindow[idx] = round(boundPercent);
  44871. valueWindow[idx] = boundValue;
  44872. percentWindow[idx] = boundPercent;
  44873. });
  44874. return {
  44875. valueWindow: asc$1(valueWindow),
  44876. percentWindow: asc$1(percentWindow)
  44877. };
  44878. },
  44879. /**
  44880. * Notice: reset should not be called before series.restoreData() called,
  44881. * so it is recommanded to be called in "process stage" but not "model init
  44882. * stage".
  44883. *
  44884. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  44885. */
  44886. reset: function (dataZoomModel) {
  44887. if (dataZoomModel !== this._dataZoomModel) {
  44888. return;
  44889. }
  44890. var targetSeries = this.getTargetSeriesModels();
  44891. // Culculate data window and data extent, and record them.
  44892. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  44893. // this.hasSeriesStacked = false;
  44894. // each(targetSeries, function (series) {
  44895. // var data = series.getData();
  44896. // var dataDim = data.mapDimension(this._dimName);
  44897. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  44898. // if (stackedDimension && stackedDimension === dataDim) {
  44899. // this.hasSeriesStacked = true;
  44900. // }
  44901. // }, this);
  44902. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  44903. this._valueWindow = dataWindow.valueWindow;
  44904. this._percentWindow = dataWindow.percentWindow;
  44905. setMinMaxSpan(this);
  44906. // Update axis setting then.
  44907. setAxisModel(this);
  44908. },
  44909. /**
  44910. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  44911. */
  44912. restore: function (dataZoomModel) {
  44913. if (dataZoomModel !== this._dataZoomModel) {
  44914. return;
  44915. }
  44916. this._valueWindow = this._percentWindow = null;
  44917. setAxisModel(this, true);
  44918. },
  44919. /**
  44920. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  44921. */
  44922. filterData: function (dataZoomModel, api) {
  44923. if (dataZoomModel !== this._dataZoomModel) {
  44924. return;
  44925. }
  44926. var axisDim = this._dimName;
  44927. var seriesModels = this.getTargetSeriesModels();
  44928. var filterMode = dataZoomModel.get('filterMode');
  44929. var valueWindow = this._valueWindow;
  44930. if (filterMode === 'none') {
  44931. return;
  44932. }
  44933. // FIXME
  44934. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  44935. // with NaN data, NaN will be filtered and stack will be wrong.
  44936. // So we need to force the mode to be set empty.
  44937. // In fect, it is not a big deal that do not support filterMode-'filter'
  44938. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  44939. // selection" some day, which might need "adapt to data extent on the
  44940. // otherAxis", which is disabled by filterMode-'empty'.
  44941. // But currently, stack has been fixed to based on value but not index,
  44942. // so this is not an issue any more.
  44943. // var otherAxisModel = this.getOtherAxisModel();
  44944. // if (dataZoomModel.get('$fromToolbox')
  44945. // && otherAxisModel
  44946. // && otherAxisModel.hasSeriesStacked
  44947. // ) {
  44948. // filterMode = 'empty';
  44949. // }
  44950. // TODO
  44951. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  44952. each$13(seriesModels, function (seriesModel) {
  44953. var seriesData = seriesModel.getData();
  44954. var dataDims = seriesData.mapDimension(axisDim, true);
  44955. if (!dataDims.length) {
  44956. return;
  44957. }
  44958. if (filterMode === 'weakFilter') {
  44959. seriesData.filterSelf(function (dataIndex) {
  44960. var leftOut;
  44961. var rightOut;
  44962. var hasValue;
  44963. for (var i = 0; i < dataDims.length; i++) {
  44964. var value = seriesData.get(dataDims[i], dataIndex);
  44965. var thisHasValue = !isNaN(value);
  44966. var thisLeftOut = value < valueWindow[0];
  44967. var thisRightOut = value > valueWindow[1];
  44968. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  44969. return true;
  44970. }
  44971. thisHasValue && (hasValue = true);
  44972. thisLeftOut && (leftOut = true);
  44973. thisRightOut && (rightOut = true);
  44974. }
  44975. // If both left out and right out, do not filter.
  44976. return hasValue && leftOut && rightOut;
  44977. });
  44978. }
  44979. else {
  44980. each$13(dataDims, function (dim) {
  44981. if (filterMode === 'empty') {
  44982. seriesModel.setData(
  44983. seriesData.map(dim, function (value) {
  44984. return !isInWindow(value) ? NaN : value;
  44985. })
  44986. );
  44987. }
  44988. else {
  44989. var range = {};
  44990. range[dim] = valueWindow;
  44991. // console.time('select');
  44992. seriesData.selectRange(range);
  44993. // console.timeEnd('select');
  44994. }
  44995. });
  44996. }
  44997. each$13(dataDims, function (dim) {
  44998. seriesData.setApproximateExtent(valueWindow, dim);
  44999. });
  45000. });
  45001. function isInWindow(value) {
  45002. return value >= valueWindow[0] && value <= valueWindow[1];
  45003. }
  45004. }
  45005. };
  45006. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  45007. var dataExtent = [Infinity, -Infinity];
  45008. each$13(seriesModels, function (seriesModel) {
  45009. var seriesData = seriesModel.getData();
  45010. if (seriesData) {
  45011. each$13(seriesData.mapDimension(axisDim, true), function (dim) {
  45012. var seriesExtent = seriesData.getApproximateExtent(dim);
  45013. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  45014. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  45015. });
  45016. }
  45017. });
  45018. if (dataExtent[1] < dataExtent[0]) {
  45019. dataExtent = [NaN, NaN];
  45020. }
  45021. // It is important to get "consistent" extent when more then one axes is
  45022. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  45023. // when zooming. But it is difficult to know what is "consistent", considering
  45024. // axes have different type or even different meanings (For example, two
  45025. // time axes are used to compare data of the same date in different years).
  45026. // So basically dataZoom just obtains extent by series.data (in category axis
  45027. // extent can be obtained from axis.data).
  45028. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  45029. // consistent.
  45030. fixExtentByAxis(axisProxy, dataExtent);
  45031. return dataExtent;
  45032. }
  45033. function fixExtentByAxis(axisProxy, dataExtent) {
  45034. var axisModel = axisProxy.getAxisModel();
  45035. var min = axisModel.getMin(true);
  45036. // For category axis, if min/max/scale are not set, extent is determined
  45037. // by axis.data by default.
  45038. var isCategoryAxis = axisModel.get('type') === 'category';
  45039. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  45040. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  45041. dataExtent[0] = min;
  45042. }
  45043. else if (isCategoryAxis) {
  45044. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  45045. }
  45046. var max = axisModel.getMax(true);
  45047. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  45048. dataExtent[1] = max;
  45049. }
  45050. else if (isCategoryAxis) {
  45051. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  45052. }
  45053. if (!axisModel.get('scale', true)) {
  45054. dataExtent[0] > 0 && (dataExtent[0] = 0);
  45055. dataExtent[1] < 0 && (dataExtent[1] = 0);
  45056. }
  45057. // For value axis, if min/max/scale are not set, we just use the extent obtained
  45058. // by series data, which may be a little different from the extent calculated by
  45059. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  45060. // little when zooming. So it will not be fixed until some users require it strongly.
  45061. return dataExtent;
  45062. }
  45063. function setAxisModel(axisProxy, isRestore) {
  45064. var axisModel = axisProxy.getAxisModel();
  45065. var percentWindow = axisProxy._percentWindow;
  45066. var valueWindow = axisProxy._valueWindow;
  45067. if (!percentWindow) {
  45068. return;
  45069. }
  45070. // [0, 500]: arbitrary value, guess axis extent.
  45071. var precision = getPixelPrecision(valueWindow, [0, 500]);
  45072. precision = Math.min(precision, 20);
  45073. // isRestore or isFull
  45074. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  45075. axisModel.setRange(
  45076. useOrigin ? null : +valueWindow[0].toFixed(precision),
  45077. useOrigin ? null : +valueWindow[1].toFixed(precision)
  45078. );
  45079. }
  45080. function setMinMaxSpan(axisProxy) {
  45081. var minMaxSpan = axisProxy._minMaxSpan = {};
  45082. var dataZoomModel = axisProxy._dataZoomModel;
  45083. each$13(['min', 'max'], function (minMax) {
  45084. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  45085. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  45086. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  45087. if (valueSpan != null) {
  45088. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  45089. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  45090. if (valueSpan != null) {
  45091. var dataExtent = axisProxy._dataExtent;
  45092. minMaxSpan[minMax + 'Span'] = linearMap(
  45093. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  45094. );
  45095. }
  45096. }
  45097. });
  45098. }
  45099. /*
  45100. * Licensed to the Apache Software Foundation (ASF) under one
  45101. * or more contributor license agreements. See the NOTICE file
  45102. * distributed with this work for additional information
  45103. * regarding copyright ownership. The ASF licenses this file
  45104. * to you under the Apache License, Version 2.0 (the
  45105. * "License"); you may not use this file except in compliance
  45106. * with the License. You may obtain a copy of the License at
  45107. *
  45108. * http://www.apache.org/licenses/LICENSE-2.0
  45109. *
  45110. * Unless required by applicable law or agreed to in writing,
  45111. * software distributed under the License is distributed on an
  45112. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45113. * KIND, either express or implied. See the License for the
  45114. * specific language governing permissions and limitations
  45115. * under the License.
  45116. */
  45117. var each$12 = each$1;
  45118. var eachAxisDim = eachAxisDim$1;
  45119. var DataZoomModel = extendComponentModel({
  45120. type: 'dataZoom',
  45121. dependencies: [
  45122. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  45123. ],
  45124. /**
  45125. * @protected
  45126. */
  45127. defaultOption: {
  45128. zlevel: 0,
  45129. z: 4, // Higher than normal component (z: 2).
  45130. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  45131. xAxisIndex: null, // Default the first horizontal category axis.
  45132. yAxisIndex: null, // Default the first vertical category axis.
  45133. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  45134. // 'filter': data items which are out of window will be removed. This option is
  45135. // applicable when filtering outliers. For each data item, it will be
  45136. // filtered if one of the relevant dimensions is out of the window.
  45137. // 'weakFilter': data items which are out of window will be removed. This option
  45138. // is applicable when filtering outliers. For each data item, it will be
  45139. // filtered only if all of the relevant dimensions are out of the same
  45140. // side of the window.
  45141. // 'empty': data items which are out of window will be set to empty.
  45142. // This option is applicable when user should not neglect
  45143. // that there are some data items out of window.
  45144. // 'none': Do not filter.
  45145. // Taking line chart as an example, line will be broken in
  45146. // the filtered points when filterModel is set to 'empty', but
  45147. // be connected when set to 'filter'.
  45148. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  45149. // default 100. Do not throttle when use null/undefined.
  45150. // If animation === true and animationDurationUpdate > 0,
  45151. // default value is 100, otherwise 20.
  45152. start: 0, // Start percent. 0 ~ 100
  45153. end: 100, // End percent. 0 ~ 100
  45154. startValue: null, // Start value. If startValue specified, start is ignored.
  45155. endValue: null, // End value. If endValue specified, end is ignored.
  45156. minSpan: null, // 0 ~ 100
  45157. maxSpan: null, // 0 ~ 100
  45158. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  45159. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  45160. rangeMode: null // Array, can be 'value' or 'percent'.
  45161. },
  45162. /**
  45163. * @override
  45164. */
  45165. init: function (option, parentModel, ecModel) {
  45166. /**
  45167. * key like x_0, y_1
  45168. * @private
  45169. * @type {Object}
  45170. */
  45171. this._dataIntervalByAxis = {};
  45172. /**
  45173. * @private
  45174. */
  45175. this._dataInfo = {};
  45176. /**
  45177. * key like x_0, y_1
  45178. * @private
  45179. */
  45180. this._axisProxies = {};
  45181. /**
  45182. * @readOnly
  45183. */
  45184. this.textStyleModel;
  45185. /**
  45186. * @private
  45187. */
  45188. this._autoThrottle = true;
  45189. /**
  45190. * 'percent' or 'value'
  45191. * @private
  45192. */
  45193. this._rangePropMode = ['percent', 'percent'];
  45194. var rawOption = retrieveRaw(option);
  45195. this.mergeDefaultAndTheme(option, ecModel);
  45196. this.doInit(rawOption);
  45197. },
  45198. /**
  45199. * @override
  45200. */
  45201. mergeOption: function (newOption) {
  45202. var rawOption = retrieveRaw(newOption);
  45203. //FIX #2591
  45204. merge(this.option, newOption, true);
  45205. this.doInit(rawOption);
  45206. },
  45207. /**
  45208. * @protected
  45209. */
  45210. doInit: function (rawOption) {
  45211. var thisOption = this.option;
  45212. // Disable realtime view update if canvas is not supported.
  45213. if (!env$1.canvasSupported) {
  45214. thisOption.realtime = false;
  45215. }
  45216. this._setDefaultThrottle(rawOption);
  45217. updateRangeUse(this, rawOption);
  45218. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  45219. // start/end has higher priority over startValue/endValue if they
  45220. // both set, but we should make chart.setOption({endValue: 1000})
  45221. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  45222. if (this._rangePropMode[index] === 'value') {
  45223. thisOption[names[0]] = null;
  45224. }
  45225. // Otherwise do nothing and use the merge result.
  45226. }, this);
  45227. this.textStyleModel = this.getModel('textStyle');
  45228. this._resetTarget();
  45229. this._giveAxisProxies();
  45230. },
  45231. /**
  45232. * @private
  45233. */
  45234. _giveAxisProxies: function () {
  45235. var axisProxies = this._axisProxies;
  45236. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  45237. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  45238. // If exists, share axisProxy with other dataZoomModels.
  45239. var axisProxy = axisModel.__dzAxisProxy || (
  45240. // Use the first dataZoomModel as the main model of axisProxy.
  45241. axisModel.__dzAxisProxy = new AxisProxy(
  45242. dimNames.name, axisIndex, this, ecModel
  45243. )
  45244. );
  45245. // FIXME
  45246. // dispose __dzAxisProxy
  45247. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  45248. }, this);
  45249. },
  45250. /**
  45251. * @private
  45252. */
  45253. _resetTarget: function () {
  45254. var thisOption = this.option;
  45255. var autoMode = this._judgeAutoMode();
  45256. eachAxisDim(function (dimNames) {
  45257. var axisIndexName = dimNames.axisIndex;
  45258. thisOption[axisIndexName] = normalizeToArray(
  45259. thisOption[axisIndexName]
  45260. );
  45261. }, this);
  45262. if (autoMode === 'axisIndex') {
  45263. this._autoSetAxisIndex();
  45264. }
  45265. else if (autoMode === 'orient') {
  45266. this._autoSetOrient();
  45267. }
  45268. },
  45269. /**
  45270. * @private
  45271. */
  45272. _judgeAutoMode: function () {
  45273. // Auto set only works for setOption at the first time.
  45274. // The following is user's reponsibility. So using merged
  45275. // option is OK.
  45276. var thisOption = this.option;
  45277. var hasIndexSpecified = false;
  45278. eachAxisDim(function (dimNames) {
  45279. // When user set axisIndex as a empty array, we think that user specify axisIndex
  45280. // but do not want use auto mode. Because empty array may be encountered when
  45281. // some error occured.
  45282. if (thisOption[dimNames.axisIndex] != null) {
  45283. hasIndexSpecified = true;
  45284. }
  45285. }, this);
  45286. var orient = thisOption.orient;
  45287. if (orient == null && hasIndexSpecified) {
  45288. return 'orient';
  45289. }
  45290. else if (!hasIndexSpecified) {
  45291. if (orient == null) {
  45292. thisOption.orient = 'horizontal';
  45293. }
  45294. return 'axisIndex';
  45295. }
  45296. },
  45297. /**
  45298. * @private
  45299. */
  45300. _autoSetAxisIndex: function () {
  45301. var autoAxisIndex = true;
  45302. var orient = this.get('orient', true);
  45303. var thisOption = this.option;
  45304. var dependentModels = this.dependentModels;
  45305. if (autoAxisIndex) {
  45306. // Find axis that parallel to dataZoom as default.
  45307. var dimName = orient === 'vertical' ? 'y' : 'x';
  45308. if (dependentModels[dimName + 'Axis'].length) {
  45309. thisOption[dimName + 'AxisIndex'] = [0];
  45310. autoAxisIndex = false;
  45311. }
  45312. else {
  45313. each$12(dependentModels.singleAxis, function (singleAxisModel) {
  45314. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  45315. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  45316. autoAxisIndex = false;
  45317. }
  45318. });
  45319. }
  45320. }
  45321. if (autoAxisIndex) {
  45322. // Find the first category axis as default. (consider polar)
  45323. eachAxisDim(function (dimNames) {
  45324. if (!autoAxisIndex) {
  45325. return;
  45326. }
  45327. var axisIndices = [];
  45328. var axisModels = this.dependentModels[dimNames.axis];
  45329. if (axisModels.length && !axisIndices.length) {
  45330. for (var i = 0, len = axisModels.length; i < len; i++) {
  45331. if (axisModels[i].get('type') === 'category') {
  45332. axisIndices.push(i);
  45333. }
  45334. }
  45335. }
  45336. thisOption[dimNames.axisIndex] = axisIndices;
  45337. if (axisIndices.length) {
  45338. autoAxisIndex = false;
  45339. }
  45340. }, this);
  45341. }
  45342. if (autoAxisIndex) {
  45343. // FIXME
  45344. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  45345. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  45346. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  45347. // dataZoom component auto adopts series that reference to
  45348. // both xAxis and yAxis which type is 'value'.
  45349. this.ecModel.eachSeries(function (seriesModel) {
  45350. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  45351. eachAxisDim(function (dimNames) {
  45352. var axisIndices = thisOption[dimNames.axisIndex];
  45353. var axisIndex = seriesModel.get(dimNames.axisIndex);
  45354. var axisId = seriesModel.get(dimNames.axisId);
  45355. var axisModel = seriesModel.ecModel.queryComponents({
  45356. mainType: dimNames.axis,
  45357. index: axisIndex,
  45358. id: axisId
  45359. })[0];
  45360. if (__DEV__) {
  45361. if (!axisModel) {
  45362. throw new Error(
  45363. dimNames.axis + ' "' + retrieve(
  45364. axisIndex,
  45365. axisId,
  45366. 0
  45367. ) + '" not found'
  45368. );
  45369. }
  45370. }
  45371. axisIndex = axisModel.componentIndex;
  45372. if (indexOf(axisIndices, axisIndex) < 0) {
  45373. axisIndices.push(axisIndex);
  45374. }
  45375. });
  45376. }
  45377. }, this);
  45378. }
  45379. },
  45380. /**
  45381. * @private
  45382. */
  45383. _autoSetOrient: function () {
  45384. var dim;
  45385. // Find the first axis
  45386. this.eachTargetAxis(function (dimNames) {
  45387. !dim && (dim = dimNames.name);
  45388. }, this);
  45389. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  45390. },
  45391. /**
  45392. * @private
  45393. */
  45394. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  45395. // FIXME
  45396. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  45397. // 例如series.type === scatter时。
  45398. var is = true;
  45399. eachAxisDim(function (dimNames) {
  45400. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  45401. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  45402. if (!axisModel || axisModel.get('type') !== axisType) {
  45403. is = false;
  45404. }
  45405. }, this);
  45406. return is;
  45407. },
  45408. /**
  45409. * @private
  45410. */
  45411. _setDefaultThrottle: function (rawOption) {
  45412. // When first time user set throttle, auto throttle ends.
  45413. if (rawOption.hasOwnProperty('throttle')) {
  45414. this._autoThrottle = false;
  45415. }
  45416. if (this._autoThrottle) {
  45417. var globalOption = this.ecModel.option;
  45418. this.option.throttle
  45419. = (globalOption.animation && globalOption.animationDurationUpdate > 0)
  45420. ? 100 : 20;
  45421. }
  45422. },
  45423. /**
  45424. * @public
  45425. */
  45426. getFirstTargetAxisModel: function () {
  45427. var firstAxisModel;
  45428. eachAxisDim(function (dimNames) {
  45429. if (firstAxisModel == null) {
  45430. var indices = this.get(dimNames.axisIndex);
  45431. if (indices.length) {
  45432. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  45433. }
  45434. }
  45435. }, this);
  45436. return firstAxisModel;
  45437. },
  45438. /**
  45439. * @public
  45440. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  45441. */
  45442. eachTargetAxis: function (callback, context) {
  45443. var ecModel = this.ecModel;
  45444. eachAxisDim(function (dimNames) {
  45445. each$12(
  45446. this.get(dimNames.axisIndex),
  45447. function (axisIndex) {
  45448. callback.call(context, dimNames, axisIndex, this, ecModel);
  45449. },
  45450. this
  45451. );
  45452. }, this);
  45453. },
  45454. /**
  45455. * @param {string} dimName
  45456. * @param {number} axisIndex
  45457. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  45458. */
  45459. getAxisProxy: function (dimName, axisIndex) {
  45460. return this._axisProxies[dimName + '_' + axisIndex];
  45461. },
  45462. /**
  45463. * @param {string} dimName
  45464. * @param {number} axisIndex
  45465. * @return {module:echarts/model/Model} If not found, return null/undefined.
  45466. */
  45467. getAxisModel: function (dimName, axisIndex) {
  45468. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  45469. return axisProxy && axisProxy.getAxisModel();
  45470. },
  45471. /**
  45472. * If not specified, set to undefined.
  45473. *
  45474. * @public
  45475. * @param {Object} opt
  45476. * @param {number} [opt.start]
  45477. * @param {number} [opt.end]
  45478. * @param {number} [opt.startValue]
  45479. * @param {number} [opt.endValue]
  45480. * @param {boolean} [ignoreUpdateRangeUsg=false]
  45481. */
  45482. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  45483. var option = this.option;
  45484. each$12([['start', 'startValue'], ['end', 'endValue']], function (names) {
  45485. // If only one of 'start' and 'startValue' is not null/undefined, the other
  45486. // should be cleared, which enable clear the option.
  45487. // If both of them are not set, keep option with the original value, which
  45488. // enable use only set start but not set end when calling `dispatchAction`.
  45489. // The same as 'end' and 'endValue'.
  45490. if (opt[names[0]] != null || opt[names[1]] != null) {
  45491. option[names[0]] = opt[names[0]];
  45492. option[names[1]] = opt[names[1]];
  45493. }
  45494. }, this);
  45495. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  45496. },
  45497. /**
  45498. * @public
  45499. * @return {Array.<number>} [startPercent, endPercent]
  45500. */
  45501. getPercentRange: function () {
  45502. var axisProxy = this.findRepresentativeAxisProxy();
  45503. if (axisProxy) {
  45504. return axisProxy.getDataPercentWindow();
  45505. }
  45506. },
  45507. /**
  45508. * @public
  45509. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  45510. *
  45511. * @param {string} [axisDimName]
  45512. * @param {number} [axisIndex]
  45513. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  45514. */
  45515. getValueRange: function (axisDimName, axisIndex) {
  45516. if (axisDimName == null && axisIndex == null) {
  45517. var axisProxy = this.findRepresentativeAxisProxy();
  45518. if (axisProxy) {
  45519. return axisProxy.getDataValueWindow();
  45520. }
  45521. }
  45522. else {
  45523. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  45524. }
  45525. },
  45526. /**
  45527. * @public
  45528. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  45529. * corresponding to the axisModel
  45530. * @return {module:echarts/component/dataZoom/AxisProxy}
  45531. */
  45532. findRepresentativeAxisProxy: function (axisModel) {
  45533. if (axisModel) {
  45534. return axisModel.__dzAxisProxy;
  45535. }
  45536. // Find the first hosted axisProxy
  45537. var axisProxies = this._axisProxies;
  45538. for (var key in axisProxies) {
  45539. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  45540. return axisProxies[key];
  45541. }
  45542. }
  45543. // If no hosted axis find not hosted axisProxy.
  45544. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  45545. // and the option.start or option.end settings are different. The percentRange
  45546. // should follow axisProxy.
  45547. // (We encounter this problem in toolbox data zoom.)
  45548. for (var key in axisProxies) {
  45549. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  45550. return axisProxies[key];
  45551. }
  45552. }
  45553. },
  45554. /**
  45555. * @return {Array.<string>}
  45556. */
  45557. getRangePropMode: function () {
  45558. return this._rangePropMode.slice();
  45559. }
  45560. });
  45561. function retrieveRaw(option) {
  45562. var ret = {};
  45563. each$12(
  45564. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  45565. function (name) {
  45566. option.hasOwnProperty(name) && (ret[name] = option[name]);
  45567. }
  45568. );
  45569. return ret;
  45570. }
  45571. function updateRangeUse(dataZoomModel, rawOption) {
  45572. var rangePropMode = dataZoomModel._rangePropMode;
  45573. var rangeModeInOption = dataZoomModel.get('rangeMode');
  45574. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  45575. var percentSpecified = rawOption[names[0]] != null;
  45576. var valueSpecified = rawOption[names[1]] != null;
  45577. if (percentSpecified && !valueSpecified) {
  45578. rangePropMode[index] = 'percent';
  45579. }
  45580. else if (!percentSpecified && valueSpecified) {
  45581. rangePropMode[index] = 'value';
  45582. }
  45583. else if (rangeModeInOption) {
  45584. rangePropMode[index] = rangeModeInOption[index];
  45585. }
  45586. else if (percentSpecified) { // percentSpecified && valueSpecified
  45587. rangePropMode[index] = 'percent';
  45588. }
  45589. // else remain its original setting.
  45590. });
  45591. }
  45592. /*
  45593. * Licensed to the Apache Software Foundation (ASF) under one
  45594. * or more contributor license agreements. See the NOTICE file
  45595. * distributed with this work for additional information
  45596. * regarding copyright ownership. The ASF licenses this file
  45597. * to you under the Apache License, Version 2.0 (the
  45598. * "License"); you may not use this file except in compliance
  45599. * with the License. You may obtain a copy of the License at
  45600. *
  45601. * http://www.apache.org/licenses/LICENSE-2.0
  45602. *
  45603. * Unless required by applicable law or agreed to in writing,
  45604. * software distributed under the License is distributed on an
  45605. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45606. * KIND, either express or implied. See the License for the
  45607. * specific language governing permissions and limitations
  45608. * under the License.
  45609. */
  45610. var DataZoomView = Component$1.extend({
  45611. type: 'dataZoom',
  45612. render: function (dataZoomModel, ecModel, api, payload) {
  45613. this.dataZoomModel = dataZoomModel;
  45614. this.ecModel = ecModel;
  45615. this.api = api;
  45616. },
  45617. /**
  45618. * Find the first target coordinate system.
  45619. *
  45620. * @protected
  45621. * @return {Object} {
  45622. * grid: [
  45623. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  45624. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  45625. * ...
  45626. * ], // cartesians must not be null/undefined.
  45627. * polar: [
  45628. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  45629. * ...
  45630. * ], // polars must not be null/undefined.
  45631. * singleAxis: [
  45632. * {model: coord0, axisModels: [], coordIndex: 0}
  45633. * ]
  45634. */
  45635. getTargetCoordInfo: function () {
  45636. var dataZoomModel = this.dataZoomModel;
  45637. var ecModel = this.ecModel;
  45638. var coordSysLists = {};
  45639. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  45640. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  45641. if (axisModel) {
  45642. var coordModel = axisModel.getCoordSysModel();
  45643. coordModel && save(
  45644. coordModel,
  45645. axisModel,
  45646. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  45647. coordModel.componentIndex
  45648. );
  45649. }
  45650. }, this);
  45651. function save(coordModel, axisModel, store, coordIndex) {
  45652. var item;
  45653. for (var i = 0; i < store.length; i++) {
  45654. if (store[i].model === coordModel) {
  45655. item = store[i];
  45656. break;
  45657. }
  45658. }
  45659. if (!item) {
  45660. store.push(item = {
  45661. model: coordModel, axisModels: [], coordIndex: coordIndex
  45662. });
  45663. }
  45664. item.axisModels.push(axisModel);
  45665. }
  45666. return coordSysLists;
  45667. }
  45668. });
  45669. /*
  45670. * Licensed to the Apache Software Foundation (ASF) under one
  45671. * or more contributor license agreements. See the NOTICE file
  45672. * distributed with this work for additional information
  45673. * regarding copyright ownership. The ASF licenses this file
  45674. * to you under the Apache License, Version 2.0 (the
  45675. * "License"); you may not use this file except in compliance
  45676. * with the License. You may obtain a copy of the License at
  45677. *
  45678. * http://www.apache.org/licenses/LICENSE-2.0
  45679. *
  45680. * Unless required by applicable law or agreed to in writing,
  45681. * software distributed under the License is distributed on an
  45682. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45683. * KIND, either express or implied. See the License for the
  45684. * specific language governing permissions and limitations
  45685. * under the License.
  45686. */
  45687. var SliderZoomModel = DataZoomModel.extend({
  45688. type: 'dataZoom.slider',
  45689. layoutMode: 'box',
  45690. /**
  45691. * @protected
  45692. */
  45693. defaultOption: {
  45694. show: true,
  45695. // ph => placeholder. Using placehoder here because
  45696. // deault value can only be drived in view stage.
  45697. right: 'ph', // Default align to grid rect.
  45698. top: 'ph', // Default align to grid rect.
  45699. width: 'ph', // Default align to grid rect.
  45700. height: 'ph', // Default align to grid rect.
  45701. left: null, // Default align to grid rect.
  45702. bottom: null, // Default align to grid rect.
  45703. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  45704. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  45705. // highest priority, remain for compatibility of
  45706. // previous version, but not recommended any more.
  45707. dataBackground: {
  45708. lineStyle: {
  45709. color: '#2f4554',
  45710. width: 0.5,
  45711. opacity: 0.3
  45712. },
  45713. areaStyle: {
  45714. color: 'rgba(47,69,84,0.3)',
  45715. opacity: 0.3
  45716. }
  45717. },
  45718. borderColor: '#ddd', // border color of the box. For compatibility,
  45719. // if dataBackgroundColor is set, borderColor
  45720. // is ignored.
  45721. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  45722. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  45723. // handleIcon: 'path://M4.9,17.8c0-1.4,4.5-10.5,5.5-12.4c0-0.1,0.6-1.1,0.9-1.1c0.4,0,0.9,1,0.9,1.1c1.1,2.2,5.4,11,5.4,12.4v17.8c0,1.5-0.6,2.1-1.3,2.1H6.1c-0.7,0-1.3-0.6-1.3-2.1V17.8z',
  45724. /* eslint-disable */
  45725. handleIcon: 'M8.2,13.6V3.9H6.3v9.7H3.1v14.9h3.3v9.7h1.8v-9.7h3.3V13.6H8.2z M9.7,24.4H4.8v-1.4h4.9V24.4z M9.7,19.1H4.8v-1.4h4.9V19.1z',
  45726. /* eslint-enable */
  45727. // Percent of the slider height
  45728. handleSize: '100%',
  45729. handleStyle: {
  45730. color: '#a7b7cc'
  45731. },
  45732. labelPrecision: null,
  45733. labelFormatter: null,
  45734. showDetail: true,
  45735. showDataShadow: 'auto', // Default auto decision.
  45736. realtime: true,
  45737. zoomLock: false, // Whether disable zoom.
  45738. textStyle: {
  45739. color: '#333'
  45740. }
  45741. }
  45742. });
  45743. /*
  45744. * Licensed to the Apache Software Foundation (ASF) under one
  45745. * or more contributor license agreements. See the NOTICE file
  45746. * distributed with this work for additional information
  45747. * regarding copyright ownership. The ASF licenses this file
  45748. * to you under the Apache License, Version 2.0 (the
  45749. * "License"); you may not use this file except in compliance
  45750. * with the License. You may obtain a copy of the License at
  45751. *
  45752. * http://www.apache.org/licenses/LICENSE-2.0
  45753. *
  45754. * Unless required by applicable law or agreed to in writing,
  45755. * software distributed under the License is distributed on an
  45756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45757. * KIND, either express or implied. See the License for the
  45758. * specific language governing permissions and limitations
  45759. * under the License.
  45760. */
  45761. /**
  45762. * Calculate slider move result.
  45763. * Usage:
  45764. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  45765. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  45766. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  45767. *
  45768. * @param {number} delta Move length.
  45769. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  45770. * handleEnds will be modified in this method.
  45771. * @param {Array.<number>} extent handleEnds is restricted by extent.
  45772. * extent[0] should less or equals than extent[1].
  45773. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  45774. * where the input minSpan and maxSpan will not work.
  45775. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  45776. * If not set, handle0 and cross handle1. If set as a non-negative
  45777. * number (including `0`), handles will push each other when reaching
  45778. * the minSpan.
  45779. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  45780. * @return {Array.<number>} The input handleEnds.
  45781. */
  45782. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  45783. // Normalize firstly.
  45784. handleEnds[0] = restrict(handleEnds[0], extent);
  45785. handleEnds[1] = restrict(handleEnds[1], extent);
  45786. delta = delta || 0;
  45787. var extentSpan = extent[1] - extent[0];
  45788. // Notice maxSpan and minSpan can be null/undefined.
  45789. if (minSpan != null) {
  45790. minSpan = restrict(minSpan, [0, extentSpan]);
  45791. }
  45792. if (maxSpan != null) {
  45793. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  45794. }
  45795. if (handleIndex === 'all') {
  45796. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  45797. handleIndex = 0;
  45798. }
  45799. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  45800. handleEnds[handleIndex] += delta;
  45801. // Restrict in extent.
  45802. var extentMinSpan = minSpan || 0;
  45803. var realExtent = extent.slice();
  45804. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  45805. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  45806. // Expand span.
  45807. var currDistSign = getSpanSign(handleEnds, handleIndex);
  45808. if (minSpan != null && (
  45809. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  45810. )) {
  45811. // If minSpan exists, 'cross' is forbinden.
  45812. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  45813. }
  45814. // Shrink span.
  45815. var currDistSign = getSpanSign(handleEnds, handleIndex);
  45816. if (maxSpan != null && currDistSign.span > maxSpan) {
  45817. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  45818. }
  45819. return handleEnds;
  45820. };
  45821. function getSpanSign(handleEnds, handleIndex) {
  45822. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  45823. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  45824. // is at left of handleEnds[1] for non-cross case.
  45825. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  45826. }
  45827. function restrict(value, extend) {
  45828. return Math.min(extend[1], Math.max(extend[0], value));
  45829. }
  45830. /*
  45831. * Licensed to the Apache Software Foundation (ASF) under one
  45832. * or more contributor license agreements. See the NOTICE file
  45833. * distributed with this work for additional information
  45834. * regarding copyright ownership. The ASF licenses this file
  45835. * to you under the Apache License, Version 2.0 (the
  45836. * "License"); you may not use this file except in compliance
  45837. * with the License. You may obtain a copy of the License at
  45838. *
  45839. * http://www.apache.org/licenses/LICENSE-2.0
  45840. *
  45841. * Unless required by applicable law or agreed to in writing,
  45842. * software distributed under the License is distributed on an
  45843. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45844. * KIND, either express or implied. See the License for the
  45845. * specific language governing permissions and limitations
  45846. * under the License.
  45847. */
  45848. var Rect$1 = Rect;
  45849. var linearMap$1 = linearMap;
  45850. var asc$2 = asc;
  45851. var bind$3 = bind;
  45852. var each$14 = each$1;
  45853. // Constants
  45854. var DEFAULT_LOCATION_EDGE_GAP = 7;
  45855. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  45856. var DEFAULT_FILLER_SIZE = 30;
  45857. var HORIZONTAL = 'horizontal';
  45858. var VERTICAL = 'vertical';
  45859. var LABEL_GAP = 5;
  45860. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  45861. var SliderZoomView = DataZoomView.extend({
  45862. type: 'dataZoom.slider',
  45863. init: function (ecModel, api) {
  45864. /**
  45865. * @private
  45866. * @type {Object}
  45867. */
  45868. this._displayables = {};
  45869. /**
  45870. * @private
  45871. * @type {string}
  45872. */
  45873. this._orient;
  45874. /**
  45875. * [0, 100]
  45876. * @private
  45877. */
  45878. this._range;
  45879. /**
  45880. * [coord of the first handle, coord of the second handle]
  45881. * @private
  45882. */
  45883. this._handleEnds;
  45884. /**
  45885. * [length, thick]
  45886. * @private
  45887. * @type {Array.<number>}
  45888. */
  45889. this._size;
  45890. /**
  45891. * @private
  45892. * @type {number}
  45893. */
  45894. this._handleWidth;
  45895. /**
  45896. * @private
  45897. * @type {number}
  45898. */
  45899. this._handleHeight;
  45900. /**
  45901. * @private
  45902. */
  45903. this._location;
  45904. /**
  45905. * @private
  45906. */
  45907. this._dragging;
  45908. /**
  45909. * @private
  45910. */
  45911. this._dataShadowInfo;
  45912. this.api = api;
  45913. },
  45914. /**
  45915. * @override
  45916. */
  45917. render: function (dataZoomModel, ecModel, api, payload) {
  45918. SliderZoomView.superApply(this, 'render', arguments);
  45919. createOrUpdate(
  45920. this,
  45921. '_dispatchZoomAction',
  45922. this.dataZoomModel.get('throttle'),
  45923. 'fixRate'
  45924. );
  45925. this._orient = dataZoomModel.get('orient');
  45926. if (this.dataZoomModel.get('show') === false) {
  45927. this.group.removeAll();
  45928. return;
  45929. }
  45930. // Notice: this._resetInterval() should not be executed when payload.type
  45931. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  45932. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  45933. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  45934. this._buildView();
  45935. }
  45936. this._updateView();
  45937. },
  45938. /**
  45939. * @override
  45940. */
  45941. remove: function () {
  45942. SliderZoomView.superApply(this, 'remove', arguments);
  45943. clear(this, '_dispatchZoomAction');
  45944. },
  45945. /**
  45946. * @override
  45947. */
  45948. dispose: function () {
  45949. SliderZoomView.superApply(this, 'dispose', arguments);
  45950. clear(this, '_dispatchZoomAction');
  45951. },
  45952. _buildView: function () {
  45953. var thisGroup = this.group;
  45954. thisGroup.removeAll();
  45955. this._resetLocation();
  45956. this._resetInterval();
  45957. var barGroup = this._displayables.barGroup = new Group();
  45958. this._renderBackground();
  45959. this._renderHandle();
  45960. this._renderDataShadow();
  45961. thisGroup.add(barGroup);
  45962. this._positionGroup();
  45963. },
  45964. /**
  45965. * @private
  45966. */
  45967. _resetLocation: function () {
  45968. var dataZoomModel = this.dataZoomModel;
  45969. var api = this.api;
  45970. // If some of x/y/width/height are not specified,
  45971. // auto-adapt according to target grid.
  45972. var coordRect = this._findCoordRect();
  45973. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  45974. // Default align by coordinate system rect.
  45975. var positionInfo = this._orient === HORIZONTAL
  45976. ? {
  45977. // Why using 'right', because right should be used in vertical,
  45978. // and it is better to be consistent for dealing with position param merge.
  45979. right: ecSize.width - coordRect.x - coordRect.width,
  45980. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  45981. width: coordRect.width,
  45982. height: DEFAULT_FILLER_SIZE
  45983. }
  45984. : { // vertical
  45985. right: DEFAULT_LOCATION_EDGE_GAP,
  45986. top: coordRect.y,
  45987. width: DEFAULT_FILLER_SIZE,
  45988. height: coordRect.height
  45989. };
  45990. // Do not write back to option and replace value 'ph', because
  45991. // the 'ph' value should be recalculated when resize.
  45992. var layoutParams = getLayoutParams(dataZoomModel.option);
  45993. // Replace the placeholder value.
  45994. each$1(['right', 'top', 'width', 'height'], function (name) {
  45995. if (layoutParams[name] === 'ph') {
  45996. layoutParams[name] = positionInfo[name];
  45997. }
  45998. });
  45999. var layoutRect = getLayoutRect(
  46000. layoutParams,
  46001. ecSize,
  46002. dataZoomModel.padding
  46003. );
  46004. this._location = {x: layoutRect.x, y: layoutRect.y};
  46005. this._size = [layoutRect.width, layoutRect.height];
  46006. this._orient === VERTICAL && this._size.reverse();
  46007. },
  46008. /**
  46009. * @private
  46010. */
  46011. _positionGroup: function () {
  46012. var thisGroup = this.group;
  46013. var location = this._location;
  46014. var orient = this._orient;
  46015. // Just use the first axis to determine mapping.
  46016. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  46017. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  46018. var barGroup = this._displayables.barGroup;
  46019. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  46020. // Transform barGroup.
  46021. barGroup.attr(
  46022. (orient === HORIZONTAL && !inverse)
  46023. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  46024. : (orient === HORIZONTAL && inverse)
  46025. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  46026. : (orient === VERTICAL && !inverse)
  46027. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  46028. // Dont use Math.PI, considering shadow direction.
  46029. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  46030. );
  46031. // Position barGroup
  46032. var rect = thisGroup.getBoundingRect([barGroup]);
  46033. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  46034. },
  46035. /**
  46036. * @private
  46037. */
  46038. _getViewExtent: function () {
  46039. return [0, this._size[0]];
  46040. },
  46041. _renderBackground: function () {
  46042. var dataZoomModel = this.dataZoomModel;
  46043. var size = this._size;
  46044. var barGroup = this._displayables.barGroup;
  46045. barGroup.add(new Rect$1({
  46046. silent: true,
  46047. shape: {
  46048. x: 0, y: 0, width: size[0], height: size[1]
  46049. },
  46050. style: {
  46051. fill: dataZoomModel.get('backgroundColor')
  46052. },
  46053. z2: -40
  46054. }));
  46055. // Click panel, over shadow, below handles.
  46056. barGroup.add(new Rect$1({
  46057. shape: {
  46058. x: 0, y: 0, width: size[0], height: size[1]
  46059. },
  46060. style: {
  46061. fill: 'transparent'
  46062. },
  46063. z2: 0,
  46064. onclick: bind(this._onClickPanelClick, this)
  46065. }));
  46066. },
  46067. _renderDataShadow: function () {
  46068. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  46069. if (!info) {
  46070. return;
  46071. }
  46072. var size = this._size;
  46073. var seriesModel = info.series;
  46074. var data = seriesModel.getRawData();
  46075. var otherDim = seriesModel.getShadowDim
  46076. ? seriesModel.getShadowDim() // @see candlestick
  46077. : info.otherDim;
  46078. if (otherDim == null) {
  46079. return;
  46080. }
  46081. var otherDataExtent = data.getDataExtent(otherDim);
  46082. // Nice extent.
  46083. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  46084. otherDataExtent = [
  46085. otherDataExtent[0] - otherOffset,
  46086. otherDataExtent[1] + otherOffset
  46087. ];
  46088. var otherShadowExtent = [0, size[1]];
  46089. var thisShadowExtent = [0, size[0]];
  46090. var areaPoints = [[size[0], 0], [0, 0]];
  46091. var linePoints = [];
  46092. var step = thisShadowExtent[1] / (data.count() - 1);
  46093. var thisCoord = 0;
  46094. // Optimize for large data shadow
  46095. var stride = Math.round(data.count() / size[0]);
  46096. var lastIsEmpty;
  46097. data.each([otherDim], function (value, index) {
  46098. if (stride > 0 && (index % stride)) {
  46099. thisCoord += step;
  46100. return;
  46101. }
  46102. // FIXME
  46103. // Should consider axis.min/axis.max when drawing dataShadow.
  46104. // FIXME
  46105. // 应该使用统一的空判断?还是在list里进行空判断?
  46106. var isEmpty = value == null || isNaN(value) || value === '';
  46107. // See #4235.
  46108. var otherCoord = isEmpty
  46109. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  46110. // Attempt to draw data shadow precisely when there are empty value.
  46111. if (isEmpty && !lastIsEmpty && index) {
  46112. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  46113. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  46114. }
  46115. else if (!isEmpty && lastIsEmpty) {
  46116. areaPoints.push([thisCoord, 0]);
  46117. linePoints.push([thisCoord, 0]);
  46118. }
  46119. areaPoints.push([thisCoord, otherCoord]);
  46120. linePoints.push([thisCoord, otherCoord]);
  46121. thisCoord += step;
  46122. lastIsEmpty = isEmpty;
  46123. });
  46124. var dataZoomModel = this.dataZoomModel;
  46125. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  46126. this._displayables.barGroup.add(new Polygon({
  46127. shape: {points: areaPoints},
  46128. style: defaults(
  46129. {fill: dataZoomModel.get('dataBackgroundColor')},
  46130. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  46131. ),
  46132. silent: true,
  46133. z2: -20
  46134. }));
  46135. this._displayables.barGroup.add(new Polyline({
  46136. shape: {points: linePoints},
  46137. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  46138. silent: true,
  46139. z2: -19
  46140. }));
  46141. },
  46142. _prepareDataShadowInfo: function () {
  46143. var dataZoomModel = this.dataZoomModel;
  46144. var showDataShadow = dataZoomModel.get('showDataShadow');
  46145. if (showDataShadow === false) {
  46146. return;
  46147. }
  46148. // Find a representative series.
  46149. var result;
  46150. var ecModel = this.ecModel;
  46151. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  46152. var seriesModels = dataZoomModel
  46153. .getAxisProxy(dimNames.name, axisIndex)
  46154. .getTargetSeriesModels();
  46155. each$1(seriesModels, function (seriesModel) {
  46156. if (result) {
  46157. return;
  46158. }
  46159. if (showDataShadow !== true && indexOf(
  46160. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  46161. ) < 0
  46162. ) {
  46163. return;
  46164. }
  46165. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  46166. var otherDim = getOtherDim(dimNames.name);
  46167. var otherAxisInverse;
  46168. var coordSys = seriesModel.coordinateSystem;
  46169. if (otherDim != null && coordSys.getOtherAxis) {
  46170. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  46171. }
  46172. otherDim = seriesModel.getData().mapDimension(otherDim);
  46173. result = {
  46174. thisAxis: thisAxis,
  46175. series: seriesModel,
  46176. thisDim: dimNames.name,
  46177. otherDim: otherDim,
  46178. otherAxisInverse: otherAxisInverse
  46179. };
  46180. }, this);
  46181. }, this);
  46182. return result;
  46183. },
  46184. _renderHandle: function () {
  46185. var displaybles = this._displayables;
  46186. var handles = displaybles.handles = [];
  46187. var handleLabels = displaybles.handleLabels = [];
  46188. var barGroup = this._displayables.barGroup;
  46189. var size = this._size;
  46190. var dataZoomModel = this.dataZoomModel;
  46191. barGroup.add(displaybles.filler = new Rect$1({
  46192. draggable: true,
  46193. cursor: getCursor(this._orient),
  46194. drift: bind$3(this._onDragMove, this, 'all'),
  46195. onmousemove: function (e) {
  46196. // Fot mobile devicem, prevent screen slider on the button.
  46197. stop(e.event);
  46198. },
  46199. ondragstart: bind$3(this._showDataInfo, this, true),
  46200. ondragend: bind$3(this._onDragEnd, this),
  46201. onmouseover: bind$3(this._showDataInfo, this, true),
  46202. onmouseout: bind$3(this._showDataInfo, this, false),
  46203. style: {
  46204. fill: dataZoomModel.get('fillerColor'),
  46205. textPosition: 'inside'
  46206. }
  46207. }));
  46208. // Frame border.
  46209. barGroup.add(new Rect$1(subPixelOptimizeRect({
  46210. silent: true,
  46211. shape: {
  46212. x: 0,
  46213. y: 0,
  46214. width: size[0],
  46215. height: size[1]
  46216. },
  46217. style: {
  46218. stroke: dataZoomModel.get('dataBackgroundColor')
  46219. || dataZoomModel.get('borderColor'),
  46220. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  46221. fill: 'rgba(0,0,0,0)'
  46222. }
  46223. })));
  46224. each$14([0, 1], function (handleIndex) {
  46225. var path = createIcon(
  46226. dataZoomModel.get('handleIcon'),
  46227. {
  46228. cursor: getCursor(this._orient),
  46229. draggable: true,
  46230. drift: bind$3(this._onDragMove, this, handleIndex),
  46231. onmousemove: function (e) {
  46232. // Fot mobile devicem, prevent screen slider on the button.
  46233. stop(e.event);
  46234. },
  46235. ondragend: bind$3(this._onDragEnd, this),
  46236. onmouseover: bind$3(this._showDataInfo, this, true),
  46237. onmouseout: bind$3(this._showDataInfo, this, false)
  46238. },
  46239. {x: -1, y: 0, width: 2, height: 2}
  46240. );
  46241. var bRect = path.getBoundingRect();
  46242. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  46243. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  46244. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  46245. var handleColor = dataZoomModel.get('handleColor');
  46246. // Compatitable with previous version
  46247. if (handleColor != null) {
  46248. path.style.fill = handleColor;
  46249. }
  46250. barGroup.add(handles[handleIndex] = path);
  46251. var textStyleModel = dataZoomModel.textStyleModel;
  46252. this.group.add(
  46253. handleLabels[handleIndex] = new Text({
  46254. silent: true,
  46255. invisible: true,
  46256. style: {
  46257. x: 0, y: 0, text: '',
  46258. textVerticalAlign: 'middle',
  46259. textAlign: 'center',
  46260. textFill: textStyleModel.getTextColor(),
  46261. textFont: textStyleModel.getFont()
  46262. },
  46263. z2: 10
  46264. }));
  46265. }, this);
  46266. },
  46267. /**
  46268. * @private
  46269. */
  46270. _resetInterval: function () {
  46271. var range = this._range = this.dataZoomModel.getPercentRange();
  46272. var viewExtent = this._getViewExtent();
  46273. this._handleEnds = [
  46274. linearMap$1(range[0], [0, 100], viewExtent, true),
  46275. linearMap$1(range[1], [0, 100], viewExtent, true)
  46276. ];
  46277. },
  46278. /**
  46279. * @private
  46280. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  46281. * @param {number} delta
  46282. * @return {boolean} changed
  46283. */
  46284. _updateInterval: function (handleIndex, delta) {
  46285. var dataZoomModel = this.dataZoomModel;
  46286. var handleEnds = this._handleEnds;
  46287. var viewExtend = this._getViewExtent();
  46288. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  46289. var percentExtent = [0, 100];
  46290. sliderMove(
  46291. delta,
  46292. handleEnds,
  46293. viewExtend,
  46294. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  46295. minMaxSpan.minSpan != null
  46296. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  46297. minMaxSpan.maxSpan != null
  46298. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  46299. );
  46300. var lastRange = this._range;
  46301. var range = this._range = asc$2([
  46302. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  46303. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  46304. ]);
  46305. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  46306. },
  46307. /**
  46308. * @private
  46309. */
  46310. _updateView: function (nonRealtime) {
  46311. var displaybles = this._displayables;
  46312. var handleEnds = this._handleEnds;
  46313. var handleInterval = asc$2(handleEnds.slice());
  46314. var size = this._size;
  46315. each$14([0, 1], function (handleIndex) {
  46316. // Handles
  46317. var handle = displaybles.handles[handleIndex];
  46318. var handleHeight = this._handleHeight;
  46319. handle.attr({
  46320. scale: [handleHeight / 2, handleHeight / 2],
  46321. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  46322. });
  46323. }, this);
  46324. // Filler
  46325. displaybles.filler.setShape({
  46326. x: handleInterval[0],
  46327. y: 0,
  46328. width: handleInterval[1] - handleInterval[0],
  46329. height: size[1]
  46330. });
  46331. this._updateDataInfo(nonRealtime);
  46332. },
  46333. /**
  46334. * @private
  46335. */
  46336. _updateDataInfo: function (nonRealtime) {
  46337. var dataZoomModel = this.dataZoomModel;
  46338. var displaybles = this._displayables;
  46339. var handleLabels = displaybles.handleLabels;
  46340. var orient = this._orient;
  46341. var labelTexts = ['', ''];
  46342. // FIXME
  46343. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  46344. if (dataZoomModel.get('showDetail')) {
  46345. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  46346. if (axisProxy) {
  46347. var axis = axisProxy.getAxisModel().axis;
  46348. var range = this._range;
  46349. var dataInterval = nonRealtime
  46350. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  46351. ? axisProxy.calculateDataWindow({
  46352. start: range[0], end: range[1]
  46353. }).valueWindow
  46354. : axisProxy.getDataValueWindow();
  46355. labelTexts = [
  46356. this._formatLabel(dataInterval[0], axis),
  46357. this._formatLabel(dataInterval[1], axis)
  46358. ];
  46359. }
  46360. }
  46361. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  46362. setLabel.call(this, 0);
  46363. setLabel.call(this, 1);
  46364. function setLabel(handleIndex) {
  46365. // Label
  46366. // Text should not transform by barGroup.
  46367. // Ignore handlers transform
  46368. var barTransform = getTransform(
  46369. displaybles.handles[handleIndex].parent, this.group
  46370. );
  46371. var direction = transformDirection(
  46372. handleIndex === 0 ? 'right' : 'left', barTransform
  46373. );
  46374. var offset = this._handleWidth / 2 + LABEL_GAP;
  46375. var textPoint = applyTransform$1(
  46376. [
  46377. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  46378. this._size[1] / 2
  46379. ],
  46380. barTransform
  46381. );
  46382. handleLabels[handleIndex].setStyle({
  46383. x: textPoint[0],
  46384. y: textPoint[1],
  46385. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  46386. textAlign: orient === HORIZONTAL ? direction : 'center',
  46387. text: labelTexts[handleIndex]
  46388. });
  46389. }
  46390. },
  46391. /**
  46392. * @private
  46393. */
  46394. _formatLabel: function (value, axis) {
  46395. var dataZoomModel = this.dataZoomModel;
  46396. var labelFormatter = dataZoomModel.get('labelFormatter');
  46397. var labelPrecision = dataZoomModel.get('labelPrecision');
  46398. if (labelPrecision == null || labelPrecision === 'auto') {
  46399. labelPrecision = axis.getPixelPrecision();
  46400. }
  46401. var valueStr = (value == null || isNaN(value))
  46402. ? ''
  46403. // FIXME Glue code
  46404. : (axis.type === 'category' || axis.type === 'time')
  46405. ? axis.scale.getLabel(Math.round(value))
  46406. // param of toFixed should less then 20.
  46407. : value.toFixed(Math.min(labelPrecision, 20));
  46408. return isFunction$1(labelFormatter)
  46409. ? labelFormatter(value, valueStr)
  46410. : isString(labelFormatter)
  46411. ? labelFormatter.replace('{value}', valueStr)
  46412. : valueStr;
  46413. },
  46414. /**
  46415. * @private
  46416. * @param {boolean} showOrHide true: show, false: hide
  46417. */
  46418. _showDataInfo: function (showOrHide) {
  46419. // Always show when drgging.
  46420. showOrHide = this._dragging || showOrHide;
  46421. var handleLabels = this._displayables.handleLabels;
  46422. handleLabels[0].attr('invisible', !showOrHide);
  46423. handleLabels[1].attr('invisible', !showOrHide);
  46424. },
  46425. _onDragMove: function (handleIndex, dx, dy) {
  46426. this._dragging = true;
  46427. // Transform dx, dy to bar coordination.
  46428. var barTransform = this._displayables.barGroup.getLocalTransform();
  46429. var vertex = applyTransform$1([dx, dy], barTransform, true);
  46430. var changed = this._updateInterval(handleIndex, vertex[0]);
  46431. var realtime = this.dataZoomModel.get('realtime');
  46432. this._updateView(!realtime);
  46433. // Avoid dispatch dataZoom repeatly but range not changed,
  46434. // which cause bad visual effect when progressive enabled.
  46435. changed && realtime && this._dispatchZoomAction();
  46436. },
  46437. _onDragEnd: function () {
  46438. this._dragging = false;
  46439. this._showDataInfo(false);
  46440. // While in realtime mode and stream mode, dispatch action when
  46441. // drag end will cause the whole view rerender, which is unnecessary.
  46442. var realtime = this.dataZoomModel.get('realtime');
  46443. !realtime && this._dispatchZoomAction();
  46444. },
  46445. _onClickPanelClick: function (e) {
  46446. var size = this._size;
  46447. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  46448. if (localPoint[0] < 0 || localPoint[0] > size[0]
  46449. || localPoint[1] < 0 || localPoint[1] > size[1]
  46450. ) {
  46451. return;
  46452. }
  46453. var handleEnds = this._handleEnds;
  46454. var center = (handleEnds[0] + handleEnds[1]) / 2;
  46455. var changed = this._updateInterval('all', localPoint[0] - center);
  46456. this._updateView();
  46457. changed && this._dispatchZoomAction();
  46458. },
  46459. /**
  46460. * This action will be throttled.
  46461. * @private
  46462. */
  46463. _dispatchZoomAction: function () {
  46464. var range = this._range;
  46465. this.api.dispatchAction({
  46466. type: 'dataZoom',
  46467. from: this.uid,
  46468. dataZoomId: this.dataZoomModel.id,
  46469. start: range[0],
  46470. end: range[1]
  46471. });
  46472. },
  46473. /**
  46474. * @private
  46475. */
  46476. _findCoordRect: function () {
  46477. // Find the grid coresponding to the first axis referred by dataZoom.
  46478. var rect;
  46479. each$14(this.getTargetCoordInfo(), function (coordInfoList) {
  46480. if (!rect && coordInfoList.length) {
  46481. var coordSys = coordInfoList[0].model.coordinateSystem;
  46482. rect = coordSys.getRect && coordSys.getRect();
  46483. }
  46484. });
  46485. if (!rect) {
  46486. var width = this.api.getWidth();
  46487. var height = this.api.getHeight();
  46488. rect = {
  46489. x: width * 0.2,
  46490. y: height * 0.2,
  46491. width: width * 0.6,
  46492. height: height * 0.6
  46493. };
  46494. }
  46495. return rect;
  46496. }
  46497. });
  46498. function getOtherDim(thisDim) {
  46499. // FIXME
  46500. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  46501. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  46502. return map$$1[thisDim];
  46503. }
  46504. function getCursor(orient) {
  46505. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  46506. }
  46507. /*
  46508. * Licensed to the Apache Software Foundation (ASF) under one
  46509. * or more contributor license agreements. See the NOTICE file
  46510. * distributed with this work for additional information
  46511. * regarding copyright ownership. The ASF licenses this file
  46512. * to you under the Apache License, Version 2.0 (the
  46513. * "License"); you may not use this file except in compliance
  46514. * with the License. You may obtain a copy of the License at
  46515. *
  46516. * http://www.apache.org/licenses/LICENSE-2.0
  46517. *
  46518. * Unless required by applicable law or agreed to in writing,
  46519. * software distributed under the License is distributed on an
  46520. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46521. * KIND, either express or implied. See the License for the
  46522. * specific language governing permissions and limitations
  46523. * under the License.
  46524. */
  46525. DataZoomModel.extend({
  46526. type: 'dataZoom.inside',
  46527. /**
  46528. * @protected
  46529. */
  46530. defaultOption: {
  46531. disabled: false, // Whether disable this inside zoom.
  46532. zoomLock: false, // Whether disable zoom but only pan.
  46533. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  46534. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  46535. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  46536. preventDefaultMouseMove: true
  46537. }
  46538. });
  46539. /*
  46540. * Licensed to the Apache Software Foundation (ASF) under one
  46541. * or more contributor license agreements. See the NOTICE file
  46542. * distributed with this work for additional information
  46543. * regarding copyright ownership. The ASF licenses this file
  46544. * to you under the Apache License, Version 2.0 (the
  46545. * "License"); you may not use this file except in compliance
  46546. * with the License. You may obtain a copy of the License at
  46547. *
  46548. * http://www.apache.org/licenses/LICENSE-2.0
  46549. *
  46550. * Unless required by applicable law or agreed to in writing,
  46551. * software distributed under the License is distributed on an
  46552. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46553. * KIND, either express or implied. See the License for the
  46554. * specific language governing permissions and limitations
  46555. * under the License.
  46556. */
  46557. var ATTR$1 = '\0_ec_interaction_mutex';
  46558. function take(zr, resourceKey, userKey) {
  46559. var store = getStore(zr);
  46560. store[resourceKey] = userKey;
  46561. }
  46562. function release(zr, resourceKey, userKey) {
  46563. var store = getStore(zr);
  46564. var uKey = store[resourceKey];
  46565. if (uKey === userKey) {
  46566. store[resourceKey] = null;
  46567. }
  46568. }
  46569. function isTaken(zr, resourceKey) {
  46570. return !!getStore(zr)[resourceKey];
  46571. }
  46572. function getStore(zr) {
  46573. return zr[ATTR$1] || (zr[ATTR$1] = {});
  46574. }
  46575. /**
  46576. * payload: {
  46577. * type: 'takeGlobalCursor',
  46578. * key: 'dataZoomSelect', or 'brush', or ...,
  46579. * If no userKey, release global cursor.
  46580. * }
  46581. */
  46582. registerAction(
  46583. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  46584. function () {}
  46585. );
  46586. /*
  46587. * Licensed to the Apache Software Foundation (ASF) under one
  46588. * or more contributor license agreements. See the NOTICE file
  46589. * distributed with this work for additional information
  46590. * regarding copyright ownership. The ASF licenses this file
  46591. * to you under the Apache License, Version 2.0 (the
  46592. * "License"); you may not use this file except in compliance
  46593. * with the License. You may obtain a copy of the License at
  46594. *
  46595. * http://www.apache.org/licenses/LICENSE-2.0
  46596. *
  46597. * Unless required by applicable law or agreed to in writing,
  46598. * software distributed under the License is distributed on an
  46599. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46600. * KIND, either express or implied. See the License for the
  46601. * specific language governing permissions and limitations
  46602. * under the License.
  46603. */
  46604. /**
  46605. * @alias module:echarts/component/helper/RoamController
  46606. * @constructor
  46607. * @mixin {module:zrender/mixin/Eventful}
  46608. *
  46609. * @param {module:zrender/zrender~ZRender} zr
  46610. */
  46611. function RoamController(zr) {
  46612. /**
  46613. * @type {Function}
  46614. */
  46615. this.pointerChecker;
  46616. /**
  46617. * @type {module:zrender}
  46618. */
  46619. this._zr = zr;
  46620. /**
  46621. * @type {Object}
  46622. */
  46623. this._opt = {};
  46624. // Avoid two roamController bind the same handler
  46625. var bind$$1 = bind;
  46626. var mousedownHandler = bind$$1(mousedown, this);
  46627. var mousemoveHandler = bind$$1(mousemove, this);
  46628. var mouseupHandler = bind$$1(mouseup, this);
  46629. var mousewheelHandler = bind$$1(mousewheel, this);
  46630. var pinchHandler = bind$$1(pinch, this);
  46631. Eventful.call(this);
  46632. /**
  46633. * @param {Function} pointerChecker
  46634. * input: x, y
  46635. * output: boolean
  46636. */
  46637. this.setPointerChecker = function (pointerChecker) {
  46638. this.pointerChecker = pointerChecker;
  46639. };
  46640. /**
  46641. * Notice: only enable needed types. For example, if 'zoom'
  46642. * is not needed, 'zoom' should not be enabled, otherwise
  46643. * default mousewheel behaviour (scroll page) will be disabled.
  46644. *
  46645. * @param {boolean|string} [controlType=true] Specify the control type,
  46646. * which can be null/undefined or true/false
  46647. * or 'pan/move' or 'zoom'/'scale'
  46648. * @param {Object} [opt]
  46649. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  46650. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  46651. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  46652. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  46653. */
  46654. this.enable = function (controlType, opt) {
  46655. // Disable previous first
  46656. this.disable();
  46657. this._opt = defaults(clone(opt) || {}, {
  46658. zoomOnMouseWheel: true,
  46659. moveOnMouseMove: true,
  46660. // By default, wheel do not trigger move.
  46661. moveOnMouseWheel: false,
  46662. preventDefaultMouseMove: true
  46663. });
  46664. if (controlType == null) {
  46665. controlType = true;
  46666. }
  46667. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  46668. zr.on('mousedown', mousedownHandler);
  46669. zr.on('mousemove', mousemoveHandler);
  46670. zr.on('mouseup', mouseupHandler);
  46671. }
  46672. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  46673. zr.on('mousewheel', mousewheelHandler);
  46674. zr.on('pinch', pinchHandler);
  46675. }
  46676. };
  46677. this.disable = function () {
  46678. zr.off('mousedown', mousedownHandler);
  46679. zr.off('mousemove', mousemoveHandler);
  46680. zr.off('mouseup', mouseupHandler);
  46681. zr.off('mousewheel', mousewheelHandler);
  46682. zr.off('pinch', pinchHandler);
  46683. };
  46684. this.dispose = this.disable;
  46685. this.isDragging = function () {
  46686. return this._dragging;
  46687. };
  46688. this.isPinching = function () {
  46689. return this._pinching;
  46690. };
  46691. }
  46692. mixin(RoamController, Eventful);
  46693. function mousedown(e) {
  46694. if (isMiddleOrRightButtonOnMouseUpDown(e)
  46695. || (e.target && e.target.draggable)
  46696. ) {
  46697. return;
  46698. }
  46699. var x = e.offsetX;
  46700. var y = e.offsetY;
  46701. // Only check on mosedown, but not mousemove.
  46702. // Mouse can be out of target when mouse moving.
  46703. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  46704. this._x = x;
  46705. this._y = y;
  46706. this._dragging = true;
  46707. }
  46708. }
  46709. function mousemove(e) {
  46710. if (!this._dragging
  46711. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  46712. || e.gestureEvent === 'pinch'
  46713. || isTaken(this._zr, 'globalPan')
  46714. ) {
  46715. return;
  46716. }
  46717. var x = e.offsetX;
  46718. var y = e.offsetY;
  46719. var oldX = this._x;
  46720. var oldY = this._y;
  46721. var dx = x - oldX;
  46722. var dy = y - oldY;
  46723. this._x = x;
  46724. this._y = y;
  46725. this._opt.preventDefaultMouseMove && stop(e.event);
  46726. trigger(this, 'pan', 'moveOnMouseMove', e, {
  46727. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  46728. });
  46729. }
  46730. function mouseup(e) {
  46731. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  46732. this._dragging = false;
  46733. }
  46734. }
  46735. function mousewheel(e) {
  46736. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  46737. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  46738. var wheelDelta = e.wheelDelta;
  46739. var absWheelDeltaDelta = Math.abs(wheelDelta);
  46740. var originX = e.offsetX;
  46741. var originY = e.offsetY;
  46742. // wheelDelta maybe -0 in chrome mac.
  46743. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  46744. return;
  46745. }
  46746. // If both `shouldZoom` and `shouldMove` is true, trigger
  46747. // their event both, and the final behavior is determined
  46748. // by event listener themselves.
  46749. if (shouldZoom) {
  46750. // Convenience:
  46751. // Mac and VM Windows on Mac: scroll up: zoom out.
  46752. // Windows: scroll up: zoom in.
  46753. // FIXME: Should do more test in different environment.
  46754. // wheelDelta is too complicated in difference nvironment
  46755. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  46756. // although it has been normallized by zrender.
  46757. // wheelDelta of mouse wheel is bigger than touch pad.
  46758. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  46759. var scale = wheelDelta > 0 ? factor : 1 / factor;
  46760. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  46761. scale: scale, originX: originX, originY: originY
  46762. });
  46763. }
  46764. if (shouldMove) {
  46765. // FIXME: Should do more test in different environment.
  46766. var absDelta = Math.abs(wheelDelta);
  46767. // wheelDelta of mouse wheel is bigger than touch pad.
  46768. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  46769. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  46770. scrollDelta: scrollDelta, originX: originX, originY: originY
  46771. });
  46772. }
  46773. }
  46774. function pinch(e) {
  46775. if (isTaken(this._zr, 'globalPan')) {
  46776. return;
  46777. }
  46778. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  46779. checkPointerAndTrigger(this, 'zoom', null, e, {
  46780. scale: scale, originX: e.pinchX, originY: e.pinchY
  46781. });
  46782. }
  46783. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  46784. if (controller.pointerChecker
  46785. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  46786. ) {
  46787. // When mouse is out of roamController rect,
  46788. // default befavoius should not be be disabled, otherwise
  46789. // page sliding is disabled, contrary to expectation.
  46790. stop(e.event);
  46791. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  46792. }
  46793. }
  46794. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  46795. // Also provide behavior checker for event listener, for some case that
  46796. // multiple components share one listener.
  46797. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  46798. controller.trigger(eventName, contollerEvent);
  46799. }
  46800. // settings: {
  46801. // zoomOnMouseWheel
  46802. // moveOnMouseMove
  46803. // moveOnMouseWheel
  46804. // }
  46805. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  46806. function isAvailableBehavior(behaviorToCheck, e, settings) {
  46807. var setting = settings[behaviorToCheck];
  46808. return !behaviorToCheck || (
  46809. setting && (!isString(setting) || e.event[setting + 'Key'])
  46810. );
  46811. }
  46812. /*
  46813. * Licensed to the Apache Software Foundation (ASF) under one
  46814. * or more contributor license agreements. See the NOTICE file
  46815. * distributed with this work for additional information
  46816. * regarding copyright ownership. The ASF licenses this file
  46817. * to you under the Apache License, Version 2.0 (the
  46818. * "License"); you may not use this file except in compliance
  46819. * with the License. You may obtain a copy of the License at
  46820. *
  46821. * http://www.apache.org/licenses/LICENSE-2.0
  46822. *
  46823. * Unless required by applicable law or agreed to in writing,
  46824. * software distributed under the License is distributed on an
  46825. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46826. * KIND, either express or implied. See the License for the
  46827. * specific language governing permissions and limitations
  46828. * under the License.
  46829. */
  46830. // Only create one roam controller for each coordinate system.
  46831. // one roam controller might be refered by two inside data zoom
  46832. // components (for example, one for x and one for y). When user
  46833. // pan or zoom, only dispatch one action for those data zoom
  46834. // components.
  46835. var ATTR = '\0_ec_dataZoom_roams';
  46836. /**
  46837. * @public
  46838. * @param {module:echarts/ExtensionAPI} api
  46839. * @param {Object} dataZoomInfo
  46840. * @param {string} dataZoomInfo.coordId
  46841. * @param {Function} dataZoomInfo.containsPoint
  46842. * @param {Array.<string>} dataZoomInfo.allCoordIds
  46843. * @param {string} dataZoomInfo.dataZoomId
  46844. * @param {Object} dataZoomInfo.getRange
  46845. * @param {Function} dataZoomInfo.getRange.pan
  46846. * @param {Function} dataZoomInfo.getRange.zoom
  46847. * @param {Function} dataZoomInfo.getRange.scrollMove
  46848. * @param {boolean} dataZoomInfo.dataZoomModel
  46849. */
  46850. function register$1(api, dataZoomInfo) {
  46851. var store = giveStore(api);
  46852. var theDataZoomId = dataZoomInfo.dataZoomId;
  46853. var theCoordId = dataZoomInfo.coordId;
  46854. // Do clean when a dataZoom changes its target coordnate system.
  46855. // Avoid memory leak, dispose all not-used-registered.
  46856. each$1(store, function (record, coordId) {
  46857. var dataZoomInfos = record.dataZoomInfos;
  46858. if (dataZoomInfos[theDataZoomId]
  46859. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  46860. ) {
  46861. delete dataZoomInfos[theDataZoomId];
  46862. record.count--;
  46863. }
  46864. });
  46865. cleanStore(store);
  46866. var record = store[theCoordId];
  46867. // Create if needed.
  46868. if (!record) {
  46869. record = store[theCoordId] = {
  46870. coordId: theCoordId,
  46871. dataZoomInfos: {},
  46872. count: 0
  46873. };
  46874. record.controller = createController(api, record);
  46875. record.dispatchAction = curry(dispatchAction, api);
  46876. }
  46877. // Update reference of dataZoom.
  46878. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  46879. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  46880. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  46881. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  46882. // Consider resize, area should be always updated.
  46883. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  46884. // Update throttle.
  46885. createOrUpdate(
  46886. record,
  46887. 'dispatchAction',
  46888. dataZoomInfo.dataZoomModel.get('throttle', true),
  46889. 'fixRate'
  46890. );
  46891. }
  46892. /**
  46893. * @public
  46894. * @param {module:echarts/ExtensionAPI} api
  46895. * @param {string} dataZoomId
  46896. */
  46897. function unregister$1(api, dataZoomId) {
  46898. var store = giveStore(api);
  46899. each$1(store, function (record) {
  46900. record.controller.dispose();
  46901. var dataZoomInfos = record.dataZoomInfos;
  46902. if (dataZoomInfos[dataZoomId]) {
  46903. delete dataZoomInfos[dataZoomId];
  46904. record.count--;
  46905. }
  46906. });
  46907. cleanStore(store);
  46908. }
  46909. /**
  46910. * @public
  46911. */
  46912. function generateCoordId(coordModel) {
  46913. return coordModel.type + '\0_' + coordModel.id;
  46914. }
  46915. /**
  46916. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  46917. * @type {Array.<Object>}
  46918. */
  46919. function giveStore(api) {
  46920. // Mount store on zrender instance, so that we do not
  46921. // need to worry about dispose.
  46922. var zr = api.getZr();
  46923. return zr[ATTR] || (zr[ATTR] = {});
  46924. }
  46925. function createController(api, newRecord) {
  46926. var controller = new RoamController(api.getZr());
  46927. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  46928. controller.on(eventName, function (event) {
  46929. var batch = [];
  46930. each$1(newRecord.dataZoomInfos, function (info) {
  46931. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  46932. // moveOnMouseWheel, ...) enabled.
  46933. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  46934. return;
  46935. }
  46936. var method = (info.getRange || {})[eventName];
  46937. var range = method && method(newRecord.controller, event);
  46938. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  46939. dataZoomId: info.dataZoomId,
  46940. start: range[0],
  46941. end: range[1]
  46942. });
  46943. });
  46944. batch.length && newRecord.dispatchAction(batch);
  46945. });
  46946. });
  46947. return controller;
  46948. }
  46949. function cleanStore(store) {
  46950. each$1(store, function (record, coordId) {
  46951. if (!record.count) {
  46952. record.controller.dispose();
  46953. delete store[coordId];
  46954. }
  46955. });
  46956. }
  46957. /**
  46958. * This action will be throttled.
  46959. */
  46960. function dispatchAction(api, batch) {
  46961. api.dispatchAction({
  46962. type: 'dataZoom',
  46963. batch: batch
  46964. });
  46965. }
  46966. /**
  46967. * Merge roamController settings when multiple dataZooms share one roamController.
  46968. */
  46969. function mergeControllerParams(dataZoomInfos) {
  46970. var controlType;
  46971. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  46972. // as string, it is probably revert to reserved word by compress tool. See #7411.
  46973. var prefix = 'type_';
  46974. var typePriority = {
  46975. 'type_true': 2,
  46976. 'type_move': 1,
  46977. 'type_false': 0,
  46978. 'type_undefined': -1
  46979. };
  46980. var preventDefaultMouseMove = true;
  46981. each$1(dataZoomInfos, function (dataZoomInfo) {
  46982. var dataZoomModel = dataZoomInfo.dataZoomModel;
  46983. var oneType = dataZoomModel.get('disabled', true)
  46984. ? false
  46985. : dataZoomModel.get('zoomLock', true)
  46986. ? 'move'
  46987. : true;
  46988. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  46989. controlType = oneType;
  46990. }
  46991. // Prevent default move event by default. If one false, do not prevent. Otherwise
  46992. // users may be confused why it does not work when multiple insideZooms exist.
  46993. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  46994. });
  46995. return {
  46996. controlType: controlType,
  46997. opt: {
  46998. // RoamController will enable all of these functionalities,
  46999. // and the final behavior is determined by its event listener
  47000. // provided by each inside zoom.
  47001. zoomOnMouseWheel: true,
  47002. moveOnMouseMove: true,
  47003. moveOnMouseWheel: true,
  47004. preventDefaultMouseMove: !!preventDefaultMouseMove
  47005. }
  47006. };
  47007. }
  47008. /*
  47009. * Licensed to the Apache Software Foundation (ASF) under one
  47010. * or more contributor license agreements. See the NOTICE file
  47011. * distributed with this work for additional information
  47012. * regarding copyright ownership. The ASF licenses this file
  47013. * to you under the Apache License, Version 2.0 (the
  47014. * "License"); you may not use this file except in compliance
  47015. * with the License. You may obtain a copy of the License at
  47016. *
  47017. * http://www.apache.org/licenses/LICENSE-2.0
  47018. *
  47019. * Unless required by applicable law or agreed to in writing,
  47020. * software distributed under the License is distributed on an
  47021. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47022. * KIND, either express or implied. See the License for the
  47023. * specific language governing permissions and limitations
  47024. * under the License.
  47025. */
  47026. var bind$4 = bind;
  47027. var InsideZoomView = DataZoomView.extend({
  47028. type: 'dataZoom.inside',
  47029. /**
  47030. * @override
  47031. */
  47032. init: function (ecModel, api) {
  47033. /**
  47034. * 'throttle' is used in this.dispatchAction, so we save range
  47035. * to avoid missing some 'pan' info.
  47036. * @private
  47037. * @type {Array.<number>}
  47038. */
  47039. this._range;
  47040. },
  47041. /**
  47042. * @override
  47043. */
  47044. render: function (dataZoomModel, ecModel, api, payload) {
  47045. InsideZoomView.superApply(this, 'render', arguments);
  47046. // Hance the `throttle` util ensures to preserve command order,
  47047. // here simply updating range all the time will not cause missing
  47048. // any of the the roam change.
  47049. this._range = dataZoomModel.getPercentRange();
  47050. // Reset controllers.
  47051. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  47052. var allCoordIds = map(coordInfoList, function (coordInfo) {
  47053. return generateCoordId(coordInfo.model);
  47054. });
  47055. each$1(coordInfoList, function (coordInfo) {
  47056. var coordModel = coordInfo.model;
  47057. var getRange = {};
  47058. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  47059. getRange[eventName] = bind$4(roamHandlers[eventName], this, coordInfo, coordSysName);
  47060. }, this);
  47061. register$1(
  47062. api,
  47063. {
  47064. coordId: generateCoordId(coordModel),
  47065. allCoordIds: allCoordIds,
  47066. containsPoint: function (e, x, y) {
  47067. return coordModel.coordinateSystem.containPoint([x, y]);
  47068. },
  47069. dataZoomId: dataZoomModel.id,
  47070. dataZoomModel: dataZoomModel,
  47071. getRange: getRange
  47072. }
  47073. );
  47074. }, this);
  47075. }, this);
  47076. },
  47077. /**
  47078. * @override
  47079. */
  47080. dispose: function () {
  47081. unregister$1(this.api, this.dataZoomModel.id);
  47082. InsideZoomView.superApply(this, 'dispose', arguments);
  47083. this._range = null;
  47084. }
  47085. });
  47086. var roamHandlers = {
  47087. /**
  47088. * @this {module:echarts/component/dataZoom/InsideZoomView}
  47089. */
  47090. zoom: function (coordInfo, coordSysName, controller, e) {
  47091. var lastRange = this._range;
  47092. var range = lastRange.slice();
  47093. // Calculate transform by the first axis.
  47094. var axisModel = coordInfo.axisModels[0];
  47095. if (!axisModel) {
  47096. return;
  47097. }
  47098. var directionInfo = getDirectionInfo[coordSysName](
  47099. null, [e.originX, e.originY], axisModel, controller, coordInfo
  47100. );
  47101. var percentPoint = (
  47102. directionInfo.signal > 0
  47103. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  47104. : (directionInfo.pixel - directionInfo.pixelStart)
  47105. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  47106. var scale = Math.max(1 / e.scale, 0);
  47107. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  47108. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  47109. // Restrict range.
  47110. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  47111. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  47112. this._range = range;
  47113. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  47114. return range;
  47115. }
  47116. },
  47117. /**
  47118. * @this {module:echarts/component/dataZoom/InsideZoomView}
  47119. */
  47120. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  47121. var directionInfo = getDirectionInfo[coordSysName](
  47122. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  47123. );
  47124. return directionInfo.signal
  47125. * (range[1] - range[0])
  47126. * directionInfo.pixel / directionInfo.pixelLength;
  47127. }),
  47128. /**
  47129. * @this {module:echarts/component/dataZoom/InsideZoomView}
  47130. */
  47131. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  47132. var directionInfo = getDirectionInfo[coordSysName](
  47133. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  47134. );
  47135. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  47136. })
  47137. };
  47138. function makeMover(getPercentDelta) {
  47139. return function (coordInfo, coordSysName, controller, e) {
  47140. var lastRange = this._range;
  47141. var range = lastRange.slice();
  47142. // Calculate transform by the first axis.
  47143. var axisModel = coordInfo.axisModels[0];
  47144. if (!axisModel) {
  47145. return;
  47146. }
  47147. var percentDelta = getPercentDelta(
  47148. range, axisModel, coordInfo, coordSysName, controller, e
  47149. );
  47150. sliderMove(percentDelta, range, [0, 100], 'all');
  47151. this._range = range;
  47152. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  47153. return range;
  47154. }
  47155. };
  47156. }
  47157. var getDirectionInfo = {
  47158. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  47159. var axis = axisModel.axis;
  47160. var ret = {};
  47161. var rect = coordInfo.model.coordinateSystem.getRect();
  47162. oldPoint = oldPoint || [0, 0];
  47163. if (axis.dim === 'x') {
  47164. ret.pixel = newPoint[0] - oldPoint[0];
  47165. ret.pixelLength = rect.width;
  47166. ret.pixelStart = rect.x;
  47167. ret.signal = axis.inverse ? 1 : -1;
  47168. }
  47169. else { // axis.dim === 'y'
  47170. ret.pixel = newPoint[1] - oldPoint[1];
  47171. ret.pixelLength = rect.height;
  47172. ret.pixelStart = rect.y;
  47173. ret.signal = axis.inverse ? -1 : 1;
  47174. }
  47175. return ret;
  47176. },
  47177. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  47178. var axis = axisModel.axis;
  47179. var ret = {};
  47180. var polar = coordInfo.model.coordinateSystem;
  47181. var radiusExtent = polar.getRadiusAxis().getExtent();
  47182. var angleExtent = polar.getAngleAxis().getExtent();
  47183. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  47184. newPoint = polar.pointToCoord(newPoint);
  47185. if (axisModel.mainType === 'radiusAxis') {
  47186. ret.pixel = newPoint[0] - oldPoint[0];
  47187. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  47188. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  47189. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  47190. ret.pixelStart = radiusExtent[0];
  47191. ret.signal = axis.inverse ? 1 : -1;
  47192. }
  47193. else { // 'angleAxis'
  47194. ret.pixel = newPoint[1] - oldPoint[1];
  47195. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  47196. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  47197. ret.pixelLength = angleExtent[1] - angleExtent[0];
  47198. ret.pixelStart = angleExtent[0];
  47199. ret.signal = axis.inverse ? -1 : 1;
  47200. }
  47201. return ret;
  47202. },
  47203. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  47204. var axis = axisModel.axis;
  47205. var rect = coordInfo.model.coordinateSystem.getRect();
  47206. var ret = {};
  47207. oldPoint = oldPoint || [0, 0];
  47208. if (axis.orient === 'horizontal') {
  47209. ret.pixel = newPoint[0] - oldPoint[0];
  47210. ret.pixelLength = rect.width;
  47211. ret.pixelStart = rect.x;
  47212. ret.signal = axis.inverse ? 1 : -1;
  47213. }
  47214. else { // 'vertical'
  47215. ret.pixel = newPoint[1] - oldPoint[1];
  47216. ret.pixelLength = rect.height;
  47217. ret.pixelStart = rect.y;
  47218. ret.signal = axis.inverse ? -1 : 1;
  47219. }
  47220. return ret;
  47221. }
  47222. };
  47223. /*
  47224. * Licensed to the Apache Software Foundation (ASF) under one
  47225. * or more contributor license agreements. See the NOTICE file
  47226. * distributed with this work for additional information
  47227. * regarding copyright ownership. The ASF licenses this file
  47228. * to you under the Apache License, Version 2.0 (the
  47229. * "License"); you may not use this file except in compliance
  47230. * with the License. You may obtain a copy of the License at
  47231. *
  47232. * http://www.apache.org/licenses/LICENSE-2.0
  47233. *
  47234. * Unless required by applicable law or agreed to in writing,
  47235. * software distributed under the License is distributed on an
  47236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47237. * KIND, either express or implied. See the License for the
  47238. * specific language governing permissions and limitations
  47239. * under the License.
  47240. */
  47241. registerProcessor({
  47242. // `dataZoomProcessor` will only be performed in needed series. Consider if
  47243. // there is a line series and a pie series, it is better not to update the
  47244. // line series if only pie series is needed to be updated.
  47245. getTargetSeries: function (ecModel) {
  47246. var seriesModelMap = createHashMap();
  47247. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  47248. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  47249. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  47250. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  47251. seriesModelMap.set(seriesModel.uid, seriesModel);
  47252. });
  47253. });
  47254. });
  47255. return seriesModelMap;
  47256. },
  47257. modifyOutputEnd: true,
  47258. // Consider appendData, where filter should be performed. Because data process is
  47259. // in block mode currently, it is not need to worry about that the overallProgress
  47260. // execute every frame.
  47261. overallReset: function (ecModel, api) {
  47262. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  47263. // We calculate window and reset axis here but not in model
  47264. // init stage and not after action dispatch handler, because
  47265. // reset should be called after seriesData.restoreData.
  47266. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  47267. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  47268. });
  47269. // Caution: data zoom filtering is order sensitive when using
  47270. // percent range and no min/max/scale set on axis.
  47271. // For example, we have dataZoom definition:
  47272. // [
  47273. // {xAxisIndex: 0, start: 30, end: 70},
  47274. // {yAxisIndex: 0, start: 20, end: 80}
  47275. // ]
  47276. // In this case, [20, 80] of y-dataZoom should be based on data
  47277. // that have filtered by x-dataZoom using range of [30, 70],
  47278. // but should not be based on full raw data. Thus sliding
  47279. // x-dataZoom will change both ranges of xAxis and yAxis,
  47280. // while sliding y-dataZoom will only change the range of yAxis.
  47281. // So we should filter x-axis after reset x-axis immediately,
  47282. // and then reset y-axis and filter y-axis.
  47283. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  47284. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  47285. });
  47286. });
  47287. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  47288. // Fullfill all of the range props so that user
  47289. // is able to get them from chart.getOption().
  47290. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  47291. var percentRange = axisProxy.getDataPercentWindow();
  47292. var valueRange = axisProxy.getDataValueWindow();
  47293. dataZoomModel.setRawRange({
  47294. start: percentRange[0],
  47295. end: percentRange[1],
  47296. startValue: valueRange[0],
  47297. endValue: valueRange[1]
  47298. }, true);
  47299. });
  47300. }
  47301. });
  47302. /*
  47303. * Licensed to the Apache Software Foundation (ASF) under one
  47304. * or more contributor license agreements. See the NOTICE file
  47305. * distributed with this work for additional information
  47306. * regarding copyright ownership. The ASF licenses this file
  47307. * to you under the Apache License, Version 2.0 (the
  47308. * "License"); you may not use this file except in compliance
  47309. * with the License. You may obtain a copy of the License at
  47310. *
  47311. * http://www.apache.org/licenses/LICENSE-2.0
  47312. *
  47313. * Unless required by applicable law or agreed to in writing,
  47314. * software distributed under the License is distributed on an
  47315. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47316. * KIND, either express or implied. See the License for the
  47317. * specific language governing permissions and limitations
  47318. * under the License.
  47319. */
  47320. registerAction('dataZoom', function (payload, ecModel) {
  47321. var linkedNodesFinder = createLinkedNodesFinder(
  47322. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  47323. eachAxisDim$1,
  47324. function (model, dimNames) {
  47325. return model.get(dimNames.axisIndex);
  47326. }
  47327. );
  47328. var effectedModels = [];
  47329. ecModel.eachComponent(
  47330. {mainType: 'dataZoom', query: payload},
  47331. function (model, index) {
  47332. effectedModels.push.apply(
  47333. effectedModels, linkedNodesFinder(model).nodes
  47334. );
  47335. }
  47336. );
  47337. each$1(effectedModels, function (dataZoomModel, index) {
  47338. dataZoomModel.setRawRange({
  47339. start: payload.start,
  47340. end: payload.end,
  47341. startValue: payload.startValue,
  47342. endValue: payload.endValue
  47343. });
  47344. });
  47345. });
  47346. /*
  47347. * Licensed to the Apache Software Foundation (ASF) under one
  47348. * or more contributor license agreements. See the NOTICE file
  47349. * distributed with this work for additional information
  47350. * regarding copyright ownership. The ASF licenses this file
  47351. * to you under the Apache License, Version 2.0 (the
  47352. * "License"); you may not use this file except in compliance
  47353. * with the License. You may obtain a copy of the License at
  47354. *
  47355. * http://www.apache.org/licenses/LICENSE-2.0
  47356. *
  47357. * Unless required by applicable law or agreed to in writing,
  47358. * software distributed under the License is distributed on an
  47359. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47360. * KIND, either express or implied. See the License for the
  47361. * specific language governing permissions and limitations
  47362. * under the License.
  47363. */
  47364. /**
  47365. * DataZoom component entry
  47366. */
  47367. /*
  47368. * Licensed to the Apache Software Foundation (ASF) under one
  47369. * or more contributor license agreements. See the NOTICE file
  47370. * distributed with this work for additional information
  47371. * regarding copyright ownership. The ASF licenses this file
  47372. * to you under the Apache License, Version 2.0 (the
  47373. * "License"); you may not use this file except in compliance
  47374. * with the License. You may obtain a copy of the License at
  47375. *
  47376. * http://www.apache.org/licenses/LICENSE-2.0
  47377. *
  47378. * Unless required by applicable law or agreed to in writing,
  47379. * software distributed under the License is distributed on an
  47380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47381. * KIND, either express or implied. See the License for the
  47382. * specific language governing permissions and limitations
  47383. * under the License.
  47384. */
  47385. var features = {};
  47386. function register$2(name, ctor) {
  47387. features[name] = ctor;
  47388. }
  47389. function get$1(name) {
  47390. return features[name];
  47391. }
  47392. /*
  47393. * Licensed to the Apache Software Foundation (ASF) under one
  47394. * or more contributor license agreements. See the NOTICE file
  47395. * distributed with this work for additional information
  47396. * regarding copyright ownership. The ASF licenses this file
  47397. * to you under the Apache License, Version 2.0 (the
  47398. * "License"); you may not use this file except in compliance
  47399. * with the License. You may obtain a copy of the License at
  47400. *
  47401. * http://www.apache.org/licenses/LICENSE-2.0
  47402. *
  47403. * Unless required by applicable law or agreed to in writing,
  47404. * software distributed under the License is distributed on an
  47405. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47406. * KIND, either express or implied. See the License for the
  47407. * specific language governing permissions and limitations
  47408. * under the License.
  47409. */
  47410. var ToolboxModel = extendComponentModel({
  47411. type: 'toolbox',
  47412. layoutMode: {
  47413. type: 'box',
  47414. ignoreSize: true
  47415. },
  47416. optionUpdated: function () {
  47417. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  47418. each$1(this.option.feature, function (featureOpt, featureName) {
  47419. var Feature = get$1(featureName);
  47420. Feature && merge(featureOpt, Feature.defaultOption);
  47421. });
  47422. },
  47423. defaultOption: {
  47424. show: true,
  47425. z: 6,
  47426. zlevel: 0,
  47427. orient: 'horizontal',
  47428. left: 'right',
  47429. top: 'top',
  47430. // right
  47431. // bottom
  47432. backgroundColor: 'transparent',
  47433. borderColor: '#ccc',
  47434. borderRadius: 0,
  47435. borderWidth: 0,
  47436. padding: 5,
  47437. itemSize: 15,
  47438. itemGap: 8,
  47439. showTitle: true,
  47440. iconStyle: {
  47441. borderColor: '#666',
  47442. color: 'none'
  47443. },
  47444. emphasis: {
  47445. iconStyle: {
  47446. borderColor: '#3E98C5'
  47447. }
  47448. }
  47449. // textStyle: {},
  47450. // feature
  47451. }
  47452. });
  47453. /*
  47454. * Licensed to the Apache Software Foundation (ASF) under one
  47455. * or more contributor license agreements. See the NOTICE file
  47456. * distributed with this work for additional information
  47457. * regarding copyright ownership. The ASF licenses this file
  47458. * to you under the Apache License, Version 2.0 (the
  47459. * "License"); you may not use this file except in compliance
  47460. * with the License. You may obtain a copy of the License at
  47461. *
  47462. * http://www.apache.org/licenses/LICENSE-2.0
  47463. *
  47464. * Unless required by applicable law or agreed to in writing,
  47465. * software distributed under the License is distributed on an
  47466. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47467. * KIND, either express or implied. See the License for the
  47468. * specific language governing permissions and limitations
  47469. * under the License.
  47470. */
  47471. extendComponentView({
  47472. type: 'toolbox',
  47473. render: function (toolboxModel, ecModel, api, payload) {
  47474. var group = this.group;
  47475. group.removeAll();
  47476. if (!toolboxModel.get('show')) {
  47477. return;
  47478. }
  47479. var itemSize = +toolboxModel.get('itemSize');
  47480. var featureOpts = toolboxModel.get('feature') || {};
  47481. var features = this._features || (this._features = {});
  47482. var featureNames = [];
  47483. each$1(featureOpts, function (opt, name) {
  47484. featureNames.push(name);
  47485. });
  47486. (new DataDiffer(this._featureNames || [], featureNames))
  47487. .add(processFeature)
  47488. .update(processFeature)
  47489. .remove(curry(processFeature, null))
  47490. .execute();
  47491. // Keep for diff.
  47492. this._featureNames = featureNames;
  47493. function processFeature(newIndex, oldIndex) {
  47494. var featureName = featureNames[newIndex];
  47495. var oldName = featureNames[oldIndex];
  47496. var featureOpt = featureOpts[featureName];
  47497. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  47498. var feature;
  47499. if (featureName && !oldName) { // Create
  47500. if (isUserFeatureName(featureName)) {
  47501. feature = {
  47502. model: featureModel,
  47503. onclick: featureModel.option.onclick,
  47504. featureName: featureName
  47505. };
  47506. }
  47507. else {
  47508. var Feature = get$1(featureName);
  47509. if (!Feature) {
  47510. return;
  47511. }
  47512. feature = new Feature(featureModel, ecModel, api);
  47513. }
  47514. features[featureName] = feature;
  47515. }
  47516. else {
  47517. feature = features[oldName];
  47518. // If feature does not exsit.
  47519. if (!feature) {
  47520. return;
  47521. }
  47522. feature.model = featureModel;
  47523. feature.ecModel = ecModel;
  47524. feature.api = api;
  47525. }
  47526. if (!featureName && oldName) {
  47527. feature.dispose && feature.dispose(ecModel, api);
  47528. return;
  47529. }
  47530. if (!featureModel.get('show') || feature.unusable) {
  47531. feature.remove && feature.remove(ecModel, api);
  47532. return;
  47533. }
  47534. createIconPaths(featureModel, feature, featureName);
  47535. featureModel.setIconStatus = function (iconName, status) {
  47536. var option = this.option;
  47537. var iconPaths = this.iconPaths;
  47538. option.iconStatus = option.iconStatus || {};
  47539. option.iconStatus[iconName] = status;
  47540. // FIXME
  47541. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  47542. };
  47543. if (feature.render) {
  47544. feature.render(featureModel, ecModel, api, payload);
  47545. }
  47546. }
  47547. function createIconPaths(featureModel, feature, featureName) {
  47548. var iconStyleModel = featureModel.getModel('iconStyle');
  47549. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  47550. // If one feature has mutiple icon. they are orginaized as
  47551. // {
  47552. // icon: {
  47553. // foo: '',
  47554. // bar: ''
  47555. // },
  47556. // title: {
  47557. // foo: '',
  47558. // bar: ''
  47559. // }
  47560. // }
  47561. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  47562. var titles = featureModel.get('title') || {};
  47563. if (typeof icons === 'string') {
  47564. var icon = icons;
  47565. var title = titles;
  47566. icons = {};
  47567. titles = {};
  47568. icons[featureName] = icon;
  47569. titles[featureName] = title;
  47570. }
  47571. var iconPaths = featureModel.iconPaths = {};
  47572. each$1(icons, function (iconStr, iconName) {
  47573. var path = createIcon(
  47574. iconStr,
  47575. {},
  47576. {
  47577. x: -itemSize / 2,
  47578. y: -itemSize / 2,
  47579. width: itemSize,
  47580. height: itemSize
  47581. }
  47582. );
  47583. path.setStyle(iconStyleModel.getItemStyle());
  47584. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  47585. setHoverStyle(path);
  47586. if (toolboxModel.get('showTitle')) {
  47587. path.__title = titles[iconName];
  47588. path.on('mouseover', function () {
  47589. // Should not reuse above hoverStyle, which might be modified.
  47590. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  47591. path.setStyle({
  47592. text: titles[iconName],
  47593. textPosition: hoverStyle.textPosition || 'bottom',
  47594. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  47595. textAlign: hoverStyle.textAlign || 'center'
  47596. });
  47597. })
  47598. .on('mouseout', function () {
  47599. path.setStyle({
  47600. textFill: null
  47601. });
  47602. });
  47603. }
  47604. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  47605. group.add(path);
  47606. path.on('click', bind(
  47607. feature.onclick, feature, ecModel, api, iconName
  47608. ));
  47609. iconPaths[iconName] = path;
  47610. });
  47611. }
  47612. layout$2(group, toolboxModel, api);
  47613. // Render background after group is layout
  47614. // FIXME
  47615. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  47616. // Adjust icon title positions to avoid them out of screen
  47617. group.eachChild(function (icon) {
  47618. var titleText = icon.__title;
  47619. var hoverStyle = icon.hoverStyle;
  47620. // May be background element
  47621. if (hoverStyle && titleText) {
  47622. var rect = getBoundingRect(
  47623. titleText, makeFont(hoverStyle)
  47624. );
  47625. var offsetX = icon.position[0] + group.position[0];
  47626. var offsetY = icon.position[1] + group.position[1] + itemSize;
  47627. var needPutOnTop = false;
  47628. if (offsetY + rect.height > api.getHeight()) {
  47629. hoverStyle.textPosition = 'top';
  47630. needPutOnTop = true;
  47631. }
  47632. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  47633. if (offsetX + rect.width / 2 > api.getWidth()) {
  47634. hoverStyle.textPosition = ['100%', topOffset];
  47635. hoverStyle.textAlign = 'right';
  47636. }
  47637. else if (offsetX - rect.width / 2 < 0) {
  47638. hoverStyle.textPosition = [0, topOffset];
  47639. hoverStyle.textAlign = 'left';
  47640. }
  47641. }
  47642. });
  47643. },
  47644. updateView: function (toolboxModel, ecModel, api, payload) {
  47645. each$1(this._features, function (feature) {
  47646. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  47647. });
  47648. },
  47649. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  47650. // zrUtil.each(this._features, function (feature) {
  47651. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  47652. // });
  47653. // },
  47654. remove: function (ecModel, api) {
  47655. each$1(this._features, function (feature) {
  47656. feature.remove && feature.remove(ecModel, api);
  47657. });
  47658. this.group.removeAll();
  47659. },
  47660. dispose: function (ecModel, api) {
  47661. each$1(this._features, function (feature) {
  47662. feature.dispose && feature.dispose(ecModel, api);
  47663. });
  47664. }
  47665. });
  47666. function isUserFeatureName(featureName) {
  47667. return featureName.indexOf('my') === 0;
  47668. }
  47669. /*
  47670. * Licensed to the Apache Software Foundation (ASF) under one
  47671. * or more contributor license agreements. See the NOTICE file
  47672. * distributed with this work for additional information
  47673. * regarding copyright ownership. The ASF licenses this file
  47674. * to you under the Apache License, Version 2.0 (the
  47675. * "License"); you may not use this file except in compliance
  47676. * with the License. You may obtain a copy of the License at
  47677. *
  47678. * http://www.apache.org/licenses/LICENSE-2.0
  47679. *
  47680. * Unless required by applicable law or agreed to in writing,
  47681. * software distributed under the License is distributed on an
  47682. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47683. * KIND, either express or implied. See the License for the
  47684. * specific language governing permissions and limitations
  47685. * under the License.
  47686. */
  47687. /* global Uint8Array */
  47688. var saveAsImageLang = lang.toolbox.saveAsImage;
  47689. function SaveAsImage(model) {
  47690. this.model = model;
  47691. }
  47692. SaveAsImage.defaultOption = {
  47693. show: true,
  47694. icon: 'M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0',
  47695. title: saveAsImageLang.title,
  47696. type: 'png',
  47697. // Default use option.backgroundColor
  47698. // backgroundColor: '#fff',
  47699. name: '',
  47700. excludeComponents: ['toolbox'],
  47701. pixelRatio: 1,
  47702. lang: saveAsImageLang.lang.slice()
  47703. };
  47704. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  47705. var proto$2 = SaveAsImage.prototype;
  47706. proto$2.onclick = function (ecModel, api) {
  47707. var model = this.model;
  47708. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  47709. var $a = document.createElement('a');
  47710. var type = model.get('type', true) || 'png';
  47711. $a.download = title + '.' + type;
  47712. $a.target = '_blank';
  47713. var url = api.getConnectedDataURL({
  47714. type: type,
  47715. backgroundColor: model.get('backgroundColor', true)
  47716. || ecModel.get('backgroundColor') || '#fff',
  47717. excludeComponents: model.get('excludeComponents'),
  47718. pixelRatio: model.get('pixelRatio')
  47719. });
  47720. $a.href = url;
  47721. // Chrome and Firefox
  47722. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  47723. var evt = new MouseEvent('click', {
  47724. view: window,
  47725. bubbles: true,
  47726. cancelable: false
  47727. });
  47728. $a.dispatchEvent(evt);
  47729. }
  47730. // IE
  47731. else {
  47732. if (window.navigator.msSaveOrOpenBlob) {
  47733. var bstr = atob(url.split(',')[1]);
  47734. var n = bstr.length;
  47735. var u8arr = new Uint8Array(n);
  47736. while (n--) {
  47737. u8arr[n] = bstr.charCodeAt(n);
  47738. }
  47739. var blob = new Blob([u8arr]);
  47740. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  47741. }
  47742. else {
  47743. var lang$$1 = model.get('lang');
  47744. var html = ''
  47745. + '<body style="margin:0;">'
  47746. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  47747. + '</body>';
  47748. var tab = window.open();
  47749. tab.document.write(html);
  47750. }
  47751. }
  47752. };
  47753. register$2(
  47754. 'saveAsImage', SaveAsImage
  47755. );
  47756. /*
  47757. * Licensed to the Apache Software Foundation (ASF) under one
  47758. * or more contributor license agreements. See the NOTICE file
  47759. * distributed with this work for additional information
  47760. * regarding copyright ownership. The ASF licenses this file
  47761. * to you under the Apache License, Version 2.0 (the
  47762. * "License"); you may not use this file except in compliance
  47763. * with the License. You may obtain a copy of the License at
  47764. *
  47765. * http://www.apache.org/licenses/LICENSE-2.0
  47766. *
  47767. * Unless required by applicable law or agreed to in writing,
  47768. * software distributed under the License is distributed on an
  47769. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47770. * KIND, either express or implied. See the License for the
  47771. * specific language governing permissions and limitations
  47772. * under the License.
  47773. */
  47774. var magicTypeLang = lang.toolbox.magicType;
  47775. function MagicType(model) {
  47776. this.model = model;
  47777. }
  47778. MagicType.defaultOption = {
  47779. show: true,
  47780. type: [],
  47781. // Icon group
  47782. icon: {
  47783. /* eslint-disable */
  47784. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  47785. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  47786. stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z', // jshint ignore:line
  47787. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  47788. /* eslint-enable */
  47789. },
  47790. // `line`, `bar`, `stack`, `tiled`
  47791. title: clone(magicTypeLang.title),
  47792. option: {},
  47793. seriesIndex: {}
  47794. };
  47795. var proto$3 = MagicType.prototype;
  47796. proto$3.getIcons = function () {
  47797. var model = this.model;
  47798. var availableIcons = model.get('icon');
  47799. var icons = {};
  47800. each$1(model.get('type'), function (type) {
  47801. if (availableIcons[type]) {
  47802. icons[type] = availableIcons[type];
  47803. }
  47804. });
  47805. return icons;
  47806. };
  47807. var seriesOptGenreator = {
  47808. 'line': function (seriesType, seriesId, seriesModel, model) {
  47809. if (seriesType === 'bar') {
  47810. return merge({
  47811. id: seriesId,
  47812. type: 'line',
  47813. // Preserve data related option
  47814. data: seriesModel.get('data'),
  47815. stack: seriesModel.get('stack'),
  47816. markPoint: seriesModel.get('markPoint'),
  47817. markLine: seriesModel.get('markLine')
  47818. }, model.get('option.line') || {}, true);
  47819. }
  47820. },
  47821. 'bar': function (seriesType, seriesId, seriesModel, model) {
  47822. if (seriesType === 'line') {
  47823. return merge({
  47824. id: seriesId,
  47825. type: 'bar',
  47826. // Preserve data related option
  47827. data: seriesModel.get('data'),
  47828. stack: seriesModel.get('stack'),
  47829. markPoint: seriesModel.get('markPoint'),
  47830. markLine: seriesModel.get('markLine')
  47831. }, model.get('option.bar') || {}, true);
  47832. }
  47833. },
  47834. 'stack': function (seriesType, seriesId, seriesModel, model) {
  47835. if (seriesType === 'line' || seriesType === 'bar') {
  47836. return merge({
  47837. id: seriesId,
  47838. stack: '__ec_magicType_stack__'
  47839. }, model.get('option.stack') || {}, true);
  47840. }
  47841. },
  47842. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  47843. if (seriesType === 'line' || seriesType === 'bar') {
  47844. return merge({
  47845. id: seriesId,
  47846. stack: ''
  47847. }, model.get('option.tiled') || {}, true);
  47848. }
  47849. }
  47850. };
  47851. var radioTypes = [
  47852. ['line', 'bar'],
  47853. ['stack', 'tiled']
  47854. ];
  47855. proto$3.onclick = function (ecModel, api, type) {
  47856. var model = this.model;
  47857. var seriesIndex = model.get('seriesIndex.' + type);
  47858. // Not supported magicType
  47859. if (!seriesOptGenreator[type]) {
  47860. return;
  47861. }
  47862. var newOption = {
  47863. series: []
  47864. };
  47865. var generateNewSeriesTypes = function (seriesModel) {
  47866. var seriesType = seriesModel.subType;
  47867. var seriesId = seriesModel.id;
  47868. var newSeriesOpt = seriesOptGenreator[type](
  47869. seriesType, seriesId, seriesModel, model
  47870. );
  47871. if (newSeriesOpt) {
  47872. // PENDING If merge original option?
  47873. defaults(newSeriesOpt, seriesModel.option);
  47874. newOption.series.push(newSeriesOpt);
  47875. }
  47876. // Modify boundaryGap
  47877. var coordSys = seriesModel.coordinateSystem;
  47878. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  47879. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  47880. if (categoryAxis) {
  47881. var axisDim = categoryAxis.dim;
  47882. var axisType = axisDim + 'Axis';
  47883. var axisModel = ecModel.queryComponents({
  47884. mainType: axisType,
  47885. index: seriesModel.get(name + 'Index'),
  47886. id: seriesModel.get(name + 'Id')
  47887. })[0];
  47888. var axisIndex = axisModel.componentIndex;
  47889. newOption[axisType] = newOption[axisType] || [];
  47890. for (var i = 0; i <= axisIndex; i++) {
  47891. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  47892. }
  47893. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  47894. }
  47895. }
  47896. };
  47897. each$1(radioTypes, function (radio) {
  47898. if (indexOf(radio, type) >= 0) {
  47899. each$1(radio, function (item) {
  47900. model.setIconStatus(item, 'normal');
  47901. });
  47902. }
  47903. });
  47904. model.setIconStatus(type, 'emphasis');
  47905. ecModel.eachComponent(
  47906. {
  47907. mainType: 'series',
  47908. query: seriesIndex == null ? null : {
  47909. seriesIndex: seriesIndex
  47910. }
  47911. }, generateNewSeriesTypes
  47912. );
  47913. api.dispatchAction({
  47914. type: 'changeMagicType',
  47915. currentType: type,
  47916. newOption: newOption
  47917. });
  47918. };
  47919. registerAction({
  47920. type: 'changeMagicType',
  47921. event: 'magicTypeChanged',
  47922. update: 'prepareAndUpdate'
  47923. }, function (payload, ecModel) {
  47924. ecModel.mergeOption(payload.newOption);
  47925. });
  47926. register$2('magicType', MagicType);
  47927. /*
  47928. * Licensed to the Apache Software Foundation (ASF) under one
  47929. * or more contributor license agreements. See the NOTICE file
  47930. * distributed with this work for additional information
  47931. * regarding copyright ownership. The ASF licenses this file
  47932. * to you under the Apache License, Version 2.0 (the
  47933. * "License"); you may not use this file except in compliance
  47934. * with the License. You may obtain a copy of the License at
  47935. *
  47936. * http://www.apache.org/licenses/LICENSE-2.0
  47937. *
  47938. * Unless required by applicable law or agreed to in writing,
  47939. * software distributed under the License is distributed on an
  47940. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47941. * KIND, either express or implied. See the License for the
  47942. * specific language governing permissions and limitations
  47943. * under the License.
  47944. */
  47945. var dataViewLang = lang.toolbox.dataView;
  47946. var BLOCK_SPLITER = new Array(60).join('-');
  47947. var ITEM_SPLITER = '\t';
  47948. /**
  47949. * Group series into two types
  47950. * 1. on category axis, like line, bar
  47951. * 2. others, like scatter, pie
  47952. * @param {module:echarts/model/Global} ecModel
  47953. * @return {Object}
  47954. * @inner
  47955. */
  47956. function groupSeries(ecModel) {
  47957. var seriesGroupByCategoryAxis = {};
  47958. var otherSeries = [];
  47959. var meta = [];
  47960. ecModel.eachRawSeries(function (seriesModel) {
  47961. var coordSys = seriesModel.coordinateSystem;
  47962. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  47963. var baseAxis = coordSys.getBaseAxis();
  47964. if (baseAxis.type === 'category') {
  47965. var key = baseAxis.dim + '_' + baseAxis.index;
  47966. if (!seriesGroupByCategoryAxis[key]) {
  47967. seriesGroupByCategoryAxis[key] = {
  47968. categoryAxis: baseAxis,
  47969. valueAxis: coordSys.getOtherAxis(baseAxis),
  47970. series: []
  47971. };
  47972. meta.push({
  47973. axisDim: baseAxis.dim,
  47974. axisIndex: baseAxis.index
  47975. });
  47976. }
  47977. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  47978. }
  47979. else {
  47980. otherSeries.push(seriesModel);
  47981. }
  47982. }
  47983. else {
  47984. otherSeries.push(seriesModel);
  47985. }
  47986. });
  47987. return {
  47988. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  47989. other: otherSeries,
  47990. meta: meta
  47991. };
  47992. }
  47993. /**
  47994. * Assemble content of series on cateogory axis
  47995. * @param {Array.<module:echarts/model/Series>} series
  47996. * @return {string}
  47997. * @inner
  47998. */
  47999. function assembleSeriesWithCategoryAxis(series) {
  48000. var tables = [];
  48001. each$1(series, function (group, key) {
  48002. var categoryAxis = group.categoryAxis;
  48003. var valueAxis = group.valueAxis;
  48004. var valueAxisDim = valueAxis.dim;
  48005. var headers = [' '].concat(map(group.series, function (series) {
  48006. return series.name;
  48007. }));
  48008. var columns = [categoryAxis.model.getCategories()];
  48009. each$1(group.series, function (series) {
  48010. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  48011. return val;
  48012. }));
  48013. });
  48014. // Assemble table content
  48015. var lines = [headers.join(ITEM_SPLITER)];
  48016. for (var i = 0; i < columns[0].length; i++) {
  48017. var items = [];
  48018. for (var j = 0; j < columns.length; j++) {
  48019. items.push(columns[j][i]);
  48020. }
  48021. lines.push(items.join(ITEM_SPLITER));
  48022. }
  48023. tables.push(lines.join('\n'));
  48024. });
  48025. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  48026. }
  48027. /**
  48028. * Assemble content of other series
  48029. * @param {Array.<module:echarts/model/Series>} series
  48030. * @return {string}
  48031. * @inner
  48032. */
  48033. function assembleOtherSeries(series) {
  48034. return map(series, function (series) {
  48035. var data = series.getRawData();
  48036. var lines = [series.name];
  48037. var vals = [];
  48038. data.each(data.dimensions, function () {
  48039. var argLen = arguments.length;
  48040. var dataIndex = arguments[argLen - 1];
  48041. var name = data.getName(dataIndex);
  48042. for (var i = 0; i < argLen - 1; i++) {
  48043. vals[i] = arguments[i];
  48044. }
  48045. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  48046. });
  48047. return lines.join('\n');
  48048. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  48049. }
  48050. /**
  48051. * @param {module:echarts/model/Global}
  48052. * @return {Object}
  48053. * @inner
  48054. */
  48055. function getContentFromModel(ecModel) {
  48056. var result = groupSeries(ecModel);
  48057. return {
  48058. value: filter([
  48059. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  48060. assembleOtherSeries(result.other)
  48061. ], function (str) {
  48062. return str.replace(/[\n\t\s]/g, '');
  48063. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  48064. meta: result.meta
  48065. };
  48066. }
  48067. function trim$1(str) {
  48068. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  48069. }
  48070. /**
  48071. * If a block is tsv format
  48072. */
  48073. function isTSVFormat(block) {
  48074. // Simple method to find out if a block is tsv format
  48075. var firstLine = block.slice(0, block.indexOf('\n'));
  48076. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  48077. return true;
  48078. }
  48079. }
  48080. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  48081. /**
  48082. * @param {string} tsv
  48083. * @return {Object}
  48084. */
  48085. function parseTSVContents(tsv) {
  48086. var tsvLines = tsv.split(/\n+/g);
  48087. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  48088. var categories = [];
  48089. var series = map(headers, function (header) {
  48090. return {
  48091. name: header,
  48092. data: []
  48093. };
  48094. });
  48095. for (var i = 0; i < tsvLines.length; i++) {
  48096. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  48097. categories.push(items.shift());
  48098. for (var j = 0; j < items.length; j++) {
  48099. series[j] && (series[j].data[i] = items[j]);
  48100. }
  48101. }
  48102. return {
  48103. series: series,
  48104. categories: categories
  48105. };
  48106. }
  48107. /**
  48108. * @param {string} str
  48109. * @return {Array.<Object>}
  48110. * @inner
  48111. */
  48112. function parseListContents(str) {
  48113. var lines = str.split(/\n+/g);
  48114. var seriesName = trim$1(lines.shift());
  48115. var data = [];
  48116. for (var i = 0; i < lines.length; i++) {
  48117. var items = trim$1(lines[i]).split(itemSplitRegex);
  48118. var name = '';
  48119. var value;
  48120. var hasName = false;
  48121. if (isNaN(items[0])) { // First item is name
  48122. hasName = true;
  48123. name = items[0];
  48124. items = items.slice(1);
  48125. data[i] = {
  48126. name: name,
  48127. value: []
  48128. };
  48129. value = data[i].value;
  48130. }
  48131. else {
  48132. value = data[i] = [];
  48133. }
  48134. for (var j = 0; j < items.length; j++) {
  48135. value.push(+items[j]);
  48136. }
  48137. if (value.length === 1) {
  48138. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  48139. }
  48140. }
  48141. return {
  48142. name: seriesName,
  48143. data: data
  48144. };
  48145. }
  48146. /**
  48147. * @param {string} str
  48148. * @param {Array.<Object>} blockMetaList
  48149. * @return {Object}
  48150. * @inner
  48151. */
  48152. function parseContents(str, blockMetaList) {
  48153. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  48154. var newOption = {
  48155. series: []
  48156. };
  48157. each$1(blocks, function (block, idx) {
  48158. if (isTSVFormat(block)) {
  48159. var result = parseTSVContents(block);
  48160. var blockMeta = blockMetaList[idx];
  48161. var axisKey = blockMeta.axisDim + 'Axis';
  48162. if (blockMeta) {
  48163. newOption[axisKey] = newOption[axisKey] || [];
  48164. newOption[axisKey][blockMeta.axisIndex] = {
  48165. data: result.categories
  48166. };
  48167. newOption.series = newOption.series.concat(result.series);
  48168. }
  48169. }
  48170. else {
  48171. var result = parseListContents(block);
  48172. newOption.series.push(result);
  48173. }
  48174. });
  48175. return newOption;
  48176. }
  48177. /**
  48178. * @alias {module:echarts/component/toolbox/feature/DataView}
  48179. * @constructor
  48180. * @param {module:echarts/model/Model} model
  48181. */
  48182. function DataView(model) {
  48183. this._dom = null;
  48184. this.model = model;
  48185. }
  48186. DataView.defaultOption = {
  48187. show: true,
  48188. readOnly: false,
  48189. optionToContent: null,
  48190. contentToOption: null,
  48191. icon: 'M17.5,17.3H33 M17.5,17.3H33 M45.4,29.5h-28 M11.5,2v56H51V14.8L38.4,2H11.5z M38.4,2.2v12.7H51 M45.4,41.7h-28',
  48192. title: clone(dataViewLang.title),
  48193. lang: clone(dataViewLang.lang),
  48194. backgroundColor: '#fff',
  48195. textColor: '#000',
  48196. textareaColor: '#fff',
  48197. textareaBorderColor: '#333',
  48198. buttonColor: '#c23531',
  48199. buttonTextColor: '#fff'
  48200. };
  48201. DataView.prototype.onclick = function (ecModel, api) {
  48202. var container = api.getDom();
  48203. var model = this.model;
  48204. if (this._dom) {
  48205. container.removeChild(this._dom);
  48206. }
  48207. var root = document.createElement('div');
  48208. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  48209. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  48210. // Create elements
  48211. var header = document.createElement('h4');
  48212. var lang$$1 = model.get('lang') || [];
  48213. header.innerHTML = lang$$1[0] || model.get('title');
  48214. header.style.cssText = 'margin: 10px 20px;';
  48215. header.style.color = model.get('textColor');
  48216. var viewMain = document.createElement('div');
  48217. var textarea = document.createElement('textarea');
  48218. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  48219. var optionToContent = model.get('optionToContent');
  48220. var contentToOption = model.get('contentToOption');
  48221. var result = getContentFromModel(ecModel);
  48222. if (typeof optionToContent === 'function') {
  48223. var htmlOrDom = optionToContent(api.getOption());
  48224. if (typeof htmlOrDom === 'string') {
  48225. viewMain.innerHTML = htmlOrDom;
  48226. }
  48227. else if (isDom(htmlOrDom)) {
  48228. viewMain.appendChild(htmlOrDom);
  48229. }
  48230. }
  48231. else {
  48232. // Use default textarea
  48233. viewMain.appendChild(textarea);
  48234. textarea.readOnly = model.get('readOnly');
  48235. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  48236. textarea.style.color = model.get('textColor');
  48237. textarea.style.borderColor = model.get('textareaBorderColor');
  48238. textarea.style.backgroundColor = model.get('textareaColor');
  48239. textarea.value = result.value;
  48240. }
  48241. var blockMetaList = result.meta;
  48242. var buttonContainer = document.createElement('div');
  48243. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  48244. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  48245. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  48246. var closeButton = document.createElement('div');
  48247. var refreshButton = document.createElement('div');
  48248. buttonStyle += ';background-color:' + model.get('buttonColor');
  48249. buttonStyle += ';color:' + model.get('buttonTextColor');
  48250. var self = this;
  48251. function close() {
  48252. container.removeChild(root);
  48253. self._dom = null;
  48254. }
  48255. addEventListener(closeButton, 'click', close);
  48256. addEventListener(refreshButton, 'click', function () {
  48257. var newOption;
  48258. try {
  48259. if (typeof contentToOption === 'function') {
  48260. newOption = contentToOption(viewMain, api.getOption());
  48261. }
  48262. else {
  48263. newOption = parseContents(textarea.value, blockMetaList);
  48264. }
  48265. }
  48266. catch (e) {
  48267. close();
  48268. throw new Error('Data view format error ' + e);
  48269. }
  48270. if (newOption) {
  48271. api.dispatchAction({
  48272. type: 'changeDataView',
  48273. newOption: newOption
  48274. });
  48275. }
  48276. close();
  48277. });
  48278. closeButton.innerHTML = lang$$1[1];
  48279. refreshButton.innerHTML = lang$$1[2];
  48280. refreshButton.style.cssText = buttonStyle;
  48281. closeButton.style.cssText = buttonStyle;
  48282. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  48283. buttonContainer.appendChild(closeButton);
  48284. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  48285. addEventListener(textarea, 'keydown', function (e) {
  48286. if ((e.keyCode || e.which) === 9) {
  48287. // get caret position/selection
  48288. var val = this.value;
  48289. var start = this.selectionStart;
  48290. var end = this.selectionEnd;
  48291. // set textarea value to: text before caret + tab + text after caret
  48292. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  48293. // put caret at right position again
  48294. this.selectionStart = this.selectionEnd = start + 1;
  48295. // prevent the focus lose
  48296. stop(e);
  48297. }
  48298. });
  48299. root.appendChild(header);
  48300. root.appendChild(viewMain);
  48301. root.appendChild(buttonContainer);
  48302. viewMain.style.height = (container.clientHeight - 80) + 'px';
  48303. container.appendChild(root);
  48304. this._dom = root;
  48305. };
  48306. DataView.prototype.remove = function (ecModel, api) {
  48307. this._dom && api.getDom().removeChild(this._dom);
  48308. };
  48309. DataView.prototype.dispose = function (ecModel, api) {
  48310. this.remove(ecModel, api);
  48311. };
  48312. /**
  48313. * @inner
  48314. */
  48315. function tryMergeDataOption(newData, originalData) {
  48316. return map(newData, function (newVal, idx) {
  48317. var original = originalData && originalData[idx];
  48318. if (isObject$1(original) && !isArray(original)) {
  48319. if (isObject$1(newVal) && !isArray(newVal)) {
  48320. newVal = newVal.value;
  48321. }
  48322. // Original data has option
  48323. return defaults({
  48324. value: newVal
  48325. }, original);
  48326. }
  48327. else {
  48328. return newVal;
  48329. }
  48330. });
  48331. }
  48332. register$2('dataView', DataView);
  48333. registerAction({
  48334. type: 'changeDataView',
  48335. event: 'dataViewChanged',
  48336. update: 'prepareAndUpdate'
  48337. }, function (payload, ecModel) {
  48338. var newSeriesOptList = [];
  48339. each$1(payload.newOption.series, function (seriesOpt) {
  48340. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  48341. if (!seriesModel) {
  48342. // New created series
  48343. // Geuss the series type
  48344. newSeriesOptList.push(extend({
  48345. // Default is scatter
  48346. type: 'scatter'
  48347. }, seriesOpt));
  48348. }
  48349. else {
  48350. var originalData = seriesModel.get('data');
  48351. newSeriesOptList.push({
  48352. name: seriesOpt.name,
  48353. data: tryMergeDataOption(seriesOpt.data, originalData)
  48354. });
  48355. }
  48356. });
  48357. ecModel.mergeOption(defaults({
  48358. series: newSeriesOptList
  48359. }, payload.newOption));
  48360. });
  48361. /*
  48362. * Licensed to the Apache Software Foundation (ASF) under one
  48363. * or more contributor license agreements. See the NOTICE file
  48364. * distributed with this work for additional information
  48365. * regarding copyright ownership. The ASF licenses this file
  48366. * to you under the Apache License, Version 2.0 (the
  48367. * "License"); you may not use this file except in compliance
  48368. * with the License. You may obtain a copy of the License at
  48369. *
  48370. * http://www.apache.org/licenses/LICENSE-2.0
  48371. *
  48372. * Unless required by applicable law or agreed to in writing,
  48373. * software distributed under the License is distributed on an
  48374. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48375. * KIND, either express or implied. See the License for the
  48376. * specific language governing permissions and limitations
  48377. * under the License.
  48378. */
  48379. var curry$5 = curry;
  48380. var each$16 = each$1;
  48381. var map$2 = map;
  48382. var mathMin$4 = Math.min;
  48383. var mathMax$4 = Math.max;
  48384. var mathPow$2 = Math.pow;
  48385. var COVER_Z = 10000;
  48386. var UNSELECT_THRESHOLD = 6;
  48387. var MIN_RESIZE_LINE_WIDTH = 6;
  48388. var MUTEX_RESOURCE_KEY = 'globalPan';
  48389. var DIRECTION_MAP = {
  48390. w: [0, 0],
  48391. e: [0, 1],
  48392. n: [1, 0],
  48393. s: [1, 1]
  48394. };
  48395. var CURSOR_MAP = {
  48396. w: 'ew',
  48397. e: 'ew',
  48398. n: 'ns',
  48399. s: 'ns',
  48400. ne: 'nesw',
  48401. sw: 'nesw',
  48402. nw: 'nwse',
  48403. se: 'nwse'
  48404. };
  48405. var DEFAULT_BRUSH_OPT = {
  48406. brushStyle: {
  48407. lineWidth: 2,
  48408. stroke: 'rgba(0,0,0,0.3)',
  48409. fill: 'rgba(0,0,0,0.1)'
  48410. },
  48411. transformable: true,
  48412. brushMode: 'single',
  48413. removeOnClick: false
  48414. };
  48415. var baseUID = 0;
  48416. /**
  48417. * @alias module:echarts/component/helper/BrushController
  48418. * @constructor
  48419. * @mixin {module:zrender/mixin/Eventful}
  48420. * @event module:echarts/component/helper/BrushController#brush
  48421. * params:
  48422. * areas: Array.<Array>, coord relates to container group,
  48423. * If no container specified, to global.
  48424. * opt {
  48425. * isEnd: boolean,
  48426. * removeOnClick: boolean
  48427. * }
  48428. *
  48429. * @param {module:zrender/zrender~ZRender} zr
  48430. */
  48431. function BrushController(zr) {
  48432. if (__DEV__) {
  48433. assert$1(zr);
  48434. }
  48435. Eventful.call(this);
  48436. /**
  48437. * @type {module:zrender/zrender~ZRender}
  48438. * @private
  48439. */
  48440. this._zr = zr;
  48441. /**
  48442. * @type {module:zrender/container/Group}
  48443. * @readOnly
  48444. */
  48445. this.group = new Group();
  48446. /**
  48447. * Only for drawing (after enabledBrush).
  48448. * 'line', 'rect', 'polygon' or false
  48449. * If passing false/null/undefined, disable brush.
  48450. * If passing 'auto', determined by panel.defaultBrushType
  48451. * @private
  48452. * @type {string}
  48453. */
  48454. this._brushType;
  48455. /**
  48456. * Only for drawing (after enabledBrush).
  48457. *
  48458. * @private
  48459. * @type {Object}
  48460. */
  48461. this._brushOption;
  48462. /**
  48463. * @private
  48464. * @type {Object}
  48465. */
  48466. this._panels;
  48467. /**
  48468. * @private
  48469. * @type {Array.<nubmer>}
  48470. */
  48471. this._track = [];
  48472. /**
  48473. * @private
  48474. * @type {boolean}
  48475. */
  48476. this._dragging;
  48477. /**
  48478. * @private
  48479. * @type {Array}
  48480. */
  48481. this._covers = [];
  48482. /**
  48483. * @private
  48484. * @type {moudule:zrender/container/Group}
  48485. */
  48486. this._creatingCover;
  48487. /**
  48488. * `true` means global panel
  48489. * @private
  48490. * @type {module:zrender/container/Group|boolean}
  48491. */
  48492. this._creatingPanel;
  48493. /**
  48494. * @private
  48495. * @type {boolean}
  48496. */
  48497. this._enableGlobalPan;
  48498. /**
  48499. * @private
  48500. * @type {boolean}
  48501. */
  48502. if (__DEV__) {
  48503. this._mounted;
  48504. }
  48505. /**
  48506. * @private
  48507. * @type {string}
  48508. */
  48509. this._uid = 'brushController_' + baseUID++;
  48510. /**
  48511. * @private
  48512. * @type {Object}
  48513. */
  48514. this._handlers = {};
  48515. each$16(mouseHandlers, function (handler, eventName) {
  48516. this._handlers[eventName] = bind(handler, this);
  48517. }, this);
  48518. }
  48519. BrushController.prototype = {
  48520. constructor: BrushController,
  48521. /**
  48522. * If set to null/undefined/false, select disabled.
  48523. * @param {Object} brushOption
  48524. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  48525. * If passing false/null/undefined, disable brush.
  48526. * If passing 'auto', determined by panel.defaultBrushType.
  48527. * ('auto' can not be used in global panel)
  48528. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  48529. * @param {boolean} [brushOption.transformable=true]
  48530. * @param {boolean} [brushOption.removeOnClick=false]
  48531. * @param {Object} [brushOption.brushStyle]
  48532. * @param {number} [brushOption.brushStyle.width]
  48533. * @param {number} [brushOption.brushStyle.lineWidth]
  48534. * @param {string} [brushOption.brushStyle.stroke]
  48535. * @param {string} [brushOption.brushStyle.fill]
  48536. * @param {number} [brushOption.z]
  48537. */
  48538. enableBrush: function (brushOption) {
  48539. if (__DEV__) {
  48540. assert$1(this._mounted);
  48541. }
  48542. this._brushType && doDisableBrush(this);
  48543. brushOption.brushType && doEnableBrush(this, brushOption);
  48544. return this;
  48545. },
  48546. /**
  48547. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  48548. * Each items: {
  48549. * panelId, // mandatory.
  48550. * clipPath, // mandatory. function.
  48551. * isTargetByCursor, // mandatory. function.
  48552. * defaultBrushType, // optional, only used when brushType is 'auto'.
  48553. * getLinearBrushOtherExtent, // optional. function.
  48554. * }
  48555. */
  48556. setPanels: function (panelOpts) {
  48557. if (panelOpts && panelOpts.length) {
  48558. var panels = this._panels = {};
  48559. each$1(panelOpts, function (panelOpts) {
  48560. panels[panelOpts.panelId] = clone(panelOpts);
  48561. });
  48562. }
  48563. else {
  48564. this._panels = null;
  48565. }
  48566. return this;
  48567. },
  48568. /**
  48569. * @param {Object} [opt]
  48570. * @return {boolean} [opt.enableGlobalPan=false]
  48571. */
  48572. mount: function (opt) {
  48573. opt = opt || {};
  48574. if (__DEV__) {
  48575. this._mounted = true; // should be at first.
  48576. }
  48577. this._enableGlobalPan = opt.enableGlobalPan;
  48578. var thisGroup = this.group;
  48579. this._zr.add(thisGroup);
  48580. thisGroup.attr({
  48581. position: opt.position || [0, 0],
  48582. rotation: opt.rotation || 0,
  48583. scale: opt.scale || [1, 1]
  48584. });
  48585. this._transform = thisGroup.getLocalTransform();
  48586. return this;
  48587. },
  48588. eachCover: function (cb, context) {
  48589. each$16(this._covers, cb, context);
  48590. },
  48591. /**
  48592. * Update covers.
  48593. * @param {Array.<Object>} brushOptionList Like:
  48594. * [
  48595. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  48596. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  48597. * ...
  48598. * ]
  48599. * `brushType` is required in each cover info. (can not be 'auto')
  48600. * `id` is not mandatory.
  48601. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  48602. * If brushOptionList is null/undefined, all covers removed.
  48603. */
  48604. updateCovers: function (brushOptionList) {
  48605. if (__DEV__) {
  48606. assert$1(this._mounted);
  48607. }
  48608. brushOptionList = map(brushOptionList, function (brushOption) {
  48609. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48610. });
  48611. var tmpIdPrefix = '\0-brush-index-';
  48612. var oldCovers = this._covers;
  48613. var newCovers = this._covers = [];
  48614. var controller = this;
  48615. var creatingCover = this._creatingCover;
  48616. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  48617. .add(addOrUpdate)
  48618. .update(addOrUpdate)
  48619. .remove(remove)
  48620. .execute();
  48621. return this;
  48622. function getKey(brushOption, index) {
  48623. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  48624. + '-' + brushOption.brushType;
  48625. }
  48626. function oldGetKey(cover, index) {
  48627. return getKey(cover.__brushOption, index);
  48628. }
  48629. function addOrUpdate(newIndex, oldIndex) {
  48630. var newBrushOption = brushOptionList[newIndex];
  48631. // Consider setOption in event listener of brushSelect,
  48632. // where updating cover when creating should be forbiden.
  48633. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  48634. newCovers[newIndex] = oldCovers[oldIndex];
  48635. }
  48636. else {
  48637. var cover = newCovers[newIndex] = oldIndex != null
  48638. ? (
  48639. oldCovers[oldIndex].__brushOption = newBrushOption,
  48640. oldCovers[oldIndex]
  48641. )
  48642. : endCreating(controller, createCover(controller, newBrushOption));
  48643. updateCoverAfterCreation(controller, cover);
  48644. }
  48645. }
  48646. function remove(oldIndex) {
  48647. if (oldCovers[oldIndex] !== creatingCover) {
  48648. controller.group.remove(oldCovers[oldIndex]);
  48649. }
  48650. }
  48651. },
  48652. unmount: function () {
  48653. if (__DEV__) {
  48654. if (!this._mounted) {
  48655. return;
  48656. }
  48657. }
  48658. this.enableBrush(false);
  48659. // container may 'removeAll' outside.
  48660. clearCovers(this);
  48661. this._zr.remove(this.group);
  48662. if (__DEV__) {
  48663. this._mounted = false; // should be at last.
  48664. }
  48665. return this;
  48666. },
  48667. dispose: function () {
  48668. this.unmount();
  48669. this.off();
  48670. }
  48671. };
  48672. mixin(BrushController, Eventful);
  48673. function doEnableBrush(controller, brushOption) {
  48674. var zr = controller._zr;
  48675. // Consider roam, which takes globalPan too.
  48676. if (!controller._enableGlobalPan) {
  48677. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  48678. }
  48679. each$16(controller._handlers, function (handler, eventName) {
  48680. zr.on(eventName, handler);
  48681. });
  48682. controller._brushType = brushOption.brushType;
  48683. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48684. }
  48685. function doDisableBrush(controller) {
  48686. var zr = controller._zr;
  48687. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  48688. each$16(controller._handlers, function (handler, eventName) {
  48689. zr.off(eventName, handler);
  48690. });
  48691. controller._brushType = controller._brushOption = null;
  48692. }
  48693. function createCover(controller, brushOption) {
  48694. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  48695. cover.__brushOption = brushOption;
  48696. updateZ$1(cover, brushOption);
  48697. controller.group.add(cover);
  48698. return cover;
  48699. }
  48700. function endCreating(controller, creatingCover) {
  48701. var coverRenderer = getCoverRenderer(creatingCover);
  48702. if (coverRenderer.endCreating) {
  48703. coverRenderer.endCreating(controller, creatingCover);
  48704. updateZ$1(creatingCover, creatingCover.__brushOption);
  48705. }
  48706. return creatingCover;
  48707. }
  48708. function updateCoverShape(controller, cover) {
  48709. var brushOption = cover.__brushOption;
  48710. getCoverRenderer(cover).updateCoverShape(
  48711. controller, cover, brushOption.range, brushOption
  48712. );
  48713. }
  48714. function updateZ$1(cover, brushOption) {
  48715. var z = brushOption.z;
  48716. z == null && (z = COVER_Z);
  48717. cover.traverse(function (el) {
  48718. el.z = z;
  48719. el.z2 = z; // Consider in given container.
  48720. });
  48721. }
  48722. function updateCoverAfterCreation(controller, cover) {
  48723. getCoverRenderer(cover).updateCommon(controller, cover);
  48724. updateCoverShape(controller, cover);
  48725. }
  48726. function getCoverRenderer(cover) {
  48727. return coverRenderers[cover.__brushOption.brushType];
  48728. }
  48729. // return target panel or `true` (means global panel)
  48730. function getPanelByPoint(controller, e, localCursorPoint) {
  48731. var panels = controller._panels;
  48732. if (!panels) {
  48733. return true; // Global panel
  48734. }
  48735. var panel;
  48736. var transform = controller._transform;
  48737. each$16(panels, function (pn) {
  48738. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  48739. });
  48740. return panel;
  48741. }
  48742. // Return a panel or true
  48743. function getPanelByCover(controller, cover) {
  48744. var panels = controller._panels;
  48745. if (!panels) {
  48746. return true; // Global panel
  48747. }
  48748. var panelId = cover.__brushOption.panelId;
  48749. // User may give cover without coord sys info,
  48750. // which is then treated as global panel.
  48751. return panelId != null ? panels[panelId] : true;
  48752. }
  48753. function clearCovers(controller) {
  48754. var covers = controller._covers;
  48755. var originalLength = covers.length;
  48756. each$16(covers, function (cover) {
  48757. controller.group.remove(cover);
  48758. }, controller);
  48759. covers.length = 0;
  48760. return !!originalLength;
  48761. }
  48762. function trigger$1(controller, opt) {
  48763. var areas = map$2(controller._covers, function (cover) {
  48764. var brushOption = cover.__brushOption;
  48765. var range = clone(brushOption.range);
  48766. return {
  48767. brushType: brushOption.brushType,
  48768. panelId: brushOption.panelId,
  48769. range: range
  48770. };
  48771. });
  48772. controller.trigger('brush', areas, {
  48773. isEnd: !!opt.isEnd,
  48774. removeOnClick: !!opt.removeOnClick
  48775. });
  48776. }
  48777. function shouldShowCover(controller) {
  48778. var track = controller._track;
  48779. if (!track.length) {
  48780. return false;
  48781. }
  48782. var p2 = track[track.length - 1];
  48783. var p1 = track[0];
  48784. var dx = p2[0] - p1[0];
  48785. var dy = p2[1] - p1[1];
  48786. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  48787. return dist > UNSELECT_THRESHOLD;
  48788. }
  48789. function getTrackEnds(track) {
  48790. var tail = track.length - 1;
  48791. tail < 0 && (tail = 0);
  48792. return [track[0], track[tail]];
  48793. }
  48794. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  48795. var cover = new Group();
  48796. cover.add(new Rect({
  48797. name: 'main',
  48798. style: makeStyle(brushOption),
  48799. silent: true,
  48800. draggable: true,
  48801. cursor: 'move',
  48802. drift: curry$5(doDrift, controller, cover, 'nswe'),
  48803. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  48804. }));
  48805. each$16(
  48806. edgeNames,
  48807. function (name) {
  48808. cover.add(new Rect({
  48809. name: name,
  48810. style: {opacity: 0},
  48811. draggable: true,
  48812. silent: true,
  48813. invisible: true,
  48814. drift: curry$5(doDrift, controller, cover, name),
  48815. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  48816. }));
  48817. }
  48818. );
  48819. return cover;
  48820. }
  48821. function updateBaseRect(controller, cover, localRange, brushOption) {
  48822. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  48823. var handleSize = mathMax$4(lineWidth, MIN_RESIZE_LINE_WIDTH);
  48824. var x = localRange[0][0];
  48825. var y = localRange[1][0];
  48826. var xa = x - lineWidth / 2;
  48827. var ya = y - lineWidth / 2;
  48828. var x2 = localRange[0][1];
  48829. var y2 = localRange[1][1];
  48830. var x2a = x2 - handleSize + lineWidth / 2;
  48831. var y2a = y2 - handleSize + lineWidth / 2;
  48832. var width = x2 - x;
  48833. var height = y2 - y;
  48834. var widtha = width + lineWidth;
  48835. var heighta = height + lineWidth;
  48836. updateRectShape(controller, cover, 'main', x, y, width, height);
  48837. if (brushOption.transformable) {
  48838. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  48839. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  48840. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  48841. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  48842. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  48843. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  48844. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  48845. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  48846. }
  48847. }
  48848. function updateCommon(controller, cover) {
  48849. var brushOption = cover.__brushOption;
  48850. var transformable = brushOption.transformable;
  48851. var mainEl = cover.childAt(0);
  48852. mainEl.useStyle(makeStyle(brushOption));
  48853. mainEl.attr({
  48854. silent: !transformable,
  48855. cursor: transformable ? 'move' : 'default'
  48856. });
  48857. each$16(
  48858. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  48859. function (name) {
  48860. var el = cover.childOfName(name);
  48861. var globalDir = getGlobalDirection(controller, name);
  48862. el && el.attr({
  48863. silent: !transformable,
  48864. invisible: !transformable,
  48865. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  48866. });
  48867. }
  48868. );
  48869. }
  48870. function updateRectShape(controller, cover, name, x, y, w, h) {
  48871. var el = cover.childOfName(name);
  48872. el && el.setShape(pointsToRect(
  48873. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  48874. ));
  48875. }
  48876. function makeStyle(brushOption) {
  48877. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  48878. }
  48879. function formatRectRange(x, y, x2, y2) {
  48880. var min = [mathMin$4(x, x2), mathMin$4(y, y2)];
  48881. var max = [mathMax$4(x, x2), mathMax$4(y, y2)];
  48882. return [
  48883. [min[0], max[0]], // x range
  48884. [min[1], max[1]] // y range
  48885. ];
  48886. }
  48887. function getTransform$1(controller) {
  48888. return getTransform(controller.group);
  48889. }
  48890. function getGlobalDirection(controller, localDirection) {
  48891. if (localDirection.length > 1) {
  48892. localDirection = localDirection.split('');
  48893. var globalDir = [
  48894. getGlobalDirection(controller, localDirection[0]),
  48895. getGlobalDirection(controller, localDirection[1])
  48896. ];
  48897. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  48898. return globalDir.join('');
  48899. }
  48900. else {
  48901. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  48902. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  48903. var globalDir = transformDirection(
  48904. map$$1[localDirection], getTransform$1(controller)
  48905. );
  48906. return inverseMap[globalDir];
  48907. }
  48908. }
  48909. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  48910. var brushOption = cover.__brushOption;
  48911. var rectRange = toRectRange(brushOption.range);
  48912. var localDelta = toLocalDelta(controller, dx, dy);
  48913. each$16(name.split(''), function (namePart) {
  48914. var ind = DIRECTION_MAP[namePart];
  48915. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  48916. });
  48917. brushOption.range = fromRectRange(formatRectRange(
  48918. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  48919. ));
  48920. updateCoverAfterCreation(controller, cover);
  48921. trigger$1(controller, {isEnd: false});
  48922. }
  48923. function driftPolygon(controller, cover, dx, dy, e) {
  48924. var range = cover.__brushOption.range;
  48925. var localDelta = toLocalDelta(controller, dx, dy);
  48926. each$16(range, function (point) {
  48927. point[0] += localDelta[0];
  48928. point[1] += localDelta[1];
  48929. });
  48930. updateCoverAfterCreation(controller, cover);
  48931. trigger$1(controller, {isEnd: false});
  48932. }
  48933. function toLocalDelta(controller, dx, dy) {
  48934. var thisGroup = controller.group;
  48935. var localD = thisGroup.transformCoordToLocal(dx, dy);
  48936. var localZero = thisGroup.transformCoordToLocal(0, 0);
  48937. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  48938. }
  48939. function clipByPanel(controller, cover, data) {
  48940. var panel = getPanelByCover(controller, cover);
  48941. return (panel && panel !== true)
  48942. ? panel.clipPath(data, controller._transform)
  48943. : clone(data);
  48944. }
  48945. function pointsToRect(points) {
  48946. var xmin = mathMin$4(points[0][0], points[1][0]);
  48947. var ymin = mathMin$4(points[0][1], points[1][1]);
  48948. var xmax = mathMax$4(points[0][0], points[1][0]);
  48949. var ymax = mathMax$4(points[0][1], points[1][1]);
  48950. return {
  48951. x: xmin,
  48952. y: ymin,
  48953. width: xmax - xmin,
  48954. height: ymax - ymin
  48955. };
  48956. }
  48957. function resetCursor(controller, e, localCursorPoint) {
  48958. // Check active
  48959. if (!controller._brushType) {
  48960. return;
  48961. }
  48962. var zr = controller._zr;
  48963. var covers = controller._covers;
  48964. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  48965. // Check whether in covers.
  48966. if (!controller._dragging) {
  48967. for (var i = 0; i < covers.length; i++) {
  48968. var brushOption = covers[i].__brushOption;
  48969. if (currPanel
  48970. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  48971. && coverRenderers[brushOption.brushType].contain(
  48972. covers[i], localCursorPoint[0], localCursorPoint[1]
  48973. )
  48974. ) {
  48975. // Use cursor style set on cover.
  48976. return;
  48977. }
  48978. }
  48979. }
  48980. currPanel && zr.setCursorStyle('crosshair');
  48981. }
  48982. function preventDefault(e) {
  48983. var rawE = e.event;
  48984. rawE.preventDefault && rawE.preventDefault();
  48985. }
  48986. function mainShapeContain(cover, x, y) {
  48987. return cover.childOfName('main').contain(x, y);
  48988. }
  48989. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  48990. var creatingCover = controller._creatingCover;
  48991. var panel = controller._creatingPanel;
  48992. var thisBrushOption = controller._brushOption;
  48993. var eventParams;
  48994. controller._track.push(localCursorPoint.slice());
  48995. if (shouldShowCover(controller) || creatingCover) {
  48996. if (panel && !creatingCover) {
  48997. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  48998. var brushOption = clone(thisBrushOption);
  48999. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  49000. brushOption.panelId = panel === true ? null : panel.panelId;
  49001. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  49002. controller._covers.push(creatingCover);
  49003. }
  49004. if (creatingCover) {
  49005. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  49006. var coverBrushOption = creatingCover.__brushOption;
  49007. coverBrushOption.range = coverRenderer.getCreatingRange(
  49008. clipByPanel(controller, creatingCover, controller._track)
  49009. );
  49010. if (isEnd) {
  49011. endCreating(controller, creatingCover);
  49012. coverRenderer.updateCommon(controller, creatingCover);
  49013. }
  49014. updateCoverShape(controller, creatingCover);
  49015. eventParams = {isEnd: isEnd};
  49016. }
  49017. }
  49018. else if (
  49019. isEnd
  49020. && thisBrushOption.brushMode === 'single'
  49021. && thisBrushOption.removeOnClick
  49022. ) {
  49023. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  49024. // But a single click do not clear covers, because user may have casual
  49025. // clicks (for example, click on other component and do not expect covers
  49026. // disappear).
  49027. // Only some cover removed, trigger action, but not every click trigger action.
  49028. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  49029. eventParams = {isEnd: isEnd, removeOnClick: true};
  49030. }
  49031. }
  49032. return eventParams;
  49033. }
  49034. function determineBrushType(brushType, panel) {
  49035. if (brushType === 'auto') {
  49036. if (__DEV__) {
  49037. assert$1(
  49038. panel && panel.defaultBrushType,
  49039. 'MUST have defaultBrushType when brushType is "atuo"'
  49040. );
  49041. }
  49042. return panel.defaultBrushType;
  49043. }
  49044. return brushType;
  49045. }
  49046. var mouseHandlers = {
  49047. mousedown: function (e) {
  49048. if (this._dragging) {
  49049. // In case some browser do not support globalOut,
  49050. // and release mose out side the browser.
  49051. handleDragEnd.call(this, e);
  49052. }
  49053. else if (!e.target || !e.target.draggable) {
  49054. preventDefault(e);
  49055. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  49056. this._creatingCover = null;
  49057. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  49058. if (panel) {
  49059. this._dragging = true;
  49060. this._track = [localCursorPoint.slice()];
  49061. }
  49062. }
  49063. },
  49064. mousemove: function (e) {
  49065. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  49066. resetCursor(this, e, localCursorPoint);
  49067. if (this._dragging) {
  49068. preventDefault(e);
  49069. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  49070. eventParams && trigger$1(this, eventParams);
  49071. }
  49072. },
  49073. mouseup: handleDragEnd //,
  49074. // FIXME
  49075. // in tooltip, globalout should not be triggered.
  49076. // globalout: handleDragEnd
  49077. };
  49078. function handleDragEnd(e) {
  49079. if (this._dragging) {
  49080. preventDefault(e);
  49081. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  49082. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  49083. this._dragging = false;
  49084. this._track = [];
  49085. this._creatingCover = null;
  49086. // trigger event shoule be at final, after procedure will be nested.
  49087. eventParams && trigger$1(this, eventParams);
  49088. }
  49089. }
  49090. /**
  49091. * key: brushType
  49092. * @type {Object}
  49093. */
  49094. var coverRenderers = {
  49095. lineX: getLineRenderer(0),
  49096. lineY: getLineRenderer(1),
  49097. rect: {
  49098. createCover: function (controller, brushOption) {
  49099. return createBaseRectCover(
  49100. curry$5(
  49101. driftRect,
  49102. function (range) {
  49103. return range;
  49104. },
  49105. function (range) {
  49106. return range;
  49107. }
  49108. ),
  49109. controller,
  49110. brushOption,
  49111. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  49112. );
  49113. },
  49114. getCreatingRange: function (localTrack) {
  49115. var ends = getTrackEnds(localTrack);
  49116. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  49117. },
  49118. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49119. updateBaseRect(controller, cover, localRange, brushOption);
  49120. },
  49121. updateCommon: updateCommon,
  49122. contain: mainShapeContain
  49123. },
  49124. polygon: {
  49125. createCover: function (controller, brushOption) {
  49126. var cover = new Group();
  49127. // Do not use graphic.Polygon because graphic.Polyline do not close the
  49128. // border of the shape when drawing, which is a better experience for user.
  49129. cover.add(new Polyline({
  49130. name: 'main',
  49131. style: makeStyle(brushOption),
  49132. silent: true
  49133. }));
  49134. return cover;
  49135. },
  49136. getCreatingRange: function (localTrack) {
  49137. return localTrack;
  49138. },
  49139. endCreating: function (controller, cover) {
  49140. cover.remove(cover.childAt(0));
  49141. // Use graphic.Polygon close the shape.
  49142. cover.add(new Polygon({
  49143. name: 'main',
  49144. draggable: true,
  49145. drift: curry$5(driftPolygon, controller, cover),
  49146. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  49147. }));
  49148. },
  49149. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49150. cover.childAt(0).setShape({
  49151. points: clipByPanel(controller, cover, localRange)
  49152. });
  49153. },
  49154. updateCommon: updateCommon,
  49155. contain: mainShapeContain
  49156. }
  49157. };
  49158. function getLineRenderer(xyIndex) {
  49159. return {
  49160. createCover: function (controller, brushOption) {
  49161. return createBaseRectCover(
  49162. curry$5(
  49163. driftRect,
  49164. function (range) {
  49165. var rectRange = [range, [0, 100]];
  49166. xyIndex && rectRange.reverse();
  49167. return rectRange;
  49168. },
  49169. function (rectRange) {
  49170. return rectRange[xyIndex];
  49171. }
  49172. ),
  49173. controller,
  49174. brushOption,
  49175. [['w', 'e'], ['n', 's']][xyIndex]
  49176. );
  49177. },
  49178. getCreatingRange: function (localTrack) {
  49179. var ends = getTrackEnds(localTrack);
  49180. var min = mathMin$4(ends[0][xyIndex], ends[1][xyIndex]);
  49181. var max = mathMax$4(ends[0][xyIndex], ends[1][xyIndex]);
  49182. return [min, max];
  49183. },
  49184. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49185. var otherExtent;
  49186. // If brushWidth not specified, fit the panel.
  49187. var panel = getPanelByCover(controller, cover);
  49188. if (panel !== true && panel.getLinearBrushOtherExtent) {
  49189. otherExtent = panel.getLinearBrushOtherExtent(
  49190. xyIndex, controller._transform
  49191. );
  49192. }
  49193. else {
  49194. var zr = controller._zr;
  49195. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  49196. }
  49197. var rectRange = [localRange, otherExtent];
  49198. xyIndex && rectRange.reverse();
  49199. updateBaseRect(controller, cover, rectRange, brushOption);
  49200. },
  49201. updateCommon: updateCommon,
  49202. contain: mainShapeContain
  49203. };
  49204. }
  49205. /*
  49206. * Licensed to the Apache Software Foundation (ASF) under one
  49207. * or more contributor license agreements. See the NOTICE file
  49208. * distributed with this work for additional information
  49209. * regarding copyright ownership. The ASF licenses this file
  49210. * to you under the Apache License, Version 2.0 (the
  49211. * "License"); you may not use this file except in compliance
  49212. * with the License. You may obtain a copy of the License at
  49213. *
  49214. * http://www.apache.org/licenses/LICENSE-2.0
  49215. *
  49216. * Unless required by applicable law or agreed to in writing,
  49217. * software distributed under the License is distributed on an
  49218. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49219. * KIND, either express or implied. See the License for the
  49220. * specific language governing permissions and limitations
  49221. * under the License.
  49222. */
  49223. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  49224. /**
  49225. * Avoid that: mouse click on a elements that is over geo or graph,
  49226. * but roam is triggered.
  49227. */
  49228. function onIrrelevantElement(e, api, targetCoordSysModel) {
  49229. var model = api.getComponentByElement(e.topTarget);
  49230. // If model is axisModel, it works only if it is injected with coordinateSystem.
  49231. var coordSys = model && model.coordinateSystem;
  49232. return model
  49233. && model !== targetCoordSysModel
  49234. && !IRRELEVANT_EXCLUDES[model.mainType]
  49235. && (coordSys && coordSys.model !== targetCoordSysModel);
  49236. }
  49237. /*
  49238. * Licensed to the Apache Software Foundation (ASF) under one
  49239. * or more contributor license agreements. See the NOTICE file
  49240. * distributed with this work for additional information
  49241. * regarding copyright ownership. The ASF licenses this file
  49242. * to you under the Apache License, Version 2.0 (the
  49243. * "License"); you may not use this file except in compliance
  49244. * with the License. You may obtain a copy of the License at
  49245. *
  49246. * http://www.apache.org/licenses/LICENSE-2.0
  49247. *
  49248. * Unless required by applicable law or agreed to in writing,
  49249. * software distributed under the License is distributed on an
  49250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49251. * KIND, either express or implied. See the License for the
  49252. * specific language governing permissions and limitations
  49253. * under the License.
  49254. */
  49255. function makeRectPanelClipPath(rect) {
  49256. rect = normalizeRect(rect);
  49257. return function (localPoints, transform) {
  49258. return clipPointsByRect(localPoints, rect);
  49259. };
  49260. }
  49261. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  49262. rect = normalizeRect(rect);
  49263. return function (xyIndex) {
  49264. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  49265. var brushWidth = idx ? rect.width : rect.height;
  49266. var base = idx ? rect.x : rect.y;
  49267. return [base, base + (brushWidth || 0)];
  49268. };
  49269. }
  49270. function makeRectIsTargetByCursor(rect, api, targetModel) {
  49271. rect = normalizeRect(rect);
  49272. return function (e, localCursorPoint, transform) {
  49273. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  49274. && !onIrrelevantElement(e, api, targetModel);
  49275. };
  49276. }
  49277. // Consider width/height is negative.
  49278. function normalizeRect(rect) {
  49279. return BoundingRect.create(rect);
  49280. }
  49281. /*
  49282. * Licensed to the Apache Software Foundation (ASF) under one
  49283. * or more contributor license agreements. See the NOTICE file
  49284. * distributed with this work for additional information
  49285. * regarding copyright ownership. The ASF licenses this file
  49286. * to you under the Apache License, Version 2.0 (the
  49287. * "License"); you may not use this file except in compliance
  49288. * with the License. You may obtain a copy of the License at
  49289. *
  49290. * http://www.apache.org/licenses/LICENSE-2.0
  49291. *
  49292. * Unless required by applicable law or agreed to in writing,
  49293. * software distributed under the License is distributed on an
  49294. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49295. * KIND, either express or implied. See the License for the
  49296. * specific language governing permissions and limitations
  49297. * under the License.
  49298. */
  49299. var each$17 = each$1;
  49300. var indexOf$2 = indexOf;
  49301. var curry$6 = curry;
  49302. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  49303. // FIXME
  49304. // how to genarialize to more coordinate systems.
  49305. var INCLUDE_FINDER_MAIN_TYPES = [
  49306. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  49307. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  49308. ];
  49309. /**
  49310. * [option in constructor]:
  49311. * {
  49312. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  49313. * }
  49314. *
  49315. *
  49316. * [targetInfo]:
  49317. *
  49318. * There can be multiple axes in a single targetInfo. Consider the case
  49319. * of `grid` component, a targetInfo represents a grid which contains one or more
  49320. * cartesian and one or more axes. And consider the case of parallel system,
  49321. * which has multiple axes in a coordinate system.
  49322. * Can be {
  49323. * panelId: ...,
  49324. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  49325. * coordSyses: all cartesians.
  49326. * gridModel: <grid component>
  49327. * xAxes: correspond to coordSyses on index
  49328. * yAxes: correspond to coordSyses on index
  49329. * }
  49330. * or {
  49331. * panelId: ...,
  49332. * coordSys: <geo coord sys>
  49333. * coordSyses: [<geo coord sys>]
  49334. * geoModel: <geo component>
  49335. * }
  49336. *
  49337. *
  49338. * [panelOpt]:
  49339. *
  49340. * Make from targetInfo. Input to BrushController.
  49341. * {
  49342. * panelId: ...,
  49343. * rect: ...
  49344. * }
  49345. *
  49346. *
  49347. * [area]:
  49348. *
  49349. * Generated by BrushController or user input.
  49350. * {
  49351. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  49352. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  49353. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  49354. * range: pixel range.
  49355. * coordRange: representitive coord range (the first one of coordRanges).
  49356. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  49357. * }
  49358. */
  49359. /**
  49360. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  49361. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  49362. * @param {module:echarts/model/Global} ecModel
  49363. * @param {Object} [opt]
  49364. * @param {Array.<string>} [opt.include] include coordinate system types.
  49365. */
  49366. function BrushTargetManager(option, ecModel, opt) {
  49367. /**
  49368. * @private
  49369. * @type {Array.<Object>}
  49370. */
  49371. var targetInfoList = this._targetInfoList = [];
  49372. var info = {};
  49373. var foundCpts = parseFinder$1(ecModel, option);
  49374. each$17(targetInfoBuilders, function (builder, type) {
  49375. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  49376. builder(foundCpts, targetInfoList, info);
  49377. }
  49378. });
  49379. }
  49380. var proto$5 = BrushTargetManager.prototype;
  49381. proto$5.setOutputRanges = function (areas, ecModel) {
  49382. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  49383. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  49384. // area.coordRange is the first of area.coordRanges
  49385. if (!area.coordRange) {
  49386. area.coordRange = coordRange;
  49387. // In 'category' axis, coord to pixel is not reversible, so we can not
  49388. // rebuild range by coordRange accrately, which may bring trouble when
  49389. // brushing only one item. So we use __rangeOffset to rebuilding range
  49390. // by coordRange. And this it only used in brush component so it is no
  49391. // need to be adapted to coordRanges.
  49392. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  49393. area.__rangeOffset = {
  49394. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  49395. xyMinMax: result.xyMinMax
  49396. };
  49397. }
  49398. });
  49399. };
  49400. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  49401. each$17(areas, function (area) {
  49402. var targetInfo = this.findTargetInfo(area, ecModel);
  49403. if (targetInfo && targetInfo !== true) {
  49404. each$1(
  49405. targetInfo.coordSyses,
  49406. function (coordSys) {
  49407. var result = coordConvert[area.brushType](1, coordSys, area.range);
  49408. cb(area, result.values, coordSys, ecModel);
  49409. }
  49410. );
  49411. }
  49412. }, this);
  49413. };
  49414. proto$5.setInputRanges = function (areas, ecModel) {
  49415. each$17(areas, function (area) {
  49416. var targetInfo = this.findTargetInfo(area, ecModel);
  49417. if (__DEV__) {
  49418. assert$1(
  49419. !targetInfo || targetInfo === true || area.coordRange,
  49420. 'coordRange must be specified when coord index specified.'
  49421. );
  49422. assert$1(
  49423. !targetInfo || targetInfo !== true || area.range,
  49424. 'range must be specified in global brush.'
  49425. );
  49426. }
  49427. area.range = area.range || [];
  49428. // convert coordRange to global range and set panelId.
  49429. if (targetInfo && targetInfo !== true) {
  49430. area.panelId = targetInfo.panelId;
  49431. // (1) area.range shoule always be calculate from coordRange but does
  49432. // not keep its original value, for the sake of the dataZoom scenario,
  49433. // where area.coordRange remains unchanged but area.range may be changed.
  49434. // (2) Only support converting one coordRange to pixel range in brush
  49435. // component. So do not consider `coordRanges`.
  49436. // (3) About __rangeOffset, see comment above.
  49437. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  49438. var rangeOffset = area.__rangeOffset;
  49439. area.range = rangeOffset
  49440. ? diffProcessor[area.brushType](
  49441. result.values,
  49442. rangeOffset.offset,
  49443. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  49444. )
  49445. : result.values;
  49446. }
  49447. }, this);
  49448. };
  49449. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  49450. return map(this._targetInfoList, function (targetInfo) {
  49451. var rect = targetInfo.getPanelRect();
  49452. return {
  49453. panelId: targetInfo.panelId,
  49454. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  49455. clipPath: makeRectPanelClipPath(rect),
  49456. isTargetByCursor: makeRectIsTargetByCursor(
  49457. rect, api, targetInfo.coordSysModel
  49458. ),
  49459. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  49460. };
  49461. });
  49462. };
  49463. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  49464. // Check whether area is bound in coord, and series do not belong to that coord.
  49465. // If do not do this check, some brush (like lineX) will controll all axes.
  49466. var targetInfo = this.findTargetInfo(area, ecModel);
  49467. return targetInfo === true || (
  49468. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  49469. );
  49470. };
  49471. /**
  49472. * If return Object, a coord found.
  49473. * If reutrn true, global found.
  49474. * Otherwise nothing found.
  49475. *
  49476. * @param {Object} area
  49477. * @param {Array} targetInfoList
  49478. * @return {Object|boolean}
  49479. */
  49480. proto$5.findTargetInfo = function (area, ecModel) {
  49481. var targetInfoList = this._targetInfoList;
  49482. var foundCpts = parseFinder$1(ecModel, area);
  49483. for (var i = 0; i < targetInfoList.length; i++) {
  49484. var targetInfo = targetInfoList[i];
  49485. var areaPanelId = area.panelId;
  49486. if (areaPanelId) {
  49487. if (targetInfo.panelId === areaPanelId) {
  49488. return targetInfo;
  49489. }
  49490. }
  49491. else {
  49492. for (var i = 0; i < targetInfoMatchers.length; i++) {
  49493. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  49494. return targetInfo;
  49495. }
  49496. }
  49497. }
  49498. }
  49499. return true;
  49500. };
  49501. function formatMinMax(minMax) {
  49502. minMax[0] > minMax[1] && minMax.reverse();
  49503. return minMax;
  49504. }
  49505. function parseFinder$1(ecModel, option) {
  49506. return parseFinder(
  49507. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  49508. );
  49509. }
  49510. var targetInfoBuilders = {
  49511. grid: function (foundCpts, targetInfoList) {
  49512. var xAxisModels = foundCpts.xAxisModels;
  49513. var yAxisModels = foundCpts.yAxisModels;
  49514. var gridModels = foundCpts.gridModels;
  49515. // Remove duplicated.
  49516. var gridModelMap = createHashMap();
  49517. var xAxesHas = {};
  49518. var yAxesHas = {};
  49519. if (!xAxisModels && !yAxisModels && !gridModels) {
  49520. return;
  49521. }
  49522. each$17(xAxisModels, function (axisModel) {
  49523. var gridModel = axisModel.axis.grid.model;
  49524. gridModelMap.set(gridModel.id, gridModel);
  49525. xAxesHas[gridModel.id] = true;
  49526. });
  49527. each$17(yAxisModels, function (axisModel) {
  49528. var gridModel = axisModel.axis.grid.model;
  49529. gridModelMap.set(gridModel.id, gridModel);
  49530. yAxesHas[gridModel.id] = true;
  49531. });
  49532. each$17(gridModels, function (gridModel) {
  49533. gridModelMap.set(gridModel.id, gridModel);
  49534. xAxesHas[gridModel.id] = true;
  49535. yAxesHas[gridModel.id] = true;
  49536. });
  49537. gridModelMap.each(function (gridModel) {
  49538. var grid = gridModel.coordinateSystem;
  49539. var cartesians = [];
  49540. each$17(grid.getCartesians(), function (cartesian, index) {
  49541. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  49542. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  49543. ) {
  49544. cartesians.push(cartesian);
  49545. }
  49546. });
  49547. targetInfoList.push({
  49548. panelId: 'grid--' + gridModel.id,
  49549. gridModel: gridModel,
  49550. coordSysModel: gridModel,
  49551. // Use the first one as the representitive coordSys.
  49552. coordSys: cartesians[0],
  49553. coordSyses: cartesians,
  49554. getPanelRect: panelRectBuilder.grid,
  49555. xAxisDeclared: xAxesHas[gridModel.id],
  49556. yAxisDeclared: yAxesHas[gridModel.id]
  49557. });
  49558. });
  49559. },
  49560. geo: function (foundCpts, targetInfoList) {
  49561. each$17(foundCpts.geoModels, function (geoModel) {
  49562. var coordSys = geoModel.coordinateSystem;
  49563. targetInfoList.push({
  49564. panelId: 'geo--' + geoModel.id,
  49565. geoModel: geoModel,
  49566. coordSysModel: geoModel,
  49567. coordSys: coordSys,
  49568. coordSyses: [coordSys],
  49569. getPanelRect: panelRectBuilder.geo
  49570. });
  49571. });
  49572. }
  49573. };
  49574. var targetInfoMatchers = [
  49575. // grid
  49576. function (foundCpts, targetInfo) {
  49577. var xAxisModel = foundCpts.xAxisModel;
  49578. var yAxisModel = foundCpts.yAxisModel;
  49579. var gridModel = foundCpts.gridModel;
  49580. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  49581. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  49582. return gridModel && gridModel === targetInfo.gridModel;
  49583. },
  49584. // geo
  49585. function (foundCpts, targetInfo) {
  49586. var geoModel = foundCpts.geoModel;
  49587. return geoModel && geoModel === targetInfo.geoModel;
  49588. }
  49589. ];
  49590. var panelRectBuilder = {
  49591. grid: function () {
  49592. // grid is not Transformable.
  49593. return this.coordSys.grid.getRect().clone();
  49594. },
  49595. geo: function () {
  49596. var coordSys = this.coordSys;
  49597. var rect = coordSys.getBoundingRect().clone();
  49598. // geo roam and zoom transform
  49599. rect.applyTransform(getTransform(coordSys));
  49600. return rect;
  49601. }
  49602. };
  49603. var coordConvert = {
  49604. lineX: curry$6(axisConvert, 0),
  49605. lineY: curry$6(axisConvert, 1),
  49606. rect: function (to, coordSys, rangeOrCoordRange) {
  49607. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  49608. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  49609. var values = [
  49610. formatMinMax([xminymin[0], xmaxymax[0]]),
  49611. formatMinMax([xminymin[1], xmaxymax[1]])
  49612. ];
  49613. return {values: values, xyMinMax: values};
  49614. },
  49615. polygon: function (to, coordSys, rangeOrCoordRange) {
  49616. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  49617. var values = map(rangeOrCoordRange, function (item) {
  49618. var p = coordSys[COORD_CONVERTS[to]](item);
  49619. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  49620. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  49621. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  49622. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  49623. return p;
  49624. });
  49625. return {values: values, xyMinMax: xyMinMax};
  49626. }
  49627. };
  49628. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  49629. if (__DEV__) {
  49630. assert$1(
  49631. coordSys.type === 'cartesian2d',
  49632. 'lineX/lineY brush is available only in cartesian2d.'
  49633. );
  49634. }
  49635. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  49636. var values = formatMinMax(map([0, 1], function (i) {
  49637. return to
  49638. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  49639. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  49640. }));
  49641. var xyMinMax = [];
  49642. xyMinMax[axisNameIndex] = values;
  49643. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  49644. return {values: values, xyMinMax: xyMinMax};
  49645. }
  49646. var diffProcessor = {
  49647. lineX: curry$6(axisDiffProcessor, 0),
  49648. lineY: curry$6(axisDiffProcessor, 1),
  49649. rect: function (values, refer, scales) {
  49650. return [
  49651. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  49652. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  49653. ];
  49654. },
  49655. polygon: function (values, refer, scales) {
  49656. return map(values, function (item, idx) {
  49657. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  49658. });
  49659. }
  49660. };
  49661. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  49662. return [
  49663. values[0] - scales[axisNameIndex] * refer[0],
  49664. values[1] - scales[axisNameIndex] * refer[1]
  49665. ];
  49666. }
  49667. // We have to process scale caused by dataZoom manually,
  49668. // although it might be not accurate.
  49669. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  49670. var sizeCurr = getSize(xyMinMaxCurr);
  49671. var sizeOrigin = getSize(xyMinMaxOrigin);
  49672. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  49673. isNaN(scales[0]) && (scales[0] = 1);
  49674. isNaN(scales[1]) && (scales[1] = 1);
  49675. return scales;
  49676. }
  49677. function getSize(xyMinMax) {
  49678. return xyMinMax
  49679. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  49680. : [NaN, NaN];
  49681. }
  49682. /*
  49683. * Licensed to the Apache Software Foundation (ASF) under one
  49684. * or more contributor license agreements. See the NOTICE file
  49685. * distributed with this work for additional information
  49686. * regarding copyright ownership. The ASF licenses this file
  49687. * to you under the Apache License, Version 2.0 (the
  49688. * "License"); you may not use this file except in compliance
  49689. * with the License. You may obtain a copy of the License at
  49690. *
  49691. * http://www.apache.org/licenses/LICENSE-2.0
  49692. *
  49693. * Unless required by applicable law or agreed to in writing,
  49694. * software distributed under the License is distributed on an
  49695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49696. * KIND, either express or implied. See the License for the
  49697. * specific language governing permissions and limitations
  49698. * under the License.
  49699. */
  49700. var each$18 = each$1;
  49701. var ATTR$2 = '\0_ec_hist_store';
  49702. /**
  49703. * @param {module:echarts/model/Global} ecModel
  49704. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  49705. */
  49706. function push(ecModel, newSnapshot) {
  49707. var store = giveStore$1(ecModel);
  49708. // If previous dataZoom can not be found,
  49709. // complete an range with current range.
  49710. each$18(newSnapshot, function (batchItem, dataZoomId) {
  49711. var i = store.length - 1;
  49712. for (; i >= 0; i--) {
  49713. var snapshot = store[i];
  49714. if (snapshot[dataZoomId]) {
  49715. break;
  49716. }
  49717. }
  49718. if (i < 0) {
  49719. // No origin range set, create one by current range.
  49720. var dataZoomModel = ecModel.queryComponents(
  49721. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  49722. )[0];
  49723. if (dataZoomModel) {
  49724. var percentRange = dataZoomModel.getPercentRange();
  49725. store[0][dataZoomId] = {
  49726. dataZoomId: dataZoomId,
  49727. start: percentRange[0],
  49728. end: percentRange[1]
  49729. };
  49730. }
  49731. }
  49732. });
  49733. store.push(newSnapshot);
  49734. }
  49735. /**
  49736. * @param {module:echarts/model/Global} ecModel
  49737. * @return {Object} snapshot
  49738. */
  49739. function pop(ecModel) {
  49740. var store = giveStore$1(ecModel);
  49741. var head = store[store.length - 1];
  49742. store.length > 1 && store.pop();
  49743. // Find top for all dataZoom.
  49744. var snapshot = {};
  49745. each$18(head, function (batchItem, dataZoomId) {
  49746. for (var i = store.length - 1; i >= 0; i--) {
  49747. var batchItem = store[i][dataZoomId];
  49748. if (batchItem) {
  49749. snapshot[dataZoomId] = batchItem;
  49750. break;
  49751. }
  49752. }
  49753. });
  49754. return snapshot;
  49755. }
  49756. /**
  49757. * @param {module:echarts/model/Global} ecModel
  49758. */
  49759. function clear$1(ecModel) {
  49760. ecModel[ATTR$2] = null;
  49761. }
  49762. /**
  49763. * @param {module:echarts/model/Global} ecModel
  49764. * @return {number} records. always >= 1.
  49765. */
  49766. function count(ecModel) {
  49767. return giveStore$1(ecModel).length;
  49768. }
  49769. /**
  49770. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  49771. * History length of each dataZoom may be different.
  49772. * this._history[0] is used to store origin range.
  49773. * @type {Array.<Object>}
  49774. */
  49775. function giveStore$1(ecModel) {
  49776. var store = ecModel[ATTR$2];
  49777. if (!store) {
  49778. store = ecModel[ATTR$2] = [{}];
  49779. }
  49780. return store;
  49781. }
  49782. /*
  49783. * Licensed to the Apache Software Foundation (ASF) under one
  49784. * or more contributor license agreements. See the NOTICE file
  49785. * distributed with this work for additional information
  49786. * regarding copyright ownership. The ASF licenses this file
  49787. * to you under the Apache License, Version 2.0 (the
  49788. * "License"); you may not use this file except in compliance
  49789. * with the License. You may obtain a copy of the License at
  49790. *
  49791. * http://www.apache.org/licenses/LICENSE-2.0
  49792. *
  49793. * Unless required by applicable law or agreed to in writing,
  49794. * software distributed under the License is distributed on an
  49795. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49796. * KIND, either express or implied. See the License for the
  49797. * specific language governing permissions and limitations
  49798. * under the License.
  49799. */
  49800. DataZoomModel.extend({
  49801. type: 'dataZoom.select'
  49802. });
  49803. /*
  49804. * Licensed to the Apache Software Foundation (ASF) under one
  49805. * or more contributor license agreements. See the NOTICE file
  49806. * distributed with this work for additional information
  49807. * regarding copyright ownership. The ASF licenses this file
  49808. * to you under the Apache License, Version 2.0 (the
  49809. * "License"); you may not use this file except in compliance
  49810. * with the License. You may obtain a copy of the License at
  49811. *
  49812. * http://www.apache.org/licenses/LICENSE-2.0
  49813. *
  49814. * Unless required by applicable law or agreed to in writing,
  49815. * software distributed under the License is distributed on an
  49816. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49817. * KIND, either express or implied. See the License for the
  49818. * specific language governing permissions and limitations
  49819. * under the License.
  49820. */
  49821. DataZoomView.extend({
  49822. type: 'dataZoom.select'
  49823. });
  49824. /*
  49825. * Licensed to the Apache Software Foundation (ASF) under one
  49826. * or more contributor license agreements. See the NOTICE file
  49827. * distributed with this work for additional information
  49828. * regarding copyright ownership. The ASF licenses this file
  49829. * to you under the Apache License, Version 2.0 (the
  49830. * "License"); you may not use this file except in compliance
  49831. * with the License. You may obtain a copy of the License at
  49832. *
  49833. * http://www.apache.org/licenses/LICENSE-2.0
  49834. *
  49835. * Unless required by applicable law or agreed to in writing,
  49836. * software distributed under the License is distributed on an
  49837. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49838. * KIND, either express or implied. See the License for the
  49839. * specific language governing permissions and limitations
  49840. * under the License.
  49841. */
  49842. /**
  49843. * DataZoom component entry
  49844. */
  49845. /*
  49846. * Licensed to the Apache Software Foundation (ASF) under one
  49847. * or more contributor license agreements. See the NOTICE file
  49848. * distributed with this work for additional information
  49849. * regarding copyright ownership. The ASF licenses this file
  49850. * to you under the Apache License, Version 2.0 (the
  49851. * "License"); you may not use this file except in compliance
  49852. * with the License. You may obtain a copy of the License at
  49853. *
  49854. * http://www.apache.org/licenses/LICENSE-2.0
  49855. *
  49856. * Unless required by applicable law or agreed to in writing,
  49857. * software distributed under the License is distributed on an
  49858. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49859. * KIND, either express or implied. See the License for the
  49860. * specific language governing permissions and limitations
  49861. * under the License.
  49862. */
  49863. // Use dataZoomSelect
  49864. var dataZoomLang = lang.toolbox.dataZoom;
  49865. var each$15 = each$1;
  49866. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  49867. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  49868. function DataZoom(model, ecModel, api) {
  49869. /**
  49870. * @private
  49871. * @type {module:echarts/component/helper/BrushController}
  49872. */
  49873. (this._brushController = new BrushController(api.getZr()))
  49874. .on('brush', bind(this._onBrush, this))
  49875. .mount();
  49876. /**
  49877. * @private
  49878. * @type {boolean}
  49879. */
  49880. this._isZoomActive;
  49881. }
  49882. DataZoom.defaultOption = {
  49883. show: true,
  49884. // Icon group
  49885. icon: {
  49886. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  49887. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  49888. },
  49889. // `zoom`, `back`
  49890. title: clone(dataZoomLang.title)
  49891. };
  49892. var proto$4 = DataZoom.prototype;
  49893. proto$4.render = function (featureModel, ecModel, api, payload) {
  49894. this.model = featureModel;
  49895. this.ecModel = ecModel;
  49896. this.api = api;
  49897. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  49898. updateBackBtnStatus(featureModel, ecModel);
  49899. };
  49900. proto$4.onclick = function (ecModel, api, type) {
  49901. handlers[type].call(this);
  49902. };
  49903. proto$4.remove = function (ecModel, api) {
  49904. this._brushController.unmount();
  49905. };
  49906. proto$4.dispose = function (ecModel, api) {
  49907. this._brushController.dispose();
  49908. };
  49909. /**
  49910. * @private
  49911. */
  49912. var handlers = {
  49913. zoom: function () {
  49914. var nextActive = !this._isZoomActive;
  49915. this.api.dispatchAction({
  49916. type: 'takeGlobalCursor',
  49917. key: 'dataZoomSelect',
  49918. dataZoomSelectActive: nextActive
  49919. });
  49920. },
  49921. back: function () {
  49922. this._dispatchZoomAction(pop(this.ecModel));
  49923. }
  49924. };
  49925. /**
  49926. * @private
  49927. */
  49928. proto$4._onBrush = function (areas, opt) {
  49929. if (!opt.isEnd || !areas.length) {
  49930. return;
  49931. }
  49932. var snapshot = {};
  49933. var ecModel = this.ecModel;
  49934. this._brushController.updateCovers([]); // remove cover
  49935. var brushTargetManager = new BrushTargetManager(
  49936. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  49937. );
  49938. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  49939. if (coordSys.type !== 'cartesian2d') {
  49940. return;
  49941. }
  49942. var brushType = area.brushType;
  49943. if (brushType === 'rect') {
  49944. setBatch('x', coordSys, coordRange[0]);
  49945. setBatch('y', coordSys, coordRange[1]);
  49946. }
  49947. else {
  49948. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  49949. }
  49950. });
  49951. push(ecModel, snapshot);
  49952. this._dispatchZoomAction(snapshot);
  49953. function setBatch(dimName, coordSys, minMax) {
  49954. var axis = coordSys.getAxis(dimName);
  49955. var axisModel = axis.model;
  49956. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  49957. // Restrict range.
  49958. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  49959. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  49960. minMax = sliderMove(
  49961. 0, minMax.slice(), axis.scale.getExtent(), 0,
  49962. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  49963. );
  49964. }
  49965. dataZoomModel && (snapshot[dataZoomModel.id] = {
  49966. dataZoomId: dataZoomModel.id,
  49967. startValue: minMax[0],
  49968. endValue: minMax[1]
  49969. });
  49970. }
  49971. function findDataZoom(dimName, axisModel, ecModel) {
  49972. var found;
  49973. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  49974. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  49975. has && (found = dzModel);
  49976. });
  49977. return found;
  49978. }
  49979. };
  49980. /**
  49981. * @private
  49982. */
  49983. proto$4._dispatchZoomAction = function (snapshot) {
  49984. var batch = [];
  49985. // Convert from hash map to array.
  49986. each$15(snapshot, function (batchItem, dataZoomId) {
  49987. batch.push(clone(batchItem));
  49988. });
  49989. batch.length && this.api.dispatchAction({
  49990. type: 'dataZoom',
  49991. from: this.uid,
  49992. batch: batch
  49993. });
  49994. };
  49995. function retrieveAxisSetting(option) {
  49996. var setting = {};
  49997. // Compatible with previous setting: null => all axis, false => no axis.
  49998. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  49999. setting[name] = option[name];
  50000. setting[name] == null && (setting[name] = 'all');
  50001. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  50002. });
  50003. return setting;
  50004. }
  50005. function updateBackBtnStatus(featureModel, ecModel) {
  50006. featureModel.setIconStatus(
  50007. 'back',
  50008. count(ecModel) > 1 ? 'emphasis' : 'normal'
  50009. );
  50010. }
  50011. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  50012. var zoomActive = view._isZoomActive;
  50013. if (payload && payload.type === 'takeGlobalCursor') {
  50014. zoomActive = payload.key === 'dataZoomSelect'
  50015. ? payload.dataZoomSelectActive : false;
  50016. }
  50017. view._isZoomActive = zoomActive;
  50018. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  50019. var brushTargetManager = new BrushTargetManager(
  50020. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  50021. );
  50022. view._brushController
  50023. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  50024. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  50025. ? 'lineX'
  50026. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  50027. ? 'lineY'
  50028. : 'rect';
  50029. }))
  50030. .enableBrush(
  50031. zoomActive
  50032. ? {
  50033. brushType: 'auto',
  50034. brushStyle: {
  50035. // FIXME user customized?
  50036. lineWidth: 0,
  50037. fill: 'rgba(0,0,0,0.2)'
  50038. }
  50039. }
  50040. : false
  50041. );
  50042. }
  50043. register$2('dataZoom', DataZoom);
  50044. // Create special dataZoom option for select
  50045. // FIXME consider the case of merge option, where axes options are not exists.
  50046. registerPreprocessor(function (option) {
  50047. if (!option) {
  50048. return;
  50049. }
  50050. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  50051. if (!isArray(dataZoomOpts)) {
  50052. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  50053. }
  50054. var toolboxOpt = option.toolbox;
  50055. if (toolboxOpt) {
  50056. // Assume there is only one toolbox
  50057. if (isArray(toolboxOpt)) {
  50058. toolboxOpt = toolboxOpt[0];
  50059. }
  50060. if (toolboxOpt && toolboxOpt.feature) {
  50061. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  50062. // FIXME: If add dataZoom when setOption in merge mode,
  50063. // no axis info to be added. See `test/dataZoom-extreme.html`
  50064. addForAxis('xAxis', dataZoomOpt);
  50065. addForAxis('yAxis', dataZoomOpt);
  50066. }
  50067. }
  50068. function addForAxis(axisName, dataZoomOpt) {
  50069. if (!dataZoomOpt) {
  50070. return;
  50071. }
  50072. // Try not to modify model, because it is not merged yet.
  50073. var axisIndicesName = axisName + 'Index';
  50074. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  50075. if (givenAxisIndices != null
  50076. && givenAxisIndices !== 'all'
  50077. && !isArray(givenAxisIndices)
  50078. ) {
  50079. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  50080. }
  50081. forEachComponent(axisName, function (axisOpt, axisIndex) {
  50082. if (givenAxisIndices != null
  50083. && givenAxisIndices !== 'all'
  50084. && indexOf(givenAxisIndices, axisIndex) === -1
  50085. ) {
  50086. return;
  50087. }
  50088. var newOpt = {
  50089. type: 'select',
  50090. $fromToolbox: true,
  50091. // Id for merge mapping.
  50092. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  50093. };
  50094. // FIXME
  50095. // Only support one axis now.
  50096. newOpt[axisIndicesName] = axisIndex;
  50097. dataZoomOpts.push(newOpt);
  50098. });
  50099. }
  50100. function forEachComponent(mainType, cb) {
  50101. var opts = option[mainType];
  50102. if (!isArray(opts)) {
  50103. opts = opts ? [opts] : [];
  50104. }
  50105. each$15(opts, cb);
  50106. }
  50107. });
  50108. /*
  50109. * Licensed to the Apache Software Foundation (ASF) under one
  50110. * or more contributor license agreements. See the NOTICE file
  50111. * distributed with this work for additional information
  50112. * regarding copyright ownership. The ASF licenses this file
  50113. * to you under the Apache License, Version 2.0 (the
  50114. * "License"); you may not use this file except in compliance
  50115. * with the License. You may obtain a copy of the License at
  50116. *
  50117. * http://www.apache.org/licenses/LICENSE-2.0
  50118. *
  50119. * Unless required by applicable law or agreed to in writing,
  50120. * software distributed under the License is distributed on an
  50121. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50122. * KIND, either express or implied. See the License for the
  50123. * specific language governing permissions and limitations
  50124. * under the License.
  50125. */
  50126. var restoreLang = lang.toolbox.restore;
  50127. function Restore(model) {
  50128. this.model = model;
  50129. }
  50130. Restore.defaultOption = {
  50131. show: true,
  50132. /* eslint-disable */
  50133. icon: 'M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5',
  50134. /* eslint-enable */
  50135. title: restoreLang.title
  50136. };
  50137. var proto$6 = Restore.prototype;
  50138. proto$6.onclick = function (ecModel, api, type) {
  50139. clear$1(ecModel);
  50140. api.dispatchAction({
  50141. type: 'restore',
  50142. from: this.uid
  50143. });
  50144. };
  50145. register$2('restore', Restore);
  50146. registerAction(
  50147. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  50148. function (payload, ecModel) {
  50149. ecModel.resetOption('recreate');
  50150. }
  50151. );
  50152. /*
  50153. * Licensed to the Apache Software Foundation (ASF) under one
  50154. * or more contributor license agreements. See the NOTICE file
  50155. * distributed with this work for additional information
  50156. * regarding copyright ownership. The ASF licenses this file
  50157. * to you under the Apache License, Version 2.0 (the
  50158. * "License"); you may not use this file except in compliance
  50159. * with the License. You may obtain a copy of the License at
  50160. *
  50161. * http://www.apache.org/licenses/LICENSE-2.0
  50162. *
  50163. * Unless required by applicable law or agreed to in writing,
  50164. * software distributed under the License is distributed on an
  50165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50166. * KIND, either express or implied. See the License for the
  50167. * specific language governing permissions and limitations
  50168. * under the License.
  50169. */
  50170. var urn = 'urn:schemas-microsoft-com:vml';
  50171. var win = typeof window === 'undefined' ? null : window;
  50172. var vmlInited = false;
  50173. var doc = win && win.document;
  50174. function createNode(tagName) {
  50175. return doCreateNode(tagName);
  50176. }
  50177. // Avoid assign to an exported variable, for transforming to cjs.
  50178. var doCreateNode;
  50179. if (doc && !env$1.canvasSupported) {
  50180. try {
  50181. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  50182. doCreateNode = function (tagName) {
  50183. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  50184. };
  50185. }
  50186. catch (e) {
  50187. doCreateNode = function (tagName) {
  50188. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  50189. };
  50190. }
  50191. }
  50192. // From raphael
  50193. function initVML() {
  50194. if (vmlInited || !doc) {
  50195. return;
  50196. }
  50197. vmlInited = true;
  50198. var styleSheets = doc.styleSheets;
  50199. if (styleSheets.length < 31) {
  50200. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  50201. }
  50202. else {
  50203. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  50204. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  50205. }
  50206. }
  50207. // http://www.w3.org/TR/NOTE-VML
  50208. // TODO Use proxy like svg instead of overwrite brush methods
  50209. var CMD$3 = PathProxy.CMD;
  50210. var round$3 = Math.round;
  50211. var sqrt = Math.sqrt;
  50212. var abs$1 = Math.abs;
  50213. var cos = Math.cos;
  50214. var sin = Math.sin;
  50215. var mathMax$5 = Math.max;
  50216. if (!env$1.canvasSupported) {
  50217. var comma = ',';
  50218. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  50219. var Z = 21600;
  50220. var Z2 = Z / 2;
  50221. var ZLEVEL_BASE = 100000;
  50222. var Z_BASE = 1000;
  50223. var initRootElStyle = function (el) {
  50224. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  50225. el.coordsize = Z + ',' + Z;
  50226. el.coordorigin = '0,0';
  50227. };
  50228. var encodeHtmlAttribute = function (s) {
  50229. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  50230. };
  50231. var rgb2Str = function (r, g, b) {
  50232. return 'rgb(' + [r, g, b].join(',') + ')';
  50233. };
  50234. var append = function (parent, child) {
  50235. if (child && parent && child.parentNode !== parent) {
  50236. parent.appendChild(child);
  50237. }
  50238. };
  50239. var remove = function (parent, child) {
  50240. if (child && parent && child.parentNode === parent) {
  50241. parent.removeChild(child);
  50242. }
  50243. };
  50244. var getZIndex = function (zlevel, z, z2) {
  50245. // z 的取值范围为 [0, 1000]
  50246. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  50247. };
  50248. var parsePercent$3 = function (value, maxValue) {
  50249. if (typeof value === 'string') {
  50250. if (value.lastIndexOf('%') >= 0) {
  50251. return parseFloat(value) / 100 * maxValue;
  50252. }
  50253. return parseFloat(value);
  50254. }
  50255. return value;
  50256. };
  50257. /***************************************************
  50258. * PATH
  50259. **************************************************/
  50260. var setColorAndOpacity = function (el, color, opacity) {
  50261. var colorArr = parse(color);
  50262. opacity = +opacity;
  50263. if (isNaN(opacity)) {
  50264. opacity = 1;
  50265. }
  50266. if (colorArr) {
  50267. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  50268. el.opacity = opacity * colorArr[3];
  50269. }
  50270. };
  50271. var getColorAndAlpha = function (color) {
  50272. var colorArr = parse(color);
  50273. return [
  50274. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  50275. colorArr[3]
  50276. ];
  50277. };
  50278. var updateFillNode = function (el, style, zrEl) {
  50279. // TODO pattern
  50280. var fill = style.fill;
  50281. if (fill != null) {
  50282. // Modified from excanvas
  50283. if (fill instanceof Gradient) {
  50284. var gradientType;
  50285. var angle = 0;
  50286. var focus = [0, 0];
  50287. // additional offset
  50288. var shift = 0;
  50289. // scale factor for offset
  50290. var expansion = 1;
  50291. var rect = zrEl.getBoundingRect();
  50292. var rectWidth = rect.width;
  50293. var rectHeight = rect.height;
  50294. if (fill.type === 'linear') {
  50295. gradientType = 'gradient';
  50296. var transform = zrEl.transform;
  50297. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  50298. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  50299. if (transform) {
  50300. applyTransform(p0, p0, transform);
  50301. applyTransform(p1, p1, transform);
  50302. }
  50303. var dx = p1[0] - p0[0];
  50304. var dy = p1[1] - p0[1];
  50305. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  50306. // The angle should be a non-negative number.
  50307. if (angle < 0) {
  50308. angle += 360;
  50309. }
  50310. // Very small angles produce an unexpected result because they are
  50311. // converted to a scientific notation string.
  50312. if (angle < 1e-6) {
  50313. angle = 0;
  50314. }
  50315. }
  50316. else {
  50317. gradientType = 'gradientradial';
  50318. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  50319. var transform = zrEl.transform;
  50320. var scale$$1 = zrEl.scale;
  50321. var width = rectWidth;
  50322. var height = rectHeight;
  50323. focus = [
  50324. // Percent in bounding rect
  50325. (p0[0] - rect.x) / width,
  50326. (p0[1] - rect.y) / height
  50327. ];
  50328. if (transform) {
  50329. applyTransform(p0, p0, transform);
  50330. }
  50331. width /= scale$$1[0] * Z;
  50332. height /= scale$$1[1] * Z;
  50333. var dimension = mathMax$5(width, height);
  50334. shift = 2 * 0 / dimension;
  50335. expansion = 2 * fill.r / dimension - shift;
  50336. }
  50337. // We need to sort the color stops in ascending order by offset,
  50338. // otherwise IE won't interpret it correctly.
  50339. var stops = fill.colorStops.slice();
  50340. stops.sort(function (cs1, cs2) {
  50341. return cs1.offset - cs2.offset;
  50342. });
  50343. var length$$1 = stops.length;
  50344. // Color and alpha list of first and last stop
  50345. var colorAndAlphaList = [];
  50346. var colors = [];
  50347. for (var i = 0; i < length$$1; i++) {
  50348. var stop = stops[i];
  50349. var colorAndAlpha = getColorAndAlpha(stop.color);
  50350. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  50351. if (i === 0 || i === length$$1 - 1) {
  50352. colorAndAlphaList.push(colorAndAlpha);
  50353. }
  50354. }
  50355. if (length$$1 >= 2) {
  50356. var color1 = colorAndAlphaList[0][0];
  50357. var color2 = colorAndAlphaList[1][0];
  50358. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  50359. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  50360. el.type = gradientType;
  50361. el.method = 'none';
  50362. el.focus = '100%';
  50363. el.angle = angle;
  50364. el.color = color1;
  50365. el.color2 = color2;
  50366. el.colors = colors.join(',');
  50367. // When colors attribute is used, the meanings of opacity and o:opacity2
  50368. // are reversed.
  50369. el.opacity = opacity2;
  50370. // FIXME g_o_:opacity ?
  50371. el.opacity2 = opacity1;
  50372. }
  50373. if (gradientType === 'radial') {
  50374. el.focusposition = focus.join(',');
  50375. }
  50376. }
  50377. else {
  50378. // FIXME Change from Gradient fill to color fill
  50379. setColorAndOpacity(el, fill, style.opacity);
  50380. }
  50381. }
  50382. };
  50383. var updateStrokeNode = function (el, style) {
  50384. // if (style.lineJoin != null) {
  50385. // el.joinstyle = style.lineJoin;
  50386. // }
  50387. // if (style.miterLimit != null) {
  50388. // el.miterlimit = style.miterLimit * Z;
  50389. // }
  50390. // if (style.lineCap != null) {
  50391. // el.endcap = style.lineCap;
  50392. // }
  50393. if (style.lineDash != null) {
  50394. el.dashstyle = style.lineDash.join(' ');
  50395. }
  50396. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  50397. setColorAndOpacity(el, style.stroke, style.opacity);
  50398. }
  50399. };
  50400. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  50401. var isFill = type === 'fill';
  50402. var el = vmlEl.getElementsByTagName(type)[0];
  50403. // Stroke must have lineWidth
  50404. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  50405. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  50406. // FIXME Remove before updating, or set `colors` will throw error
  50407. if (style[type] instanceof Gradient) {
  50408. remove(vmlEl, el);
  50409. }
  50410. if (!el) {
  50411. el = createNode(type);
  50412. }
  50413. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  50414. append(vmlEl, el);
  50415. }
  50416. else {
  50417. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  50418. remove(vmlEl, el);
  50419. }
  50420. };
  50421. var points$1 = [[], [], []];
  50422. var pathDataToString = function (path, m) {
  50423. var M = CMD$3.M;
  50424. var C = CMD$3.C;
  50425. var L = CMD$3.L;
  50426. var A = CMD$3.A;
  50427. var Q = CMD$3.Q;
  50428. var str = [];
  50429. var nPoint;
  50430. var cmdStr;
  50431. var cmd;
  50432. var i;
  50433. var xi;
  50434. var yi;
  50435. var data = path.data;
  50436. var dataLength = path.len();
  50437. for (i = 0; i < dataLength;) {
  50438. cmd = data[i++];
  50439. cmdStr = '';
  50440. nPoint = 0;
  50441. switch (cmd) {
  50442. case M:
  50443. cmdStr = ' m ';
  50444. nPoint = 1;
  50445. xi = data[i++];
  50446. yi = data[i++];
  50447. points$1[0][0] = xi;
  50448. points$1[0][1] = yi;
  50449. break;
  50450. case L:
  50451. cmdStr = ' l ';
  50452. nPoint = 1;
  50453. xi = data[i++];
  50454. yi = data[i++];
  50455. points$1[0][0] = xi;
  50456. points$1[0][1] = yi;
  50457. break;
  50458. case Q:
  50459. case C:
  50460. cmdStr = ' c ';
  50461. nPoint = 3;
  50462. var x1 = data[i++];
  50463. var y1 = data[i++];
  50464. var x2 = data[i++];
  50465. var y2 = data[i++];
  50466. var x3;
  50467. var y3;
  50468. if (cmd === Q) {
  50469. // Convert quadratic to cubic using degree elevation
  50470. x3 = x2;
  50471. y3 = y2;
  50472. x2 = (x2 + 2 * x1) / 3;
  50473. y2 = (y2 + 2 * y1) / 3;
  50474. x1 = (xi + 2 * x1) / 3;
  50475. y1 = (yi + 2 * y1) / 3;
  50476. }
  50477. else {
  50478. x3 = data[i++];
  50479. y3 = data[i++];
  50480. }
  50481. points$1[0][0] = x1;
  50482. points$1[0][1] = y1;
  50483. points$1[1][0] = x2;
  50484. points$1[1][1] = y2;
  50485. points$1[2][0] = x3;
  50486. points$1[2][1] = y3;
  50487. xi = x3;
  50488. yi = y3;
  50489. break;
  50490. case A:
  50491. var x = 0;
  50492. var y = 0;
  50493. var sx = 1;
  50494. var sy = 1;
  50495. var angle = 0;
  50496. if (m) {
  50497. // Extract SRT from matrix
  50498. x = m[4];
  50499. y = m[5];
  50500. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  50501. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  50502. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  50503. }
  50504. var cx = data[i++];
  50505. var cy = data[i++];
  50506. var rx = data[i++];
  50507. var ry = data[i++];
  50508. var startAngle = data[i++] + angle;
  50509. var endAngle = data[i++] + startAngle + angle;
  50510. // FIXME
  50511. // var psi = data[i++];
  50512. i++;
  50513. var clockwise = data[i++];
  50514. var x0 = cx + cos(startAngle) * rx;
  50515. var y0 = cy + sin(startAngle) * ry;
  50516. var x1 = cx + cos(endAngle) * rx;
  50517. var y1 = cy + sin(endAngle) * ry;
  50518. var type = clockwise ? ' wa ' : ' at ';
  50519. if (Math.abs(x0 - x1) < 1e-4) {
  50520. // IE won't render arches drawn counter clockwise if x0 == x1.
  50521. if (Math.abs(endAngle - startAngle) > 1e-2) {
  50522. // Offset x0 by 1/80 of a pixel. Use something
  50523. // that can be represented in binary
  50524. if (clockwise) {
  50525. x0 += 270 / Z;
  50526. }
  50527. }
  50528. else {
  50529. // Avoid case draw full circle
  50530. if (Math.abs(y0 - cy) < 1e-4) {
  50531. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  50532. y1 -= 270 / Z;
  50533. }
  50534. else {
  50535. y1 += 270 / Z;
  50536. }
  50537. }
  50538. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  50539. x1 += 270 / Z;
  50540. }
  50541. else {
  50542. x1 -= 270 / Z;
  50543. }
  50544. }
  50545. }
  50546. str.push(
  50547. type,
  50548. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  50549. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  50550. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  50551. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  50552. round$3((x0 * sx + x) * Z - Z2), comma,
  50553. round$3((y0 * sy + y) * Z - Z2), comma,
  50554. round$3((x1 * sx + x) * Z - Z2), comma,
  50555. round$3((y1 * sy + y) * Z - Z2)
  50556. );
  50557. xi = x1;
  50558. yi = y1;
  50559. break;
  50560. case CMD$3.R:
  50561. var p0 = points$1[0];
  50562. var p1 = points$1[1];
  50563. // x0, y0
  50564. p0[0] = data[i++];
  50565. p0[1] = data[i++];
  50566. // x1, y1
  50567. p1[0] = p0[0] + data[i++];
  50568. p1[1] = p0[1] + data[i++];
  50569. if (m) {
  50570. applyTransform(p0, p0, m);
  50571. applyTransform(p1, p1, m);
  50572. }
  50573. p0[0] = round$3(p0[0] * Z - Z2);
  50574. p1[0] = round$3(p1[0] * Z - Z2);
  50575. p0[1] = round$3(p0[1] * Z - Z2);
  50576. p1[1] = round$3(p1[1] * Z - Z2);
  50577. str.push(
  50578. // x0, y0
  50579. ' m ', p0[0], comma, p0[1],
  50580. // x1, y0
  50581. ' l ', p1[0], comma, p0[1],
  50582. // x1, y1
  50583. ' l ', p1[0], comma, p1[1],
  50584. // x0, y1
  50585. ' l ', p0[0], comma, p1[1]
  50586. );
  50587. break;
  50588. case CMD$3.Z:
  50589. // FIXME Update xi, yi
  50590. str.push(' x ');
  50591. }
  50592. if (nPoint > 0) {
  50593. str.push(cmdStr);
  50594. for (var k = 0; k < nPoint; k++) {
  50595. var p = points$1[k];
  50596. m && applyTransform(p, p, m);
  50597. // 不 round 会非常慢
  50598. str.push(
  50599. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  50600. k < nPoint - 1 ? comma : ''
  50601. );
  50602. }
  50603. }
  50604. }
  50605. return str.join('');
  50606. };
  50607. // Rewrite the original path method
  50608. Path.prototype.brushVML = function (vmlRoot) {
  50609. var style = this.style;
  50610. var vmlEl = this._vmlEl;
  50611. if (!vmlEl) {
  50612. vmlEl = createNode('shape');
  50613. initRootElStyle(vmlEl);
  50614. this._vmlEl = vmlEl;
  50615. }
  50616. updateFillAndStroke(vmlEl, 'fill', style, this);
  50617. updateFillAndStroke(vmlEl, 'stroke', style, this);
  50618. var m = this.transform;
  50619. var needTransform = m != null;
  50620. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  50621. if (strokeEl) {
  50622. var lineWidth = style.lineWidth;
  50623. // Get the line scale.
  50624. // Determinant of this.m_ means how much the area is enlarged by the
  50625. // transformation. So its square root can be used as a scale factor
  50626. // for width.
  50627. if (needTransform && !style.strokeNoScale) {
  50628. var det = m[0] * m[3] - m[1] * m[2];
  50629. lineWidth *= sqrt(abs$1(det));
  50630. }
  50631. strokeEl.weight = lineWidth + 'px';
  50632. }
  50633. var path = this.path || (this.path = new PathProxy());
  50634. if (this.__dirtyPath) {
  50635. path.beginPath();
  50636. path.subPixelOptimize = false;
  50637. this.buildPath(path, this.shape);
  50638. path.toStatic();
  50639. this.__dirtyPath = false;
  50640. }
  50641. vmlEl.path = pathDataToString(path, this.transform);
  50642. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  50643. // Append to root
  50644. append(vmlRoot, vmlEl);
  50645. // Text
  50646. if (style.text != null) {
  50647. this.drawRectText(vmlRoot, this.getBoundingRect());
  50648. }
  50649. else {
  50650. this.removeRectText(vmlRoot);
  50651. }
  50652. };
  50653. Path.prototype.onRemove = function (vmlRoot) {
  50654. remove(vmlRoot, this._vmlEl);
  50655. this.removeRectText(vmlRoot);
  50656. };
  50657. Path.prototype.onAdd = function (vmlRoot) {
  50658. append(vmlRoot, this._vmlEl);
  50659. this.appendRectText(vmlRoot);
  50660. };
  50661. /***************************************************
  50662. * IMAGE
  50663. **************************************************/
  50664. var isImage = function (img) {
  50665. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  50666. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  50667. // return img instanceof Image;
  50668. };
  50669. // Rewrite the original path method
  50670. ZImage.prototype.brushVML = function (vmlRoot) {
  50671. var style = this.style;
  50672. var image = style.image;
  50673. // Image original width, height
  50674. var ow;
  50675. var oh;
  50676. if (isImage(image)) {
  50677. var src = image.src;
  50678. if (src === this._imageSrc) {
  50679. ow = this._imageWidth;
  50680. oh = this._imageHeight;
  50681. }
  50682. else {
  50683. var imageRuntimeStyle = image.runtimeStyle;
  50684. var oldRuntimeWidth = imageRuntimeStyle.width;
  50685. var oldRuntimeHeight = imageRuntimeStyle.height;
  50686. imageRuntimeStyle.width = 'auto';
  50687. imageRuntimeStyle.height = 'auto';
  50688. // get the original size
  50689. ow = image.width;
  50690. oh = image.height;
  50691. // and remove overides
  50692. imageRuntimeStyle.width = oldRuntimeWidth;
  50693. imageRuntimeStyle.height = oldRuntimeHeight;
  50694. // Caching image original width, height and src
  50695. this._imageSrc = src;
  50696. this._imageWidth = ow;
  50697. this._imageHeight = oh;
  50698. }
  50699. image = src;
  50700. }
  50701. else {
  50702. if (image === this._imageSrc) {
  50703. ow = this._imageWidth;
  50704. oh = this._imageHeight;
  50705. }
  50706. }
  50707. if (!image) {
  50708. return;
  50709. }
  50710. var x = style.x || 0;
  50711. var y = style.y || 0;
  50712. var dw = style.width;
  50713. var dh = style.height;
  50714. var sw = style.sWidth;
  50715. var sh = style.sHeight;
  50716. var sx = style.sx || 0;
  50717. var sy = style.sy || 0;
  50718. var hasCrop = sw && sh;
  50719. var vmlEl = this._vmlEl;
  50720. if (!vmlEl) {
  50721. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  50722. // vmlEl = vmlCore.createNode('group');
  50723. vmlEl = doc.createElement('div');
  50724. initRootElStyle(vmlEl);
  50725. this._vmlEl = vmlEl;
  50726. }
  50727. var vmlElStyle = vmlEl.style;
  50728. var hasRotation = false;
  50729. var m;
  50730. var scaleX = 1;
  50731. var scaleY = 1;
  50732. if (this.transform) {
  50733. m = this.transform;
  50734. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  50735. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  50736. hasRotation = m[1] || m[2];
  50737. }
  50738. if (hasRotation) {
  50739. // If filters are necessary (rotation exists), create them
  50740. // filters are bog-slow, so only create them if abbsolutely necessary
  50741. // The following check doesn't account for skews (which don't exist
  50742. // in the canvas spec (yet) anyway.
  50743. // From excanvas
  50744. var p0 = [x, y];
  50745. var p1 = [x + dw, y];
  50746. var p2 = [x, y + dh];
  50747. var p3 = [x + dw, y + dh];
  50748. applyTransform(p0, p0, m);
  50749. applyTransform(p1, p1, m);
  50750. applyTransform(p2, p2, m);
  50751. applyTransform(p3, p3, m);
  50752. var maxX = mathMax$5(p0[0], p1[0], p2[0], p3[0]);
  50753. var maxY = mathMax$5(p0[1], p1[1], p2[1], p3[1]);
  50754. var transformFilter = [];
  50755. transformFilter.push('M11=', m[0] / scaleX, comma,
  50756. 'M12=', m[2] / scaleY, comma,
  50757. 'M21=', m[1] / scaleX, comma,
  50758. 'M22=', m[3] / scaleY, comma,
  50759. 'Dx=', round$3(x * scaleX + m[4]), comma,
  50760. 'Dy=', round$3(y * scaleY + m[5]));
  50761. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  50762. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  50763. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  50764. + transformFilter.join('') + ', SizingMethod=clip)';
  50765. }
  50766. else {
  50767. if (m) {
  50768. x = x * scaleX + m[4];
  50769. y = y * scaleY + m[5];
  50770. }
  50771. vmlElStyle.filter = '';
  50772. vmlElStyle.left = round$3(x) + 'px';
  50773. vmlElStyle.top = round$3(y) + 'px';
  50774. }
  50775. var imageEl = this._imageEl;
  50776. var cropEl = this._cropEl;
  50777. if (!imageEl) {
  50778. imageEl = doc.createElement('div');
  50779. this._imageEl = imageEl;
  50780. }
  50781. var imageELStyle = imageEl.style;
  50782. if (hasCrop) {
  50783. // Needs know image original width and height
  50784. if (!(ow && oh)) {
  50785. var tmpImage = new Image();
  50786. var self = this;
  50787. tmpImage.onload = function () {
  50788. tmpImage.onload = null;
  50789. ow = tmpImage.width;
  50790. oh = tmpImage.height;
  50791. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  50792. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  50793. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  50794. // Caching image original width, height and src
  50795. self._imageWidth = ow;
  50796. self._imageHeight = oh;
  50797. self._imageSrc = image;
  50798. };
  50799. tmpImage.src = image;
  50800. }
  50801. else {
  50802. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  50803. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  50804. }
  50805. if (!cropEl) {
  50806. cropEl = doc.createElement('div');
  50807. cropEl.style.overflow = 'hidden';
  50808. this._cropEl = cropEl;
  50809. }
  50810. var cropElStyle = cropEl.style;
  50811. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  50812. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  50813. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  50814. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  50815. if (!cropEl.parentNode) {
  50816. vmlEl.appendChild(cropEl);
  50817. }
  50818. if (imageEl.parentNode !== cropEl) {
  50819. cropEl.appendChild(imageEl);
  50820. }
  50821. }
  50822. else {
  50823. imageELStyle.width = round$3(scaleX * dw) + 'px';
  50824. imageELStyle.height = round$3(scaleY * dh) + 'px';
  50825. vmlEl.appendChild(imageEl);
  50826. if (cropEl && cropEl.parentNode) {
  50827. vmlEl.removeChild(cropEl);
  50828. this._cropEl = null;
  50829. }
  50830. }
  50831. var filterStr = '';
  50832. var alpha = style.opacity;
  50833. if (alpha < 1) {
  50834. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  50835. }
  50836. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  50837. imageELStyle.filter = filterStr;
  50838. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  50839. // Append to root
  50840. append(vmlRoot, vmlEl);
  50841. // Text
  50842. if (style.text != null) {
  50843. this.drawRectText(vmlRoot, this.getBoundingRect());
  50844. }
  50845. };
  50846. ZImage.prototype.onRemove = function (vmlRoot) {
  50847. remove(vmlRoot, this._vmlEl);
  50848. this._vmlEl = null;
  50849. this._cropEl = null;
  50850. this._imageEl = null;
  50851. this.removeRectText(vmlRoot);
  50852. };
  50853. ZImage.prototype.onAdd = function (vmlRoot) {
  50854. append(vmlRoot, this._vmlEl);
  50855. this.appendRectText(vmlRoot);
  50856. };
  50857. /***************************************************
  50858. * TEXT
  50859. **************************************************/
  50860. var DEFAULT_STYLE_NORMAL = 'normal';
  50861. var fontStyleCache = {};
  50862. var fontStyleCacheCount = 0;
  50863. var MAX_FONT_CACHE_SIZE = 100;
  50864. var fontEl = document.createElement('div');
  50865. var getFontStyle = function (fontString) {
  50866. var fontStyle = fontStyleCache[fontString];
  50867. if (!fontStyle) {
  50868. // Clear cache
  50869. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  50870. fontStyleCacheCount = 0;
  50871. fontStyleCache = {};
  50872. }
  50873. var style = fontEl.style;
  50874. var fontFamily;
  50875. try {
  50876. style.font = fontString;
  50877. fontFamily = style.fontFamily.split(',')[0];
  50878. }
  50879. catch (e) {
  50880. }
  50881. fontStyle = {
  50882. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  50883. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  50884. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  50885. size: parseFloat(style.fontSize || 12) | 0,
  50886. family: fontFamily || 'Microsoft YaHei'
  50887. };
  50888. fontStyleCache[fontString] = fontStyle;
  50889. fontStyleCacheCount++;
  50890. }
  50891. return fontStyle;
  50892. };
  50893. var textMeasureEl;
  50894. // Overwrite measure text method
  50895. $override$1('measureText', function (text, textFont) {
  50896. var doc$$1 = doc;
  50897. if (!textMeasureEl) {
  50898. textMeasureEl = doc$$1.createElement('div');
  50899. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  50900. + 'padding:0;margin:0;border:none;white-space:pre;';
  50901. doc.body.appendChild(textMeasureEl);
  50902. }
  50903. try {
  50904. textMeasureEl.style.font = textFont;
  50905. }
  50906. catch (ex) {
  50907. // Ignore failures to set to invalid font.
  50908. }
  50909. textMeasureEl.innerHTML = '';
  50910. // Don't use innerHTML or innerText because they allow markup/whitespace.
  50911. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  50912. return {
  50913. width: textMeasureEl.offsetWidth
  50914. };
  50915. });
  50916. var tmpRect$2 = new BoundingRect();
  50917. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  50918. var style = this.style;
  50919. // Optimize, avoid normalize every time.
  50920. this.__dirty && normalizeTextStyle(style, true);
  50921. var text = style.text;
  50922. // Convert to string
  50923. text != null && (text += '');
  50924. if (!text) {
  50925. return;
  50926. }
  50927. // Convert rich text to plain text. Rich text is not supported in
  50928. // IE8-, but tags in rich text template will be removed.
  50929. if (style.rich) {
  50930. var contentBlock = parseRichText(text, style);
  50931. text = [];
  50932. for (var i = 0; i < contentBlock.lines.length; i++) {
  50933. var tokens = contentBlock.lines[i].tokens;
  50934. var textLine = [];
  50935. for (var j = 0; j < tokens.length; j++) {
  50936. textLine.push(tokens[j].text);
  50937. }
  50938. text.push(textLine.join(''));
  50939. }
  50940. text = text.join('\n');
  50941. }
  50942. var x;
  50943. var y;
  50944. var align = style.textAlign;
  50945. var verticalAlign = style.textVerticalAlign;
  50946. var fontStyle = getFontStyle(style.font);
  50947. // FIXME encodeHtmlAttribute ?
  50948. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  50949. + fontStyle.size + 'px "' + fontStyle.family + '"';
  50950. textRect = textRect || getBoundingRect(
  50951. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  50952. );
  50953. // Transform rect to view space
  50954. var m = this.transform;
  50955. // Ignore transform for text in other element
  50956. if (m && !fromTextEl) {
  50957. tmpRect$2.copy(rect);
  50958. tmpRect$2.applyTransform(m);
  50959. rect = tmpRect$2;
  50960. }
  50961. if (!fromTextEl) {
  50962. var textPosition = style.textPosition;
  50963. var distance$$1 = style.textDistance;
  50964. // Text position represented by coord
  50965. if (textPosition instanceof Array) {
  50966. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  50967. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  50968. align = align || 'left';
  50969. }
  50970. else {
  50971. var res = adjustTextPositionOnRect(
  50972. textPosition, rect, distance$$1
  50973. );
  50974. x = res.x;
  50975. y = res.y;
  50976. // Default align and baseline when has textPosition
  50977. align = align || res.textAlign;
  50978. verticalAlign = verticalAlign || res.textVerticalAlign;
  50979. }
  50980. }
  50981. else {
  50982. x = rect.x;
  50983. y = rect.y;
  50984. }
  50985. x = adjustTextX(x, textRect.width, align);
  50986. y = adjustTextY(y, textRect.height, verticalAlign);
  50987. // Force baseline 'middle'
  50988. y += textRect.height / 2;
  50989. // var fontSize = fontStyle.size;
  50990. // 1.75 is an arbitrary number, as there is no info about the text baseline
  50991. // switch (baseline) {
  50992. // case 'hanging':
  50993. // case 'top':
  50994. // y += fontSize / 1.75;
  50995. // break;
  50996. // case 'middle':
  50997. // break;
  50998. // default:
  50999. // // case null:
  51000. // // case 'alphabetic':
  51001. // // case 'ideographic':
  51002. // // case 'bottom':
  51003. // y -= fontSize / 2.25;
  51004. // break;
  51005. // }
  51006. // switch (align) {
  51007. // case 'left':
  51008. // break;
  51009. // case 'center':
  51010. // x -= textRect.width / 2;
  51011. // break;
  51012. // case 'right':
  51013. // x -= textRect.width;
  51014. // break;
  51015. // case 'end':
  51016. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  51017. // break;
  51018. // case 'start':
  51019. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  51020. // break;
  51021. // default:
  51022. // align = 'left';
  51023. // }
  51024. var createNode$$1 = createNode;
  51025. var textVmlEl = this._textVmlEl;
  51026. var pathEl;
  51027. var textPathEl;
  51028. var skewEl;
  51029. if (!textVmlEl) {
  51030. textVmlEl = createNode$$1('line');
  51031. pathEl = createNode$$1('path');
  51032. textPathEl = createNode$$1('textpath');
  51033. skewEl = createNode$$1('skew');
  51034. // FIXME Why here is not cammel case
  51035. // Align 'center' seems wrong
  51036. textPathEl.style['v-text-align'] = 'left';
  51037. initRootElStyle(textVmlEl);
  51038. pathEl.textpathok = true;
  51039. textPathEl.on = true;
  51040. textVmlEl.from = '0 0';
  51041. textVmlEl.to = '1000 0.05';
  51042. append(textVmlEl, skewEl);
  51043. append(textVmlEl, pathEl);
  51044. append(textVmlEl, textPathEl);
  51045. this._textVmlEl = textVmlEl;
  51046. }
  51047. else {
  51048. // 这里是在前面 appendChild 保证顺序的前提下
  51049. skewEl = textVmlEl.firstChild;
  51050. pathEl = skewEl.nextSibling;
  51051. textPathEl = pathEl.nextSibling;
  51052. }
  51053. var coords = [x, y];
  51054. var textVmlElStyle = textVmlEl.style;
  51055. // Ignore transform for text in other element
  51056. if (m && fromTextEl) {
  51057. applyTransform(coords, coords, m);
  51058. skewEl.on = true;
  51059. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  51060. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  51061. // Text position
  51062. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  51063. // Left top point as origin
  51064. skewEl.origin = '0 0';
  51065. textVmlElStyle.left = '0px';
  51066. textVmlElStyle.top = '0px';
  51067. }
  51068. else {
  51069. skewEl.on = false;
  51070. textVmlElStyle.left = round$3(x) + 'px';
  51071. textVmlElStyle.top = round$3(y) + 'px';
  51072. }
  51073. textPathEl.string = encodeHtmlAttribute(text);
  51074. // TODO
  51075. try {
  51076. textPathEl.style.font = font;
  51077. }
  51078. // Error font format
  51079. catch (e) {}
  51080. updateFillAndStroke(textVmlEl, 'fill', {
  51081. fill: style.textFill,
  51082. opacity: style.opacity
  51083. }, this);
  51084. updateFillAndStroke(textVmlEl, 'stroke', {
  51085. stroke: style.textStroke,
  51086. opacity: style.opacity,
  51087. lineDash: style.lineDash
  51088. }, this);
  51089. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  51090. // Attached to root
  51091. append(vmlRoot, textVmlEl);
  51092. };
  51093. var removeRectText = function (vmlRoot) {
  51094. remove(vmlRoot, this._textVmlEl);
  51095. this._textVmlEl = null;
  51096. };
  51097. var appendRectText = function (vmlRoot) {
  51098. append(vmlRoot, this._textVmlEl);
  51099. };
  51100. var list = [RectText, Displayable, ZImage, Path, Text];
  51101. // In case Displayable has been mixed in RectText
  51102. for (var i$1 = 0; i$1 < list.length; i$1++) {
  51103. var proto$7 = list[i$1].prototype;
  51104. proto$7.drawRectText = drawRectText;
  51105. proto$7.removeRectText = removeRectText;
  51106. proto$7.appendRectText = appendRectText;
  51107. }
  51108. Text.prototype.brushVML = function (vmlRoot) {
  51109. var style = this.style;
  51110. if (style.text != null) {
  51111. this.drawRectText(vmlRoot, {
  51112. x: style.x || 0, y: style.y || 0,
  51113. width: 0, height: 0
  51114. }, this.getBoundingRect(), true);
  51115. }
  51116. else {
  51117. this.removeRectText(vmlRoot);
  51118. }
  51119. };
  51120. Text.prototype.onRemove = function (vmlRoot) {
  51121. this.removeRectText(vmlRoot);
  51122. };
  51123. Text.prototype.onAdd = function (vmlRoot) {
  51124. this.appendRectText(vmlRoot);
  51125. };
  51126. }
  51127. /**
  51128. * VML Painter.
  51129. *
  51130. * @module zrender/vml/Painter
  51131. */
  51132. function parseInt10$1(val) {
  51133. return parseInt(val, 10);
  51134. }
  51135. /**
  51136. * @alias module:zrender/vml/Painter
  51137. */
  51138. function VMLPainter(root, storage) {
  51139. initVML();
  51140. this.root = root;
  51141. this.storage = storage;
  51142. var vmlViewport = document.createElement('div');
  51143. var vmlRoot = document.createElement('div');
  51144. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  51145. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  51146. root.appendChild(vmlViewport);
  51147. this._vmlRoot = vmlRoot;
  51148. this._vmlViewport = vmlViewport;
  51149. this.resize();
  51150. // Modify storage
  51151. var oldDelFromStorage = storage.delFromStorage;
  51152. var oldAddToStorage = storage.addToStorage;
  51153. storage.delFromStorage = function (el) {
  51154. oldDelFromStorage.call(storage, el);
  51155. if (el) {
  51156. el.onRemove && el.onRemove(vmlRoot);
  51157. }
  51158. };
  51159. storage.addToStorage = function (el) {
  51160. // Displayable already has a vml node
  51161. el.onAdd && el.onAdd(vmlRoot);
  51162. oldAddToStorage.call(storage, el);
  51163. };
  51164. this._firstPaint = true;
  51165. }
  51166. VMLPainter.prototype = {
  51167. constructor: VMLPainter,
  51168. getType: function () {
  51169. return 'vml';
  51170. },
  51171. /**
  51172. * @return {HTMLDivElement}
  51173. */
  51174. getViewportRoot: function () {
  51175. return this._vmlViewport;
  51176. },
  51177. getViewportRootOffset: function () {
  51178. var viewportRoot = this.getViewportRoot();
  51179. if (viewportRoot) {
  51180. return {
  51181. offsetLeft: viewportRoot.offsetLeft || 0,
  51182. offsetTop: viewportRoot.offsetTop || 0
  51183. };
  51184. }
  51185. },
  51186. /**
  51187. * 刷新
  51188. */
  51189. refresh: function () {
  51190. var list = this.storage.getDisplayList(true, true);
  51191. this._paintList(list);
  51192. },
  51193. _paintList: function (list) {
  51194. var vmlRoot = this._vmlRoot;
  51195. for (var i = 0; i < list.length; i++) {
  51196. var el = list[i];
  51197. if (el.invisible || el.ignore) {
  51198. if (!el.__alreadyNotVisible) {
  51199. el.onRemove(vmlRoot);
  51200. }
  51201. // Set as already invisible
  51202. el.__alreadyNotVisible = true;
  51203. }
  51204. else {
  51205. if (el.__alreadyNotVisible) {
  51206. el.onAdd(vmlRoot);
  51207. }
  51208. el.__alreadyNotVisible = false;
  51209. if (el.__dirty) {
  51210. el.beforeBrush && el.beforeBrush();
  51211. (el.brushVML || el.brush).call(el, vmlRoot);
  51212. el.afterBrush && el.afterBrush();
  51213. }
  51214. }
  51215. el.__dirty = false;
  51216. }
  51217. if (this._firstPaint) {
  51218. // Detached from document at first time
  51219. // to avoid page refreshing too many times
  51220. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  51221. this._vmlViewport.appendChild(vmlRoot);
  51222. this._firstPaint = false;
  51223. }
  51224. },
  51225. resize: function (width, height) {
  51226. var width = width == null ? this._getWidth() : width;
  51227. var height = height == null ? this._getHeight() : height;
  51228. if (this._width !== width || this._height !== height) {
  51229. this._width = width;
  51230. this._height = height;
  51231. var vmlViewportStyle = this._vmlViewport.style;
  51232. vmlViewportStyle.width = width + 'px';
  51233. vmlViewportStyle.height = height + 'px';
  51234. }
  51235. },
  51236. dispose: function () {
  51237. this.root.innerHTML = '';
  51238. this._vmlRoot =
  51239. this._vmlViewport =
  51240. this.storage = null;
  51241. },
  51242. getWidth: function () {
  51243. return this._width;
  51244. },
  51245. getHeight: function () {
  51246. return this._height;
  51247. },
  51248. clear: function () {
  51249. if (this._vmlViewport) {
  51250. this.root.removeChild(this._vmlViewport);
  51251. }
  51252. },
  51253. _getWidth: function () {
  51254. var root = this.root;
  51255. var stl = root.currentStyle;
  51256. return ((root.clientWidth || parseInt10$1(stl.width))
  51257. - parseInt10$1(stl.paddingLeft)
  51258. - parseInt10$1(stl.paddingRight)) | 0;
  51259. },
  51260. _getHeight: function () {
  51261. var root = this.root;
  51262. var stl = root.currentStyle;
  51263. return ((root.clientHeight || parseInt10$1(stl.height))
  51264. - parseInt10$1(stl.paddingTop)
  51265. - parseInt10$1(stl.paddingBottom)) | 0;
  51266. }
  51267. };
  51268. // Not supported methods
  51269. function createMethodNotSupport(method) {
  51270. return function () {
  51271. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  51272. };
  51273. }
  51274. // Unsupported methods
  51275. each$1([
  51276. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  51277. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  51278. ], function (name) {
  51279. VMLPainter.prototype[name] = createMethodNotSupport(name);
  51280. });
  51281. registerPainter('vml', VMLPainter);
  51282. var svgURI = 'http://www.w3.org/2000/svg';
  51283. function createElement(name) {
  51284. return document.createElementNS(svgURI, name);
  51285. }
  51286. // TODO
  51287. // 1. shadow
  51288. // 2. Image: sx, sy, sw, sh
  51289. var CMD$4 = PathProxy.CMD;
  51290. var arrayJoin = Array.prototype.join;
  51291. var NONE = 'none';
  51292. var mathRound = Math.round;
  51293. var mathSin$3 = Math.sin;
  51294. var mathCos$3 = Math.cos;
  51295. var PI$3 = Math.PI;
  51296. var PI2$5 = Math.PI * 2;
  51297. var degree = 180 / PI$3;
  51298. var EPSILON$4 = 1e-4;
  51299. function round4(val) {
  51300. return mathRound(val * 1e4) / 1e4;
  51301. }
  51302. function isAroundZero$1(val) {
  51303. return val < EPSILON$4 && val > -EPSILON$4;
  51304. }
  51305. function pathHasFill(style, isText) {
  51306. var fill = isText ? style.textFill : style.fill;
  51307. return fill != null && fill !== NONE;
  51308. }
  51309. function pathHasStroke(style, isText) {
  51310. var stroke = isText ? style.textStroke : style.stroke;
  51311. return stroke != null && stroke !== NONE;
  51312. }
  51313. function setTransform(svgEl, m) {
  51314. if (m) {
  51315. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  51316. }
  51317. }
  51318. function attr(el, key, val) {
  51319. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  51320. // Don't set attribute for gradient, since it need new dom nodes
  51321. el.setAttribute(key, val);
  51322. }
  51323. }
  51324. function attrXLink(el, key, val) {
  51325. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  51326. }
  51327. function bindStyle(svgEl, style, isText, el) {
  51328. if (pathHasFill(style, isText)) {
  51329. var fill = isText ? style.textFill : style.fill;
  51330. fill = fill === 'transparent' ? NONE : fill;
  51331. /**
  51332. * FIXME:
  51333. * This is a temporary fix for Chrome's clipping bug
  51334. * that happens when a clip-path is referring another one.
  51335. * This fix should be used before Chrome's bug is fixed.
  51336. * For an element that has clip-path, and fill is none,
  51337. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  51338. * Otherwise, it will show black fill color.
  51339. * 0.002 is used because this won't work for alpha values smaller
  51340. * than 0.002.
  51341. *
  51342. * See
  51343. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  51344. * for more information.
  51345. */
  51346. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  51347. fill = 'rgba(0, 0, 0, 0.002)';
  51348. }
  51349. attr(svgEl, 'fill', fill);
  51350. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  51351. }
  51352. else {
  51353. attr(svgEl, 'fill', NONE);
  51354. }
  51355. if (pathHasStroke(style, isText)) {
  51356. var stroke = isText ? style.textStroke : style.stroke;
  51357. stroke = stroke === 'transparent' ? NONE : stroke;
  51358. attr(svgEl, 'stroke', stroke);
  51359. var strokeWidth = isText
  51360. ? style.textStrokeWidth
  51361. : style.lineWidth;
  51362. var strokeScale = !isText && style.strokeNoScale
  51363. ? el.getLineScale()
  51364. : 1;
  51365. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  51366. // stroke then fill for text; fill then stroke for others
  51367. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  51368. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  51369. var lineDash = style.lineDash;
  51370. if (lineDash) {
  51371. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  51372. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  51373. }
  51374. else {
  51375. attr(svgEl, 'stroke-dasharray', '');
  51376. }
  51377. // PENDING
  51378. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  51379. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  51380. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  51381. }
  51382. else {
  51383. attr(svgEl, 'stroke', NONE);
  51384. }
  51385. }
  51386. /***************************************************
  51387. * PATH
  51388. **************************************************/
  51389. function pathDataToString$1(path) {
  51390. var str = [];
  51391. var data = path.data;
  51392. var dataLength = path.len();
  51393. for (var i = 0; i < dataLength;) {
  51394. var cmd = data[i++];
  51395. var cmdStr = '';
  51396. var nData = 0;
  51397. switch (cmd) {
  51398. case CMD$4.M:
  51399. cmdStr = 'M';
  51400. nData = 2;
  51401. break;
  51402. case CMD$4.L:
  51403. cmdStr = 'L';
  51404. nData = 2;
  51405. break;
  51406. case CMD$4.Q:
  51407. cmdStr = 'Q';
  51408. nData = 4;
  51409. break;
  51410. case CMD$4.C:
  51411. cmdStr = 'C';
  51412. nData = 6;
  51413. break;
  51414. case CMD$4.A:
  51415. var cx = data[i++];
  51416. var cy = data[i++];
  51417. var rx = data[i++];
  51418. var ry = data[i++];
  51419. var theta = data[i++];
  51420. var dTheta = data[i++];
  51421. var psi = data[i++];
  51422. var clockwise = data[i++];
  51423. var dThetaPositive = Math.abs(dTheta);
  51424. var isCircle = isAroundZero$1(dThetaPositive - PI2$5)
  51425. && !isAroundZero$1(dThetaPositive);
  51426. var large = false;
  51427. if (dThetaPositive >= PI2$5) {
  51428. large = true;
  51429. }
  51430. else if (isAroundZero$1(dThetaPositive)) {
  51431. large = false;
  51432. }
  51433. else {
  51434. large = (dTheta > -PI$3 && dTheta < 0 || dTheta > PI$3)
  51435. === !!clockwise;
  51436. }
  51437. var x0 = round4(cx + rx * mathCos$3(theta));
  51438. var y0 = round4(cy + ry * mathSin$3(theta));
  51439. // It will not draw if start point and end point are exactly the same
  51440. // We need to shift the end point with a small value
  51441. // FIXME A better way to draw circle ?
  51442. if (isCircle) {
  51443. if (clockwise) {
  51444. dTheta = PI2$5 - 1e-4;
  51445. }
  51446. else {
  51447. dTheta = -PI2$5 + 1e-4;
  51448. }
  51449. large = true;
  51450. if (i === 9) {
  51451. // Move to (x0, y0) only when CMD.A comes at the
  51452. // first position of a shape.
  51453. // For instance, when drawing a ring, CMD.A comes
  51454. // after CMD.M, so it's unnecessary to move to
  51455. // (x0, y0).
  51456. str.push('M', x0, y0);
  51457. }
  51458. }
  51459. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  51460. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  51461. // FIXME Ellipse
  51462. str.push('A', round4(rx), round4(ry),
  51463. mathRound(psi * degree), +large, +clockwise, x, y);
  51464. break;
  51465. case CMD$4.Z:
  51466. cmdStr = 'Z';
  51467. break;
  51468. case CMD$4.R:
  51469. var x = round4(data[i++]);
  51470. var y = round4(data[i++]);
  51471. var w = round4(data[i++]);
  51472. var h = round4(data[i++]);
  51473. str.push(
  51474. 'M', x, y,
  51475. 'L', x + w, y,
  51476. 'L', x + w, y + h,
  51477. 'L', x, y + h,
  51478. 'L', x, y
  51479. );
  51480. break;
  51481. }
  51482. cmdStr && str.push(cmdStr);
  51483. for (var j = 0; j < nData; j++) {
  51484. // PENDING With scale
  51485. str.push(round4(data[i++]));
  51486. }
  51487. }
  51488. return str.join(' ');
  51489. }
  51490. var svgPath = {};
  51491. svgPath.brush = function (el) {
  51492. var style = el.style;
  51493. var svgEl = el.__svgEl;
  51494. if (!svgEl) {
  51495. svgEl = createElement('path');
  51496. el.__svgEl = svgEl;
  51497. }
  51498. if (!el.path) {
  51499. el.createPathProxy();
  51500. }
  51501. var path = el.path;
  51502. if (el.__dirtyPath) {
  51503. path.beginPath();
  51504. path.subPixelOptimize = false;
  51505. el.buildPath(path, el.shape);
  51506. el.__dirtyPath = false;
  51507. var pathStr = pathDataToString$1(path);
  51508. if (pathStr.indexOf('NaN') < 0) {
  51509. // Ignore illegal path, which may happen such in out-of-range
  51510. // data in Calendar series.
  51511. attr(svgEl, 'd', pathStr);
  51512. }
  51513. }
  51514. bindStyle(svgEl, style, false, el);
  51515. setTransform(svgEl, el.transform);
  51516. if (style.text != null) {
  51517. svgTextDrawRectText(el, el.getBoundingRect());
  51518. }
  51519. };
  51520. /***************************************************
  51521. * IMAGE
  51522. **************************************************/
  51523. var svgImage = {};
  51524. svgImage.brush = function (el) {
  51525. var style = el.style;
  51526. var image = style.image;
  51527. if (image instanceof HTMLImageElement) {
  51528. var src = image.src;
  51529. image = src;
  51530. }
  51531. if (!image) {
  51532. return;
  51533. }
  51534. var x = style.x || 0;
  51535. var y = style.y || 0;
  51536. var dw = style.width;
  51537. var dh = style.height;
  51538. var svgEl = el.__svgEl;
  51539. if (!svgEl) {
  51540. svgEl = createElement('image');
  51541. el.__svgEl = svgEl;
  51542. }
  51543. if (image !== el.__imageSrc) {
  51544. attrXLink(svgEl, 'href', image);
  51545. // Caching image src
  51546. el.__imageSrc = image;
  51547. }
  51548. attr(svgEl, 'width', dw);
  51549. attr(svgEl, 'height', dh);
  51550. attr(svgEl, 'x', x);
  51551. attr(svgEl, 'y', y);
  51552. setTransform(svgEl, el.transform);
  51553. if (style.text != null) {
  51554. svgTextDrawRectText(el, el.getBoundingRect());
  51555. }
  51556. };
  51557. /***************************************************
  51558. * TEXT
  51559. **************************************************/
  51560. var svgText = {};
  51561. var tmpRect$3 = new BoundingRect();
  51562. var svgTextDrawRectText = function (el, rect, textRect) {
  51563. var style = el.style;
  51564. el.__dirty && normalizeTextStyle(style, true);
  51565. var text = style.text;
  51566. // Convert to string
  51567. if (text == null) {
  51568. // Draw no text only when text is set to null, but not ''
  51569. return;
  51570. }
  51571. else {
  51572. text += '';
  51573. }
  51574. var textSvgEl = el.__textSvgEl;
  51575. if (!textSvgEl) {
  51576. textSvgEl = createElement('text');
  51577. el.__textSvgEl = textSvgEl;
  51578. }
  51579. var x;
  51580. var y;
  51581. var textPosition = style.textPosition;
  51582. var distance = style.textDistance;
  51583. var align = style.textAlign || 'left';
  51584. if (typeof style.fontSize === 'number') {
  51585. style.fontSize += 'px';
  51586. }
  51587. var font = style.font
  51588. || [
  51589. style.fontStyle || '',
  51590. style.fontWeight || '',
  51591. style.fontSize || '',
  51592. style.fontFamily || ''
  51593. ].join(' ')
  51594. || DEFAULT_FONT$1;
  51595. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  51596. textRect = getBoundingRect(
  51597. text, font, align,
  51598. verticalAlign, style.textPadding, style.textLineHeight
  51599. );
  51600. var lineHeight = textRect.lineHeight;
  51601. // Text position represented by coord
  51602. if (textPosition instanceof Array) {
  51603. x = rect.x + textPosition[0];
  51604. y = rect.y + textPosition[1];
  51605. }
  51606. else {
  51607. var newPos = adjustTextPositionOnRect(
  51608. textPosition, rect, distance
  51609. );
  51610. x = newPos.x;
  51611. y = newPos.y;
  51612. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  51613. align = newPos.textAlign;
  51614. }
  51615. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  51616. if (font) {
  51617. textSvgEl.style.font = font;
  51618. }
  51619. var textPadding = style.textPadding;
  51620. // Make baseline top
  51621. attr(textSvgEl, 'x', x);
  51622. attr(textSvgEl, 'y', y);
  51623. bindStyle(textSvgEl, style, true, el);
  51624. if (el instanceof Text || el.style.transformText) {
  51625. // Transform text with element
  51626. setTransform(textSvgEl, el.transform);
  51627. }
  51628. else {
  51629. if (el.transform) {
  51630. tmpRect$3.copy(rect);
  51631. tmpRect$3.applyTransform(el.transform);
  51632. rect = tmpRect$3;
  51633. }
  51634. else {
  51635. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  51636. rect.x = pos[0];
  51637. rect.y = pos[1];
  51638. el.transform = identity(create$1());
  51639. }
  51640. // Text rotation, but no element transform
  51641. var origin = style.textOrigin;
  51642. if (origin === 'center') {
  51643. x = textRect.width / 2 + x;
  51644. y = textRect.height / 2 + y;
  51645. }
  51646. else if (origin) {
  51647. x = origin[0] + x;
  51648. y = origin[1] + y;
  51649. }
  51650. var rotate$$1 = -style.textRotation || 0;
  51651. var transform = create$1();
  51652. // Apply textRotate to element matrix
  51653. rotate(transform, transform, rotate$$1);
  51654. var pos = [el.transform[4], el.transform[5]];
  51655. translate(transform, transform, pos);
  51656. setTransform(textSvgEl, transform);
  51657. }
  51658. var textLines = text.split('\n');
  51659. var nTextLines = textLines.length;
  51660. var textAnchor = align;
  51661. // PENDING
  51662. if (textAnchor === 'left') {
  51663. textAnchor = 'start';
  51664. textPadding && (x += textPadding[3]);
  51665. }
  51666. else if (textAnchor === 'right') {
  51667. textAnchor = 'end';
  51668. textPadding && (x -= textPadding[1]);
  51669. }
  51670. else if (textAnchor === 'center') {
  51671. textAnchor = 'middle';
  51672. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  51673. }
  51674. var dy = 0;
  51675. if (verticalAlign === 'after-edge') {
  51676. dy = -textRect.height + lineHeight;
  51677. textPadding && (dy -= textPadding[2]);
  51678. }
  51679. else if (verticalAlign === 'middle') {
  51680. dy = (-textRect.height + lineHeight) / 2;
  51681. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  51682. }
  51683. else {
  51684. textPadding && (dy += textPadding[0]);
  51685. }
  51686. // Font may affect position of each tspan elements
  51687. if (el.__text !== text || el.__textFont !== font) {
  51688. var tspanList = el.__tspanList || [];
  51689. el.__tspanList = tspanList;
  51690. for (var i = 0; i < nTextLines; i++) {
  51691. // Using cached tspan elements
  51692. var tspan = tspanList[i];
  51693. if (!tspan) {
  51694. tspan = tspanList[i] = createElement('tspan');
  51695. textSvgEl.appendChild(tspan);
  51696. attr(tspan, 'alignment-baseline', verticalAlign);
  51697. attr(tspan, 'text-anchor', textAnchor);
  51698. }
  51699. else {
  51700. tspan.innerHTML = '';
  51701. }
  51702. attr(tspan, 'x', x);
  51703. attr(tspan, 'y', y + i * lineHeight + dy);
  51704. tspan.appendChild(document.createTextNode(textLines[i]));
  51705. }
  51706. // Remove unsed tspan elements
  51707. for (; i < tspanList.length; i++) {
  51708. textSvgEl.removeChild(tspanList[i]);
  51709. }
  51710. tspanList.length = nTextLines;
  51711. el.__text = text;
  51712. el.__textFont = font;
  51713. }
  51714. else if (el.__tspanList.length) {
  51715. // Update span x and y
  51716. var len = el.__tspanList.length;
  51717. for (var i = 0; i < len; ++i) {
  51718. var tspan = el.__tspanList[i];
  51719. if (tspan) {
  51720. attr(tspan, 'x', x);
  51721. attr(tspan, 'y', y + i * lineHeight + dy);
  51722. }
  51723. }
  51724. }
  51725. };
  51726. function getVerticalAlignForSvg(verticalAlign) {
  51727. if (verticalAlign === 'middle') {
  51728. return 'middle';
  51729. }
  51730. else if (verticalAlign === 'bottom') {
  51731. return 'after-edge';
  51732. }
  51733. else {
  51734. return 'hanging';
  51735. }
  51736. }
  51737. svgText.drawRectText = svgTextDrawRectText;
  51738. svgText.brush = function (el) {
  51739. var style = el.style;
  51740. if (style.text != null) {
  51741. // 强制设置 textPosition
  51742. style.textPosition = [0, 0];
  51743. svgTextDrawRectText(el, {
  51744. x: style.x || 0, y: style.y || 0,
  51745. width: 0, height: 0
  51746. }, el.getBoundingRect());
  51747. }
  51748. };
  51749. // Myers' Diff Algorithm
  51750. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  51751. function Diff() {}
  51752. Diff.prototype = {
  51753. diff: function (oldArr, newArr, equals) {
  51754. if (!equals) {
  51755. equals = function (a, b) {
  51756. return a === b;
  51757. };
  51758. }
  51759. this.equals = equals;
  51760. var self = this;
  51761. oldArr = oldArr.slice();
  51762. newArr = newArr.slice();
  51763. // Allow subclasses to massage the input prior to running
  51764. var newLen = newArr.length;
  51765. var oldLen = oldArr.length;
  51766. var editLength = 1;
  51767. var maxEditLength = newLen + oldLen;
  51768. var bestPath = [{ newPos: -1, components: [] }];
  51769. // Seed editLength = 0, i.e. the content starts with the same values
  51770. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  51771. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  51772. var indices = [];
  51773. for (var i = 0; i < newArr.length; i++) {
  51774. indices.push(i);
  51775. }
  51776. // Identity per the equality and tokenizer
  51777. return [{
  51778. indices: indices, count: newArr.length
  51779. }];
  51780. }
  51781. // Main worker method. checks all permutations of a given edit length for acceptance.
  51782. function execEditLength() {
  51783. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  51784. var basePath;
  51785. var addPath = bestPath[diagonalPath - 1];
  51786. var removePath = bestPath[diagonalPath + 1];
  51787. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  51788. if (addPath) {
  51789. // No one else is going to attempt to use this value, clear it
  51790. bestPath[diagonalPath - 1] = undefined;
  51791. }
  51792. var canAdd = addPath && addPath.newPos + 1 < newLen;
  51793. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  51794. if (!canAdd && !canRemove) {
  51795. // If this path is a terminal then prune
  51796. bestPath[diagonalPath] = undefined;
  51797. continue;
  51798. }
  51799. // Select the diagonal that we want to branch from. We select the prior
  51800. // path whose position in the new string is the farthest from the origin
  51801. // and does not pass the bounds of the diff graph
  51802. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  51803. basePath = clonePath(removePath);
  51804. self.pushComponent(basePath.components, undefined, true);
  51805. }
  51806. else {
  51807. basePath = addPath; // No need to clone, we've pulled it from the list
  51808. basePath.newPos++;
  51809. self.pushComponent(basePath.components, true, undefined);
  51810. }
  51811. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  51812. // If we have hit the end of both strings, then we are done
  51813. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  51814. return buildValues(self, basePath.components, newArr, oldArr);
  51815. }
  51816. else {
  51817. // Otherwise track this path as a potential candidate and continue.
  51818. bestPath[diagonalPath] = basePath;
  51819. }
  51820. }
  51821. editLength++;
  51822. }
  51823. while (editLength <= maxEditLength) {
  51824. var ret = execEditLength();
  51825. if (ret) {
  51826. return ret;
  51827. }
  51828. }
  51829. },
  51830. pushComponent: function (components, added, removed) {
  51831. var last = components[components.length - 1];
  51832. if (last && last.added === added && last.removed === removed) {
  51833. // We need to clone here as the component clone operation is just
  51834. // as shallow array clone
  51835. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  51836. }
  51837. else {
  51838. components.push({count: 1, added: added, removed: removed });
  51839. }
  51840. },
  51841. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  51842. var newLen = newArr.length;
  51843. var oldLen = oldArr.length;
  51844. var newPos = basePath.newPos;
  51845. var oldPos = newPos - diagonalPath;
  51846. var commonCount = 0;
  51847. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  51848. newPos++;
  51849. oldPos++;
  51850. commonCount++;
  51851. }
  51852. if (commonCount) {
  51853. basePath.components.push({count: commonCount});
  51854. }
  51855. basePath.newPos = newPos;
  51856. return oldPos;
  51857. },
  51858. tokenize: function (value) {
  51859. return value.slice();
  51860. },
  51861. join: function (value) {
  51862. return value.slice();
  51863. }
  51864. };
  51865. function buildValues(diff, components, newArr, oldArr) {
  51866. var componentPos = 0;
  51867. var componentLen = components.length;
  51868. var newPos = 0;
  51869. var oldPos = 0;
  51870. for (; componentPos < componentLen; componentPos++) {
  51871. var component = components[componentPos];
  51872. if (!component.removed) {
  51873. var indices = [];
  51874. for (var i = newPos; i < newPos + component.count; i++) {
  51875. indices.push(i);
  51876. }
  51877. component.indices = indices;
  51878. newPos += component.count;
  51879. // Common case
  51880. if (!component.added) {
  51881. oldPos += component.count;
  51882. }
  51883. }
  51884. else {
  51885. var indices = [];
  51886. for (var i = oldPos; i < oldPos + component.count; i++) {
  51887. indices.push(i);
  51888. }
  51889. component.indices = indices;
  51890. oldPos += component.count;
  51891. }
  51892. }
  51893. return components;
  51894. }
  51895. function clonePath(path) {
  51896. return { newPos: path.newPos, components: path.components.slice(0) };
  51897. }
  51898. var arrayDiff = new Diff();
  51899. var arrayDiff$1 = function (oldArr, newArr, callback) {
  51900. return arrayDiff.diff(oldArr, newArr, callback);
  51901. };
  51902. /**
  51903. * @file Manages elements that can be defined in <defs> in SVG,
  51904. * e.g., gradients, clip path, etc.
  51905. * @author Zhang Wenli
  51906. */
  51907. var MARK_UNUSED = '0';
  51908. var MARK_USED = '1';
  51909. /**
  51910. * Manages elements that can be defined in <defs> in SVG,
  51911. * e.g., gradients, clip path, etc.
  51912. *
  51913. * @class
  51914. * @param {number} zrId zrender instance id
  51915. * @param {SVGElement} svgRoot root of SVG document
  51916. * @param {string|string[]} tagNames possible tag names
  51917. * @param {string} markLabel label name to make if the element
  51918. * is used
  51919. */
  51920. function Definable(
  51921. zrId,
  51922. svgRoot,
  51923. tagNames,
  51924. markLabel,
  51925. domName
  51926. ) {
  51927. this._zrId = zrId;
  51928. this._svgRoot = svgRoot;
  51929. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  51930. this._markLabel = markLabel;
  51931. this._domName = domName || '_dom';
  51932. this.nextId = 0;
  51933. }
  51934. Definable.prototype.createElement = createElement;
  51935. /**
  51936. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  51937. *
  51938. * @param {boolean} isForceCreating if need to create when not exists
  51939. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  51940. * exist and isForceCreating is false
  51941. */
  51942. Definable.prototype.getDefs = function (isForceCreating) {
  51943. var svgRoot = this._svgRoot;
  51944. var defs = this._svgRoot.getElementsByTagName('defs');
  51945. if (defs.length === 0) {
  51946. // Not exist
  51947. if (isForceCreating) {
  51948. defs = svgRoot.insertBefore(
  51949. this.createElement('defs'), // Create new tag
  51950. svgRoot.firstChild // Insert in the front of svg
  51951. );
  51952. if (!defs.contains) {
  51953. // IE doesn't support contains method
  51954. defs.contains = function (el) {
  51955. var children = defs.children;
  51956. if (!children) {
  51957. return false;
  51958. }
  51959. for (var i = children.length - 1; i >= 0; --i) {
  51960. if (children[i] === el) {
  51961. return true;
  51962. }
  51963. }
  51964. return false;
  51965. };
  51966. }
  51967. return defs;
  51968. }
  51969. else {
  51970. return null;
  51971. }
  51972. }
  51973. else {
  51974. return defs[0];
  51975. }
  51976. };
  51977. /**
  51978. * Update DOM element if necessary.
  51979. *
  51980. * @param {Object|string} element style element. e.g., for gradient,
  51981. * it may be '#ccc' or {type: 'linear', ...}
  51982. * @param {Function|undefined} onUpdate update callback
  51983. */
  51984. Definable.prototype.update = function (element, onUpdate) {
  51985. if (!element) {
  51986. return;
  51987. }
  51988. var defs = this.getDefs(false);
  51989. if (element[this._domName] && defs.contains(element[this._domName])) {
  51990. // Update DOM
  51991. if (typeof onUpdate === 'function') {
  51992. onUpdate(element);
  51993. }
  51994. }
  51995. else {
  51996. // No previous dom, create new
  51997. var dom = this.add(element);
  51998. if (dom) {
  51999. element[this._domName] = dom;
  52000. }
  52001. }
  52002. };
  52003. /**
  52004. * Add gradient dom to defs
  52005. *
  52006. * @param {SVGElement} dom DOM to be added to <defs>
  52007. */
  52008. Definable.prototype.addDom = function (dom) {
  52009. var defs = this.getDefs(true);
  52010. defs.appendChild(dom);
  52011. };
  52012. /**
  52013. * Remove DOM of a given element.
  52014. *
  52015. * @param {SVGElement} element element to remove dom
  52016. */
  52017. Definable.prototype.removeDom = function (element) {
  52018. var defs = this.getDefs(false);
  52019. if (defs && element[this._domName]) {
  52020. defs.removeChild(element[this._domName]);
  52021. element[this._domName] = null;
  52022. }
  52023. };
  52024. /**
  52025. * Get DOMs of this element.
  52026. *
  52027. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  52028. */
  52029. Definable.prototype.getDoms = function () {
  52030. var defs = this.getDefs(false);
  52031. if (!defs) {
  52032. // No dom when defs is not defined
  52033. return [];
  52034. }
  52035. var doms = [];
  52036. each$1(this._tagNames, function (tagName) {
  52037. var tags = defs.getElementsByTagName(tagName);
  52038. // Note that tags is HTMLCollection, which is array-like
  52039. // rather than real array.
  52040. // So `doms.concat(tags)` add tags as one object.
  52041. doms = doms.concat([].slice.call(tags));
  52042. });
  52043. return doms;
  52044. };
  52045. /**
  52046. * Mark DOMs to be unused before painting, and clear unused ones at the end
  52047. * of the painting.
  52048. */
  52049. Definable.prototype.markAllUnused = function () {
  52050. var doms = this.getDoms();
  52051. var that = this;
  52052. each$1(doms, function (dom) {
  52053. dom[that._markLabel] = MARK_UNUSED;
  52054. });
  52055. };
  52056. /**
  52057. * Mark a single DOM to be used.
  52058. *
  52059. * @param {SVGElement} dom DOM to mark
  52060. */
  52061. Definable.prototype.markUsed = function (dom) {
  52062. if (dom) {
  52063. dom[this._markLabel] = MARK_USED;
  52064. }
  52065. };
  52066. /**
  52067. * Remove unused DOMs defined in <defs>
  52068. */
  52069. Definable.prototype.removeUnused = function () {
  52070. var defs = this.getDefs(false);
  52071. if (!defs) {
  52072. // Nothing to remove
  52073. return;
  52074. }
  52075. var doms = this.getDoms();
  52076. var that = this;
  52077. each$1(doms, function (dom) {
  52078. if (dom[that._markLabel] !== MARK_USED) {
  52079. // Remove gradient
  52080. defs.removeChild(dom);
  52081. }
  52082. });
  52083. };
  52084. /**
  52085. * Get SVG proxy.
  52086. *
  52087. * @param {Displayable} displayable displayable element
  52088. * @return {Path|Image|Text} svg proxy of given element
  52089. */
  52090. Definable.prototype.getSvgProxy = function (displayable) {
  52091. if (displayable instanceof Path) {
  52092. return svgPath;
  52093. }
  52094. else if (displayable instanceof ZImage) {
  52095. return svgImage;
  52096. }
  52097. else if (displayable instanceof Text) {
  52098. return svgText;
  52099. }
  52100. else {
  52101. return svgPath;
  52102. }
  52103. };
  52104. /**
  52105. * Get text SVG element.
  52106. *
  52107. * @param {Displayable} displayable displayable element
  52108. * @return {SVGElement} SVG element of text
  52109. */
  52110. Definable.prototype.getTextSvgElement = function (displayable) {
  52111. return displayable.__textSvgEl;
  52112. };
  52113. /**
  52114. * Get SVG element.
  52115. *
  52116. * @param {Displayable} displayable displayable element
  52117. * @return {SVGElement} SVG element
  52118. */
  52119. Definable.prototype.getSvgElement = function (displayable) {
  52120. return displayable.__svgEl;
  52121. };
  52122. /**
  52123. * @file Manages SVG gradient elements.
  52124. * @author Zhang Wenli
  52125. */
  52126. /**
  52127. * Manages SVG gradient elements.
  52128. *
  52129. * @class
  52130. * @extends Definable
  52131. * @param {number} zrId zrender instance id
  52132. * @param {SVGElement} svgRoot root of SVG document
  52133. */
  52134. function GradientManager(zrId, svgRoot) {
  52135. Definable.call(
  52136. this,
  52137. zrId,
  52138. svgRoot,
  52139. ['linearGradient', 'radialGradient'],
  52140. '__gradient_in_use__'
  52141. );
  52142. }
  52143. inherits(GradientManager, Definable);
  52144. /**
  52145. * Create new gradient DOM for fill or stroke if not exist,
  52146. * but will not update gradient if exists.
  52147. *
  52148. * @param {SvgElement} svgElement SVG element to paint
  52149. * @param {Displayable} displayable zrender displayable element
  52150. */
  52151. GradientManager.prototype.addWithoutUpdate = function (
  52152. svgElement,
  52153. displayable
  52154. ) {
  52155. if (displayable && displayable.style) {
  52156. var that = this;
  52157. each$1(['fill', 'stroke'], function (fillOrStroke) {
  52158. if (displayable.style[fillOrStroke]
  52159. && (displayable.style[fillOrStroke].type === 'linear'
  52160. || displayable.style[fillOrStroke].type === 'radial')
  52161. ) {
  52162. var gradient = displayable.style[fillOrStroke];
  52163. var defs = that.getDefs(true);
  52164. // Create dom in <defs> if not exists
  52165. var dom;
  52166. if (gradient._dom) {
  52167. // Gradient exists
  52168. dom = gradient._dom;
  52169. if (!defs.contains(gradient._dom)) {
  52170. // _dom is no longer in defs, recreate
  52171. that.addDom(dom);
  52172. }
  52173. }
  52174. else {
  52175. // New dom
  52176. dom = that.add(gradient);
  52177. }
  52178. that.markUsed(displayable);
  52179. var id = dom.getAttribute('id');
  52180. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  52181. }
  52182. });
  52183. }
  52184. };
  52185. /**
  52186. * Add a new gradient tag in <defs>
  52187. *
  52188. * @param {Gradient} gradient zr gradient instance
  52189. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  52190. * created DOM
  52191. */
  52192. GradientManager.prototype.add = function (gradient) {
  52193. var dom;
  52194. if (gradient.type === 'linear') {
  52195. dom = this.createElement('linearGradient');
  52196. }
  52197. else if (gradient.type === 'radial') {
  52198. dom = this.createElement('radialGradient');
  52199. }
  52200. else {
  52201. zrLog('Illegal gradient type.');
  52202. return null;
  52203. }
  52204. // Set dom id with gradient id, since each gradient instance
  52205. // will have no more than one dom element.
  52206. // id may exists before for those dirty elements, in which case
  52207. // id should remain the same, and other attributes should be
  52208. // updated.
  52209. gradient.id = gradient.id || this.nextId++;
  52210. dom.setAttribute('id', 'zr' + this._zrId
  52211. + '-gradient-' + gradient.id);
  52212. this.updateDom(gradient, dom);
  52213. this.addDom(dom);
  52214. return dom;
  52215. };
  52216. /**
  52217. * Update gradient.
  52218. *
  52219. * @param {Gradient} gradient zr gradient instance
  52220. */
  52221. GradientManager.prototype.update = function (gradient) {
  52222. var that = this;
  52223. Definable.prototype.update.call(this, gradient, function () {
  52224. var type = gradient.type;
  52225. var tagName = gradient._dom.tagName;
  52226. if (type === 'linear' && tagName === 'linearGradient'
  52227. || type === 'radial' && tagName === 'radialGradient'
  52228. ) {
  52229. // Gradient type is not changed, update gradient
  52230. that.updateDom(gradient, gradient._dom);
  52231. }
  52232. else {
  52233. // Remove and re-create if type is changed
  52234. that.removeDom(gradient);
  52235. that.add(gradient);
  52236. }
  52237. });
  52238. };
  52239. /**
  52240. * Update gradient dom
  52241. *
  52242. * @param {Gradient} gradient zr gradient instance
  52243. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  52244. * DOM to update
  52245. */
  52246. GradientManager.prototype.updateDom = function (gradient, dom) {
  52247. if (gradient.type === 'linear') {
  52248. dom.setAttribute('x1', gradient.x);
  52249. dom.setAttribute('y1', gradient.y);
  52250. dom.setAttribute('x2', gradient.x2);
  52251. dom.setAttribute('y2', gradient.y2);
  52252. }
  52253. else if (gradient.type === 'radial') {
  52254. dom.setAttribute('cx', gradient.x);
  52255. dom.setAttribute('cy', gradient.y);
  52256. dom.setAttribute('r', gradient.r);
  52257. }
  52258. else {
  52259. zrLog('Illegal gradient type.');
  52260. return;
  52261. }
  52262. if (gradient.global) {
  52263. // x1, x2, y1, y2 in range of 0 to canvas width or height
  52264. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  52265. }
  52266. else {
  52267. // x1, x2, y1, y2 in range of 0 to 1
  52268. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  52269. }
  52270. // Remove color stops if exists
  52271. dom.innerHTML = '';
  52272. // Add color stops
  52273. var colors = gradient.colorStops;
  52274. for (var i = 0, len = colors.length; i < len; ++i) {
  52275. var stop = this.createElement('stop');
  52276. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  52277. var color = colors[i].color;
  52278. if (color.indexOf('rgba' > -1)) {
  52279. // Fix Safari bug that stop-color not recognizing alpha #9014
  52280. var opacity = parse(color)[3];
  52281. var hex = toHex(color);
  52282. // stop-color cannot be color, since:
  52283. // The opacity value used for the gradient calculation is the
  52284. // *product* of the value of stop-opacity and the opacity of the
  52285. // value of stop-color.
  52286. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  52287. stop.setAttribute('stop-color', '#' + hex);
  52288. stop.setAttribute('stop-opacity', opacity);
  52289. }
  52290. else {
  52291. stop.setAttribute('stop-color', colors[i].color);
  52292. }
  52293. dom.appendChild(stop);
  52294. }
  52295. // Store dom element in gradient, to avoid creating multiple
  52296. // dom instances for the same gradient element
  52297. gradient._dom = dom;
  52298. };
  52299. /**
  52300. * Mark a single gradient to be used
  52301. *
  52302. * @param {Displayable} displayable displayable element
  52303. */
  52304. GradientManager.prototype.markUsed = function (displayable) {
  52305. if (displayable.style) {
  52306. var gradient = displayable.style.fill;
  52307. if (gradient && gradient._dom) {
  52308. Definable.prototype.markUsed.call(this, gradient._dom);
  52309. }
  52310. gradient = displayable.style.stroke;
  52311. if (gradient && gradient._dom) {
  52312. Definable.prototype.markUsed.call(this, gradient._dom);
  52313. }
  52314. }
  52315. };
  52316. /**
  52317. * @file Manages SVG clipPath elements.
  52318. * @author Zhang Wenli
  52319. */
  52320. /**
  52321. * Manages SVG clipPath elements.
  52322. *
  52323. * @class
  52324. * @extends Definable
  52325. * @param {number} zrId zrender instance id
  52326. * @param {SVGElement} svgRoot root of SVG document
  52327. */
  52328. function ClippathManager(zrId, svgRoot) {
  52329. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  52330. }
  52331. inherits(ClippathManager, Definable);
  52332. /**
  52333. * Update clipPath.
  52334. *
  52335. * @param {Displayable} displayable displayable element
  52336. */
  52337. ClippathManager.prototype.update = function (displayable) {
  52338. var svgEl = this.getSvgElement(displayable);
  52339. if (svgEl) {
  52340. this.updateDom(svgEl, displayable.__clipPaths, false);
  52341. }
  52342. var textEl = this.getTextSvgElement(displayable);
  52343. if (textEl) {
  52344. // Make another clipPath for text, since it's transform
  52345. // matrix is not the same with svgElement
  52346. this.updateDom(textEl, displayable.__clipPaths, true);
  52347. }
  52348. this.markUsed(displayable);
  52349. };
  52350. /**
  52351. * Create an SVGElement of displayable and create a <clipPath> of its
  52352. * clipPath
  52353. *
  52354. * @param {Displayable} parentEl parent element
  52355. * @param {ClipPath[]} clipPaths clipPaths of parent element
  52356. * @param {boolean} isText if parent element is Text
  52357. */
  52358. ClippathManager.prototype.updateDom = function (
  52359. parentEl,
  52360. clipPaths,
  52361. isText
  52362. ) {
  52363. if (clipPaths && clipPaths.length > 0) {
  52364. // Has clipPath, create <clipPath> with the first clipPath
  52365. var defs = this.getDefs(true);
  52366. var clipPath = clipPaths[0];
  52367. var clipPathEl;
  52368. var id;
  52369. var dom = isText ? '_textDom' : '_dom';
  52370. if (clipPath[dom]) {
  52371. // Use a dom that is already in <defs>
  52372. id = clipPath[dom].getAttribute('id');
  52373. clipPathEl = clipPath[dom];
  52374. // Use a dom that is already in <defs>
  52375. if (!defs.contains(clipPathEl)) {
  52376. // This happens when set old clipPath that has
  52377. // been previously removed
  52378. defs.appendChild(clipPathEl);
  52379. }
  52380. }
  52381. else {
  52382. // New <clipPath>
  52383. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  52384. ++this.nextId;
  52385. clipPathEl = this.createElement('clipPath');
  52386. clipPathEl.setAttribute('id', id);
  52387. defs.appendChild(clipPathEl);
  52388. clipPath[dom] = clipPathEl;
  52389. }
  52390. // Build path and add to <clipPath>
  52391. var svgProxy = this.getSvgProxy(clipPath);
  52392. if (clipPath.transform
  52393. && clipPath.parent.invTransform
  52394. && !isText
  52395. ) {
  52396. /**
  52397. * If a clipPath has a parent with transform, the transform
  52398. * of parent should not be considered when setting transform
  52399. * of clipPath. So we need to transform back from parent's
  52400. * transform, which is done by multiplying parent's inverse
  52401. * transform.
  52402. */
  52403. // Store old transform
  52404. var transform = Array.prototype.slice.call(
  52405. clipPath.transform
  52406. );
  52407. // Transform back from parent, and brush path
  52408. mul$1(
  52409. clipPath.transform,
  52410. clipPath.parent.invTransform,
  52411. clipPath.transform
  52412. );
  52413. svgProxy.brush(clipPath);
  52414. // Set back transform of clipPath
  52415. clipPath.transform = transform;
  52416. }
  52417. else {
  52418. svgProxy.brush(clipPath);
  52419. }
  52420. var pathEl = this.getSvgElement(clipPath);
  52421. clipPathEl.innerHTML = '';
  52422. /**
  52423. * Use `cloneNode()` here to appendChild to multiple parents,
  52424. * which may happend when Text and other shapes are using the same
  52425. * clipPath. Since Text will create an extra clipPath DOM due to
  52426. * different transform rules.
  52427. */
  52428. clipPathEl.appendChild(pathEl.cloneNode());
  52429. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  52430. if (clipPaths.length > 1) {
  52431. // Make the other clipPaths recursively
  52432. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  52433. }
  52434. }
  52435. else {
  52436. // No clipPath
  52437. if (parentEl) {
  52438. parentEl.setAttribute('clip-path', 'none');
  52439. }
  52440. }
  52441. };
  52442. /**
  52443. * Mark a single clipPath to be used
  52444. *
  52445. * @param {Displayable} displayable displayable element
  52446. */
  52447. ClippathManager.prototype.markUsed = function (displayable) {
  52448. var that = this;
  52449. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  52450. each$1(displayable.__clipPaths, function (clipPath) {
  52451. if (clipPath._dom) {
  52452. Definable.prototype.markUsed.call(that, clipPath._dom);
  52453. }
  52454. if (clipPath._textDom) {
  52455. Definable.prototype.markUsed.call(that, clipPath._textDom);
  52456. }
  52457. });
  52458. }
  52459. };
  52460. /**
  52461. * @file Manages SVG shadow elements.
  52462. * @author Zhang Wenli
  52463. */
  52464. /**
  52465. * Manages SVG shadow elements.
  52466. *
  52467. * @class
  52468. * @extends Definable
  52469. * @param {number} zrId zrender instance id
  52470. * @param {SVGElement} svgRoot root of SVG document
  52471. */
  52472. function ShadowManager(zrId, svgRoot) {
  52473. Definable.call(
  52474. this,
  52475. zrId,
  52476. svgRoot,
  52477. ['filter'],
  52478. '__filter_in_use__',
  52479. '_shadowDom'
  52480. );
  52481. }
  52482. inherits(ShadowManager, Definable);
  52483. /**
  52484. * Create new shadow DOM for fill or stroke if not exist,
  52485. * but will not update shadow if exists.
  52486. *
  52487. * @param {SvgElement} svgElement SVG element to paint
  52488. * @param {Displayable} displayable zrender displayable element
  52489. */
  52490. ShadowManager.prototype.addWithoutUpdate = function (
  52491. svgElement,
  52492. displayable
  52493. ) {
  52494. if (displayable && hasShadow(displayable.style)) {
  52495. var style = displayable.style;
  52496. // Create dom in <defs> if not exists
  52497. var dom;
  52498. if (style._shadowDom) {
  52499. // Gradient exists
  52500. dom = style._shadowDom;
  52501. var defs = this.getDefs(true);
  52502. if (!defs.contains(style._shadowDom)) {
  52503. // _shadowDom is no longer in defs, recreate
  52504. this.addDom(dom);
  52505. }
  52506. }
  52507. else {
  52508. // New dom
  52509. dom = this.add(displayable);
  52510. }
  52511. this.markUsed(displayable);
  52512. var id = dom.getAttribute('id');
  52513. svgElement.style.filter = 'url(#' + id + ')';
  52514. }
  52515. };
  52516. /**
  52517. * Add a new shadow tag in <defs>
  52518. *
  52519. * @param {Displayable} displayable zrender displayable element
  52520. * @return {SVGFilterElement} created DOM
  52521. */
  52522. ShadowManager.prototype.add = function (displayable) {
  52523. var dom = this.createElement('filter');
  52524. var style = displayable.style;
  52525. // Set dom id with shadow id, since each shadow instance
  52526. // will have no more than one dom element.
  52527. // id may exists before for those dirty elements, in which case
  52528. // id should remain the same, and other attributes should be
  52529. // updated.
  52530. style._shadowDomId = style._shadowDomId || this.nextId++;
  52531. dom.setAttribute('id', 'zr' + this._zrId
  52532. + '-shadow-' + style._shadowDomId);
  52533. this.updateDom(displayable, dom);
  52534. this.addDom(dom);
  52535. return dom;
  52536. };
  52537. /**
  52538. * Update shadow.
  52539. *
  52540. * @param {Displayable} displayable zrender displayable element
  52541. */
  52542. ShadowManager.prototype.update = function (svgElement, displayable) {
  52543. var style = displayable.style;
  52544. if (hasShadow(style)) {
  52545. var that = this;
  52546. Definable.prototype.update.call(this, displayable, function (style) {
  52547. that.updateDom(displayable, style._shadowDom);
  52548. });
  52549. }
  52550. else {
  52551. // Remove shadow
  52552. this.remove(svgElement, style);
  52553. }
  52554. };
  52555. /**
  52556. * Remove DOM and clear parent filter
  52557. */
  52558. ShadowManager.prototype.remove = function (svgElement, style) {
  52559. if (style._shadowDomId != null) {
  52560. this.removeDom(style);
  52561. svgElement.style.filter = '';
  52562. }
  52563. };
  52564. /**
  52565. * Update shadow dom
  52566. *
  52567. * @param {Displayable} displayable zrender displayable element
  52568. * @param {SVGFilterElement} dom DOM to update
  52569. */
  52570. ShadowManager.prototype.updateDom = function (displayable, dom) {
  52571. var domChild = dom.getElementsByTagName('feDropShadow');
  52572. if (domChild.length === 0) {
  52573. domChild = this.createElement('feDropShadow');
  52574. }
  52575. else {
  52576. domChild = domChild[0];
  52577. }
  52578. var style = displayable.style;
  52579. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  52580. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  52581. // TODO: textBoxShadowBlur is not supported yet
  52582. var offsetX, offsetY, blur, color;
  52583. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  52584. offsetX = style.shadowOffsetX || 0;
  52585. offsetY = style.shadowOffsetY || 0;
  52586. blur = style.shadowBlur;
  52587. color = style.shadowColor;
  52588. }
  52589. else if (style.textShadowBlur) {
  52590. offsetX = style.textShadowOffsetX || 0;
  52591. offsetY = style.textShadowOffsetY || 0;
  52592. blur = style.textShadowBlur;
  52593. color = style.textShadowColor;
  52594. }
  52595. else {
  52596. // Remove shadow
  52597. this.removeDom(dom, style);
  52598. return;
  52599. }
  52600. domChild.setAttribute('dx', offsetX / scaleX);
  52601. domChild.setAttribute('dy', offsetY / scaleY);
  52602. domChild.setAttribute('flood-color', color);
  52603. // Divide by two here so that it looks the same as in canvas
  52604. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  52605. var stdDx = blur / 2 / scaleX;
  52606. var stdDy = blur / 2 / scaleY;
  52607. var stdDeviation = stdDx + ' ' + stdDy;
  52608. domChild.setAttribute('stdDeviation', stdDeviation);
  52609. // Fix filter clipping problem
  52610. dom.setAttribute('x', '-100%');
  52611. dom.setAttribute('y', '-100%');
  52612. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  52613. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  52614. dom.appendChild(domChild);
  52615. // Store dom element in shadow, to avoid creating multiple
  52616. // dom instances for the same shadow element
  52617. style._shadowDom = dom;
  52618. };
  52619. /**
  52620. * Mark a single shadow to be used
  52621. *
  52622. * @param {Displayable} displayable displayable element
  52623. */
  52624. ShadowManager.prototype.markUsed = function (displayable) {
  52625. var style = displayable.style;
  52626. if (style && style._shadowDom) {
  52627. Definable.prototype.markUsed.call(this, style._shadowDom);
  52628. }
  52629. };
  52630. function hasShadow(style) {
  52631. // TODO: textBoxShadowBlur is not supported yet
  52632. return style
  52633. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  52634. || style.textShadowBlur || style.textShadowOffsetX
  52635. || style.textShadowOffsetY);
  52636. }
  52637. /**
  52638. * SVG Painter
  52639. * @module zrender/svg/Painter
  52640. */
  52641. function parseInt10$2(val) {
  52642. return parseInt(val, 10);
  52643. }
  52644. function getSvgProxy(el) {
  52645. if (el instanceof Path) {
  52646. return svgPath;
  52647. }
  52648. else if (el instanceof ZImage) {
  52649. return svgImage;
  52650. }
  52651. else if (el instanceof Text) {
  52652. return svgText;
  52653. }
  52654. else {
  52655. return svgPath;
  52656. }
  52657. }
  52658. function checkParentAvailable(parent, child) {
  52659. return child && parent && child.parentNode !== parent;
  52660. }
  52661. function insertAfter(parent, child, prevSibling) {
  52662. if (checkParentAvailable(parent, child) && prevSibling) {
  52663. var nextSibling = prevSibling.nextSibling;
  52664. nextSibling ? parent.insertBefore(child, nextSibling)
  52665. : parent.appendChild(child);
  52666. }
  52667. }
  52668. function prepend(parent, child) {
  52669. if (checkParentAvailable(parent, child)) {
  52670. var firstChild = parent.firstChild;
  52671. firstChild ? parent.insertBefore(child, firstChild)
  52672. : parent.appendChild(child);
  52673. }
  52674. }
  52675. function remove$1(parent, child) {
  52676. if (child && parent && child.parentNode === parent) {
  52677. parent.removeChild(child);
  52678. }
  52679. }
  52680. function getTextSvgElement(displayable) {
  52681. return displayable.__textSvgEl;
  52682. }
  52683. function getSvgElement(displayable) {
  52684. return displayable.__svgEl;
  52685. }
  52686. /**
  52687. * @alias module:zrender/svg/Painter
  52688. * @constructor
  52689. * @param {HTMLElement} root 绘图容器
  52690. * @param {module:zrender/Storage} storage
  52691. * @param {Object} opts
  52692. */
  52693. var SVGPainter = function (root, storage, opts, zrId) {
  52694. this.root = root;
  52695. this.storage = storage;
  52696. this._opts = opts = extend({}, opts || {});
  52697. var svgRoot = createElement('svg');
  52698. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  52699. svgRoot.setAttribute('version', '1.1');
  52700. svgRoot.setAttribute('baseProfile', 'full');
  52701. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  52702. this.gradientManager = new GradientManager(zrId, svgRoot);
  52703. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  52704. this.shadowManager = new ShadowManager(zrId, svgRoot);
  52705. var viewport = document.createElement('div');
  52706. viewport.style.cssText = 'overflow:hidden;position:relative';
  52707. this._svgRoot = svgRoot;
  52708. this._viewport = viewport;
  52709. root.appendChild(viewport);
  52710. viewport.appendChild(svgRoot);
  52711. this.resize(opts.width, opts.height);
  52712. this._visibleList = [];
  52713. };
  52714. SVGPainter.prototype = {
  52715. constructor: SVGPainter,
  52716. getType: function () {
  52717. return 'svg';
  52718. },
  52719. getViewportRoot: function () {
  52720. return this._viewport;
  52721. },
  52722. getViewportRootOffset: function () {
  52723. var viewportRoot = this.getViewportRoot();
  52724. if (viewportRoot) {
  52725. return {
  52726. offsetLeft: viewportRoot.offsetLeft || 0,
  52727. offsetTop: viewportRoot.offsetTop || 0
  52728. };
  52729. }
  52730. },
  52731. refresh: function () {
  52732. var list = this.storage.getDisplayList(true);
  52733. this._paintList(list);
  52734. },
  52735. setBackgroundColor: function (backgroundColor) {
  52736. // TODO gradient
  52737. this._viewport.style.background = backgroundColor;
  52738. },
  52739. _paintList: function (list) {
  52740. this.gradientManager.markAllUnused();
  52741. this.clipPathManager.markAllUnused();
  52742. this.shadowManager.markAllUnused();
  52743. var svgRoot = this._svgRoot;
  52744. var visibleList = this._visibleList;
  52745. var listLen = list.length;
  52746. var newVisibleList = [];
  52747. var i;
  52748. for (i = 0; i < listLen; i++) {
  52749. var displayable = list[i];
  52750. var svgProxy = getSvgProxy(displayable);
  52751. var svgElement = getSvgElement(displayable)
  52752. || getTextSvgElement(displayable);
  52753. if (!displayable.invisible) {
  52754. if (displayable.__dirty) {
  52755. svgProxy && svgProxy.brush(displayable);
  52756. // Update clipPath
  52757. this.clipPathManager.update(displayable);
  52758. // Update gradient and shadow
  52759. if (displayable.style) {
  52760. this.gradientManager
  52761. .update(displayable.style.fill);
  52762. this.gradientManager
  52763. .update(displayable.style.stroke);
  52764. this.shadowManager
  52765. .update(svgElement, displayable);
  52766. }
  52767. displayable.__dirty = false;
  52768. }
  52769. newVisibleList.push(displayable);
  52770. }
  52771. }
  52772. var diff = arrayDiff$1(visibleList, newVisibleList);
  52773. var prevSvgElement;
  52774. // First do remove, in case element moved to the head and do remove
  52775. // after add
  52776. for (i = 0; i < diff.length; i++) {
  52777. var item = diff[i];
  52778. if (item.removed) {
  52779. for (var k = 0; k < item.count; k++) {
  52780. var displayable = visibleList[item.indices[k]];
  52781. var svgElement = getSvgElement(displayable);
  52782. var textSvgElement = getTextSvgElement(displayable);
  52783. remove$1(svgRoot, svgElement);
  52784. remove$1(svgRoot, textSvgElement);
  52785. }
  52786. }
  52787. }
  52788. for (i = 0; i < diff.length; i++) {
  52789. var item = diff[i];
  52790. if (item.added) {
  52791. for (var k = 0; k < item.count; k++) {
  52792. var displayable = newVisibleList[item.indices[k]];
  52793. var svgElement = getSvgElement(displayable);
  52794. var textSvgElement = getTextSvgElement(displayable);
  52795. prevSvgElement
  52796. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  52797. : prepend(svgRoot, svgElement);
  52798. if (svgElement) {
  52799. insertAfter(svgRoot, textSvgElement, svgElement);
  52800. }
  52801. else if (prevSvgElement) {
  52802. insertAfter(
  52803. svgRoot, textSvgElement, prevSvgElement
  52804. );
  52805. }
  52806. else {
  52807. prepend(svgRoot, textSvgElement);
  52808. }
  52809. // Insert text
  52810. insertAfter(svgRoot, textSvgElement, svgElement);
  52811. prevSvgElement = textSvgElement || svgElement
  52812. || prevSvgElement;
  52813. this.gradientManager
  52814. .addWithoutUpdate(svgElement, displayable);
  52815. this.shadowManager
  52816. .addWithoutUpdate(prevSvgElement, displayable);
  52817. this.clipPathManager.markUsed(displayable);
  52818. }
  52819. }
  52820. else if (!item.removed) {
  52821. for (var k = 0; k < item.count; k++) {
  52822. var displayable = newVisibleList[item.indices[k]];
  52823. prevSvgElement =
  52824. svgElement =
  52825. getTextSvgElement(displayable)
  52826. || getSvgElement(displayable)
  52827. || prevSvgElement;
  52828. this.gradientManager.markUsed(displayable);
  52829. this.gradientManager
  52830. .addWithoutUpdate(svgElement, displayable);
  52831. this.shadowManager.markUsed(displayable);
  52832. this.shadowManager
  52833. .addWithoutUpdate(svgElement, displayable);
  52834. this.clipPathManager.markUsed(displayable);
  52835. }
  52836. }
  52837. }
  52838. this.gradientManager.removeUnused();
  52839. this.clipPathManager.removeUnused();
  52840. this.shadowManager.removeUnused();
  52841. this._visibleList = newVisibleList;
  52842. },
  52843. _getDefs: function (isForceCreating) {
  52844. var svgRoot = this._svgRoot;
  52845. var defs = this._svgRoot.getElementsByTagName('defs');
  52846. if (defs.length === 0) {
  52847. // Not exist
  52848. if (isForceCreating) {
  52849. var defs = svgRoot.insertBefore(
  52850. createElement('defs'), // Create new tag
  52851. svgRoot.firstChild // Insert in the front of svg
  52852. );
  52853. if (!defs.contains) {
  52854. // IE doesn't support contains method
  52855. defs.contains = function (el) {
  52856. var children = defs.children;
  52857. if (!children) {
  52858. return false;
  52859. }
  52860. for (var i = children.length - 1; i >= 0; --i) {
  52861. if (children[i] === el) {
  52862. return true;
  52863. }
  52864. }
  52865. return false;
  52866. };
  52867. }
  52868. return defs;
  52869. }
  52870. else {
  52871. return null;
  52872. }
  52873. }
  52874. else {
  52875. return defs[0];
  52876. }
  52877. },
  52878. resize: function (width, height) {
  52879. var viewport = this._viewport;
  52880. // FIXME Why ?
  52881. viewport.style.display = 'none';
  52882. // Save input w/h
  52883. var opts = this._opts;
  52884. width != null && (opts.width = width);
  52885. height != null && (opts.height = height);
  52886. width = this._getSize(0);
  52887. height = this._getSize(1);
  52888. viewport.style.display = '';
  52889. if (this._width !== width || this._height !== height) {
  52890. this._width = width;
  52891. this._height = height;
  52892. var viewportStyle = viewport.style;
  52893. viewportStyle.width = width + 'px';
  52894. viewportStyle.height = height + 'px';
  52895. var svgRoot = this._svgRoot;
  52896. // Set width by 'svgRoot.width = width' is invalid
  52897. svgRoot.setAttribute('width', width);
  52898. svgRoot.setAttribute('height', height);
  52899. }
  52900. },
  52901. /**
  52902. * 获取绘图区域宽度
  52903. */
  52904. getWidth: function () {
  52905. return this._width;
  52906. },
  52907. /**
  52908. * 获取绘图区域高度
  52909. */
  52910. getHeight: function () {
  52911. return this._height;
  52912. },
  52913. _getSize: function (whIdx) {
  52914. var opts = this._opts;
  52915. var wh = ['width', 'height'][whIdx];
  52916. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  52917. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  52918. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  52919. if (opts[wh] != null && opts[wh] !== 'auto') {
  52920. return parseFloat(opts[wh]);
  52921. }
  52922. var root = this.root;
  52923. // IE8 does not support getComputedStyle, but it use VML.
  52924. var stl = document.defaultView.getComputedStyle(root);
  52925. return (
  52926. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  52927. - (parseInt10$2(stl[plt]) || 0)
  52928. - (parseInt10$2(stl[prb]) || 0)
  52929. ) | 0;
  52930. },
  52931. dispose: function () {
  52932. this.root.innerHTML = '';
  52933. this._svgRoot =
  52934. this._viewport =
  52935. this.storage =
  52936. null;
  52937. },
  52938. clear: function () {
  52939. if (this._viewport) {
  52940. this.root.removeChild(this._viewport);
  52941. }
  52942. },
  52943. pathToDataUrl: function () {
  52944. this.refresh();
  52945. var html = this._svgRoot.outerHTML;
  52946. return 'data:image/svg+xml;charset=UTF-8,' + html;
  52947. }
  52948. };
  52949. // Not supported methods
  52950. function createMethodNotSupport$1(method) {
  52951. return function () {
  52952. zrLog('In SVG mode painter not support method "' + method + '"');
  52953. };
  52954. }
  52955. // Unsuppoted methods
  52956. each$1([
  52957. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  52958. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  52959. 'toDataURL', 'pathToImage'
  52960. ], function (name) {
  52961. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  52962. });
  52963. registerPainter('svg', SVGPainter);
  52964. /*
  52965. * Licensed to the Apache Software Foundation (ASF) under one
  52966. * or more contributor license agreements. See the NOTICE file
  52967. * distributed with this work for additional information
  52968. * regarding copyright ownership. The ASF licenses this file
  52969. * to you under the Apache License, Version 2.0 (the
  52970. * "License"); you may not use this file except in compliance
  52971. * with the License. You may obtain a copy of the License at
  52972. *
  52973. * http://www.apache.org/licenses/LICENSE-2.0
  52974. *
  52975. * Unless required by applicable law or agreed to in writing,
  52976. * software distributed under the License is distributed on an
  52977. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52978. * KIND, either express or implied. See the License for the
  52979. * specific language governing permissions and limitations
  52980. * under the License.
  52981. */
  52982. exports.version = version;
  52983. exports.dependencies = dependencies;
  52984. exports.PRIORITY = PRIORITY;
  52985. exports.init = init;
  52986. exports.connect = connect;
  52987. exports.disConnect = disConnect;
  52988. exports.disconnect = disconnect;
  52989. exports.dispose = dispose;
  52990. exports.getInstanceByDom = getInstanceByDom;
  52991. exports.getInstanceById = getInstanceById;
  52992. exports.registerTheme = registerTheme;
  52993. exports.registerPreprocessor = registerPreprocessor;
  52994. exports.registerProcessor = registerProcessor;
  52995. exports.registerPostUpdate = registerPostUpdate;
  52996. exports.registerAction = registerAction;
  52997. exports.registerCoordinateSystem = registerCoordinateSystem;
  52998. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  52999. exports.registerLayout = registerLayout;
  53000. exports.registerVisual = registerVisual;
  53001. exports.registerLoading = registerLoading;
  53002. exports.extendComponentModel = extendComponentModel;
  53003. exports.extendComponentView = extendComponentView;
  53004. exports.extendSeriesModel = extendSeriesModel;
  53005. exports.extendChartView = extendChartView;
  53006. exports.setCanvasCreator = setCanvasCreator;
  53007. exports.registerMap = registerMap;
  53008. exports.getMap = getMap;
  53009. exports.dataTool = dataTool;
  53010. exports.zrender = zrender;
  53011. exports.number = number;
  53012. exports.format = format;
  53013. exports.throttle = throttle;
  53014. exports.helper = helper;
  53015. exports.matrix = matrix;
  53016. exports.vector = vector;
  53017. exports.color = color;
  53018. exports.parseGeoJSON = parseGeoJSON;
  53019. exports.parseGeoJson = parseGeoJson;
  53020. exports.util = ecUtil;
  53021. exports.graphic = graphic$1;
  53022. exports.List = List;
  53023. exports.Model = Model;
  53024. exports.Axis = Axis;
  53025. exports.env = env$1;
  53026. })));