echarts-en.common.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. /* global wx */
  59. var env = {};
  60. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  61. // In Weixin Application
  62. env = {
  63. browser: {},
  64. os: {},
  65. node: false,
  66. wxa: true, // Weixin Application
  67. canvasSupported: true,
  68. svgSupported: false,
  69. touchEventsSupported: true,
  70. domSupported: false
  71. };
  72. }
  73. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  74. // In worker
  75. env = {
  76. browser: {},
  77. os: {},
  78. node: false,
  79. worker: true,
  80. canvasSupported: true,
  81. domSupported: false
  82. };
  83. }
  84. else if (typeof navigator === 'undefined') {
  85. // In node
  86. env = {
  87. browser: {},
  88. os: {},
  89. node: true,
  90. worker: false,
  91. // Assume canvas is supported
  92. canvasSupported: true,
  93. svgSupported: true,
  94. domSupported: false
  95. };
  96. }
  97. else {
  98. env = detect(navigator.userAgent);
  99. }
  100. var env$1 = env;
  101. // Zepto.js
  102. // (c) 2010-2013 Thomas Fuchs
  103. // Zepto.js may be freely distributed under the MIT license.
  104. function detect(ua) {
  105. var os = {};
  106. var browser = {};
  107. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  108. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  109. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  110. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  111. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  112. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  113. // var touchpad = webos && ua.match(/TouchPad/);
  114. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  115. // var silk = ua.match(/Silk\/([\d._]+)/);
  116. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  117. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  118. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  119. // var playbook = ua.match(/PlayBook/);
  120. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  121. var firefox = ua.match(/Firefox\/([\d.]+)/);
  122. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  123. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  124. var ie = ua.match(/MSIE\s([\d.]+)/)
  125. // IE 11 Trident/7.0; rv:11.0
  126. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  127. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  128. var weChat = (/micromessenger/i).test(ua);
  129. // Todo: clean this up with a better OS/browser seperation:
  130. // - discern (more) between multiple browsers on android
  131. // - decide if kindle fire in silk mode is android or not
  132. // - Firefox on Android doesn't specify the Android version
  133. // - possibly devide in os, device and browser hashes
  134. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  135. // if (android) os.android = true, os.version = android[2];
  136. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  137. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  138. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  139. // if (webos) os.webos = true, os.version = webos[2];
  140. // if (touchpad) os.touchpad = true;
  141. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  142. // if (bb10) os.bb10 = true, os.version = bb10[2];
  143. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  144. // if (playbook) browser.playbook = true;
  145. // if (kindle) os.kindle = true, os.version = kindle[1];
  146. // if (silk) browser.silk = true, browser.version = silk[1];
  147. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  148. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  149. if (firefox) {
  150. browser.firefox = true;
  151. browser.version = firefox[1];
  152. }
  153. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  154. // if (webview) browser.webview = true;
  155. if (ie) {
  156. browser.ie = true;
  157. browser.version = ie[1];
  158. }
  159. if (edge) {
  160. browser.edge = true;
  161. browser.version = edge[1];
  162. }
  163. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  164. // not be set on win phone. So we do not consider Win Phone.
  165. if (weChat) {
  166. browser.weChat = true;
  167. }
  168. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  169. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  170. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  171. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  172. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  173. return {
  174. browser: browser,
  175. os: os,
  176. node: false,
  177. // 原生canvas支持,改极端点了
  178. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  179. canvasSupported: !!document.createElement('canvas').getContext,
  180. svgSupported: typeof SVGRect !== 'undefined',
  181. // works on most browsers
  182. // IE10/11 does not support touch event, and MS Edge supports them but not by
  183. // default, so we dont check navigator.maxTouchPoints for them here.
  184. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  185. // <http://caniuse.com/#search=pointer%20event>.
  186. pointerEventsSupported:
  187. // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  188. // events currently. So we dont use that on other browsers unless tested sufficiently.
  189. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  190. // scroll, the `pointermove` event can not be fired any more. That will break some
  191. // features like "pan horizontally to move something and pan vertically to page scroll".
  192. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  193. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  194. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  195. 'onpointerdown' in window
  196. && (browser.edge || (browser.ie && browser.version >= 11)),
  197. // passiveSupported: detectPassiveSupport()
  198. domSupported: typeof document !== 'undefined'
  199. };
  200. }
  201. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  202. // function detectPassiveSupport() {
  203. // // Test via a getter in the options object to see if the passive property is accessed
  204. // var supportsPassive = false;
  205. // try {
  206. // var opts = Object.defineProperty({}, 'passive', {
  207. // get: function() {
  208. // supportsPassive = true;
  209. // }
  210. // });
  211. // window.addEventListener('testPassive', function() {}, opts);
  212. // } catch (e) {
  213. // }
  214. // return supportsPassive;
  215. // }
  216. /**
  217. * @module zrender/core/util
  218. */
  219. // 用于处理merge时无法遍历Date等对象的问题
  220. var BUILTIN_OBJECT = {
  221. '[object Function]': 1,
  222. '[object RegExp]': 1,
  223. '[object Date]': 1,
  224. '[object Error]': 1,
  225. '[object CanvasGradient]': 1,
  226. '[object CanvasPattern]': 1,
  227. // For node-canvas
  228. '[object Image]': 1,
  229. '[object Canvas]': 1
  230. };
  231. var TYPED_ARRAY = {
  232. '[object Int8Array]': 1,
  233. '[object Uint8Array]': 1,
  234. '[object Uint8ClampedArray]': 1,
  235. '[object Int16Array]': 1,
  236. '[object Uint16Array]': 1,
  237. '[object Int32Array]': 1,
  238. '[object Uint32Array]': 1,
  239. '[object Float32Array]': 1,
  240. '[object Float64Array]': 1
  241. };
  242. var objToString = Object.prototype.toString;
  243. var arrayProto = Array.prototype;
  244. var nativeForEach = arrayProto.forEach;
  245. var nativeFilter = arrayProto.filter;
  246. var nativeSlice = arrayProto.slice;
  247. var nativeMap = arrayProto.map;
  248. var nativeReduce = arrayProto.reduce;
  249. // Avoid assign to an exported variable, for transforming to cjs.
  250. var methods = {};
  251. function $override(name, fn) {
  252. // Clear ctx instance for different environment
  253. if (name === 'createCanvas') {
  254. _ctx = null;
  255. }
  256. methods[name] = fn;
  257. }
  258. /**
  259. * Those data types can be cloned:
  260. * Plain object, Array, TypedArray, number, string, null, undefined.
  261. * Those data types will be assgined using the orginal data:
  262. * BUILTIN_OBJECT
  263. * Instance of user defined class will be cloned to a plain object, without
  264. * properties in prototype.
  265. * Other data types is not supported (not sure what will happen).
  266. *
  267. * Caution: do not support clone Date, for performance consideration.
  268. * (There might be a large number of date in `series.data`).
  269. * So date should not be modified in and out of echarts.
  270. *
  271. * @param {*} source
  272. * @return {*} new
  273. */
  274. function clone(source) {
  275. if (source == null || typeof source !== 'object') {
  276. return source;
  277. }
  278. var result = source;
  279. var typeStr = objToString.call(source);
  280. if (typeStr === '[object Array]') {
  281. if (!isPrimitive(source)) {
  282. result = [];
  283. for (var i = 0, len = source.length; i < len; i++) {
  284. result[i] = clone(source[i]);
  285. }
  286. }
  287. }
  288. else if (TYPED_ARRAY[typeStr]) {
  289. if (!isPrimitive(source)) {
  290. var Ctor = source.constructor;
  291. if (source.constructor.from) {
  292. result = Ctor.from(source);
  293. }
  294. else {
  295. result = new Ctor(source.length);
  296. for (var i = 0, len = source.length; i < len; i++) {
  297. result[i] = clone(source[i]);
  298. }
  299. }
  300. }
  301. }
  302. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  303. result = {};
  304. for (var key in source) {
  305. if (source.hasOwnProperty(key)) {
  306. result[key] = clone(source[key]);
  307. }
  308. }
  309. }
  310. return result;
  311. }
  312. /**
  313. * @memberOf module:zrender/core/util
  314. * @param {*} target
  315. * @param {*} source
  316. * @param {boolean} [overwrite=false]
  317. */
  318. function merge(target, source, overwrite) {
  319. // We should escapse that source is string
  320. // and enter for ... in ...
  321. if (!isObject$1(source) || !isObject$1(target)) {
  322. return overwrite ? clone(source) : target;
  323. }
  324. for (var key in source) {
  325. if (source.hasOwnProperty(key)) {
  326. var targetProp = target[key];
  327. var sourceProp = source[key];
  328. if (isObject$1(sourceProp)
  329. && isObject$1(targetProp)
  330. && !isArray(sourceProp)
  331. && !isArray(targetProp)
  332. && !isDom(sourceProp)
  333. && !isDom(targetProp)
  334. && !isBuiltInObject(sourceProp)
  335. && !isBuiltInObject(targetProp)
  336. && !isPrimitive(sourceProp)
  337. && !isPrimitive(targetProp)
  338. ) {
  339. // 如果需要递归覆盖,就递归调用merge
  340. merge(targetProp, sourceProp, overwrite);
  341. }
  342. else if (overwrite || !(key in target)) {
  343. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  344. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  345. target[key] = clone(source[key], true);
  346. }
  347. }
  348. }
  349. return target;
  350. }
  351. /**
  352. * @param {Array} targetAndSources The first item is target, and the rests are source.
  353. * @param {boolean} [overwrite=false]
  354. * @return {*} target
  355. */
  356. function mergeAll(targetAndSources, overwrite) {
  357. var result = targetAndSources[0];
  358. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  359. result = merge(result, targetAndSources[i], overwrite);
  360. }
  361. return result;
  362. }
  363. /**
  364. * @param {*} target
  365. * @param {*} source
  366. * @memberOf module:zrender/core/util
  367. */
  368. function extend(target, source) {
  369. for (var key in source) {
  370. if (source.hasOwnProperty(key)) {
  371. target[key] = source[key];
  372. }
  373. }
  374. return target;
  375. }
  376. /**
  377. * @param {*} target
  378. * @param {*} source
  379. * @param {boolean} [overlay=false]
  380. * @memberOf module:zrender/core/util
  381. */
  382. function defaults(target, source, overlay) {
  383. for (var key in source) {
  384. if (source.hasOwnProperty(key)
  385. && (overlay ? source[key] != null : target[key] == null)
  386. ) {
  387. target[key] = source[key];
  388. }
  389. }
  390. return target;
  391. }
  392. var createCanvas = function () {
  393. return methods.createCanvas();
  394. };
  395. methods.createCanvas = function () {
  396. return document.createElement('canvas');
  397. };
  398. // FIXME
  399. var _ctx;
  400. function getContext() {
  401. if (!_ctx) {
  402. // Use util.createCanvas instead of createCanvas
  403. // because createCanvas may be overwritten in different environment
  404. _ctx = createCanvas().getContext('2d');
  405. }
  406. return _ctx;
  407. }
  408. /**
  409. * 查询数组中元素的index
  410. * @memberOf module:zrender/core/util
  411. */
  412. function indexOf(array, value) {
  413. if (array) {
  414. if (array.indexOf) {
  415. return array.indexOf(value);
  416. }
  417. for (var i = 0, len = array.length; i < len; i++) {
  418. if (array[i] === value) {
  419. return i;
  420. }
  421. }
  422. }
  423. return -1;
  424. }
  425. /**
  426. * 构造类继承关系
  427. *
  428. * @memberOf module:zrender/core/util
  429. * @param {Function} clazz 源类
  430. * @param {Function} baseClazz 基类
  431. */
  432. function inherits(clazz, baseClazz) {
  433. var clazzPrototype = clazz.prototype;
  434. function F() {}
  435. F.prototype = baseClazz.prototype;
  436. clazz.prototype = new F();
  437. for (var prop in clazzPrototype) {
  438. if (clazzPrototype.hasOwnProperty(prop)) {
  439. clazz.prototype[prop] = clazzPrototype[prop];
  440. }
  441. }
  442. clazz.prototype.constructor = clazz;
  443. clazz.superClass = baseClazz;
  444. }
  445. /**
  446. * @memberOf module:zrender/core/util
  447. * @param {Object|Function} target
  448. * @param {Object|Function} sorce
  449. * @param {boolean} overlay
  450. */
  451. function mixin(target, source, overlay) {
  452. target = 'prototype' in target ? target.prototype : target;
  453. source = 'prototype' in source ? source.prototype : source;
  454. defaults(target, source, overlay);
  455. }
  456. /**
  457. * Consider typed array.
  458. * @param {Array|TypedArray} data
  459. */
  460. function isArrayLike(data) {
  461. if (!data) {
  462. return;
  463. }
  464. if (typeof data === 'string') {
  465. return false;
  466. }
  467. return typeof data.length === 'number';
  468. }
  469. /**
  470. * 数组或对象遍历
  471. * @memberOf module:zrender/core/util
  472. * @param {Object|Array} obj
  473. * @param {Function} cb
  474. * @param {*} [context]
  475. */
  476. function each$1(obj, cb, context) {
  477. if (!(obj && cb)) {
  478. return;
  479. }
  480. if (obj.forEach && obj.forEach === nativeForEach) {
  481. obj.forEach(cb, context);
  482. }
  483. else if (obj.length === +obj.length) {
  484. for (var i = 0, len = obj.length; i < len; i++) {
  485. cb.call(context, obj[i], i, obj);
  486. }
  487. }
  488. else {
  489. for (var key in obj) {
  490. if (obj.hasOwnProperty(key)) {
  491. cb.call(context, obj[key], key, obj);
  492. }
  493. }
  494. }
  495. }
  496. /**
  497. * 数组映射
  498. * @memberOf module:zrender/core/util
  499. * @param {Array} obj
  500. * @param {Function} cb
  501. * @param {*} [context]
  502. * @return {Array}
  503. */
  504. function map(obj, cb, context) {
  505. if (!(obj && cb)) {
  506. return;
  507. }
  508. if (obj.map && obj.map === nativeMap) {
  509. return obj.map(cb, context);
  510. }
  511. else {
  512. var result = [];
  513. for (var i = 0, len = obj.length; i < len; i++) {
  514. result.push(cb.call(context, obj[i], i, obj));
  515. }
  516. return result;
  517. }
  518. }
  519. /**
  520. * @memberOf module:zrender/core/util
  521. * @param {Array} obj
  522. * @param {Function} cb
  523. * @param {Object} [memo]
  524. * @param {*} [context]
  525. * @return {Array}
  526. */
  527. function reduce(obj, cb, memo, context) {
  528. if (!(obj && cb)) {
  529. return;
  530. }
  531. if (obj.reduce && obj.reduce === nativeReduce) {
  532. return obj.reduce(cb, memo, context);
  533. }
  534. else {
  535. for (var i = 0, len = obj.length; i < len; i++) {
  536. memo = cb.call(context, memo, obj[i], i, obj);
  537. }
  538. return memo;
  539. }
  540. }
  541. /**
  542. * 数组过滤
  543. * @memberOf module:zrender/core/util
  544. * @param {Array} obj
  545. * @param {Function} cb
  546. * @param {*} [context]
  547. * @return {Array}
  548. */
  549. function filter(obj, cb, context) {
  550. if (!(obj && cb)) {
  551. return;
  552. }
  553. if (obj.filter && obj.filter === nativeFilter) {
  554. return obj.filter(cb, context);
  555. }
  556. else {
  557. var result = [];
  558. for (var i = 0, len = obj.length; i < len; i++) {
  559. if (cb.call(context, obj[i], i, obj)) {
  560. result.push(obj[i]);
  561. }
  562. }
  563. return result;
  564. }
  565. }
  566. /**
  567. * 数组项查找
  568. * @memberOf module:zrender/core/util
  569. * @param {Array} obj
  570. * @param {Function} cb
  571. * @param {*} [context]
  572. * @return {*}
  573. */
  574. function find(obj, cb, context) {
  575. if (!(obj && cb)) {
  576. return;
  577. }
  578. for (var i = 0, len = obj.length; i < len; i++) {
  579. if (cb.call(context, obj[i], i, obj)) {
  580. return obj[i];
  581. }
  582. }
  583. }
  584. /**
  585. * @memberOf module:zrender/core/util
  586. * @param {Function} func
  587. * @param {*} context
  588. * @return {Function}
  589. */
  590. function bind(func, context) {
  591. var args = nativeSlice.call(arguments, 2);
  592. return function () {
  593. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  594. };
  595. }
  596. /**
  597. * @memberOf module:zrender/core/util
  598. * @param {Function} func
  599. * @return {Function}
  600. */
  601. function curry(func) {
  602. var args = nativeSlice.call(arguments, 1);
  603. return function () {
  604. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  605. };
  606. }
  607. /**
  608. * @memberOf module:zrender/core/util
  609. * @param {*} value
  610. * @return {boolean}
  611. */
  612. function isArray(value) {
  613. return objToString.call(value) === '[object Array]';
  614. }
  615. /**
  616. * @memberOf module:zrender/core/util
  617. * @param {*} value
  618. * @return {boolean}
  619. */
  620. function isFunction$1(value) {
  621. return typeof value === 'function';
  622. }
  623. /**
  624. * @memberOf module:zrender/core/util
  625. * @param {*} value
  626. * @return {boolean}
  627. */
  628. function isString(value) {
  629. return objToString.call(value) === '[object String]';
  630. }
  631. /**
  632. * @memberOf module:zrender/core/util
  633. * @param {*} value
  634. * @return {boolean}
  635. */
  636. function isObject$1(value) {
  637. // Avoid a V8 JIT bug in Chrome 19-20.
  638. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  639. var type = typeof value;
  640. return type === 'function' || (!!value && type === 'object');
  641. }
  642. /**
  643. * @memberOf module:zrender/core/util
  644. * @param {*} value
  645. * @return {boolean}
  646. */
  647. function isBuiltInObject(value) {
  648. return !!BUILTIN_OBJECT[objToString.call(value)];
  649. }
  650. /**
  651. * @memberOf module:zrender/core/util
  652. * @param {*} value
  653. * @return {boolean}
  654. */
  655. function isTypedArray(value) {
  656. return !!TYPED_ARRAY[objToString.call(value)];
  657. }
  658. /**
  659. * @memberOf module:zrender/core/util
  660. * @param {*} value
  661. * @return {boolean}
  662. */
  663. function isDom(value) {
  664. return typeof value === 'object'
  665. && typeof value.nodeType === 'number'
  666. && typeof value.ownerDocument === 'object';
  667. }
  668. /**
  669. * Whether is exactly NaN. Notice isNaN('a') returns true.
  670. * @param {*} value
  671. * @return {boolean}
  672. */
  673. function eqNaN(value) {
  674. /* eslint-disable-next-line no-self-compare */
  675. return value !== value;
  676. }
  677. /**
  678. * If value1 is not null, then return value1, otherwise judget rest of values.
  679. * Low performance.
  680. * @memberOf module:zrender/core/util
  681. * @return {*} Final value
  682. */
  683. function retrieve(values) {
  684. for (var i = 0, len = arguments.length; i < len; i++) {
  685. if (arguments[i] != null) {
  686. return arguments[i];
  687. }
  688. }
  689. }
  690. function retrieve2(value0, value1) {
  691. return value0 != null
  692. ? value0
  693. : value1;
  694. }
  695. function retrieve3(value0, value1, value2) {
  696. return value0 != null
  697. ? value0
  698. : value1 != null
  699. ? value1
  700. : value2;
  701. }
  702. /**
  703. * @memberOf module:zrender/core/util
  704. * @param {Array} arr
  705. * @param {number} startIndex
  706. * @param {number} endIndex
  707. * @return {Array}
  708. */
  709. function slice() {
  710. return Function.call.apply(nativeSlice, arguments);
  711. }
  712. /**
  713. * Normalize css liked array configuration
  714. * e.g.
  715. * 3 => [3, 3, 3, 3]
  716. * [4, 2] => [4, 2, 4, 2]
  717. * [4, 3, 2] => [4, 3, 2, 3]
  718. * @param {number|Array.<number>} val
  719. * @return {Array.<number>}
  720. */
  721. function normalizeCssArray(val) {
  722. if (typeof (val) === 'number') {
  723. return [val, val, val, val];
  724. }
  725. var len = val.length;
  726. if (len === 2) {
  727. // vertical | horizontal
  728. return [val[0], val[1], val[0], val[1]];
  729. }
  730. else if (len === 3) {
  731. // top | horizontal | bottom
  732. return [val[0], val[1], val[2], val[1]];
  733. }
  734. return val;
  735. }
  736. /**
  737. * @memberOf module:zrender/core/util
  738. * @param {boolean} condition
  739. * @param {string} message
  740. */
  741. function assert$1(condition, message) {
  742. if (!condition) {
  743. throw new Error(message);
  744. }
  745. }
  746. /**
  747. * @memberOf module:zrender/core/util
  748. * @param {string} str string to be trimed
  749. * @return {string} trimed string
  750. */
  751. function trim(str) {
  752. if (str == null) {
  753. return null;
  754. }
  755. else if (typeof str.trim === 'function') {
  756. return str.trim();
  757. }
  758. else {
  759. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  760. }
  761. }
  762. var primitiveKey = '__ec_primitive__';
  763. /**
  764. * Set an object as primitive to be ignored traversing children in clone or merge
  765. */
  766. function setAsPrimitive(obj) {
  767. obj[primitiveKey] = true;
  768. }
  769. function isPrimitive(obj) {
  770. return obj[primitiveKey];
  771. }
  772. /**
  773. * @constructor
  774. * @param {Object} obj Only apply `ownProperty`.
  775. */
  776. function HashMap(obj) {
  777. var isArr = isArray(obj);
  778. // Key should not be set on this, otherwise
  779. // methods get/set/... may be overrided.
  780. this.data = {};
  781. var thisMap = this;
  782. (obj instanceof HashMap)
  783. ? obj.each(visit)
  784. : (obj && each$1(obj, visit));
  785. function visit(value, key) {
  786. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  787. }
  788. }
  789. HashMap.prototype = {
  790. constructor: HashMap,
  791. // Do not provide `has` method to avoid defining what is `has`.
  792. // (We usually treat `null` and `undefined` as the same, different
  793. // from ES6 Map).
  794. get: function (key) {
  795. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  796. },
  797. set: function (key, value) {
  798. // Comparing with invocation chaining, `return value` is more commonly
  799. // used in this case: `var someVal = map.set('a', genVal());`
  800. return (this.data[key] = value);
  801. },
  802. // Although util.each can be performed on this hashMap directly, user
  803. // should not use the exposed keys, who are prefixed.
  804. each: function (cb, context) {
  805. context !== void 0 && (cb = bind(cb, context));
  806. /* eslint-disable guard-for-in */
  807. for (var key in this.data) {
  808. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  809. }
  810. /* eslint-enable guard-for-in */
  811. },
  812. // Do not use this method if performance sensitive.
  813. removeKey: function (key) {
  814. delete this.data[key];
  815. }
  816. };
  817. function createHashMap(obj) {
  818. return new HashMap(obj);
  819. }
  820. function concatArray(a, b) {
  821. var newArray = new a.constructor(a.length + b.length);
  822. for (var i = 0; i < a.length; i++) {
  823. newArray[i] = a[i];
  824. }
  825. var offset = a.length;
  826. for (i = 0; i < b.length; i++) {
  827. newArray[i + offset] = b[i];
  828. }
  829. return newArray;
  830. }
  831. function noop() {}
  832. var zrUtil = (Object.freeze || Object)({
  833. $override: $override,
  834. clone: clone,
  835. merge: merge,
  836. mergeAll: mergeAll,
  837. extend: extend,
  838. defaults: defaults,
  839. createCanvas: createCanvas,
  840. getContext: getContext,
  841. indexOf: indexOf,
  842. inherits: inherits,
  843. mixin: mixin,
  844. isArrayLike: isArrayLike,
  845. each: each$1,
  846. map: map,
  847. reduce: reduce,
  848. filter: filter,
  849. find: find,
  850. bind: bind,
  851. curry: curry,
  852. isArray: isArray,
  853. isFunction: isFunction$1,
  854. isString: isString,
  855. isObject: isObject$1,
  856. isBuiltInObject: isBuiltInObject,
  857. isTypedArray: isTypedArray,
  858. isDom: isDom,
  859. eqNaN: eqNaN,
  860. retrieve: retrieve,
  861. retrieve2: retrieve2,
  862. retrieve3: retrieve3,
  863. slice: slice,
  864. normalizeCssArray: normalizeCssArray,
  865. assert: assert$1,
  866. trim: trim,
  867. setAsPrimitive: setAsPrimitive,
  868. isPrimitive: isPrimitive,
  869. createHashMap: createHashMap,
  870. concatArray: concatArray,
  871. noop: noop
  872. });
  873. /* global Float32Array */
  874. var ArrayCtor = typeof Float32Array === 'undefined'
  875. ? Array
  876. : Float32Array;
  877. /**
  878. * 创建一个向量
  879. * @param {number} [x=0]
  880. * @param {number} [y=0]
  881. * @return {Vector2}
  882. */
  883. function create(x, y) {
  884. var out = new ArrayCtor(2);
  885. if (x == null) {
  886. x = 0;
  887. }
  888. if (y == null) {
  889. y = 0;
  890. }
  891. out[0] = x;
  892. out[1] = y;
  893. return out;
  894. }
  895. /**
  896. * 复制向量数据
  897. * @param {Vector2} out
  898. * @param {Vector2} v
  899. * @return {Vector2}
  900. */
  901. function copy(out, v) {
  902. out[0] = v[0];
  903. out[1] = v[1];
  904. return out;
  905. }
  906. /**
  907. * 克隆一个向量
  908. * @param {Vector2} v
  909. * @return {Vector2}
  910. */
  911. function clone$1(v) {
  912. var out = new ArrayCtor(2);
  913. out[0] = v[0];
  914. out[1] = v[1];
  915. return out;
  916. }
  917. /**
  918. * 设置向量的两个项
  919. * @param {Vector2} out
  920. * @param {number} a
  921. * @param {number} b
  922. * @return {Vector2} 结果
  923. */
  924. function set(out, a, b) {
  925. out[0] = a;
  926. out[1] = b;
  927. return out;
  928. }
  929. /**
  930. * 向量相加
  931. * @param {Vector2} out
  932. * @param {Vector2} v1
  933. * @param {Vector2} v2
  934. */
  935. function add(out, v1, v2) {
  936. out[0] = v1[0] + v2[0];
  937. out[1] = v1[1] + v2[1];
  938. return out;
  939. }
  940. /**
  941. * 向量缩放后相加
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. * @param {number} a
  946. */
  947. function scaleAndAdd(out, v1, v2, a) {
  948. out[0] = v1[0] + v2[0] * a;
  949. out[1] = v1[1] + v2[1] * a;
  950. return out;
  951. }
  952. /**
  953. * 向量相减
  954. * @param {Vector2} out
  955. * @param {Vector2} v1
  956. * @param {Vector2} v2
  957. */
  958. function sub(out, v1, v2) {
  959. out[0] = v1[0] - v2[0];
  960. out[1] = v1[1] - v2[1];
  961. return out;
  962. }
  963. /**
  964. * 向量长度
  965. * @param {Vector2} v
  966. * @return {number}
  967. */
  968. function len(v) {
  969. return Math.sqrt(lenSquare(v));
  970. }
  971. var length = len; // jshint ignore:line
  972. /**
  973. * 向量长度平方
  974. * @param {Vector2} v
  975. * @return {number}
  976. */
  977. function lenSquare(v) {
  978. return v[0] * v[0] + v[1] * v[1];
  979. }
  980. var lengthSquare = lenSquare;
  981. /**
  982. * 向量乘法
  983. * @param {Vector2} out
  984. * @param {Vector2} v1
  985. * @param {Vector2} v2
  986. */
  987. function mul(out, v1, v2) {
  988. out[0] = v1[0] * v2[0];
  989. out[1] = v1[1] * v2[1];
  990. return out;
  991. }
  992. /**
  993. * 向量除法
  994. * @param {Vector2} out
  995. * @param {Vector2} v1
  996. * @param {Vector2} v2
  997. */
  998. function div(out, v1, v2) {
  999. out[0] = v1[0] / v2[0];
  1000. out[1] = v1[1] / v2[1];
  1001. return out;
  1002. }
  1003. /**
  1004. * 向量点乘
  1005. * @param {Vector2} v1
  1006. * @param {Vector2} v2
  1007. * @return {number}
  1008. */
  1009. function dot(v1, v2) {
  1010. return v1[0] * v2[0] + v1[1] * v2[1];
  1011. }
  1012. /**
  1013. * 向量缩放
  1014. * @param {Vector2} out
  1015. * @param {Vector2} v
  1016. * @param {number} s
  1017. */
  1018. function scale(out, v, s) {
  1019. out[0] = v[0] * s;
  1020. out[1] = v[1] * s;
  1021. return out;
  1022. }
  1023. /**
  1024. * 向量归一化
  1025. * @param {Vector2} out
  1026. * @param {Vector2} v
  1027. */
  1028. function normalize(out, v) {
  1029. var d = len(v);
  1030. if (d === 0) {
  1031. out[0] = 0;
  1032. out[1] = 0;
  1033. }
  1034. else {
  1035. out[0] = v[0] / d;
  1036. out[1] = v[1] / d;
  1037. }
  1038. return out;
  1039. }
  1040. /**
  1041. * 计算向量间距离
  1042. * @param {Vector2} v1
  1043. * @param {Vector2} v2
  1044. * @return {number}
  1045. */
  1046. function distance(v1, v2) {
  1047. return Math.sqrt(
  1048. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1049. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1050. );
  1051. }
  1052. var dist = distance;
  1053. /**
  1054. * 向量距离平方
  1055. * @param {Vector2} v1
  1056. * @param {Vector2} v2
  1057. * @return {number}
  1058. */
  1059. function distanceSquare(v1, v2) {
  1060. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1061. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1062. }
  1063. var distSquare = distanceSquare;
  1064. /**
  1065. * 求负向量
  1066. * @param {Vector2} out
  1067. * @param {Vector2} v
  1068. */
  1069. function negate(out, v) {
  1070. out[0] = -v[0];
  1071. out[1] = -v[1];
  1072. return out;
  1073. }
  1074. /**
  1075. * 插值两个点
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v1
  1078. * @param {Vector2} v2
  1079. * @param {number} t
  1080. */
  1081. function lerp(out, v1, v2, t) {
  1082. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1083. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1084. return out;
  1085. }
  1086. /**
  1087. * 矩阵左乘向量
  1088. * @param {Vector2} out
  1089. * @param {Vector2} v
  1090. * @param {Vector2} m
  1091. */
  1092. function applyTransform(out, v, m) {
  1093. var x = v[0];
  1094. var y = v[1];
  1095. out[0] = m[0] * x + m[2] * y + m[4];
  1096. out[1] = m[1] * x + m[3] * y + m[5];
  1097. return out;
  1098. }
  1099. /**
  1100. * 求两个向量最小值
  1101. * @param {Vector2} out
  1102. * @param {Vector2} v1
  1103. * @param {Vector2} v2
  1104. */
  1105. function min(out, v1, v2) {
  1106. out[0] = Math.min(v1[0], v2[0]);
  1107. out[1] = Math.min(v1[1], v2[1]);
  1108. return out;
  1109. }
  1110. /**
  1111. * 求两个向量最大值
  1112. * @param {Vector2} out
  1113. * @param {Vector2} v1
  1114. * @param {Vector2} v2
  1115. */
  1116. function max(out, v1, v2) {
  1117. out[0] = Math.max(v1[0], v2[0]);
  1118. out[1] = Math.max(v1[1], v2[1]);
  1119. return out;
  1120. }
  1121. var vector = (Object.freeze || Object)({
  1122. create: create,
  1123. copy: copy,
  1124. clone: clone$1,
  1125. set: set,
  1126. add: add,
  1127. scaleAndAdd: scaleAndAdd,
  1128. sub: sub,
  1129. len: len,
  1130. length: length,
  1131. lenSquare: lenSquare,
  1132. lengthSquare: lengthSquare,
  1133. mul: mul,
  1134. div: div,
  1135. dot: dot,
  1136. scale: scale,
  1137. normalize: normalize,
  1138. distance: distance,
  1139. dist: dist,
  1140. distanceSquare: distanceSquare,
  1141. distSquare: distSquare,
  1142. negate: negate,
  1143. lerp: lerp,
  1144. applyTransform: applyTransform,
  1145. min: min,
  1146. max: max
  1147. });
  1148. // TODO Draggable for group
  1149. // FIXME Draggable on element which has parent rotation or scale
  1150. function Draggable() {
  1151. this.on('mousedown', this._dragStart, this);
  1152. this.on('mousemove', this._drag, this);
  1153. this.on('mouseup', this._dragEnd, this);
  1154. // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1155. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1156. // `_dragEnd` when globalout. That would brings better user experience.
  1157. // this.on('globalout', this._dragEnd, this);
  1158. // this._dropTarget = null;
  1159. // this._draggingTarget = null;
  1160. // this._x = 0;
  1161. // this._y = 0;
  1162. }
  1163. Draggable.prototype = {
  1164. constructor: Draggable,
  1165. _dragStart: function (e) {
  1166. var draggingTarget = e.target;
  1167. // Find if there is draggable in the ancestor
  1168. while (draggingTarget && !draggingTarget.draggable) {
  1169. draggingTarget = draggingTarget.parent;
  1170. }
  1171. if (draggingTarget) {
  1172. this._draggingTarget = draggingTarget;
  1173. draggingTarget.dragging = true;
  1174. this._x = e.offsetX;
  1175. this._y = e.offsetY;
  1176. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1177. }
  1178. },
  1179. _drag: function (e) {
  1180. var draggingTarget = this._draggingTarget;
  1181. if (draggingTarget) {
  1182. var x = e.offsetX;
  1183. var y = e.offsetY;
  1184. var dx = x - this._x;
  1185. var dy = y - this._y;
  1186. this._x = x;
  1187. this._y = y;
  1188. draggingTarget.drift(dx, dy, e);
  1189. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1190. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1191. var lastDropTarget = this._dropTarget;
  1192. this._dropTarget = dropTarget;
  1193. if (draggingTarget !== dropTarget) {
  1194. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1195. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1196. }
  1197. if (dropTarget && dropTarget !== lastDropTarget) {
  1198. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1199. }
  1200. }
  1201. }
  1202. },
  1203. _dragEnd: function (e) {
  1204. var draggingTarget = this._draggingTarget;
  1205. if (draggingTarget) {
  1206. draggingTarget.dragging = false;
  1207. }
  1208. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1209. if (this._dropTarget) {
  1210. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1211. }
  1212. this._draggingTarget = null;
  1213. this._dropTarget = null;
  1214. }
  1215. };
  1216. function param(target, e) {
  1217. return {target: target, topTarget: e && e.topTarget};
  1218. }
  1219. /**
  1220. * Event Mixin
  1221. * @module zrender/mixin/Eventful
  1222. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1223. * pissang (https://www.github.com/pissang)
  1224. */
  1225. var arrySlice = Array.prototype.slice;
  1226. /**
  1227. * Event dispatcher.
  1228. *
  1229. * @alias module:zrender/mixin/Eventful
  1230. * @constructor
  1231. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1232. * `eventProcessor.xxx` called.
  1233. * @param {Function} [eventProcessor.normalizeQuery]
  1234. * param: {string|Object} Raw query.
  1235. * return: {string|Object} Normalized query.
  1236. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1237. * if it returns `true`.
  1238. * param: {string} eventType
  1239. * param: {string|Object} query
  1240. * return: {boolean}
  1241. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1242. * param: {string} eventType
  1243. */
  1244. var Eventful = function (eventProcessor) {
  1245. this._$handlers = {};
  1246. this._$eventProcessor = eventProcessor;
  1247. };
  1248. Eventful.prototype = {
  1249. constructor: Eventful,
  1250. /**
  1251. * The handler can only be triggered once, then removed.
  1252. *
  1253. * @param {string} event The event name.
  1254. * @param {string|Object} [query] Condition used on event filter.
  1255. * @param {Function} handler The event handler.
  1256. * @param {Object} context
  1257. */
  1258. one: function (event, query, handler, context) {
  1259. return on(this, event, query, handler, context, true);
  1260. },
  1261. /**
  1262. * Bind a handler.
  1263. *
  1264. * @param {string} event The event name.
  1265. * @param {string|Object} [query] Condition used on event filter.
  1266. * @param {Function} handler The event handler.
  1267. * @param {Object} [context]
  1268. */
  1269. on: function (event, query, handler, context) {
  1270. return on(this, event, query, handler, context, false);
  1271. },
  1272. /**
  1273. * Whether any handler has bound.
  1274. *
  1275. * @param {string} event
  1276. * @return {boolean}
  1277. */
  1278. isSilent: function (event) {
  1279. var _h = this._$handlers;
  1280. return !_h[event] || !_h[event].length;
  1281. },
  1282. /**
  1283. * Unbind a event.
  1284. *
  1285. * @param {string} [event] The event name.
  1286. * If no `event` input, "off" all listeners.
  1287. * @param {Function} [handler] The event handler.
  1288. * If no `handler` input, "off" all listeners of the `event`.
  1289. */
  1290. off: function (event, handler) {
  1291. var _h = this._$handlers;
  1292. if (!event) {
  1293. this._$handlers = {};
  1294. return this;
  1295. }
  1296. if (handler) {
  1297. if (_h[event]) {
  1298. var newList = [];
  1299. for (var i = 0, l = _h[event].length; i < l; i++) {
  1300. if (_h[event][i].h !== handler) {
  1301. newList.push(_h[event][i]);
  1302. }
  1303. }
  1304. _h[event] = newList;
  1305. }
  1306. if (_h[event] && _h[event].length === 0) {
  1307. delete _h[event];
  1308. }
  1309. }
  1310. else {
  1311. delete _h[event];
  1312. }
  1313. return this;
  1314. },
  1315. /**
  1316. * Dispatch a event.
  1317. *
  1318. * @param {string} type The event name.
  1319. */
  1320. trigger: function (type) {
  1321. var _h = this._$handlers[type];
  1322. var eventProcessor = this._$eventProcessor;
  1323. if (_h) {
  1324. var args = arguments;
  1325. var argLen = args.length;
  1326. if (argLen > 3) {
  1327. args = arrySlice.call(args, 1);
  1328. }
  1329. var len = _h.length;
  1330. for (var i = 0; i < len;) {
  1331. var hItem = _h[i];
  1332. if (eventProcessor
  1333. && eventProcessor.filter
  1334. && hItem.query != null
  1335. && !eventProcessor.filter(type, hItem.query)
  1336. ) {
  1337. i++;
  1338. continue;
  1339. }
  1340. // Optimize advise from backbone
  1341. switch (argLen) {
  1342. case 1:
  1343. hItem.h.call(hItem.ctx);
  1344. break;
  1345. case 2:
  1346. hItem.h.call(hItem.ctx, args[1]);
  1347. break;
  1348. case 3:
  1349. hItem.h.call(hItem.ctx, args[1], args[2]);
  1350. break;
  1351. default:
  1352. // have more than 2 given arguments
  1353. hItem.h.apply(hItem.ctx, args);
  1354. break;
  1355. }
  1356. if (hItem.one) {
  1357. _h.splice(i, 1);
  1358. len--;
  1359. }
  1360. else {
  1361. i++;
  1362. }
  1363. }
  1364. }
  1365. eventProcessor && eventProcessor.afterTrigger
  1366. && eventProcessor.afterTrigger(type);
  1367. return this;
  1368. },
  1369. /**
  1370. * Dispatch a event with context, which is specified at the last parameter.
  1371. *
  1372. * @param {string} type The event name.
  1373. */
  1374. triggerWithContext: function (type) {
  1375. var _h = this._$handlers[type];
  1376. var eventProcessor = this._$eventProcessor;
  1377. if (_h) {
  1378. var args = arguments;
  1379. var argLen = args.length;
  1380. if (argLen > 4) {
  1381. args = arrySlice.call(args, 1, args.length - 1);
  1382. }
  1383. var ctx = args[args.length - 1];
  1384. var len = _h.length;
  1385. for (var i = 0; i < len;) {
  1386. var hItem = _h[i];
  1387. if (eventProcessor
  1388. && eventProcessor.filter
  1389. && hItem.query != null
  1390. && !eventProcessor.filter(type, hItem.query)
  1391. ) {
  1392. i++;
  1393. continue;
  1394. }
  1395. // Optimize advise from backbone
  1396. switch (argLen) {
  1397. case 1:
  1398. hItem.h.call(ctx);
  1399. break;
  1400. case 2:
  1401. hItem.h.call(ctx, args[1]);
  1402. break;
  1403. case 3:
  1404. hItem.h.call(ctx, args[1], args[2]);
  1405. break;
  1406. default:
  1407. // have more than 2 given arguments
  1408. hItem.h.apply(ctx, args);
  1409. break;
  1410. }
  1411. if (hItem.one) {
  1412. _h.splice(i, 1);
  1413. len--;
  1414. }
  1415. else {
  1416. i++;
  1417. }
  1418. }
  1419. }
  1420. eventProcessor && eventProcessor.afterTrigger
  1421. && eventProcessor.afterTrigger(type);
  1422. return this;
  1423. }
  1424. };
  1425. function normalizeQuery(host, query) {
  1426. var eventProcessor = host._$eventProcessor;
  1427. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1428. query = eventProcessor.normalizeQuery(query);
  1429. }
  1430. return query;
  1431. }
  1432. function on(eventful, event, query, handler, context, isOnce) {
  1433. var _h = eventful._$handlers;
  1434. if (typeof query === 'function') {
  1435. context = handler;
  1436. handler = query;
  1437. query = null;
  1438. }
  1439. if (!handler || !event) {
  1440. return eventful;
  1441. }
  1442. query = normalizeQuery(eventful, query);
  1443. if (!_h[event]) {
  1444. _h[event] = [];
  1445. }
  1446. for (var i = 0; i < _h[event].length; i++) {
  1447. if (_h[event][i].h === handler) {
  1448. return eventful;
  1449. }
  1450. }
  1451. var wrap = {
  1452. h: handler,
  1453. one: isOnce,
  1454. query: query,
  1455. ctx: context || eventful,
  1456. // FIXME
  1457. // Do not publish this feature util it is proved that it makes sense.
  1458. callAtLast: handler.zrEventfulCallAtLast
  1459. };
  1460. var lastIndex = _h[event].length - 1;
  1461. var lastWrap = _h[event][lastIndex];
  1462. (lastWrap && lastWrap.callAtLast)
  1463. ? _h[event].splice(lastIndex, 0, wrap)
  1464. : _h[event].push(wrap);
  1465. return eventful;
  1466. }
  1467. /**
  1468. * The algoritm is learnt from
  1469. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1470. * And we made some optimization for matrix inversion.
  1471. * Other similar approaches:
  1472. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1473. */
  1474. var LN2 = Math.log(2);
  1475. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1476. var cacheKey = rowMask + '-' + colMask;
  1477. var fullRank = rows.length;
  1478. if (detCache.hasOwnProperty(cacheKey)) {
  1479. return detCache[cacheKey];
  1480. }
  1481. if (rank === 1) {
  1482. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1483. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1484. return rows[rowStart][colStart];
  1485. }
  1486. var subRowMask = rowMask | (1 << rowStart);
  1487. var subRowStart = rowStart + 1;
  1488. while (rowMask & (1 << subRowStart)) {
  1489. subRowStart++;
  1490. }
  1491. var sum = 0;
  1492. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1493. var colTag = 1 << j;
  1494. if (!(colTag & colMask)) {
  1495. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1496. // det(subMatrix(0, j))
  1497. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1498. colLocalIdx++;
  1499. }
  1500. }
  1501. detCache[cacheKey] = sum;
  1502. return sum;
  1503. }
  1504. /**
  1505. * Usage:
  1506. * ```js
  1507. * var transformer = buildTransformer(
  1508. * [10, 44, 100, 44, 100, 300, 10, 300],
  1509. * [50, 54, 130, 14, 140, 330, 14, 220]
  1510. * );
  1511. * var out = [];
  1512. * transformer && transformer([11, 33], out);
  1513. * ```
  1514. *
  1515. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1516. *
  1517. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1518. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1519. * @return {Function} transformer If fail, return null/undefined.
  1520. */
  1521. function buildTransformer(src, dest) {
  1522. var mA = [
  1523. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1524. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1525. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1526. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1527. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1528. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1529. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1530. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1531. ];
  1532. var detCache = {};
  1533. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1534. if (det === 0) {
  1535. // can not make transformer when and only when
  1536. // any three of the markers are collinear.
  1537. return;
  1538. }
  1539. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1540. var vh = [];
  1541. for (var i = 0; i < 8; i++) {
  1542. for (var j = 0; j < 8; j++) {
  1543. vh[j] == null && (vh[j] = 0);
  1544. vh[j] += ((i + j) % 2 ? -1 : 1)
  1545. // det(subMatrix(i, j))
  1546. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1547. / det * dest[i];
  1548. }
  1549. }
  1550. return function (out, srcPointX, srcPointY) {
  1551. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1552. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1553. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1554. };
  1555. }
  1556. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1557. var _calcOut$1 = [];
  1558. /**
  1559. * Transform "local coord" from `elFrom` to `elTarget`.
  1560. * "local coord": the coord based on the input `el`. The origin point is at
  1561. * the position of "left: 0; top: 0;" in the `el`.
  1562. *
  1563. * Support when CSS transform is used.
  1564. *
  1565. * Having the `out` (that is, `[outX, outY]`), we can create an DOM element
  1566. * and set the CSS style as "left: outX; top: outY;" and append it to `elTarge`
  1567. * to locate the element.
  1568. *
  1569. * For example, this code below positions a child of `document.body` on the event
  1570. * point, no matter whether `body` has `margin`/`paddin`/`transfrom`/... :
  1571. * ```js
  1572. * transformLocalCoord(out, container, document.body, event.offsetX, event.offsetY);
  1573. * if (!eqNaN(out[0])) {
  1574. * // Then locate the tip element on the event point.
  1575. * var tipEl = document.createElement('div');
  1576. * tipEl.style.cssText = 'position: absolute; left:' + out[0] + ';top:' + out[1] + ';';
  1577. * document.body.appendChild(tipEl);
  1578. * }
  1579. * ```
  1580. *
  1581. * Notice: In some env this method is not supported. If called, `out` will be `[NaN, NaN]`.
  1582. *
  1583. * @param {Array.<number>} out [inX: number, inY: number] The output..
  1584. * If can not transform, `out` will not be modified but return `false`.
  1585. * @param {HTMLElement} elFrom The `[inX, inY]` is based on elFrom.
  1586. * @param {HTMLElement} elTarget The `out` is based on elTarget.
  1587. * @param {number} inX
  1588. * @param {number} inY
  1589. * @return {boolean} Whether transform successfully.
  1590. */
  1591. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1592. return transformCoordWithViewport(_calcOut$1, elFrom, inX, inY, true)
  1593. && transformCoordWithViewport(out, elTarget, _calcOut$1[0], _calcOut$1[1]);
  1594. }
  1595. /**
  1596. * Transform between a "viewport coord" and a "local coord".
  1597. * "viewport coord": the coord based on the left-top corner of the viewport
  1598. * of the browser.
  1599. * "local coord": the coord based on the input `el`. The origin point is at
  1600. * the position of "left: 0; top: 0;" in the `el`.
  1601. *
  1602. * Support the case when CSS transform is used on el.
  1603. *
  1604. * @param {Array.<number>} out [inX: number, inY: number] The output. If `inverse: false`,
  1605. * it represents "local coord", otherwise "vireport coord".
  1606. * If can not transform, `out` will not be modified but return `false`.
  1607. * @param {HTMLElement} el The "local coord" is based on the `el`, see comment above.
  1608. * @param {number} inX If `inverse: false`,
  1609. * it represents "vireport coord", otherwise "local coord".
  1610. * @param {number} inY If `inverse: false`,
  1611. * it represents "vireport coord", otherwise "local coord".
  1612. * @param {boolean} [inverse=false]
  1613. * `true`: from "viewport coord" to "local coord".
  1614. * `false`: from "local coord" to "viewport coord".
  1615. * @return {boolean} Whether transform successfully.
  1616. */
  1617. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1618. if (el.getBoundingClientRect && env$1.domSupported && !isCanvasEl(el)) {
  1619. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1620. var markers = prepareCoordMarkers(el, saved);
  1621. var transformer = preparePointerTransformer(markers, saved, inverse);
  1622. if (transformer) {
  1623. transformer(out, inX, inY);
  1624. return true;
  1625. }
  1626. }
  1627. return false;
  1628. }
  1629. function prepareCoordMarkers(el, saved) {
  1630. var markers = saved.markers;
  1631. if (markers) {
  1632. return markers;
  1633. }
  1634. markers = saved.markers = [];
  1635. var propLR = ['left', 'right'];
  1636. var propTB = ['top', 'bottom'];
  1637. for (var i = 0; i < 4; i++) {
  1638. var marker = document.createElement('div');
  1639. var stl = marker.style;
  1640. var idxLR = i % 2;
  1641. var idxTB = (i >> 1) % 2;
  1642. stl.cssText = [
  1643. 'position: absolute',
  1644. 'visibility: hidden',
  1645. 'padding: 0',
  1646. 'margin: 0',
  1647. 'border-width: 0',
  1648. 'user-select: none',
  1649. 'width:0',
  1650. 'height:0',
  1651. // 'width: 5px',
  1652. // 'height: 5px',
  1653. propLR[idxLR] + ':0',
  1654. propTB[idxTB] + ':0',
  1655. propLR[1 - idxLR] + ':auto',
  1656. propTB[1 - idxTB] + ':auto',
  1657. ''
  1658. ].join('!important;');
  1659. el.appendChild(marker);
  1660. markers.push(marker);
  1661. }
  1662. return markers;
  1663. }
  1664. function preparePointerTransformer(markers, saved, inverse) {
  1665. var transformerName = inverse ? 'invTrans' : 'trans';
  1666. var transformer = saved[transformerName];
  1667. var oldSrcCoords = saved.srcCoords;
  1668. var oldCoordTheSame = true;
  1669. var srcCoords = [];
  1670. var destCoords = [];
  1671. for (var i = 0; i < 4; i++) {
  1672. var rect = markers[i].getBoundingClientRect();
  1673. var ii = 2 * i;
  1674. var x = rect.left;
  1675. var y = rect.top;
  1676. srcCoords.push(x, y);
  1677. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1678. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1679. }
  1680. // Cache to avoid time consuming of `buildTransformer`.
  1681. return (oldCoordTheSame && transformer)
  1682. ? transformer
  1683. : (
  1684. saved.srcCoords = srcCoords,
  1685. saved[transformerName] = inverse
  1686. ? buildTransformer(destCoords, srcCoords)
  1687. : buildTransformer(srcCoords, destCoords)
  1688. );
  1689. }
  1690. function isCanvasEl(el) {
  1691. return el.nodeName.toUpperCase() === 'CANVAS';
  1692. }
  1693. /**
  1694. * Utilities for mouse or touch events.
  1695. */
  1696. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1697. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1698. var _calcOut = [];
  1699. /**
  1700. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1701. * the input `el`.
  1702. * CSS transform (2D & 3D) is supported.
  1703. *
  1704. * The strategy to fetch the coords:
  1705. * + If `calculate` is not set as `true`, users of this method should
  1706. * ensure that `el` is the same or the same size & location as `e.target`.
  1707. * Otherwise the result coords are probably not expected. Because we
  1708. * firstly try to get coords from e.offsetX/e.offsetY.
  1709. * + If `calculate` is set as `true`, the input `el` can be any element
  1710. * and we force to calculate the coords based on `el`.
  1711. * + The input `el` should be positionable (not position:static).
  1712. *
  1713. * The force `calculate` can be used in case like:
  1714. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1715. *
  1716. * @param {HTMLElement} el DOM element.
  1717. * @param {Event} e Mouse event or touch event.
  1718. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1719. * @param {boolean} [calculate=false] Whether to force calculate
  1720. * the coordinates but not use ones provided by browser.
  1721. */
  1722. function clientToLocal(el, e, out, calculate) {
  1723. out = out || {};
  1724. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1725. // to the padding edge of the target element. The only browser using this convention
  1726. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1727. // not support the properties.
  1728. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1729. // In zr painter.dom, padding edge equals to border edge.
  1730. if (calculate || !env$1.canvasSupported) {
  1731. calculateZrXY(el, e, out);
  1732. }
  1733. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1734. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1735. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1736. // zoom-factor, overflow / opacity layers, transforms ...)
  1737. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1738. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1739. // BTW3, In ff, offsetX/offsetY is always 0.
  1740. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1741. out.zrX = e.layerX;
  1742. out.zrY = e.layerY;
  1743. }
  1744. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1745. else if (e.offsetX != null) {
  1746. out.zrX = e.offsetX;
  1747. out.zrY = e.offsetY;
  1748. }
  1749. // For some other device, e.g., IOS safari.
  1750. else {
  1751. calculateZrXY(el, e, out);
  1752. }
  1753. return out;
  1754. }
  1755. function calculateZrXY(el, e, out) {
  1756. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1757. if (env$1.domSupported && el.getBoundingClientRect) {
  1758. var ex = e.clientX;
  1759. var ey = e.clientY;
  1760. if (isCanvasEl(el)) {
  1761. // Original approach, which do not support CSS transform.
  1762. // marker can not be locationed in a canvas container
  1763. // (getBoundingClientRect is always 0). We do not support
  1764. // that input a pre-created canvas to zr while using css
  1765. // transform in iOS.
  1766. var box = el.getBoundingClientRect();
  1767. out.zrX = ex - box.left;
  1768. out.zrY = ey - box.top;
  1769. return;
  1770. }
  1771. else {
  1772. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  1773. out.zrX = _calcOut[0];
  1774. out.zrY = _calcOut[1];
  1775. return;
  1776. }
  1777. }
  1778. }
  1779. out.zrX = out.zrY = 0;
  1780. }
  1781. /**
  1782. * Find native event compat for legency IE.
  1783. * Should be called at the begining of a native event listener.
  1784. *
  1785. * @param {Event} [e] Mouse event or touch event or pointer event.
  1786. * For lagency IE, we use `window.event` is used.
  1787. * @return {Event} The native event.
  1788. */
  1789. function getNativeEvent(e) {
  1790. return e || window.event;
  1791. }
  1792. /**
  1793. * Normalize the coordinates of the input event.
  1794. *
  1795. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1796. * the input `el`.
  1797. * Get `e.zrDelta` if using mouse wheel.
  1798. * Get `e.which`, see the comment inside this function.
  1799. *
  1800. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1801. *
  1802. * Notice: see comments in `clientToLocal`. check the relationship
  1803. * between the result coords and the parameters `el` and `calculate`.
  1804. *
  1805. * @param {HTMLElement} el DOM element.
  1806. * @param {Event} [e] See `getNativeEvent`.
  1807. * @param {boolean} [calculate=false] Whether to force calculate
  1808. * the coordinates but not use ones provided by browser.
  1809. * @return {UIEvent} The normalized native UIEvent.
  1810. */
  1811. function normalizeEvent(el, e, calculate) {
  1812. e = getNativeEvent(e);
  1813. if (e.zrX != null) {
  1814. return e;
  1815. }
  1816. var eventType = e.type;
  1817. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1818. if (!isTouch) {
  1819. clientToLocal(el, e, e, calculate);
  1820. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1821. }
  1822. else {
  1823. var touch = eventType !== 'touchend'
  1824. ? e.targetTouches[0]
  1825. : e.changedTouches[0];
  1826. touch && clientToLocal(el, touch, e, calculate);
  1827. }
  1828. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1829. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1830. // If e.which has been defined, it may be readonly,
  1831. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1832. var button = e.button;
  1833. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1834. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1835. }
  1836. // [Caution]: `e.which` from browser is not always reliable. For example,
  1837. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1838. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1839. // `mousedown (pointerdown)` is the same as Chrome does.
  1840. return e;
  1841. }
  1842. /**
  1843. * @param {HTMLElement} el
  1844. * @param {string} name
  1845. * @param {Function} handler
  1846. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1847. * @param {boolean} [opt.capture=false]
  1848. * @param {boolean} [opt.passive=false]
  1849. */
  1850. function addEventListener(el, name, handler, opt) {
  1851. if (isDomLevel2) {
  1852. // Reproduct the console warning:
  1853. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1854. // Consider marking event handler as 'passive' to make the page more responsive.
  1855. // Just set console log level: verbose in chrome dev tool.
  1856. // then the warning log will be printed when addEventListener called.
  1857. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1858. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1859. // listener delegate all of the upper events of element. Some of those events need
  1860. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1861. // Before passive can be adopted, these issues should be considered:
  1862. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1863. // passive or not.
  1864. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1865. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1866. // compatibility should be handled.
  1867. // var opts = (env.passiveSupported && name === 'mousewheel')
  1868. // ? {passive: true}
  1869. // // By default, the third param of el.addEventListener is `capture: false`.
  1870. // : void 0;
  1871. // el.addEventListener(name, handler /* , opts */);
  1872. el.addEventListener(name, handler, opt);
  1873. }
  1874. else {
  1875. // For simplicity, do not implement `setCapture` for IE9-.
  1876. el.attachEvent('on' + name, handler);
  1877. }
  1878. }
  1879. /**
  1880. * Parameter are the same as `addEventListener`.
  1881. *
  1882. * Notice that if a listener is registered twice, one with capture and one without,
  1883. * remove each one separately. Removal of a capturing listener does not affect a
  1884. * non-capturing version of the same listener, and vice versa.
  1885. */
  1886. function removeEventListener(el, name, handler, opt) {
  1887. if (isDomLevel2) {
  1888. el.removeEventListener(name, handler, opt);
  1889. }
  1890. else {
  1891. el.detachEvent('on' + name, handler);
  1892. }
  1893. }
  1894. /**
  1895. * preventDefault and stopPropagation.
  1896. * Notice: do not use this method in zrender. It can only be
  1897. * used by upper applications if necessary.
  1898. *
  1899. * @param {Event} e A mouse or touch event.
  1900. */
  1901. var stop = isDomLevel2
  1902. ? function (e) {
  1903. e.preventDefault();
  1904. e.stopPropagation();
  1905. e.cancelBubble = true;
  1906. }
  1907. : function (e) {
  1908. e.returnValue = false;
  1909. e.cancelBubble = true;
  1910. };
  1911. /**
  1912. * This method only works for mouseup and mousedown. The functionality is restricted
  1913. * for fault tolerance, See the `e.which` compatibility above.
  1914. *
  1915. * @param {MouseEvent} e
  1916. * @return {boolean}
  1917. */
  1918. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1919. return e.which === 2 || e.which === 3;
  1920. }
  1921. /**
  1922. * To be removed.
  1923. * @deprecated
  1924. */
  1925. /**
  1926. * Only implements needed gestures for mobile.
  1927. */
  1928. var GestureMgr = function () {
  1929. /**
  1930. * @private
  1931. * @type {Array.<Object>}
  1932. */
  1933. this._track = [];
  1934. };
  1935. GestureMgr.prototype = {
  1936. constructor: GestureMgr,
  1937. recognize: function (event, target, root) {
  1938. this._doTrack(event, target, root);
  1939. return this._recognize(event);
  1940. },
  1941. clear: function () {
  1942. this._track.length = 0;
  1943. return this;
  1944. },
  1945. _doTrack: function (event, target, root) {
  1946. var touches = event.touches;
  1947. if (!touches) {
  1948. return;
  1949. }
  1950. var trackItem = {
  1951. points: [],
  1952. touches: [],
  1953. target: target,
  1954. event: event
  1955. };
  1956. for (var i = 0, len = touches.length; i < len; i++) {
  1957. var touch = touches[i];
  1958. var pos = clientToLocal(root, touch, {});
  1959. trackItem.points.push([pos.zrX, pos.zrY]);
  1960. trackItem.touches.push(touch);
  1961. }
  1962. this._track.push(trackItem);
  1963. },
  1964. _recognize: function (event) {
  1965. for (var eventName in recognizers) {
  1966. if (recognizers.hasOwnProperty(eventName)) {
  1967. var gestureInfo = recognizers[eventName](this._track, event);
  1968. if (gestureInfo) {
  1969. return gestureInfo;
  1970. }
  1971. }
  1972. }
  1973. }
  1974. };
  1975. function dist$1(pointPair) {
  1976. var dx = pointPair[1][0] - pointPair[0][0];
  1977. var dy = pointPair[1][1] - pointPair[0][1];
  1978. return Math.sqrt(dx * dx + dy * dy);
  1979. }
  1980. function center(pointPair) {
  1981. return [
  1982. (pointPair[0][0] + pointPair[1][0]) / 2,
  1983. (pointPair[0][1] + pointPair[1][1]) / 2
  1984. ];
  1985. }
  1986. var recognizers = {
  1987. pinch: function (track, event) {
  1988. var trackLen = track.length;
  1989. if (!trackLen) {
  1990. return;
  1991. }
  1992. var pinchEnd = (track[trackLen - 1] || {}).points;
  1993. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1994. if (pinchPre
  1995. && pinchPre.length > 1
  1996. && pinchEnd
  1997. && pinchEnd.length > 1
  1998. ) {
  1999. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  2000. !isFinite(pinchScale) && (pinchScale = 1);
  2001. event.pinchScale = pinchScale;
  2002. var pinchCenter = center(pinchEnd);
  2003. event.pinchX = pinchCenter[0];
  2004. event.pinchY = pinchCenter[1];
  2005. return {
  2006. type: 'pinch',
  2007. target: track[0].target,
  2008. event: event
  2009. };
  2010. }
  2011. }
  2012. // Only pinch currently.
  2013. };
  2014. /**
  2015. * [The interface between `Handler` and `HandlerProxy`]:
  2016. *
  2017. * The default `HandlerProxy` only support the common standard web environment
  2018. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  2019. * But `HandlerProxy` can be replaced to support more non-standard environment
  2020. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  2021. * not provided (like echarts-gl did).
  2022. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  2023. * make break changes util inevitable. The interface include the public methods
  2024. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  2025. * drives `Handler`.
  2026. */
  2027. /**
  2028. * [Drag outside]:
  2029. *
  2030. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  2031. * zrender area when dragging. That is important for the improvement of the user experience
  2032. * when dragging something near the boundary without being terminated unexpectedly.
  2033. *
  2034. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  2035. * to resolve this issue. But some drawbacks of it is described in
  2036. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  2037. *
  2038. * Instead, we referenced the specifications:
  2039. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  2040. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  2041. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  2042. * operation and the pointer has left the boundary. (for the mouse event, browsers
  2043. * only do it on `document` and when the pointer has left the boundary of the browser.)
  2044. *
  2045. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  2046. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  2047. * to fire until release the pointer. That is implemented by listen to those event on
  2048. * `document`.
  2049. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  2050. * The touch event support this feature by default.
  2051. *
  2052. * Note:
  2053. * There might be some cases that the mouse event can not be
  2054. * received on `document`. For example,
  2055. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  2056. * of zr dom throw Error .
  2057. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  2058. * zr dom call `stopPropagation`.
  2059. * In these cases, the `mousemove` event might be keep triggered event
  2060. * if the mouse is released. We try to reduce the side-effect in those cases.
  2061. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  2062. *
  2063. * Note:
  2064. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  2065. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  2066. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  2067. * `document` capture phase to prevent the propagation to any listener of the webpage.
  2068. * But they are needed to work when the pointer inside the zrender dom.
  2069. */
  2070. var SILENT = 'silent';
  2071. function makeEventPacket(eveType, targetInfo, event) {
  2072. return {
  2073. type: eveType,
  2074. event: event,
  2075. // target can only be an element that is not silent.
  2076. target: targetInfo.target,
  2077. // topTarget can be a silent element.
  2078. topTarget: targetInfo.topTarget,
  2079. cancelBubble: false,
  2080. offsetX: event.zrX,
  2081. offsetY: event.zrY,
  2082. gestureEvent: event.gestureEvent,
  2083. pinchX: event.pinchX,
  2084. pinchY: event.pinchY,
  2085. pinchScale: event.pinchScale,
  2086. wheelDelta: event.zrDelta,
  2087. zrByTouch: event.zrByTouch,
  2088. which: event.which,
  2089. stop: stopEvent
  2090. };
  2091. }
  2092. function stopEvent() {
  2093. stop(this.event);
  2094. }
  2095. function EmptyProxy() {}
  2096. EmptyProxy.prototype.dispose = function () {};
  2097. var handlerNames = [
  2098. 'click', 'dblclick', 'mousewheel', 'mouseout',
  2099. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  2100. ];
  2101. /**
  2102. * @alias module:zrender/Handler
  2103. * @constructor
  2104. * @extends module:zrender/mixin/Eventful
  2105. * @param {module:zrender/Storage} storage Storage instance.
  2106. * @param {module:zrender/Painter} painter Painter instance.
  2107. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  2108. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  2109. */
  2110. var Handler = function (storage, painter, proxy, painterRoot) {
  2111. Eventful.call(this);
  2112. this.storage = storage;
  2113. this.painter = painter;
  2114. this.painterRoot = painterRoot;
  2115. proxy = proxy || new EmptyProxy();
  2116. /**
  2117. * Proxy of event. can be Dom, WebGLSurface, etc.
  2118. */
  2119. this.proxy = null;
  2120. /**
  2121. * {target, topTarget, x, y}
  2122. * @private
  2123. * @type {Object}
  2124. */
  2125. this._hovered = {};
  2126. /**
  2127. * @private
  2128. * @type {Date}
  2129. */
  2130. this._lastTouchMoment;
  2131. /**
  2132. * @private
  2133. * @type {number}
  2134. */
  2135. this._lastX;
  2136. /**
  2137. * @private
  2138. * @type {number}
  2139. */
  2140. this._lastY;
  2141. /**
  2142. * @private
  2143. * @type {module:zrender/core/GestureMgr}
  2144. */
  2145. this._gestureMgr;
  2146. Draggable.call(this);
  2147. this.setHandlerProxy(proxy);
  2148. };
  2149. Handler.prototype = {
  2150. constructor: Handler,
  2151. setHandlerProxy: function (proxy) {
  2152. if (this.proxy) {
  2153. this.proxy.dispose();
  2154. }
  2155. if (proxy) {
  2156. each$1(handlerNames, function (name) {
  2157. proxy.on && proxy.on(name, this[name], this);
  2158. }, this);
  2159. // Attach handler
  2160. proxy.handler = this;
  2161. }
  2162. this.proxy = proxy;
  2163. },
  2164. mousemove: function (event) {
  2165. var x = event.zrX;
  2166. var y = event.zrY;
  2167. var isOutside = isOutsideBoundary(this, x, y);
  2168. var lastHovered = this._hovered;
  2169. var lastHoveredTarget = lastHovered.target;
  2170. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2171. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2172. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2173. // See #6198.
  2174. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2175. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2176. lastHoveredTarget = lastHovered.target;
  2177. }
  2178. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  2179. var hoveredTarget = hovered.target;
  2180. var proxy = this.proxy;
  2181. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2182. // Mouse out on previous hovered element
  2183. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2184. this.dispatchToElement(lastHovered, 'mouseout', event);
  2185. }
  2186. // Mouse moving on one element
  2187. this.dispatchToElement(hovered, 'mousemove', event);
  2188. // Mouse over on a new element
  2189. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2190. this.dispatchToElement(hovered, 'mouseover', event);
  2191. }
  2192. },
  2193. mouseout: function (event) {
  2194. var eventControl = event.zrEventControl;
  2195. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2196. if (eventControl !== 'only_globalout') {
  2197. this.dispatchToElement(this._hovered, 'mouseout', event);
  2198. }
  2199. if (eventControl !== 'no_globalout') {
  2200. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2201. // the `globalout` should have been triggered. But currently not.
  2202. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2203. }
  2204. },
  2205. /**
  2206. * Resize
  2207. */
  2208. resize: function (event) {
  2209. this._hovered = {};
  2210. },
  2211. /**
  2212. * Dispatch event
  2213. * @param {string} eventName
  2214. * @param {event=} eventArgs
  2215. */
  2216. dispatch: function (eventName, eventArgs) {
  2217. var handler = this[eventName];
  2218. handler && handler.call(this, eventArgs);
  2219. },
  2220. /**
  2221. * Dispose
  2222. */
  2223. dispose: function () {
  2224. this.proxy.dispose();
  2225. this.storage =
  2226. this.proxy =
  2227. this.painter = null;
  2228. },
  2229. /**
  2230. * 设置默认的cursor style
  2231. * @param {string} [cursorStyle='default'] 例如 crosshair
  2232. */
  2233. setCursorStyle: function (cursorStyle) {
  2234. var proxy = this.proxy;
  2235. proxy.setCursor && proxy.setCursor(cursorStyle);
  2236. },
  2237. /**
  2238. * 事件分发代理
  2239. *
  2240. * @private
  2241. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2242. * @param {string} eventName 事件名称
  2243. * @param {Object} event 事件对象
  2244. */
  2245. dispatchToElement: function (targetInfo, eventName, event) {
  2246. targetInfo = targetInfo || {};
  2247. var el = targetInfo.target;
  2248. if (el && el.silent) {
  2249. return;
  2250. }
  2251. var eventHandler = 'on' + eventName;
  2252. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2253. while (el) {
  2254. el[eventHandler]
  2255. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2256. el.trigger(eventName, eventPacket);
  2257. el = el.parent;
  2258. if (eventPacket.cancelBubble) {
  2259. break;
  2260. }
  2261. }
  2262. if (!eventPacket.cancelBubble) {
  2263. // 冒泡到顶级 zrender 对象
  2264. this.trigger(eventName, eventPacket);
  2265. // 分发事件到用户自定义层
  2266. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2267. this.painter && this.painter.eachOtherLayer(function (layer) {
  2268. if (typeof (layer[eventHandler]) === 'function') {
  2269. layer[eventHandler].call(layer, eventPacket);
  2270. }
  2271. if (layer.trigger) {
  2272. layer.trigger(eventName, eventPacket);
  2273. }
  2274. });
  2275. }
  2276. },
  2277. /**
  2278. * @private
  2279. * @param {number} x
  2280. * @param {number} y
  2281. * @param {module:zrender/graphic/Displayable} exclude
  2282. * @return {model:zrender/Element}
  2283. * @method
  2284. */
  2285. findHover: function (x, y, exclude) {
  2286. var list = this.storage.getDisplayList();
  2287. var out = {x: x, y: y};
  2288. for (var i = list.length - 1; i >= 0; i--) {
  2289. var hoverCheckResult;
  2290. if (list[i] !== exclude
  2291. // getDisplayList may include ignored item in VML mode
  2292. && !list[i].ignore
  2293. && (hoverCheckResult = isHover(list[i], x, y))
  2294. ) {
  2295. !out.topTarget && (out.topTarget = list[i]);
  2296. if (hoverCheckResult !== SILENT) {
  2297. out.target = list[i];
  2298. break;
  2299. }
  2300. }
  2301. }
  2302. return out;
  2303. },
  2304. processGesture: function (event, stage) {
  2305. if (!this._gestureMgr) {
  2306. this._gestureMgr = new GestureMgr();
  2307. }
  2308. var gestureMgr = this._gestureMgr;
  2309. stage === 'start' && gestureMgr.clear();
  2310. var gestureInfo = gestureMgr.recognize(
  2311. event,
  2312. this.findHover(event.zrX, event.zrY, null).target,
  2313. this.proxy.dom
  2314. );
  2315. stage === 'end' && gestureMgr.clear();
  2316. // Do not do any preventDefault here. Upper application do that if necessary.
  2317. if (gestureInfo) {
  2318. var type = gestureInfo.type;
  2319. event.gestureEvent = type;
  2320. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2321. }
  2322. }
  2323. };
  2324. // Common handlers
  2325. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2326. Handler.prototype[name] = function (event) {
  2327. var x = event.zrX;
  2328. var y = event.zrY;
  2329. var isOutside = isOutsideBoundary(this, x, y);
  2330. var hovered;
  2331. var hoveredTarget;
  2332. if (name !== 'mouseup' || !isOutside) {
  2333. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2334. hovered = this.findHover(x, y);
  2335. hoveredTarget = hovered.target;
  2336. }
  2337. if (name === 'mousedown') {
  2338. this._downEl = hoveredTarget;
  2339. this._downPoint = [event.zrX, event.zrY];
  2340. // In case click triggered before mouseup
  2341. this._upEl = hoveredTarget;
  2342. }
  2343. else if (name === 'mouseup') {
  2344. this._upEl = hoveredTarget;
  2345. }
  2346. else if (name === 'click') {
  2347. if (this._downEl !== this._upEl
  2348. // Original click event is triggered on the whole canvas element,
  2349. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2350. // which should be filtered, otherwise it will bring trouble to
  2351. // pan and zoom.
  2352. || !this._downPoint
  2353. // Arbitrary value
  2354. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2355. ) {
  2356. return;
  2357. }
  2358. this._downPoint = null;
  2359. }
  2360. this.dispatchToElement(hovered, name, event);
  2361. };
  2362. });
  2363. function isHover(displayable, x, y) {
  2364. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2365. var el = displayable;
  2366. var isSilent;
  2367. while (el) {
  2368. // If clipped by ancestor.
  2369. // FIXME: If clipPath has neither stroke nor fill,
  2370. // el.clipPath.contain(x, y) will always return false.
  2371. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2372. return false;
  2373. }
  2374. if (el.silent) {
  2375. isSilent = true;
  2376. }
  2377. el = el.parent;
  2378. }
  2379. return isSilent ? SILENT : true;
  2380. }
  2381. return false;
  2382. }
  2383. /**
  2384. * See [Drag outside].
  2385. */
  2386. function isOutsideBoundary(handlerInstance, x, y) {
  2387. var painter = handlerInstance.painter;
  2388. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2389. }
  2390. mixin(Handler, Eventful);
  2391. mixin(Handler, Draggable);
  2392. /**
  2393. * 3x2矩阵操作类
  2394. * @exports zrender/tool/matrix
  2395. */
  2396. /* global Float32Array */
  2397. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2398. ? Array
  2399. : Float32Array;
  2400. /**
  2401. * Create a identity matrix.
  2402. * @return {Float32Array|Array.<number>}
  2403. */
  2404. function create$1() {
  2405. var out = new ArrayCtor$1(6);
  2406. identity(out);
  2407. return out;
  2408. }
  2409. /**
  2410. * 设置矩阵为单位矩阵
  2411. * @param {Float32Array|Array.<number>} out
  2412. */
  2413. function identity(out) {
  2414. out[0] = 1;
  2415. out[1] = 0;
  2416. out[2] = 0;
  2417. out[3] = 1;
  2418. out[4] = 0;
  2419. out[5] = 0;
  2420. return out;
  2421. }
  2422. /**
  2423. * 复制矩阵
  2424. * @param {Float32Array|Array.<number>} out
  2425. * @param {Float32Array|Array.<number>} m
  2426. */
  2427. function copy$1(out, m) {
  2428. out[0] = m[0];
  2429. out[1] = m[1];
  2430. out[2] = m[2];
  2431. out[3] = m[3];
  2432. out[4] = m[4];
  2433. out[5] = m[5];
  2434. return out;
  2435. }
  2436. /**
  2437. * 矩阵相乘
  2438. * @param {Float32Array|Array.<number>} out
  2439. * @param {Float32Array|Array.<number>} m1
  2440. * @param {Float32Array|Array.<number>} m2
  2441. */
  2442. function mul$1(out, m1, m2) {
  2443. // Consider matrix.mul(m, m2, m);
  2444. // where out is the same as m2.
  2445. // So use temp variable to escape error.
  2446. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2447. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2448. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2449. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2450. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2451. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2452. out[0] = out0;
  2453. out[1] = out1;
  2454. out[2] = out2;
  2455. out[3] = out3;
  2456. out[4] = out4;
  2457. out[5] = out5;
  2458. return out;
  2459. }
  2460. /**
  2461. * 平移变换
  2462. * @param {Float32Array|Array.<number>} out
  2463. * @param {Float32Array|Array.<number>} a
  2464. * @param {Float32Array|Array.<number>} v
  2465. */
  2466. function translate(out, a, v) {
  2467. out[0] = a[0];
  2468. out[1] = a[1];
  2469. out[2] = a[2];
  2470. out[3] = a[3];
  2471. out[4] = a[4] + v[0];
  2472. out[5] = a[5] + v[1];
  2473. return out;
  2474. }
  2475. /**
  2476. * 旋转变换
  2477. * @param {Float32Array|Array.<number>} out
  2478. * @param {Float32Array|Array.<number>} a
  2479. * @param {number} rad
  2480. */
  2481. function rotate(out, a, rad) {
  2482. var aa = a[0];
  2483. var ac = a[2];
  2484. var atx = a[4];
  2485. var ab = a[1];
  2486. var ad = a[3];
  2487. var aty = a[5];
  2488. var st = Math.sin(rad);
  2489. var ct = Math.cos(rad);
  2490. out[0] = aa * ct + ab * st;
  2491. out[1] = -aa * st + ab * ct;
  2492. out[2] = ac * ct + ad * st;
  2493. out[3] = -ac * st + ct * ad;
  2494. out[4] = ct * atx + st * aty;
  2495. out[5] = ct * aty - st * atx;
  2496. return out;
  2497. }
  2498. /**
  2499. * 缩放变换
  2500. * @param {Float32Array|Array.<number>} out
  2501. * @param {Float32Array|Array.<number>} a
  2502. * @param {Float32Array|Array.<number>} v
  2503. */
  2504. function scale$1(out, a, v) {
  2505. var vx = v[0];
  2506. var vy = v[1];
  2507. out[0] = a[0] * vx;
  2508. out[1] = a[1] * vy;
  2509. out[2] = a[2] * vx;
  2510. out[3] = a[3] * vy;
  2511. out[4] = a[4] * vx;
  2512. out[5] = a[5] * vy;
  2513. return out;
  2514. }
  2515. /**
  2516. * 求逆矩阵
  2517. * @param {Float32Array|Array.<number>} out
  2518. * @param {Float32Array|Array.<number>} a
  2519. */
  2520. function invert(out, a) {
  2521. var aa = a[0];
  2522. var ac = a[2];
  2523. var atx = a[4];
  2524. var ab = a[1];
  2525. var ad = a[3];
  2526. var aty = a[5];
  2527. var det = aa * ad - ab * ac;
  2528. if (!det) {
  2529. return null;
  2530. }
  2531. det = 1.0 / det;
  2532. out[0] = ad * det;
  2533. out[1] = -ab * det;
  2534. out[2] = -ac * det;
  2535. out[3] = aa * det;
  2536. out[4] = (ac * aty - ad * atx) * det;
  2537. out[5] = (ab * atx - aa * aty) * det;
  2538. return out;
  2539. }
  2540. /**
  2541. * Clone a new matrix.
  2542. * @param {Float32Array|Array.<number>} a
  2543. */
  2544. function clone$2(a) {
  2545. var b = create$1();
  2546. copy$1(b, a);
  2547. return b;
  2548. }
  2549. var matrix = (Object.freeze || Object)({
  2550. create: create$1,
  2551. identity: identity,
  2552. copy: copy$1,
  2553. mul: mul$1,
  2554. translate: translate,
  2555. rotate: rotate,
  2556. scale: scale$1,
  2557. invert: invert,
  2558. clone: clone$2
  2559. });
  2560. /**
  2561. * 提供变换扩展
  2562. * @module zrender/mixin/Transformable
  2563. * @author pissang (https://www.github.com/pissang)
  2564. */
  2565. var mIdentity = identity;
  2566. var EPSILON = 5e-5;
  2567. function isNotAroundZero(val) {
  2568. return val > EPSILON || val < -EPSILON;
  2569. }
  2570. /**
  2571. * @alias module:zrender/mixin/Transformable
  2572. * @constructor
  2573. */
  2574. var Transformable = function (opts) {
  2575. opts = opts || {};
  2576. // If there are no given position, rotation, scale
  2577. if (!opts.position) {
  2578. /**
  2579. * 平移
  2580. * @type {Array.<number>}
  2581. * @default [0, 0]
  2582. */
  2583. this.position = [0, 0];
  2584. }
  2585. if (opts.rotation == null) {
  2586. /**
  2587. * 旋转
  2588. * @type {Array.<number>}
  2589. * @default 0
  2590. */
  2591. this.rotation = 0;
  2592. }
  2593. if (!opts.scale) {
  2594. /**
  2595. * 缩放
  2596. * @type {Array.<number>}
  2597. * @default [1, 1]
  2598. */
  2599. this.scale = [1, 1];
  2600. }
  2601. /**
  2602. * 旋转和缩放的原点
  2603. * @type {Array.<number>}
  2604. * @default null
  2605. */
  2606. this.origin = this.origin || null;
  2607. };
  2608. var transformableProto = Transformable.prototype;
  2609. transformableProto.transform = null;
  2610. /**
  2611. * 判断是否需要有坐标变换
  2612. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2613. */
  2614. transformableProto.needLocalTransform = function () {
  2615. return isNotAroundZero(this.rotation)
  2616. || isNotAroundZero(this.position[0])
  2617. || isNotAroundZero(this.position[1])
  2618. || isNotAroundZero(this.scale[0] - 1)
  2619. || isNotAroundZero(this.scale[1] - 1);
  2620. };
  2621. var scaleTmp = [];
  2622. transformableProto.updateTransform = function () {
  2623. var parent = this.parent;
  2624. var parentHasTransform = parent && parent.transform;
  2625. var needLocalTransform = this.needLocalTransform();
  2626. var m = this.transform;
  2627. if (!(needLocalTransform || parentHasTransform)) {
  2628. m && mIdentity(m);
  2629. return;
  2630. }
  2631. m = m || create$1();
  2632. if (needLocalTransform) {
  2633. this.getLocalTransform(m);
  2634. }
  2635. else {
  2636. mIdentity(m);
  2637. }
  2638. // 应用父节点变换
  2639. if (parentHasTransform) {
  2640. if (needLocalTransform) {
  2641. mul$1(m, parent.transform, m);
  2642. }
  2643. else {
  2644. copy$1(m, parent.transform);
  2645. }
  2646. }
  2647. // 保存这个变换矩阵
  2648. this.transform = m;
  2649. var globalScaleRatio = this.globalScaleRatio;
  2650. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2651. this.getGlobalScale(scaleTmp);
  2652. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2653. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2654. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2655. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2656. m[0] *= sx;
  2657. m[1] *= sx;
  2658. m[2] *= sy;
  2659. m[3] *= sy;
  2660. }
  2661. this.invTransform = this.invTransform || create$1();
  2662. invert(this.invTransform, m);
  2663. };
  2664. transformableProto.getLocalTransform = function (m) {
  2665. return Transformable.getLocalTransform(this, m);
  2666. };
  2667. /**
  2668. * 将自己的transform应用到context上
  2669. * @param {CanvasRenderingContext2D} ctx
  2670. */
  2671. transformableProto.setTransform = function (ctx) {
  2672. var m = this.transform;
  2673. var dpr = ctx.dpr || 1;
  2674. if (m) {
  2675. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2676. }
  2677. else {
  2678. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2679. }
  2680. };
  2681. transformableProto.restoreTransform = function (ctx) {
  2682. var dpr = ctx.dpr || 1;
  2683. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2684. };
  2685. var tmpTransform = [];
  2686. var originTransform = create$1();
  2687. transformableProto.setLocalTransform = function (m) {
  2688. if (!m) {
  2689. // TODO return or set identity?
  2690. return;
  2691. }
  2692. var sx = m[0] * m[0] + m[1] * m[1];
  2693. var sy = m[2] * m[2] + m[3] * m[3];
  2694. var position = this.position;
  2695. var scale$$1 = this.scale;
  2696. if (isNotAroundZero(sx - 1)) {
  2697. sx = Math.sqrt(sx);
  2698. }
  2699. if (isNotAroundZero(sy - 1)) {
  2700. sy = Math.sqrt(sy);
  2701. }
  2702. if (m[0] < 0) {
  2703. sx = -sx;
  2704. }
  2705. if (m[3] < 0) {
  2706. sy = -sy;
  2707. }
  2708. position[0] = m[4];
  2709. position[1] = m[5];
  2710. scale$$1[0] = sx;
  2711. scale$$1[1] = sy;
  2712. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2713. };
  2714. /**
  2715. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2716. */
  2717. transformableProto.decomposeTransform = function () {
  2718. if (!this.transform) {
  2719. return;
  2720. }
  2721. var parent = this.parent;
  2722. var m = this.transform;
  2723. if (parent && parent.transform) {
  2724. // Get local transform and decompose them to position, scale, rotation
  2725. mul$1(tmpTransform, parent.invTransform, m);
  2726. m = tmpTransform;
  2727. }
  2728. var origin = this.origin;
  2729. if (origin && (origin[0] || origin[1])) {
  2730. originTransform[4] = origin[0];
  2731. originTransform[5] = origin[1];
  2732. mul$1(tmpTransform, m, originTransform);
  2733. tmpTransform[4] -= origin[0];
  2734. tmpTransform[5] -= origin[1];
  2735. m = tmpTransform;
  2736. }
  2737. this.setLocalTransform(m);
  2738. };
  2739. /**
  2740. * Get global scale
  2741. * @return {Array.<number>}
  2742. */
  2743. transformableProto.getGlobalScale = function (out) {
  2744. var m = this.transform;
  2745. out = out || [];
  2746. if (!m) {
  2747. out[0] = 1;
  2748. out[1] = 1;
  2749. return out;
  2750. }
  2751. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2752. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2753. if (m[0] < 0) {
  2754. out[0] = -out[0];
  2755. }
  2756. if (m[3] < 0) {
  2757. out[1] = -out[1];
  2758. }
  2759. return out;
  2760. };
  2761. /**
  2762. * 变换坐标位置到 shape 的局部坐标空间
  2763. * @method
  2764. * @param {number} x
  2765. * @param {number} y
  2766. * @return {Array.<number>}
  2767. */
  2768. transformableProto.transformCoordToLocal = function (x, y) {
  2769. var v2 = [x, y];
  2770. var invTransform = this.invTransform;
  2771. if (invTransform) {
  2772. applyTransform(v2, v2, invTransform);
  2773. }
  2774. return v2;
  2775. };
  2776. /**
  2777. * 变换局部坐标位置到全局坐标空间
  2778. * @method
  2779. * @param {number} x
  2780. * @param {number} y
  2781. * @return {Array.<number>}
  2782. */
  2783. transformableProto.transformCoordToGlobal = function (x, y) {
  2784. var v2 = [x, y];
  2785. var transform = this.transform;
  2786. if (transform) {
  2787. applyTransform(v2, v2, transform);
  2788. }
  2789. return v2;
  2790. };
  2791. /**
  2792. * @static
  2793. * @param {Object} target
  2794. * @param {Array.<number>} target.origin
  2795. * @param {number} target.rotation
  2796. * @param {Array.<number>} target.position
  2797. * @param {Array.<number>} [m]
  2798. */
  2799. Transformable.getLocalTransform = function (target, m) {
  2800. m = m || [];
  2801. mIdentity(m);
  2802. var origin = target.origin;
  2803. var scale$$1 = target.scale || [1, 1];
  2804. var rotation = target.rotation || 0;
  2805. var position = target.position || [0, 0];
  2806. if (origin) {
  2807. // Translate to origin
  2808. m[4] -= origin[0];
  2809. m[5] -= origin[1];
  2810. }
  2811. scale$1(m, m, scale$$1);
  2812. if (rotation) {
  2813. rotate(m, m, rotation);
  2814. }
  2815. if (origin) {
  2816. // Translate back from origin
  2817. m[4] += origin[0];
  2818. m[5] += origin[1];
  2819. }
  2820. m[4] += position[0];
  2821. m[5] += position[1];
  2822. return m;
  2823. };
  2824. /**
  2825. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2826. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2827. * @exports zrender/animation/easing
  2828. */
  2829. var easing = {
  2830. /**
  2831. * @param {number} k
  2832. * @return {number}
  2833. */
  2834. linear: function (k) {
  2835. return k;
  2836. },
  2837. /**
  2838. * @param {number} k
  2839. * @return {number}
  2840. */
  2841. quadraticIn: function (k) {
  2842. return k * k;
  2843. },
  2844. /**
  2845. * @param {number} k
  2846. * @return {number}
  2847. */
  2848. quadraticOut: function (k) {
  2849. return k * (2 - k);
  2850. },
  2851. /**
  2852. * @param {number} k
  2853. * @return {number}
  2854. */
  2855. quadraticInOut: function (k) {
  2856. if ((k *= 2) < 1) {
  2857. return 0.5 * k * k;
  2858. }
  2859. return -0.5 * (--k * (k - 2) - 1);
  2860. },
  2861. // 三次方的缓动(t^3)
  2862. /**
  2863. * @param {number} k
  2864. * @return {number}
  2865. */
  2866. cubicIn: function (k) {
  2867. return k * k * k;
  2868. },
  2869. /**
  2870. * @param {number} k
  2871. * @return {number}
  2872. */
  2873. cubicOut: function (k) {
  2874. return --k * k * k + 1;
  2875. },
  2876. /**
  2877. * @param {number} k
  2878. * @return {number}
  2879. */
  2880. cubicInOut: function (k) {
  2881. if ((k *= 2) < 1) {
  2882. return 0.5 * k * k * k;
  2883. }
  2884. return 0.5 * ((k -= 2) * k * k + 2);
  2885. },
  2886. // 四次方的缓动(t^4)
  2887. /**
  2888. * @param {number} k
  2889. * @return {number}
  2890. */
  2891. quarticIn: function (k) {
  2892. return k * k * k * k;
  2893. },
  2894. /**
  2895. * @param {number} k
  2896. * @return {number}
  2897. */
  2898. quarticOut: function (k) {
  2899. return 1 - (--k * k * k * k);
  2900. },
  2901. /**
  2902. * @param {number} k
  2903. * @return {number}
  2904. */
  2905. quarticInOut: function (k) {
  2906. if ((k *= 2) < 1) {
  2907. return 0.5 * k * k * k * k;
  2908. }
  2909. return -0.5 * ((k -= 2) * k * k * k - 2);
  2910. },
  2911. // 五次方的缓动(t^5)
  2912. /**
  2913. * @param {number} k
  2914. * @return {number}
  2915. */
  2916. quinticIn: function (k) {
  2917. return k * k * k * k * k;
  2918. },
  2919. /**
  2920. * @param {number} k
  2921. * @return {number}
  2922. */
  2923. quinticOut: function (k) {
  2924. return --k * k * k * k * k + 1;
  2925. },
  2926. /**
  2927. * @param {number} k
  2928. * @return {number}
  2929. */
  2930. quinticInOut: function (k) {
  2931. if ((k *= 2) < 1) {
  2932. return 0.5 * k * k * k * k * k;
  2933. }
  2934. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2935. },
  2936. // 正弦曲线的缓动(sin(t))
  2937. /**
  2938. * @param {number} k
  2939. * @return {number}
  2940. */
  2941. sinusoidalIn: function (k) {
  2942. return 1 - Math.cos(k * Math.PI / 2);
  2943. },
  2944. /**
  2945. * @param {number} k
  2946. * @return {number}
  2947. */
  2948. sinusoidalOut: function (k) {
  2949. return Math.sin(k * Math.PI / 2);
  2950. },
  2951. /**
  2952. * @param {number} k
  2953. * @return {number}
  2954. */
  2955. sinusoidalInOut: function (k) {
  2956. return 0.5 * (1 - Math.cos(Math.PI * k));
  2957. },
  2958. // 指数曲线的缓动(2^t)
  2959. /**
  2960. * @param {number} k
  2961. * @return {number}
  2962. */
  2963. exponentialIn: function (k) {
  2964. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2965. },
  2966. /**
  2967. * @param {number} k
  2968. * @return {number}
  2969. */
  2970. exponentialOut: function (k) {
  2971. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2972. },
  2973. /**
  2974. * @param {number} k
  2975. * @return {number}
  2976. */
  2977. exponentialInOut: function (k) {
  2978. if (k === 0) {
  2979. return 0;
  2980. }
  2981. if (k === 1) {
  2982. return 1;
  2983. }
  2984. if ((k *= 2) < 1) {
  2985. return 0.5 * Math.pow(1024, k - 1);
  2986. }
  2987. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2988. },
  2989. // 圆形曲线的缓动(sqrt(1-t^2))
  2990. /**
  2991. * @param {number} k
  2992. * @return {number}
  2993. */
  2994. circularIn: function (k) {
  2995. return 1 - Math.sqrt(1 - k * k);
  2996. },
  2997. /**
  2998. * @param {number} k
  2999. * @return {number}
  3000. */
  3001. circularOut: function (k) {
  3002. return Math.sqrt(1 - (--k * k));
  3003. },
  3004. /**
  3005. * @param {number} k
  3006. * @return {number}
  3007. */
  3008. circularInOut: function (k) {
  3009. if ((k *= 2) < 1) {
  3010. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  3011. }
  3012. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3013. },
  3014. // 创建类似于弹簧在停止前来回振荡的动画
  3015. /**
  3016. * @param {number} k
  3017. * @return {number}
  3018. */
  3019. elasticIn: function (k) {
  3020. var s;
  3021. var a = 0.1;
  3022. var p = 0.4;
  3023. if (k === 0) {
  3024. return 0;
  3025. }
  3026. if (k === 1) {
  3027. return 1;
  3028. }
  3029. if (!a || a < 1) {
  3030. a = 1;
  3031. s = p / 4;
  3032. }
  3033. else {
  3034. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3035. }
  3036. return -(a * Math.pow(2, 10 * (k -= 1))
  3037. * Math.sin((k - s) * (2 * Math.PI) / p));
  3038. },
  3039. /**
  3040. * @param {number} k
  3041. * @return {number}
  3042. */
  3043. elasticOut: function (k) {
  3044. var s;
  3045. var a = 0.1;
  3046. var p = 0.4;
  3047. if (k === 0) {
  3048. return 0;
  3049. }
  3050. if (k === 1) {
  3051. return 1;
  3052. }
  3053. if (!a || a < 1) {
  3054. a = 1;
  3055. s = p / 4;
  3056. }
  3057. else {
  3058. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3059. }
  3060. return (a * Math.pow(2, -10 * k)
  3061. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3062. },
  3063. /**
  3064. * @param {number} k
  3065. * @return {number}
  3066. */
  3067. elasticInOut: function (k) {
  3068. var s;
  3069. var a = 0.1;
  3070. var p = 0.4;
  3071. if (k === 0) {
  3072. return 0;
  3073. }
  3074. if (k === 1) {
  3075. return 1;
  3076. }
  3077. if (!a || a < 1) {
  3078. a = 1;
  3079. s = p / 4;
  3080. }
  3081. else {
  3082. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3083. }
  3084. if ((k *= 2) < 1) {
  3085. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3086. * Math.sin((k - s) * (2 * Math.PI) / p));
  3087. }
  3088. return a * Math.pow(2, -10 * (k -= 1))
  3089. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3090. },
  3091. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  3092. /**
  3093. * @param {number} k
  3094. * @return {number}
  3095. */
  3096. backIn: function (k) {
  3097. var s = 1.70158;
  3098. return k * k * ((s + 1) * k - s);
  3099. },
  3100. /**
  3101. * @param {number} k
  3102. * @return {number}
  3103. */
  3104. backOut: function (k) {
  3105. var s = 1.70158;
  3106. return --k * k * ((s + 1) * k + s) + 1;
  3107. },
  3108. /**
  3109. * @param {number} k
  3110. * @return {number}
  3111. */
  3112. backInOut: function (k) {
  3113. var s = 1.70158 * 1.525;
  3114. if ((k *= 2) < 1) {
  3115. return 0.5 * (k * k * ((s + 1) * k - s));
  3116. }
  3117. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3118. },
  3119. // 创建弹跳效果
  3120. /**
  3121. * @param {number} k
  3122. * @return {number}
  3123. */
  3124. bounceIn: function (k) {
  3125. return 1 - easing.bounceOut(1 - k);
  3126. },
  3127. /**
  3128. * @param {number} k
  3129. * @return {number}
  3130. */
  3131. bounceOut: function (k) {
  3132. if (k < (1 / 2.75)) {
  3133. return 7.5625 * k * k;
  3134. }
  3135. else if (k < (2 / 2.75)) {
  3136. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3137. }
  3138. else if (k < (2.5 / 2.75)) {
  3139. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3140. }
  3141. else {
  3142. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3143. }
  3144. },
  3145. /**
  3146. * @param {number} k
  3147. * @return {number}
  3148. */
  3149. bounceInOut: function (k) {
  3150. if (k < 0.5) {
  3151. return easing.bounceIn(k * 2) * 0.5;
  3152. }
  3153. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3154. }
  3155. };
  3156. /**
  3157. * 动画主控制器
  3158. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  3159. * @config life(1000) 动画时长
  3160. * @config delay(0) 动画延迟时间
  3161. * @config loop(true)
  3162. * @config gap(0) 循环的间隔时间
  3163. * @config onframe
  3164. * @config easing(optional)
  3165. * @config ondestroy(optional)
  3166. * @config onrestart(optional)
  3167. *
  3168. * TODO pause
  3169. */
  3170. function Clip(options) {
  3171. this._target = options.target;
  3172. // 生命周期
  3173. this._life = options.life || 1000;
  3174. // 延时
  3175. this._delay = options.delay || 0;
  3176. // 开始时间
  3177. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  3178. this._initialized = false;
  3179. // 是否循环
  3180. this.loop = options.loop == null ? false : options.loop;
  3181. this.gap = options.gap || 0;
  3182. this.easing = options.easing || 'Linear';
  3183. this.onframe = options.onframe;
  3184. this.ondestroy = options.ondestroy;
  3185. this.onrestart = options.onrestart;
  3186. this._pausedTime = 0;
  3187. this._paused = false;
  3188. }
  3189. Clip.prototype = {
  3190. constructor: Clip,
  3191. step: function (globalTime, deltaTime) {
  3192. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3193. // PENDING
  3194. if (!this._initialized) {
  3195. this._startTime = globalTime + this._delay;
  3196. this._initialized = true;
  3197. }
  3198. if (this._paused) {
  3199. this._pausedTime += deltaTime;
  3200. return;
  3201. }
  3202. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  3203. // 还没开始
  3204. if (percent < 0) {
  3205. return;
  3206. }
  3207. percent = Math.min(percent, 1);
  3208. var easing$$1 = this.easing;
  3209. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3210. var schedule = typeof easingFunc === 'function'
  3211. ? easingFunc(percent)
  3212. : percent;
  3213. this.fire('frame', schedule);
  3214. // 结束
  3215. if (percent === 1) {
  3216. if (this.loop) {
  3217. this.restart(globalTime);
  3218. // 重新开始周期
  3219. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3220. return 'restart';
  3221. }
  3222. // 动画完成将这个控制器标识为待删除
  3223. // 在Animation.update中进行批量删除
  3224. this._needsRemove = true;
  3225. return 'destroy';
  3226. }
  3227. return null;
  3228. },
  3229. restart: function (globalTime) {
  3230. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3231. this._startTime = globalTime - remainder + this.gap;
  3232. this._pausedTime = 0;
  3233. this._needsRemove = false;
  3234. },
  3235. fire: function (eventType, arg) {
  3236. eventType = 'on' + eventType;
  3237. if (this[eventType]) {
  3238. this[eventType](this._target, arg);
  3239. }
  3240. },
  3241. pause: function () {
  3242. this._paused = true;
  3243. },
  3244. resume: function () {
  3245. this._paused = false;
  3246. }
  3247. };
  3248. // Simple LRU cache use doubly linked list
  3249. // @module zrender/core/LRU
  3250. /**
  3251. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3252. * @constructor
  3253. */
  3254. var LinkedList = function () {
  3255. /**
  3256. * @type {module:zrender/core/LRU~Entry}
  3257. */
  3258. this.head = null;
  3259. /**
  3260. * @type {module:zrender/core/LRU~Entry}
  3261. */
  3262. this.tail = null;
  3263. this._len = 0;
  3264. };
  3265. var linkedListProto = LinkedList.prototype;
  3266. /**
  3267. * Insert a new value at the tail
  3268. * @param {} val
  3269. * @return {module:zrender/core/LRU~Entry}
  3270. */
  3271. linkedListProto.insert = function (val) {
  3272. var entry = new Entry(val);
  3273. this.insertEntry(entry);
  3274. return entry;
  3275. };
  3276. /**
  3277. * Insert an entry at the tail
  3278. * @param {module:zrender/core/LRU~Entry} entry
  3279. */
  3280. linkedListProto.insertEntry = function (entry) {
  3281. if (!this.head) {
  3282. this.head = this.tail = entry;
  3283. }
  3284. else {
  3285. this.tail.next = entry;
  3286. entry.prev = this.tail;
  3287. entry.next = null;
  3288. this.tail = entry;
  3289. }
  3290. this._len++;
  3291. };
  3292. /**
  3293. * Remove entry.
  3294. * @param {module:zrender/core/LRU~Entry} entry
  3295. */
  3296. linkedListProto.remove = function (entry) {
  3297. var prev = entry.prev;
  3298. var next = entry.next;
  3299. if (prev) {
  3300. prev.next = next;
  3301. }
  3302. else {
  3303. // Is head
  3304. this.head = next;
  3305. }
  3306. if (next) {
  3307. next.prev = prev;
  3308. }
  3309. else {
  3310. // Is tail
  3311. this.tail = prev;
  3312. }
  3313. entry.next = entry.prev = null;
  3314. this._len--;
  3315. };
  3316. /**
  3317. * @return {number}
  3318. */
  3319. linkedListProto.len = function () {
  3320. return this._len;
  3321. };
  3322. /**
  3323. * Clear list
  3324. */
  3325. linkedListProto.clear = function () {
  3326. this.head = this.tail = null;
  3327. this._len = 0;
  3328. };
  3329. /**
  3330. * @constructor
  3331. * @param {} val
  3332. */
  3333. var Entry = function (val) {
  3334. /**
  3335. * @type {}
  3336. */
  3337. this.value = val;
  3338. /**
  3339. * @type {module:zrender/core/LRU~Entry}
  3340. */
  3341. this.next;
  3342. /**
  3343. * @type {module:zrender/core/LRU~Entry}
  3344. */
  3345. this.prev;
  3346. };
  3347. /**
  3348. * LRU Cache
  3349. * @constructor
  3350. * @alias module:zrender/core/LRU
  3351. */
  3352. var LRU = function (maxSize) {
  3353. this._list = new LinkedList();
  3354. this._map = {};
  3355. this._maxSize = maxSize || 10;
  3356. this._lastRemovedEntry = null;
  3357. };
  3358. var LRUProto = LRU.prototype;
  3359. /**
  3360. * @param {string} key
  3361. * @param {} value
  3362. * @return {} Removed value
  3363. */
  3364. LRUProto.put = function (key, value) {
  3365. var list = this._list;
  3366. var map = this._map;
  3367. var removed = null;
  3368. if (map[key] == null) {
  3369. var len = list.len();
  3370. // Reuse last removed entry
  3371. var entry = this._lastRemovedEntry;
  3372. if (len >= this._maxSize && len > 0) {
  3373. // Remove the least recently used
  3374. var leastUsedEntry = list.head;
  3375. list.remove(leastUsedEntry);
  3376. delete map[leastUsedEntry.key];
  3377. removed = leastUsedEntry.value;
  3378. this._lastRemovedEntry = leastUsedEntry;
  3379. }
  3380. if (entry) {
  3381. entry.value = value;
  3382. }
  3383. else {
  3384. entry = new Entry(value);
  3385. }
  3386. entry.key = key;
  3387. list.insertEntry(entry);
  3388. map[key] = entry;
  3389. }
  3390. return removed;
  3391. };
  3392. /**
  3393. * @param {string} key
  3394. * @return {}
  3395. */
  3396. LRUProto.get = function (key) {
  3397. var entry = this._map[key];
  3398. var list = this._list;
  3399. if (entry != null) {
  3400. // Put the latest used entry in the tail
  3401. if (entry !== list.tail) {
  3402. list.remove(entry);
  3403. list.insertEntry(entry);
  3404. }
  3405. return entry.value;
  3406. }
  3407. };
  3408. /**
  3409. * Clear the cache
  3410. */
  3411. LRUProto.clear = function () {
  3412. this._list.clear();
  3413. this._map = {};
  3414. };
  3415. var kCSSColorTable = {
  3416. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3417. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3418. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3419. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3420. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3421. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3422. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3423. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3424. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3425. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3426. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3427. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3428. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3429. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3430. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3431. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3432. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3433. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3434. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3435. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3436. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3437. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3438. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3439. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3440. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3441. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3442. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3443. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3444. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3445. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3446. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3447. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3448. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3449. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3450. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3451. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3452. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3453. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3454. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3455. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3456. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3457. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3458. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3459. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3460. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3461. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3462. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3463. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3464. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3465. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3466. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3467. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3468. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3469. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3470. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3471. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3472. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3473. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3474. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3475. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3476. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3477. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3478. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3479. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3480. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3481. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3482. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3483. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3484. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3485. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3486. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3487. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3488. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3489. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3490. };
  3491. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3492. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3493. return i < 0 ? 0 : i > 255 ? 255 : i;
  3494. }
  3495. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  3496. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3497. return i < 0 ? 0 : i > 360 ? 360 : i;
  3498. }
  3499. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3500. return f < 0 ? 0 : f > 1 ? 1 : f;
  3501. }
  3502. function parseCssInt(str) { // int or percentage.
  3503. if (str.length && str.charAt(str.length - 1) === '%') {
  3504. return clampCssByte(parseFloat(str) / 100 * 255);
  3505. }
  3506. return clampCssByte(parseInt(str, 10));
  3507. }
  3508. function parseCssFloat(str) { // float or percentage.
  3509. if (str.length && str.charAt(str.length - 1) === '%') {
  3510. return clampCssFloat(parseFloat(str) / 100);
  3511. }
  3512. return clampCssFloat(parseFloat(str));
  3513. }
  3514. function cssHueToRgb(m1, m2, h) {
  3515. if (h < 0) {
  3516. h += 1;
  3517. }
  3518. else if (h > 1) {
  3519. h -= 1;
  3520. }
  3521. if (h * 6 < 1) {
  3522. return m1 + (m2 - m1) * h * 6;
  3523. }
  3524. if (h * 2 < 1) {
  3525. return m2;
  3526. }
  3527. if (h * 3 < 2) {
  3528. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3529. }
  3530. return m1;
  3531. }
  3532. function lerpNumber(a, b, p) {
  3533. return a + (b - a) * p;
  3534. }
  3535. function setRgba(out, r, g, b, a) {
  3536. out[0] = r;
  3537. out[1] = g;
  3538. out[2] = b;
  3539. out[3] = a;
  3540. return out;
  3541. }
  3542. function copyRgba(out, a) {
  3543. out[0] = a[0];
  3544. out[1] = a[1];
  3545. out[2] = a[2];
  3546. out[3] = a[3];
  3547. return out;
  3548. }
  3549. var colorCache = new LRU(20);
  3550. var lastRemovedArr = null;
  3551. function putToCache(colorStr, rgbaArr) {
  3552. // Reuse removed array
  3553. if (lastRemovedArr) {
  3554. copyRgba(lastRemovedArr, rgbaArr);
  3555. }
  3556. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3557. }
  3558. /**
  3559. * @param {string} colorStr
  3560. * @param {Array.<number>} out
  3561. * @return {Array.<number>}
  3562. * @memberOf module:zrender/util/color
  3563. */
  3564. function parse(colorStr, rgbaArr) {
  3565. if (!colorStr) {
  3566. return;
  3567. }
  3568. rgbaArr = rgbaArr || [];
  3569. var cached = colorCache.get(colorStr);
  3570. if (cached) {
  3571. return copyRgba(rgbaArr, cached);
  3572. }
  3573. // colorStr may be not string
  3574. colorStr = colorStr + '';
  3575. // Remove all whitespace, not compliant, but should just be more accepting.
  3576. var str = colorStr.replace(/ /g, '').toLowerCase();
  3577. // Color keywords (and transparent) lookup.
  3578. if (str in kCSSColorTable) {
  3579. copyRgba(rgbaArr, kCSSColorTable[str]);
  3580. putToCache(colorStr, rgbaArr);
  3581. return rgbaArr;
  3582. }
  3583. // #abc and #abc123 syntax.
  3584. if (str.charAt(0) === '#') {
  3585. if (str.length === 4) {
  3586. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3587. if (!(iv >= 0 && iv <= 0xfff)) {
  3588. setRgba(rgbaArr, 0, 0, 0, 1);
  3589. return; // Covers NaN.
  3590. }
  3591. setRgba(rgbaArr,
  3592. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3593. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3594. (iv & 0xf) | ((iv & 0xf) << 4),
  3595. 1
  3596. );
  3597. putToCache(colorStr, rgbaArr);
  3598. return rgbaArr;
  3599. }
  3600. else if (str.length === 7) {
  3601. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3602. if (!(iv >= 0 && iv <= 0xffffff)) {
  3603. setRgba(rgbaArr, 0, 0, 0, 1);
  3604. return; // Covers NaN.
  3605. }
  3606. setRgba(rgbaArr,
  3607. (iv & 0xff0000) >> 16,
  3608. (iv & 0xff00) >> 8,
  3609. iv & 0xff,
  3610. 1
  3611. );
  3612. putToCache(colorStr, rgbaArr);
  3613. return rgbaArr;
  3614. }
  3615. return;
  3616. }
  3617. var op = str.indexOf('(');
  3618. var ep = str.indexOf(')');
  3619. if (op !== -1 && ep + 1 === str.length) {
  3620. var fname = str.substr(0, op);
  3621. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3622. var alpha = 1; // To allow case fallthrough.
  3623. switch (fname) {
  3624. case 'rgba':
  3625. if (params.length !== 4) {
  3626. setRgba(rgbaArr, 0, 0, 0, 1);
  3627. return;
  3628. }
  3629. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3630. // Fall through.
  3631. case 'rgb':
  3632. if (params.length !== 3) {
  3633. setRgba(rgbaArr, 0, 0, 0, 1);
  3634. return;
  3635. }
  3636. setRgba(rgbaArr,
  3637. parseCssInt(params[0]),
  3638. parseCssInt(params[1]),
  3639. parseCssInt(params[2]),
  3640. alpha
  3641. );
  3642. putToCache(colorStr, rgbaArr);
  3643. return rgbaArr;
  3644. case 'hsla':
  3645. if (params.length !== 4) {
  3646. setRgba(rgbaArr, 0, 0, 0, 1);
  3647. return;
  3648. }
  3649. params[3] = parseCssFloat(params[3]);
  3650. hsla2rgba(params, rgbaArr);
  3651. putToCache(colorStr, rgbaArr);
  3652. return rgbaArr;
  3653. case 'hsl':
  3654. if (params.length !== 3) {
  3655. setRgba(rgbaArr, 0, 0, 0, 1);
  3656. return;
  3657. }
  3658. hsla2rgba(params, rgbaArr);
  3659. putToCache(colorStr, rgbaArr);
  3660. return rgbaArr;
  3661. default:
  3662. return;
  3663. }
  3664. }
  3665. setRgba(rgbaArr, 0, 0, 0, 1);
  3666. return;
  3667. }
  3668. /**
  3669. * @param {Array.<number>} hsla
  3670. * @param {Array.<number>} rgba
  3671. * @return {Array.<number>} rgba
  3672. */
  3673. function hsla2rgba(hsla, rgba) {
  3674. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3675. // NOTE(deanm): According to the CSS spec s/l should only be
  3676. // percentages, but we don't bother and let float or percentage.
  3677. var s = parseCssFloat(hsla[1]);
  3678. var l = parseCssFloat(hsla[2]);
  3679. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3680. var m1 = l * 2 - m2;
  3681. rgba = rgba || [];
  3682. setRgba(rgba,
  3683. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3684. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3685. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3686. 1
  3687. );
  3688. if (hsla.length === 4) {
  3689. rgba[3] = hsla[3];
  3690. }
  3691. return rgba;
  3692. }
  3693. /**
  3694. * @param {Array.<number>} rgba
  3695. * @return {Array.<number>} hsla
  3696. */
  3697. function rgba2hsla(rgba) {
  3698. if (!rgba) {
  3699. return;
  3700. }
  3701. // RGB from 0 to 255
  3702. var R = rgba[0] / 255;
  3703. var G = rgba[1] / 255;
  3704. var B = rgba[2] / 255;
  3705. var vMin = Math.min(R, G, B); // Min. value of RGB
  3706. var vMax = Math.max(R, G, B); // Max. value of RGB
  3707. var delta = vMax - vMin; // Delta RGB value
  3708. var L = (vMax + vMin) / 2;
  3709. var H;
  3710. var S;
  3711. // HSL results from 0 to 1
  3712. if (delta === 0) {
  3713. H = 0;
  3714. S = 0;
  3715. }
  3716. else {
  3717. if (L < 0.5) {
  3718. S = delta / (vMax + vMin);
  3719. }
  3720. else {
  3721. S = delta / (2 - vMax - vMin);
  3722. }
  3723. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3724. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3725. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3726. if (R === vMax) {
  3727. H = deltaB - deltaG;
  3728. }
  3729. else if (G === vMax) {
  3730. H = (1 / 3) + deltaR - deltaB;
  3731. }
  3732. else if (B === vMax) {
  3733. H = (2 / 3) + deltaG - deltaR;
  3734. }
  3735. if (H < 0) {
  3736. H += 1;
  3737. }
  3738. if (H > 1) {
  3739. H -= 1;
  3740. }
  3741. }
  3742. var hsla = [H * 360, S, L];
  3743. if (rgba[3] != null) {
  3744. hsla.push(rgba[3]);
  3745. }
  3746. return hsla;
  3747. }
  3748. /**
  3749. * @param {string} color
  3750. * @param {number} level
  3751. * @return {string}
  3752. * @memberOf module:zrender/util/color
  3753. */
  3754. function lift(color, level) {
  3755. var colorArr = parse(color);
  3756. if (colorArr) {
  3757. for (var i = 0; i < 3; i++) {
  3758. if (level < 0) {
  3759. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3760. }
  3761. else {
  3762. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3763. }
  3764. if (colorArr[i] > 255) {
  3765. colorArr[i] = 255;
  3766. }
  3767. else if (color[i] < 0) {
  3768. colorArr[i] = 0;
  3769. }
  3770. }
  3771. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3772. }
  3773. }
  3774. /**
  3775. * @param {string} color
  3776. * @return {string}
  3777. * @memberOf module:zrender/util/color
  3778. */
  3779. function toHex(color) {
  3780. var colorArr = parse(color);
  3781. if (colorArr) {
  3782. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3783. }
  3784. }
  3785. /**
  3786. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3787. * @param {number} normalizedValue A float between 0 and 1.
  3788. * @param {Array.<Array.<number>>} colors List of rgba color array
  3789. * @param {Array.<number>} [out] Mapped gba color array
  3790. * @return {Array.<number>} will be null/undefined if input illegal.
  3791. */
  3792. function fastLerp(normalizedValue, colors, out) {
  3793. if (!(colors && colors.length)
  3794. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3795. ) {
  3796. return;
  3797. }
  3798. out = out || [];
  3799. var value = normalizedValue * (colors.length - 1);
  3800. var leftIndex = Math.floor(value);
  3801. var rightIndex = Math.ceil(value);
  3802. var leftColor = colors[leftIndex];
  3803. var rightColor = colors[rightIndex];
  3804. var dv = value - leftIndex;
  3805. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3806. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3807. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3808. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3809. return out;
  3810. }
  3811. /**
  3812. * @deprecated
  3813. */
  3814. var fastMapToColor = fastLerp;
  3815. /**
  3816. * @param {number} normalizedValue A float between 0 and 1.
  3817. * @param {Array.<string>} colors Color list.
  3818. * @param {boolean=} fullOutput Default false.
  3819. * @return {(string|Object)} Result color. If fullOutput,
  3820. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3821. * @memberOf module:zrender/util/color
  3822. */
  3823. function lerp$1(normalizedValue, colors, fullOutput) {
  3824. if (!(colors && colors.length)
  3825. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3826. ) {
  3827. return;
  3828. }
  3829. var value = normalizedValue * (colors.length - 1);
  3830. var leftIndex = Math.floor(value);
  3831. var rightIndex = Math.ceil(value);
  3832. var leftColor = parse(colors[leftIndex]);
  3833. var rightColor = parse(colors[rightIndex]);
  3834. var dv = value - leftIndex;
  3835. var color = stringify(
  3836. [
  3837. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3838. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3839. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3840. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3841. ],
  3842. 'rgba'
  3843. );
  3844. return fullOutput
  3845. ? {
  3846. color: color,
  3847. leftIndex: leftIndex,
  3848. rightIndex: rightIndex,
  3849. value: value
  3850. }
  3851. : color;
  3852. }
  3853. /**
  3854. * @deprecated
  3855. */
  3856. var mapToColor = lerp$1;
  3857. /**
  3858. * @param {string} color
  3859. * @param {number=} h 0 ~ 360, ignore when null.
  3860. * @param {number=} s 0 ~ 1, ignore when null.
  3861. * @param {number=} l 0 ~ 1, ignore when null.
  3862. * @return {string} Color string in rgba format.
  3863. * @memberOf module:zrender/util/color
  3864. */
  3865. function modifyHSL(color, h, s, l) {
  3866. color = parse(color);
  3867. if (color) {
  3868. color = rgba2hsla(color);
  3869. h != null && (color[0] = clampCssAngle(h));
  3870. s != null && (color[1] = parseCssFloat(s));
  3871. l != null && (color[2] = parseCssFloat(l));
  3872. return stringify(hsla2rgba(color), 'rgba');
  3873. }
  3874. }
  3875. /**
  3876. * @param {string} color
  3877. * @param {number=} alpha 0 ~ 1
  3878. * @return {string} Color string in rgba format.
  3879. * @memberOf module:zrender/util/color
  3880. */
  3881. function modifyAlpha(color, alpha) {
  3882. color = parse(color);
  3883. if (color && alpha != null) {
  3884. color[3] = clampCssFloat(alpha);
  3885. return stringify(color, 'rgba');
  3886. }
  3887. }
  3888. /**
  3889. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3890. * @param {string} type 'rgba', 'hsva', ...
  3891. * @return {string} Result color. (If input illegal, return undefined).
  3892. */
  3893. function stringify(arrColor, type) {
  3894. if (!arrColor || !arrColor.length) {
  3895. return;
  3896. }
  3897. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3898. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3899. colorStr += ',' + arrColor[3];
  3900. }
  3901. return type + '(' + colorStr + ')';
  3902. }
  3903. var color = (Object.freeze || Object)({
  3904. parse: parse,
  3905. lift: lift,
  3906. toHex: toHex,
  3907. fastLerp: fastLerp,
  3908. fastMapToColor: fastMapToColor,
  3909. lerp: lerp$1,
  3910. mapToColor: mapToColor,
  3911. modifyHSL: modifyHSL,
  3912. modifyAlpha: modifyAlpha,
  3913. stringify: stringify
  3914. });
  3915. /**
  3916. * @module echarts/animation/Animator
  3917. */
  3918. var arraySlice = Array.prototype.slice;
  3919. function defaultGetter(target, key) {
  3920. return target[key];
  3921. }
  3922. function defaultSetter(target, key, value) {
  3923. target[key] = value;
  3924. }
  3925. /**
  3926. * @param {number} p0
  3927. * @param {number} p1
  3928. * @param {number} percent
  3929. * @return {number}
  3930. */
  3931. function interpolateNumber(p0, p1, percent) {
  3932. return (p1 - p0) * percent + p0;
  3933. }
  3934. /**
  3935. * @param {string} p0
  3936. * @param {string} p1
  3937. * @param {number} percent
  3938. * @return {string}
  3939. */
  3940. function interpolateString(p0, p1, percent) {
  3941. return percent > 0.5 ? p1 : p0;
  3942. }
  3943. /**
  3944. * @param {Array} p0
  3945. * @param {Array} p1
  3946. * @param {number} percent
  3947. * @param {Array} out
  3948. * @param {number} arrDim
  3949. */
  3950. function interpolateArray(p0, p1, percent, out, arrDim) {
  3951. var len = p0.length;
  3952. if (arrDim === 1) {
  3953. for (var i = 0; i < len; i++) {
  3954. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3955. }
  3956. }
  3957. else {
  3958. var len2 = len && p0[0].length;
  3959. for (var i = 0; i < len; i++) {
  3960. for (var j = 0; j < len2; j++) {
  3961. out[i][j] = interpolateNumber(
  3962. p0[i][j], p1[i][j], percent
  3963. );
  3964. }
  3965. }
  3966. }
  3967. }
  3968. // arr0 is source array, arr1 is target array.
  3969. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3970. function fillArr(arr0, arr1, arrDim) {
  3971. var arr0Len = arr0.length;
  3972. var arr1Len = arr1.length;
  3973. if (arr0Len !== arr1Len) {
  3974. // FIXME Not work for TypedArray
  3975. var isPreviousLarger = arr0Len > arr1Len;
  3976. if (isPreviousLarger) {
  3977. // Cut the previous
  3978. arr0.length = arr1Len;
  3979. }
  3980. else {
  3981. // Fill the previous
  3982. for (var i = arr0Len; i < arr1Len; i++) {
  3983. arr0.push(
  3984. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3985. );
  3986. }
  3987. }
  3988. }
  3989. // Handling NaN value
  3990. var len2 = arr0[0] && arr0[0].length;
  3991. for (var i = 0; i < arr0.length; i++) {
  3992. if (arrDim === 1) {
  3993. if (isNaN(arr0[i])) {
  3994. arr0[i] = arr1[i];
  3995. }
  3996. }
  3997. else {
  3998. for (var j = 0; j < len2; j++) {
  3999. if (isNaN(arr0[i][j])) {
  4000. arr0[i][j] = arr1[i][j];
  4001. }
  4002. }
  4003. }
  4004. }
  4005. }
  4006. /**
  4007. * @param {Array} arr0
  4008. * @param {Array} arr1
  4009. * @param {number} arrDim
  4010. * @return {boolean}
  4011. */
  4012. function isArraySame(arr0, arr1, arrDim) {
  4013. if (arr0 === arr1) {
  4014. return true;
  4015. }
  4016. var len = arr0.length;
  4017. if (len !== arr1.length) {
  4018. return false;
  4019. }
  4020. if (arrDim === 1) {
  4021. for (var i = 0; i < len; i++) {
  4022. if (arr0[i] !== arr1[i]) {
  4023. return false;
  4024. }
  4025. }
  4026. }
  4027. else {
  4028. var len2 = arr0[0].length;
  4029. for (var i = 0; i < len; i++) {
  4030. for (var j = 0; j < len2; j++) {
  4031. if (arr0[i][j] !== arr1[i][j]) {
  4032. return false;
  4033. }
  4034. }
  4035. }
  4036. }
  4037. return true;
  4038. }
  4039. /**
  4040. * Catmull Rom interpolate array
  4041. * @param {Array} p0
  4042. * @param {Array} p1
  4043. * @param {Array} p2
  4044. * @param {Array} p3
  4045. * @param {number} t
  4046. * @param {number} t2
  4047. * @param {number} t3
  4048. * @param {Array} out
  4049. * @param {number} arrDim
  4050. */
  4051. function catmullRomInterpolateArray(
  4052. p0, p1, p2, p3, t, t2, t3, out, arrDim
  4053. ) {
  4054. var len = p0.length;
  4055. if (arrDim === 1) {
  4056. for (var i = 0; i < len; i++) {
  4057. out[i] = catmullRomInterpolate(
  4058. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  4059. );
  4060. }
  4061. }
  4062. else {
  4063. var len2 = p0[0].length;
  4064. for (var i = 0; i < len; i++) {
  4065. for (var j = 0; j < len2; j++) {
  4066. out[i][j] = catmullRomInterpolate(
  4067. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  4068. t, t2, t3
  4069. );
  4070. }
  4071. }
  4072. }
  4073. }
  4074. /**
  4075. * Catmull Rom interpolate number
  4076. * @param {number} p0
  4077. * @param {number} p1
  4078. * @param {number} p2
  4079. * @param {number} p3
  4080. * @param {number} t
  4081. * @param {number} t2
  4082. * @param {number} t3
  4083. * @return {number}
  4084. */
  4085. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  4086. var v0 = (p2 - p0) * 0.5;
  4087. var v1 = (p3 - p1) * 0.5;
  4088. return (2 * (p1 - p2) + v0 + v1) * t3
  4089. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  4090. + v0 * t + p1;
  4091. }
  4092. function cloneValue(value) {
  4093. if (isArrayLike(value)) {
  4094. var len = value.length;
  4095. if (isArrayLike(value[0])) {
  4096. var ret = [];
  4097. for (var i = 0; i < len; i++) {
  4098. ret.push(arraySlice.call(value[i]));
  4099. }
  4100. return ret;
  4101. }
  4102. return arraySlice.call(value);
  4103. }
  4104. return value;
  4105. }
  4106. function rgba2String(rgba) {
  4107. rgba[0] = Math.floor(rgba[0]);
  4108. rgba[1] = Math.floor(rgba[1]);
  4109. rgba[2] = Math.floor(rgba[2]);
  4110. return 'rgba(' + rgba.join(',') + ')';
  4111. }
  4112. function getArrayDim(keyframes) {
  4113. var lastValue = keyframes[keyframes.length - 1].value;
  4114. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  4115. }
  4116. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  4117. var getter = animator._getter;
  4118. var setter = animator._setter;
  4119. var useSpline = easing === 'spline';
  4120. var trackLen = keyframes.length;
  4121. if (!trackLen) {
  4122. return;
  4123. }
  4124. // Guess data type
  4125. var firstVal = keyframes[0].value;
  4126. var isValueArray = isArrayLike(firstVal);
  4127. var isValueColor = false;
  4128. var isValueString = false;
  4129. // For vertices morphing
  4130. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  4131. var trackMaxTime;
  4132. // Sort keyframe as ascending
  4133. keyframes.sort(function (a, b) {
  4134. return a.time - b.time;
  4135. });
  4136. trackMaxTime = keyframes[trackLen - 1].time;
  4137. // Percents of each keyframe
  4138. var kfPercents = [];
  4139. // Value of each keyframe
  4140. var kfValues = [];
  4141. var prevValue = keyframes[0].value;
  4142. var isAllValueEqual = true;
  4143. for (var i = 0; i < trackLen; i++) {
  4144. kfPercents.push(keyframes[i].time / trackMaxTime);
  4145. // Assume value is a color when it is a string
  4146. var value = keyframes[i].value;
  4147. // Check if value is equal, deep check if value is array
  4148. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  4149. || (!isValueArray && value === prevValue))) {
  4150. isAllValueEqual = false;
  4151. }
  4152. prevValue = value;
  4153. // Try converting a string to a color array
  4154. if (typeof value === 'string') {
  4155. var colorArray = parse(value);
  4156. if (colorArray) {
  4157. value = colorArray;
  4158. isValueColor = true;
  4159. }
  4160. else {
  4161. isValueString = true;
  4162. }
  4163. }
  4164. kfValues.push(value);
  4165. }
  4166. if (!forceAnimate && isAllValueEqual) {
  4167. return;
  4168. }
  4169. var lastValue = kfValues[trackLen - 1];
  4170. // Polyfill array and NaN value
  4171. for (var i = 0; i < trackLen - 1; i++) {
  4172. if (isValueArray) {
  4173. fillArr(kfValues[i], lastValue, arrDim);
  4174. }
  4175. else {
  4176. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  4177. kfValues[i] = lastValue;
  4178. }
  4179. }
  4180. }
  4181. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  4182. // Cache the key of last frame to speed up when
  4183. // animation playback is sequency
  4184. var lastFrame = 0;
  4185. var lastFramePercent = 0;
  4186. var start;
  4187. var w;
  4188. var p0;
  4189. var p1;
  4190. var p2;
  4191. var p3;
  4192. if (isValueColor) {
  4193. var rgba = [0, 0, 0, 0];
  4194. }
  4195. var onframe = function (target, percent) {
  4196. // Find the range keyframes
  4197. // kf1-----kf2---------current--------kf3
  4198. // find kf2 and kf3 and do interpolation
  4199. var frame;
  4200. // In the easing function like elasticOut, percent may less than 0
  4201. if (percent < 0) {
  4202. frame = 0;
  4203. }
  4204. else if (percent < lastFramePercent) {
  4205. // Start from next key
  4206. // PENDING start from lastFrame ?
  4207. start = Math.min(lastFrame + 1, trackLen - 1);
  4208. for (frame = start; frame >= 0; frame--) {
  4209. if (kfPercents[frame] <= percent) {
  4210. break;
  4211. }
  4212. }
  4213. // PENDING really need to do this ?
  4214. frame = Math.min(frame, trackLen - 2);
  4215. }
  4216. else {
  4217. for (frame = lastFrame; frame < trackLen; frame++) {
  4218. if (kfPercents[frame] > percent) {
  4219. break;
  4220. }
  4221. }
  4222. frame = Math.min(frame - 1, trackLen - 2);
  4223. }
  4224. lastFrame = frame;
  4225. lastFramePercent = percent;
  4226. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  4227. if (range === 0) {
  4228. return;
  4229. }
  4230. else {
  4231. w = (percent - kfPercents[frame]) / range;
  4232. }
  4233. if (useSpline) {
  4234. p1 = kfValues[frame];
  4235. p0 = kfValues[frame === 0 ? frame : frame - 1];
  4236. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  4237. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  4238. if (isValueArray) {
  4239. catmullRomInterpolateArray(
  4240. p0, p1, p2, p3, w, w * w, w * w * w,
  4241. getter(target, propName),
  4242. arrDim
  4243. );
  4244. }
  4245. else {
  4246. var value;
  4247. if (isValueColor) {
  4248. value = catmullRomInterpolateArray(
  4249. p0, p1, p2, p3, w, w * w, w * w * w,
  4250. rgba, 1
  4251. );
  4252. value = rgba2String(rgba);
  4253. }
  4254. else if (isValueString) {
  4255. // String is step(0.5)
  4256. return interpolateString(p1, p2, w);
  4257. }
  4258. else {
  4259. value = catmullRomInterpolate(
  4260. p0, p1, p2, p3, w, w * w, w * w * w
  4261. );
  4262. }
  4263. setter(
  4264. target,
  4265. propName,
  4266. value
  4267. );
  4268. }
  4269. }
  4270. else {
  4271. if (isValueArray) {
  4272. interpolateArray(
  4273. kfValues[frame], kfValues[frame + 1], w,
  4274. getter(target, propName),
  4275. arrDim
  4276. );
  4277. }
  4278. else {
  4279. var value;
  4280. if (isValueColor) {
  4281. interpolateArray(
  4282. kfValues[frame], kfValues[frame + 1], w,
  4283. rgba, 1
  4284. );
  4285. value = rgba2String(rgba);
  4286. }
  4287. else if (isValueString) {
  4288. // String is step(0.5)
  4289. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4290. }
  4291. else {
  4292. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4293. }
  4294. setter(
  4295. target,
  4296. propName,
  4297. value
  4298. );
  4299. }
  4300. }
  4301. };
  4302. var clip = new Clip({
  4303. target: animator._target,
  4304. life: trackMaxTime,
  4305. loop: animator._loop,
  4306. delay: animator._delay,
  4307. onframe: onframe,
  4308. ondestroy: oneTrackDone
  4309. });
  4310. if (easing && easing !== 'spline') {
  4311. clip.easing = easing;
  4312. }
  4313. return clip;
  4314. }
  4315. /**
  4316. * @alias module:zrender/animation/Animator
  4317. * @constructor
  4318. * @param {Object} target
  4319. * @param {boolean} loop
  4320. * @param {Function} getter
  4321. * @param {Function} setter
  4322. */
  4323. var Animator = function (target, loop, getter, setter) {
  4324. this._tracks = {};
  4325. this._target = target;
  4326. this._loop = loop || false;
  4327. this._getter = getter || defaultGetter;
  4328. this._setter = setter || defaultSetter;
  4329. this._clipCount = 0;
  4330. this._delay = 0;
  4331. this._doneList = [];
  4332. this._onframeList = [];
  4333. this._clipList = [];
  4334. };
  4335. Animator.prototype = {
  4336. /**
  4337. * Set Animation keyframe
  4338. * @param {number} time 关键帧时间,单位是ms
  4339. * @param {Object} props 关键帧的属性值,key-value表示
  4340. * @return {module:zrender/animation/Animator}
  4341. */
  4342. when: function (time /* ms */, props) {
  4343. var tracks = this._tracks;
  4344. for (var propName in props) {
  4345. if (!props.hasOwnProperty(propName)) {
  4346. continue;
  4347. }
  4348. if (!tracks[propName]) {
  4349. tracks[propName] = [];
  4350. // Invalid value
  4351. var value = this._getter(this._target, propName);
  4352. if (value == null) {
  4353. // zrLog('Invalid property ' + propName);
  4354. continue;
  4355. }
  4356. // If time is 0
  4357. // Then props is given initialize value
  4358. // Else
  4359. // Initialize value from current prop value
  4360. if (time !== 0) {
  4361. tracks[propName].push({
  4362. time: 0,
  4363. value: cloneValue(value)
  4364. });
  4365. }
  4366. }
  4367. tracks[propName].push({
  4368. time: time,
  4369. value: props[propName]
  4370. });
  4371. }
  4372. return this;
  4373. },
  4374. /**
  4375. * 添加动画每一帧的回调函数
  4376. * @param {Function} callback
  4377. * @return {module:zrender/animation/Animator}
  4378. */
  4379. during: function (callback) {
  4380. this._onframeList.push(callback);
  4381. return this;
  4382. },
  4383. pause: function () {
  4384. for (var i = 0; i < this._clipList.length; i++) {
  4385. this._clipList[i].pause();
  4386. }
  4387. this._paused = true;
  4388. },
  4389. resume: function () {
  4390. for (var i = 0; i < this._clipList.length; i++) {
  4391. this._clipList[i].resume();
  4392. }
  4393. this._paused = false;
  4394. },
  4395. isPaused: function () {
  4396. return !!this._paused;
  4397. },
  4398. _doneCallback: function () {
  4399. // Clear all tracks
  4400. this._tracks = {};
  4401. // Clear all clips
  4402. this._clipList.length = 0;
  4403. var doneList = this._doneList;
  4404. var len = doneList.length;
  4405. for (var i = 0; i < len; i++) {
  4406. doneList[i].call(this);
  4407. }
  4408. },
  4409. /**
  4410. * Start the animation
  4411. * @param {string|Function} [easing]
  4412. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4413. * @param {boolean} forceAnimate
  4414. * @return {module:zrender/animation/Animator}
  4415. */
  4416. start: function (easing, forceAnimate) {
  4417. var self = this;
  4418. var clipCount = 0;
  4419. var oneTrackDone = function () {
  4420. clipCount--;
  4421. if (!clipCount) {
  4422. self._doneCallback();
  4423. }
  4424. };
  4425. var lastClip;
  4426. for (var propName in this._tracks) {
  4427. if (!this._tracks.hasOwnProperty(propName)) {
  4428. continue;
  4429. }
  4430. var clip = createTrackClip(
  4431. this, easing, oneTrackDone,
  4432. this._tracks[propName], propName, forceAnimate
  4433. );
  4434. if (clip) {
  4435. this._clipList.push(clip);
  4436. clipCount++;
  4437. // If start after added to animation
  4438. if (this.animation) {
  4439. this.animation.addClip(clip);
  4440. }
  4441. lastClip = clip;
  4442. }
  4443. }
  4444. // Add during callback on the last clip
  4445. if (lastClip) {
  4446. var oldOnFrame = lastClip.onframe;
  4447. lastClip.onframe = function (target, percent) {
  4448. oldOnFrame(target, percent);
  4449. for (var i = 0; i < self._onframeList.length; i++) {
  4450. self._onframeList[i](target, percent);
  4451. }
  4452. };
  4453. }
  4454. // This optimization will help the case that in the upper application
  4455. // the view may be refreshed frequently, where animation will be
  4456. // called repeatly but nothing changed.
  4457. if (!clipCount) {
  4458. this._doneCallback();
  4459. }
  4460. return this;
  4461. },
  4462. /**
  4463. * Stop animation
  4464. * @param {boolean} forwardToLast If move to last frame before stop
  4465. */
  4466. stop: function (forwardToLast) {
  4467. var clipList = this._clipList;
  4468. var animation = this.animation;
  4469. for (var i = 0; i < clipList.length; i++) {
  4470. var clip = clipList[i];
  4471. if (forwardToLast) {
  4472. // Move to last frame before stop
  4473. clip.onframe(this._target, 1);
  4474. }
  4475. animation && animation.removeClip(clip);
  4476. }
  4477. clipList.length = 0;
  4478. },
  4479. /**
  4480. * Set when animation delay starts
  4481. * @param {number} time 单位ms
  4482. * @return {module:zrender/animation/Animator}
  4483. */
  4484. delay: function (time) {
  4485. this._delay = time;
  4486. return this;
  4487. },
  4488. /**
  4489. * Add callback for animation end
  4490. * @param {Function} cb
  4491. * @return {module:zrender/animation/Animator}
  4492. */
  4493. done: function (cb) {
  4494. if (cb) {
  4495. this._doneList.push(cb);
  4496. }
  4497. return this;
  4498. },
  4499. /**
  4500. * @return {Array.<module:zrender/animation/Clip>}
  4501. */
  4502. getClips: function () {
  4503. return this._clipList;
  4504. }
  4505. };
  4506. var dpr = 1;
  4507. // If in browser environment
  4508. if (typeof window !== 'undefined') {
  4509. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4510. }
  4511. /**
  4512. * config默认配置项
  4513. * @exports zrender/config
  4514. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4515. */
  4516. /**
  4517. * Debug log mode:
  4518. * 0: Do nothing, for release.
  4519. * 1: console.error, for debug.
  4520. */
  4521. var debugMode = 0;
  4522. // retina 屏幕优化
  4523. var devicePixelRatio = dpr;
  4524. var logError = function () {
  4525. };
  4526. if (debugMode === 1) {
  4527. logError = console.error;
  4528. }
  4529. var logError$1 = logError;
  4530. /**
  4531. * @alias module:zrender/mixin/Animatable
  4532. * @constructor
  4533. */
  4534. var Animatable = function () {
  4535. /**
  4536. * @type {Array.<module:zrender/animation/Animator>}
  4537. * @readOnly
  4538. */
  4539. this.animators = [];
  4540. };
  4541. Animatable.prototype = {
  4542. constructor: Animatable,
  4543. /**
  4544. * 动画
  4545. *
  4546. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4547. * @param {boolean} [loop] Whether to loop animation.
  4548. * @return {module:zrender/animation/Animator}
  4549. * @example:
  4550. * el.animate('style', false)
  4551. * .when(1000, {x: 10} )
  4552. * .done(function(){ // Animation done })
  4553. * .start()
  4554. */
  4555. animate: function (path, loop) {
  4556. var target;
  4557. var animatingShape = false;
  4558. var el = this;
  4559. var zr = this.__zr;
  4560. if (path) {
  4561. var pathSplitted = path.split('.');
  4562. var prop = el;
  4563. // If animating shape
  4564. animatingShape = pathSplitted[0] === 'shape';
  4565. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4566. if (!prop) {
  4567. continue;
  4568. }
  4569. prop = prop[pathSplitted[i]];
  4570. }
  4571. if (prop) {
  4572. target = prop;
  4573. }
  4574. }
  4575. else {
  4576. target = el;
  4577. }
  4578. if (!target) {
  4579. logError$1(
  4580. 'Property "'
  4581. + path
  4582. + '" is not existed in element '
  4583. + el.id
  4584. );
  4585. return;
  4586. }
  4587. var animators = el.animators;
  4588. var animator = new Animator(target, loop);
  4589. animator.during(function (target) {
  4590. el.dirty(animatingShape);
  4591. })
  4592. .done(function () {
  4593. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4594. animators.splice(indexOf(animators, animator), 1);
  4595. });
  4596. animators.push(animator);
  4597. // If animate after added to the zrender
  4598. if (zr) {
  4599. zr.animation.addAnimator(animator);
  4600. }
  4601. return animator;
  4602. },
  4603. /**
  4604. * 停止动画
  4605. * @param {boolean} forwardToLast If move to last frame before stop
  4606. */
  4607. stopAnimation: function (forwardToLast) {
  4608. var animators = this.animators;
  4609. var len = animators.length;
  4610. for (var i = 0; i < len; i++) {
  4611. animators[i].stop(forwardToLast);
  4612. }
  4613. animators.length = 0;
  4614. return this;
  4615. },
  4616. /**
  4617. * Caution: this method will stop previous animation.
  4618. * So do not use this method to one element twice before
  4619. * animation starts, unless you know what you are doing.
  4620. * @param {Object} target
  4621. * @param {number} [time=500] Time in ms
  4622. * @param {string} [easing='linear']
  4623. * @param {number} [delay=0]
  4624. * @param {Function} [callback]
  4625. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4626. * immediently when target values are the same as current values.
  4627. *
  4628. * @example
  4629. * // Animate position
  4630. * el.animateTo({
  4631. * position: [10, 10]
  4632. * }, function () { // done })
  4633. *
  4634. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4635. * el.animateTo({
  4636. * shape: {
  4637. * width: 500
  4638. * },
  4639. * style: {
  4640. * fill: 'red'
  4641. * }
  4642. * position: [10, 10]
  4643. * }, 100, 100, 'cubicOut', function () { // done })
  4644. */
  4645. // TODO Return animation key
  4646. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4647. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4648. },
  4649. /**
  4650. * Animate from the target state to current state.
  4651. * The params and the return value are the same as `this.animateTo`.
  4652. */
  4653. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4654. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4655. }
  4656. };
  4657. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4658. // animateTo(target, time, easing, callback);
  4659. if (isString(delay)) {
  4660. callback = easing;
  4661. easing = delay;
  4662. delay = 0;
  4663. }
  4664. // animateTo(target, time, delay, callback);
  4665. else if (isFunction$1(easing)) {
  4666. callback = easing;
  4667. easing = 'linear';
  4668. delay = 0;
  4669. }
  4670. // animateTo(target, time, callback);
  4671. else if (isFunction$1(delay)) {
  4672. callback = delay;
  4673. delay = 0;
  4674. }
  4675. // animateTo(target, callback)
  4676. else if (isFunction$1(time)) {
  4677. callback = time;
  4678. time = 500;
  4679. }
  4680. // animateTo(target)
  4681. else if (!time) {
  4682. time = 500;
  4683. }
  4684. // Stop all previous animations
  4685. animatable.stopAnimation();
  4686. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4687. // Animators may be removed immediately after start
  4688. // if there is nothing to animate
  4689. var animators = animatable.animators.slice();
  4690. var count = animators.length;
  4691. function done() {
  4692. count--;
  4693. if (!count) {
  4694. callback && callback();
  4695. }
  4696. }
  4697. // No animators. This should be checked before animators[i].start(),
  4698. // because 'done' may be executed immediately if no need to animate.
  4699. if (!count) {
  4700. callback && callback();
  4701. }
  4702. // Start after all animators created
  4703. // Incase any animator is done immediately when all animation properties are not changed
  4704. for (var i = 0; i < animators.length; i++) {
  4705. animators[i]
  4706. .done(done)
  4707. .start(easing, forceAnimate);
  4708. }
  4709. }
  4710. /**
  4711. * @param {string} path=''
  4712. * @param {Object} source=animatable
  4713. * @param {Object} target
  4714. * @param {number} [time=500]
  4715. * @param {number} [delay=0]
  4716. * @param {boolean} [reverse] If `true`, animate
  4717. * from the `target` to current state.
  4718. *
  4719. * @example
  4720. * // Animate position
  4721. * el._animateToShallow({
  4722. * position: [10, 10]
  4723. * })
  4724. *
  4725. * // Animate shape, style and position in 100ms, delayed 100ms
  4726. * el._animateToShallow({
  4727. * shape: {
  4728. * width: 500
  4729. * },
  4730. * style: {
  4731. * fill: 'red'
  4732. * }
  4733. * position: [10, 10]
  4734. * }, 100, 100)
  4735. */
  4736. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4737. var objShallow = {};
  4738. var propertyCount = 0;
  4739. for (var name in target) {
  4740. if (!target.hasOwnProperty(name)) {
  4741. continue;
  4742. }
  4743. if (source[name] != null) {
  4744. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4745. animateToShallow(
  4746. animatable,
  4747. path ? path + '.' + name : name,
  4748. source[name],
  4749. target[name],
  4750. time,
  4751. delay,
  4752. reverse
  4753. );
  4754. }
  4755. else {
  4756. if (reverse) {
  4757. objShallow[name] = source[name];
  4758. setAttrByPath(animatable, path, name, target[name]);
  4759. }
  4760. else {
  4761. objShallow[name] = target[name];
  4762. }
  4763. propertyCount++;
  4764. }
  4765. }
  4766. else if (target[name] != null && !reverse) {
  4767. setAttrByPath(animatable, path, name, target[name]);
  4768. }
  4769. }
  4770. if (propertyCount > 0) {
  4771. animatable.animate(path, false)
  4772. .when(time == null ? 500 : time, objShallow)
  4773. .delay(delay || 0);
  4774. }
  4775. }
  4776. function setAttrByPath(el, path, name, value) {
  4777. // Attr directly if not has property
  4778. // FIXME, if some property not needed for element ?
  4779. if (!path) {
  4780. el.attr(name, value);
  4781. }
  4782. else {
  4783. // Only support set shape or style
  4784. var props = {};
  4785. props[path] = {};
  4786. props[path][name] = value;
  4787. el.attr(props);
  4788. }
  4789. }
  4790. /**
  4791. * @alias module:zrender/Element
  4792. * @constructor
  4793. * @extends {module:zrender/mixin/Animatable}
  4794. * @extends {module:zrender/mixin/Transformable}
  4795. * @extends {module:zrender/mixin/Eventful}
  4796. */
  4797. var Element = function (opts) { // jshint ignore:line
  4798. Transformable.call(this, opts);
  4799. Eventful.call(this, opts);
  4800. Animatable.call(this, opts);
  4801. /**
  4802. * 画布元素ID
  4803. * @type {string}
  4804. */
  4805. this.id = opts.id || guid();
  4806. };
  4807. Element.prototype = {
  4808. /**
  4809. * 元素类型
  4810. * Element type
  4811. * @type {string}
  4812. */
  4813. type: 'element',
  4814. /**
  4815. * 元素名字
  4816. * Element name
  4817. * @type {string}
  4818. */
  4819. name: '',
  4820. /**
  4821. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4822. * ZRender instance will be assigned when element is associated with zrender
  4823. * @name module:/zrender/Element#__zr
  4824. * @type {module:zrender/ZRender}
  4825. */
  4826. __zr: null,
  4827. /**
  4828. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4829. * If ignore drawing and events of the element object
  4830. * @name module:/zrender/Element#ignore
  4831. * @type {boolean}
  4832. * @default false
  4833. */
  4834. ignore: false,
  4835. /**
  4836. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4837. * 该路径会继承被裁减对象的变换
  4838. * @type {module:zrender/graphic/Path}
  4839. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4840. * @readOnly
  4841. */
  4842. clipPath: null,
  4843. /**
  4844. * 是否是 Group
  4845. * @type {boolean}
  4846. */
  4847. isGroup: false,
  4848. /**
  4849. * Drift element
  4850. * @param {number} dx dx on the global space
  4851. * @param {number} dy dy on the global space
  4852. */
  4853. drift: function (dx, dy) {
  4854. switch (this.draggable) {
  4855. case 'horizontal':
  4856. dy = 0;
  4857. break;
  4858. case 'vertical':
  4859. dx = 0;
  4860. break;
  4861. }
  4862. var m = this.transform;
  4863. if (!m) {
  4864. m = this.transform = [1, 0, 0, 1, 0, 0];
  4865. }
  4866. m[4] += dx;
  4867. m[5] += dy;
  4868. this.decomposeTransform();
  4869. this.dirty(false);
  4870. },
  4871. /**
  4872. * Hook before update
  4873. */
  4874. beforeUpdate: function () {},
  4875. /**
  4876. * Hook after update
  4877. */
  4878. afterUpdate: function () {},
  4879. /**
  4880. * Update each frame
  4881. */
  4882. update: function () {
  4883. this.updateTransform();
  4884. },
  4885. /**
  4886. * @param {Function} cb
  4887. * @param {} context
  4888. */
  4889. traverse: function (cb, context) {},
  4890. /**
  4891. * @protected
  4892. */
  4893. attrKV: function (key, value) {
  4894. if (key === 'position' || key === 'scale' || key === 'origin') {
  4895. // Copy the array
  4896. if (value) {
  4897. var target = this[key];
  4898. if (!target) {
  4899. target = this[key] = [];
  4900. }
  4901. target[0] = value[0];
  4902. target[1] = value[1];
  4903. }
  4904. }
  4905. else {
  4906. this[key] = value;
  4907. }
  4908. },
  4909. /**
  4910. * Hide the element
  4911. */
  4912. hide: function () {
  4913. this.ignore = true;
  4914. this.__zr && this.__zr.refresh();
  4915. },
  4916. /**
  4917. * Show the element
  4918. */
  4919. show: function () {
  4920. this.ignore = false;
  4921. this.__zr && this.__zr.refresh();
  4922. },
  4923. /**
  4924. * @param {string|Object} key
  4925. * @param {*} value
  4926. */
  4927. attr: function (key, value) {
  4928. if (typeof key === 'string') {
  4929. this.attrKV(key, value);
  4930. }
  4931. else if (isObject$1(key)) {
  4932. for (var name in key) {
  4933. if (key.hasOwnProperty(name)) {
  4934. this.attrKV(name, key[name]);
  4935. }
  4936. }
  4937. }
  4938. this.dirty(false);
  4939. return this;
  4940. },
  4941. /**
  4942. * @param {module:zrender/graphic/Path} clipPath
  4943. */
  4944. setClipPath: function (clipPath) {
  4945. var zr = this.__zr;
  4946. if (zr) {
  4947. clipPath.addSelfToZr(zr);
  4948. }
  4949. // Remove previous clip path
  4950. if (this.clipPath && this.clipPath !== clipPath) {
  4951. this.removeClipPath();
  4952. }
  4953. this.clipPath = clipPath;
  4954. clipPath.__zr = zr;
  4955. clipPath.__clipTarget = this;
  4956. this.dirty(false);
  4957. },
  4958. /**
  4959. */
  4960. removeClipPath: function () {
  4961. var clipPath = this.clipPath;
  4962. if (clipPath) {
  4963. if (clipPath.__zr) {
  4964. clipPath.removeSelfFromZr(clipPath.__zr);
  4965. }
  4966. clipPath.__zr = null;
  4967. clipPath.__clipTarget = null;
  4968. this.clipPath = null;
  4969. this.dirty(false);
  4970. }
  4971. },
  4972. /**
  4973. * Add self from zrender instance.
  4974. * Not recursively because it will be invoked when element added to storage.
  4975. * @param {module:zrender/ZRender} zr
  4976. */
  4977. addSelfToZr: function (zr) {
  4978. this.__zr = zr;
  4979. // 添加动画
  4980. var animators = this.animators;
  4981. if (animators) {
  4982. for (var i = 0; i < animators.length; i++) {
  4983. zr.animation.addAnimator(animators[i]);
  4984. }
  4985. }
  4986. if (this.clipPath) {
  4987. this.clipPath.addSelfToZr(zr);
  4988. }
  4989. },
  4990. /**
  4991. * Remove self from zrender instance.
  4992. * Not recursively because it will be invoked when element added to storage.
  4993. * @param {module:zrender/ZRender} zr
  4994. */
  4995. removeSelfFromZr: function (zr) {
  4996. this.__zr = null;
  4997. // 移除动画
  4998. var animators = this.animators;
  4999. if (animators) {
  5000. for (var i = 0; i < animators.length; i++) {
  5001. zr.animation.removeAnimator(animators[i]);
  5002. }
  5003. }
  5004. if (this.clipPath) {
  5005. this.clipPath.removeSelfFromZr(zr);
  5006. }
  5007. }
  5008. };
  5009. mixin(Element, Animatable);
  5010. mixin(Element, Transformable);
  5011. mixin(Element, Eventful);
  5012. /**
  5013. * @module echarts/core/BoundingRect
  5014. */
  5015. var v2ApplyTransform = applyTransform;
  5016. var mathMin = Math.min;
  5017. var mathMax = Math.max;
  5018. /**
  5019. * @alias module:echarts/core/BoundingRect
  5020. */
  5021. function BoundingRect(x, y, width, height) {
  5022. if (width < 0) {
  5023. x = x + width;
  5024. width = -width;
  5025. }
  5026. if (height < 0) {
  5027. y = y + height;
  5028. height = -height;
  5029. }
  5030. /**
  5031. * @type {number}
  5032. */
  5033. this.x = x;
  5034. /**
  5035. * @type {number}
  5036. */
  5037. this.y = y;
  5038. /**
  5039. * @type {number}
  5040. */
  5041. this.width = width;
  5042. /**
  5043. * @type {number}
  5044. */
  5045. this.height = height;
  5046. }
  5047. BoundingRect.prototype = {
  5048. constructor: BoundingRect,
  5049. /**
  5050. * @param {module:echarts/core/BoundingRect} other
  5051. */
  5052. union: function (other) {
  5053. var x = mathMin(other.x, this.x);
  5054. var y = mathMin(other.y, this.y);
  5055. this.width = mathMax(
  5056. other.x + other.width,
  5057. this.x + this.width
  5058. ) - x;
  5059. this.height = mathMax(
  5060. other.y + other.height,
  5061. this.y + this.height
  5062. ) - y;
  5063. this.x = x;
  5064. this.y = y;
  5065. },
  5066. /**
  5067. * @param {Array.<number>} m
  5068. * @methods
  5069. */
  5070. applyTransform: (function () {
  5071. var lt = [];
  5072. var rb = [];
  5073. var lb = [];
  5074. var rt = [];
  5075. return function (m) {
  5076. // In case usage like this
  5077. // el.getBoundingRect().applyTransform(el.transform)
  5078. // And element has no transform
  5079. if (!m) {
  5080. return;
  5081. }
  5082. lt[0] = lb[0] = this.x;
  5083. lt[1] = rt[1] = this.y;
  5084. rb[0] = rt[0] = this.x + this.width;
  5085. rb[1] = lb[1] = this.y + this.height;
  5086. v2ApplyTransform(lt, lt, m);
  5087. v2ApplyTransform(rb, rb, m);
  5088. v2ApplyTransform(lb, lb, m);
  5089. v2ApplyTransform(rt, rt, m);
  5090. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  5091. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  5092. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  5093. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  5094. this.width = maxX - this.x;
  5095. this.height = maxY - this.y;
  5096. };
  5097. })(),
  5098. /**
  5099. * Calculate matrix of transforming from self to target rect
  5100. * @param {module:zrender/core/BoundingRect} b
  5101. * @return {Array.<number>}
  5102. */
  5103. calculateTransform: function (b) {
  5104. var a = this;
  5105. var sx = b.width / a.width;
  5106. var sy = b.height / a.height;
  5107. var m = create$1();
  5108. // 矩阵右乘
  5109. translate(m, m, [-a.x, -a.y]);
  5110. scale$1(m, m, [sx, sy]);
  5111. translate(m, m, [b.x, b.y]);
  5112. return m;
  5113. },
  5114. /**
  5115. * @param {(module:echarts/core/BoundingRect|Object)} b
  5116. * @return {boolean}
  5117. */
  5118. intersect: function (b) {
  5119. if (!b) {
  5120. return false;
  5121. }
  5122. if (!(b instanceof BoundingRect)) {
  5123. // Normalize negative width/height.
  5124. b = BoundingRect.create(b);
  5125. }
  5126. var a = this;
  5127. var ax0 = a.x;
  5128. var ax1 = a.x + a.width;
  5129. var ay0 = a.y;
  5130. var ay1 = a.y + a.height;
  5131. var bx0 = b.x;
  5132. var bx1 = b.x + b.width;
  5133. var by0 = b.y;
  5134. var by1 = b.y + b.height;
  5135. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  5136. },
  5137. contain: function (x, y) {
  5138. var rect = this;
  5139. return x >= rect.x
  5140. && x <= (rect.x + rect.width)
  5141. && y >= rect.y
  5142. && y <= (rect.y + rect.height);
  5143. },
  5144. /**
  5145. * @return {module:echarts/core/BoundingRect}
  5146. */
  5147. clone: function () {
  5148. return new BoundingRect(this.x, this.y, this.width, this.height);
  5149. },
  5150. /**
  5151. * Copy from another rect
  5152. */
  5153. copy: function (other) {
  5154. this.x = other.x;
  5155. this.y = other.y;
  5156. this.width = other.width;
  5157. this.height = other.height;
  5158. },
  5159. plain: function () {
  5160. return {
  5161. x: this.x,
  5162. y: this.y,
  5163. width: this.width,
  5164. height: this.height
  5165. };
  5166. }
  5167. };
  5168. /**
  5169. * @param {Object|module:zrender/core/BoundingRect} rect
  5170. * @param {number} rect.x
  5171. * @param {number} rect.y
  5172. * @param {number} rect.width
  5173. * @param {number} rect.height
  5174. * @return {module:zrender/core/BoundingRect}
  5175. */
  5176. BoundingRect.create = function (rect) {
  5177. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  5178. };
  5179. /**
  5180. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  5181. * @module zrender/graphic/Group
  5182. * @example
  5183. * var Group = require('zrender/container/Group');
  5184. * var Circle = require('zrender/graphic/shape/Circle');
  5185. * var g = new Group();
  5186. * g.position[0] = 100;
  5187. * g.position[1] = 100;
  5188. * g.add(new Circle({
  5189. * style: {
  5190. * x: 100,
  5191. * y: 100,
  5192. * r: 20,
  5193. * }
  5194. * }));
  5195. * zr.add(g);
  5196. */
  5197. /**
  5198. * @alias module:zrender/graphic/Group
  5199. * @constructor
  5200. * @extends module:zrender/mixin/Transformable
  5201. * @extends module:zrender/mixin/Eventful
  5202. */
  5203. var Group = function (opts) {
  5204. opts = opts || {};
  5205. Element.call(this, opts);
  5206. for (var key in opts) {
  5207. if (opts.hasOwnProperty(key)) {
  5208. this[key] = opts[key];
  5209. }
  5210. }
  5211. this._children = [];
  5212. this.__storage = null;
  5213. this.__dirty = true;
  5214. };
  5215. Group.prototype = {
  5216. constructor: Group,
  5217. isGroup: true,
  5218. /**
  5219. * @type {string}
  5220. */
  5221. type: 'group',
  5222. /**
  5223. * 所有子孙元素是否响应鼠标事件
  5224. * @name module:/zrender/container/Group#silent
  5225. * @type {boolean}
  5226. * @default false
  5227. */
  5228. silent: false,
  5229. /**
  5230. * @return {Array.<module:zrender/Element>}
  5231. */
  5232. children: function () {
  5233. return this._children.slice();
  5234. },
  5235. /**
  5236. * 获取指定 index 的儿子节点
  5237. * @param {number} idx
  5238. * @return {module:zrender/Element}
  5239. */
  5240. childAt: function (idx) {
  5241. return this._children[idx];
  5242. },
  5243. /**
  5244. * 获取指定名字的儿子节点
  5245. * @param {string} name
  5246. * @return {module:zrender/Element}
  5247. */
  5248. childOfName: function (name) {
  5249. var children = this._children;
  5250. for (var i = 0; i < children.length; i++) {
  5251. if (children[i].name === name) {
  5252. return children[i];
  5253. }
  5254. }
  5255. },
  5256. /**
  5257. * @return {number}
  5258. */
  5259. childCount: function () {
  5260. return this._children.length;
  5261. },
  5262. /**
  5263. * 添加子节点到最后
  5264. * @param {module:zrender/Element} child
  5265. */
  5266. add: function (child) {
  5267. if (child && child !== this && child.parent !== this) {
  5268. this._children.push(child);
  5269. this._doAdd(child);
  5270. }
  5271. return this;
  5272. },
  5273. /**
  5274. * 添加子节点在 nextSibling 之前
  5275. * @param {module:zrender/Element} child
  5276. * @param {module:zrender/Element} nextSibling
  5277. */
  5278. addBefore: function (child, nextSibling) {
  5279. if (child && child !== this && child.parent !== this
  5280. && nextSibling && nextSibling.parent === this) {
  5281. var children = this._children;
  5282. var idx = children.indexOf(nextSibling);
  5283. if (idx >= 0) {
  5284. children.splice(idx, 0, child);
  5285. this._doAdd(child);
  5286. }
  5287. }
  5288. return this;
  5289. },
  5290. _doAdd: function (child) {
  5291. if (child.parent) {
  5292. child.parent.remove(child);
  5293. }
  5294. child.parent = this;
  5295. var storage = this.__storage;
  5296. var zr = this.__zr;
  5297. if (storage && storage !== child.__storage) {
  5298. storage.addToStorage(child);
  5299. if (child instanceof Group) {
  5300. child.addChildrenToStorage(storage);
  5301. }
  5302. }
  5303. zr && zr.refresh();
  5304. },
  5305. /**
  5306. * 移除子节点
  5307. * @param {module:zrender/Element} child
  5308. */
  5309. remove: function (child) {
  5310. var zr = this.__zr;
  5311. var storage = this.__storage;
  5312. var children = this._children;
  5313. var idx = indexOf(children, child);
  5314. if (idx < 0) {
  5315. return this;
  5316. }
  5317. children.splice(idx, 1);
  5318. child.parent = null;
  5319. if (storage) {
  5320. storage.delFromStorage(child);
  5321. if (child instanceof Group) {
  5322. child.delChildrenFromStorage(storage);
  5323. }
  5324. }
  5325. zr && zr.refresh();
  5326. return this;
  5327. },
  5328. /**
  5329. * 移除所有子节点
  5330. */
  5331. removeAll: function () {
  5332. var children = this._children;
  5333. var storage = this.__storage;
  5334. var child;
  5335. var i;
  5336. for (i = 0; i < children.length; i++) {
  5337. child = children[i];
  5338. if (storage) {
  5339. storage.delFromStorage(child);
  5340. if (child instanceof Group) {
  5341. child.delChildrenFromStorage(storage);
  5342. }
  5343. }
  5344. child.parent = null;
  5345. }
  5346. children.length = 0;
  5347. return this;
  5348. },
  5349. /**
  5350. * 遍历所有子节点
  5351. * @param {Function} cb
  5352. * @param {} context
  5353. */
  5354. eachChild: function (cb, context) {
  5355. var children = this._children;
  5356. for (var i = 0; i < children.length; i++) {
  5357. var child = children[i];
  5358. cb.call(context, child, i);
  5359. }
  5360. return this;
  5361. },
  5362. /**
  5363. * 深度优先遍历所有子孙节点
  5364. * @param {Function} cb
  5365. * @param {} context
  5366. */
  5367. traverse: function (cb, context) {
  5368. for (var i = 0; i < this._children.length; i++) {
  5369. var child = this._children[i];
  5370. cb.call(context, child);
  5371. if (child.type === 'group') {
  5372. child.traverse(cb, context);
  5373. }
  5374. }
  5375. return this;
  5376. },
  5377. addChildrenToStorage: function (storage) {
  5378. for (var i = 0; i < this._children.length; i++) {
  5379. var child = this._children[i];
  5380. storage.addToStorage(child);
  5381. if (child instanceof Group) {
  5382. child.addChildrenToStorage(storage);
  5383. }
  5384. }
  5385. },
  5386. delChildrenFromStorage: function (storage) {
  5387. for (var i = 0; i < this._children.length; i++) {
  5388. var child = this._children[i];
  5389. storage.delFromStorage(child);
  5390. if (child instanceof Group) {
  5391. child.delChildrenFromStorage(storage);
  5392. }
  5393. }
  5394. },
  5395. dirty: function () {
  5396. this.__dirty = true;
  5397. this.__zr && this.__zr.refresh();
  5398. return this;
  5399. },
  5400. /**
  5401. * @return {module:zrender/core/BoundingRect}
  5402. */
  5403. getBoundingRect: function (includeChildren) {
  5404. // TODO Caching
  5405. var rect = null;
  5406. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5407. var children = includeChildren || this._children;
  5408. var tmpMat = [];
  5409. for (var i = 0; i < children.length; i++) {
  5410. var child = children[i];
  5411. if (child.ignore || child.invisible) {
  5412. continue;
  5413. }
  5414. var childRect = child.getBoundingRect();
  5415. var transform = child.getLocalTransform(tmpMat);
  5416. // TODO
  5417. // The boundingRect cacluated by transforming original
  5418. // rect may be bigger than the actual bundingRect when rotation
  5419. // is used. (Consider a circle rotated aginst its center, where
  5420. // the actual boundingRect should be the same as that not be
  5421. // rotated.) But we can not find better approach to calculate
  5422. // actual boundingRect yet, considering performance.
  5423. if (transform) {
  5424. tmpRect.copy(childRect);
  5425. tmpRect.applyTransform(transform);
  5426. rect = rect || tmpRect.clone();
  5427. rect.union(tmpRect);
  5428. }
  5429. else {
  5430. rect = rect || childRect.clone();
  5431. rect.union(childRect);
  5432. }
  5433. }
  5434. return rect || tmpRect;
  5435. }
  5436. };
  5437. inherits(Group, Element);
  5438. // https://github.com/mziccard/node-timsort
  5439. var DEFAULT_MIN_MERGE = 32;
  5440. var DEFAULT_MIN_GALLOPING = 7;
  5441. function minRunLength(n) {
  5442. var r = 0;
  5443. while (n >= DEFAULT_MIN_MERGE) {
  5444. r |= n & 1;
  5445. n >>= 1;
  5446. }
  5447. return n + r;
  5448. }
  5449. function makeAscendingRun(array, lo, hi, compare) {
  5450. var runHi = lo + 1;
  5451. if (runHi === hi) {
  5452. return 1;
  5453. }
  5454. if (compare(array[runHi++], array[lo]) < 0) {
  5455. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5456. runHi++;
  5457. }
  5458. reverseRun(array, lo, runHi);
  5459. }
  5460. else {
  5461. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5462. runHi++;
  5463. }
  5464. }
  5465. return runHi - lo;
  5466. }
  5467. function reverseRun(array, lo, hi) {
  5468. hi--;
  5469. while (lo < hi) {
  5470. var t = array[lo];
  5471. array[lo++] = array[hi];
  5472. array[hi--] = t;
  5473. }
  5474. }
  5475. function binaryInsertionSort(array, lo, hi, start, compare) {
  5476. if (start === lo) {
  5477. start++;
  5478. }
  5479. for (; start < hi; start++) {
  5480. var pivot = array[start];
  5481. var left = lo;
  5482. var right = start;
  5483. var mid;
  5484. while (left < right) {
  5485. mid = left + right >>> 1;
  5486. if (compare(pivot, array[mid]) < 0) {
  5487. right = mid;
  5488. }
  5489. else {
  5490. left = mid + 1;
  5491. }
  5492. }
  5493. var n = start - left;
  5494. switch (n) {
  5495. case 3:
  5496. array[left + 3] = array[left + 2];
  5497. case 2:
  5498. array[left + 2] = array[left + 1];
  5499. case 1:
  5500. array[left + 1] = array[left];
  5501. break;
  5502. default:
  5503. while (n > 0) {
  5504. array[left + n] = array[left + n - 1];
  5505. n--;
  5506. }
  5507. }
  5508. array[left] = pivot;
  5509. }
  5510. }
  5511. function gallopLeft(value, array, start, length, hint, compare) {
  5512. var lastOffset = 0;
  5513. var maxOffset = 0;
  5514. var offset = 1;
  5515. if (compare(value, array[start + hint]) > 0) {
  5516. maxOffset = length - hint;
  5517. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5518. lastOffset = offset;
  5519. offset = (offset << 1) + 1;
  5520. if (offset <= 0) {
  5521. offset = maxOffset;
  5522. }
  5523. }
  5524. if (offset > maxOffset) {
  5525. offset = maxOffset;
  5526. }
  5527. lastOffset += hint;
  5528. offset += hint;
  5529. }
  5530. else {
  5531. maxOffset = hint + 1;
  5532. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5533. lastOffset = offset;
  5534. offset = (offset << 1) + 1;
  5535. if (offset <= 0) {
  5536. offset = maxOffset;
  5537. }
  5538. }
  5539. if (offset > maxOffset) {
  5540. offset = maxOffset;
  5541. }
  5542. var tmp = lastOffset;
  5543. lastOffset = hint - offset;
  5544. offset = hint - tmp;
  5545. }
  5546. lastOffset++;
  5547. while (lastOffset < offset) {
  5548. var m = lastOffset + (offset - lastOffset >>> 1);
  5549. if (compare(value, array[start + m]) > 0) {
  5550. lastOffset = m + 1;
  5551. }
  5552. else {
  5553. offset = m;
  5554. }
  5555. }
  5556. return offset;
  5557. }
  5558. function gallopRight(value, array, start, length, hint, compare) {
  5559. var lastOffset = 0;
  5560. var maxOffset = 0;
  5561. var offset = 1;
  5562. if (compare(value, array[start + hint]) < 0) {
  5563. maxOffset = hint + 1;
  5564. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5565. lastOffset = offset;
  5566. offset = (offset << 1) + 1;
  5567. if (offset <= 0) {
  5568. offset = maxOffset;
  5569. }
  5570. }
  5571. if (offset > maxOffset) {
  5572. offset = maxOffset;
  5573. }
  5574. var tmp = lastOffset;
  5575. lastOffset = hint - offset;
  5576. offset = hint - tmp;
  5577. }
  5578. else {
  5579. maxOffset = length - hint;
  5580. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5581. lastOffset = offset;
  5582. offset = (offset << 1) + 1;
  5583. if (offset <= 0) {
  5584. offset = maxOffset;
  5585. }
  5586. }
  5587. if (offset > maxOffset) {
  5588. offset = maxOffset;
  5589. }
  5590. lastOffset += hint;
  5591. offset += hint;
  5592. }
  5593. lastOffset++;
  5594. while (lastOffset < offset) {
  5595. var m = lastOffset + (offset - lastOffset >>> 1);
  5596. if (compare(value, array[start + m]) < 0) {
  5597. offset = m;
  5598. }
  5599. else {
  5600. lastOffset = m + 1;
  5601. }
  5602. }
  5603. return offset;
  5604. }
  5605. function TimSort(array, compare) {
  5606. var minGallop = DEFAULT_MIN_GALLOPING;
  5607. var runStart;
  5608. var runLength;
  5609. var stackSize = 0;
  5610. var tmp = [];
  5611. runStart = [];
  5612. runLength = [];
  5613. function pushRun(_runStart, _runLength) {
  5614. runStart[stackSize] = _runStart;
  5615. runLength[stackSize] = _runLength;
  5616. stackSize += 1;
  5617. }
  5618. function mergeRuns() {
  5619. while (stackSize > 1) {
  5620. var n = stackSize - 2;
  5621. if (
  5622. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5623. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5624. ) {
  5625. if (runLength[n - 1] < runLength[n + 1]) {
  5626. n--;
  5627. }
  5628. }
  5629. else if (runLength[n] > runLength[n + 1]) {
  5630. break;
  5631. }
  5632. mergeAt(n);
  5633. }
  5634. }
  5635. function forceMergeRuns() {
  5636. while (stackSize > 1) {
  5637. var n = stackSize - 2;
  5638. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5639. n--;
  5640. }
  5641. mergeAt(n);
  5642. }
  5643. }
  5644. function mergeAt(i) {
  5645. var start1 = runStart[i];
  5646. var length1 = runLength[i];
  5647. var start2 = runStart[i + 1];
  5648. var length2 = runLength[i + 1];
  5649. runLength[i] = length1 + length2;
  5650. if (i === stackSize - 3) {
  5651. runStart[i + 1] = runStart[i + 2];
  5652. runLength[i + 1] = runLength[i + 2];
  5653. }
  5654. stackSize--;
  5655. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5656. start1 += k;
  5657. length1 -= k;
  5658. if (length1 === 0) {
  5659. return;
  5660. }
  5661. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5662. if (length2 === 0) {
  5663. return;
  5664. }
  5665. if (length1 <= length2) {
  5666. mergeLow(start1, length1, start2, length2);
  5667. }
  5668. else {
  5669. mergeHigh(start1, length1, start2, length2);
  5670. }
  5671. }
  5672. function mergeLow(start1, length1, start2, length2) {
  5673. var i = 0;
  5674. for (i = 0; i < length1; i++) {
  5675. tmp[i] = array[start1 + i];
  5676. }
  5677. var cursor1 = 0;
  5678. var cursor2 = start2;
  5679. var dest = start1;
  5680. array[dest++] = array[cursor2++];
  5681. if (--length2 === 0) {
  5682. for (i = 0; i < length1; i++) {
  5683. array[dest + i] = tmp[cursor1 + i];
  5684. }
  5685. return;
  5686. }
  5687. if (length1 === 1) {
  5688. for (i = 0; i < length2; i++) {
  5689. array[dest + i] = array[cursor2 + i];
  5690. }
  5691. array[dest + length2] = tmp[cursor1];
  5692. return;
  5693. }
  5694. var _minGallop = minGallop;
  5695. var count1;
  5696. var count2;
  5697. var exit;
  5698. while (1) {
  5699. count1 = 0;
  5700. count2 = 0;
  5701. exit = false;
  5702. do {
  5703. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5704. array[dest++] = array[cursor2++];
  5705. count2++;
  5706. count1 = 0;
  5707. if (--length2 === 0) {
  5708. exit = true;
  5709. break;
  5710. }
  5711. }
  5712. else {
  5713. array[dest++] = tmp[cursor1++];
  5714. count1++;
  5715. count2 = 0;
  5716. if (--length1 === 1) {
  5717. exit = true;
  5718. break;
  5719. }
  5720. }
  5721. } while ((count1 | count2) < _minGallop);
  5722. if (exit) {
  5723. break;
  5724. }
  5725. do {
  5726. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5727. if (count1 !== 0) {
  5728. for (i = 0; i < count1; i++) {
  5729. array[dest + i] = tmp[cursor1 + i];
  5730. }
  5731. dest += count1;
  5732. cursor1 += count1;
  5733. length1 -= count1;
  5734. if (length1 <= 1) {
  5735. exit = true;
  5736. break;
  5737. }
  5738. }
  5739. array[dest++] = array[cursor2++];
  5740. if (--length2 === 0) {
  5741. exit = true;
  5742. break;
  5743. }
  5744. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5745. if (count2 !== 0) {
  5746. for (i = 0; i < count2; i++) {
  5747. array[dest + i] = array[cursor2 + i];
  5748. }
  5749. dest += count2;
  5750. cursor2 += count2;
  5751. length2 -= count2;
  5752. if (length2 === 0) {
  5753. exit = true;
  5754. break;
  5755. }
  5756. }
  5757. array[dest++] = tmp[cursor1++];
  5758. if (--length1 === 1) {
  5759. exit = true;
  5760. break;
  5761. }
  5762. _minGallop--;
  5763. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5764. if (exit) {
  5765. break;
  5766. }
  5767. if (_minGallop < 0) {
  5768. _minGallop = 0;
  5769. }
  5770. _minGallop += 2;
  5771. }
  5772. minGallop = _minGallop;
  5773. minGallop < 1 && (minGallop = 1);
  5774. if (length1 === 1) {
  5775. for (i = 0; i < length2; i++) {
  5776. array[dest + i] = array[cursor2 + i];
  5777. }
  5778. array[dest + length2] = tmp[cursor1];
  5779. }
  5780. else if (length1 === 0) {
  5781. throw new Error();
  5782. // throw new Error('mergeLow preconditions were not respected');
  5783. }
  5784. else {
  5785. for (i = 0; i < length1; i++) {
  5786. array[dest + i] = tmp[cursor1 + i];
  5787. }
  5788. }
  5789. }
  5790. function mergeHigh(start1, length1, start2, length2) {
  5791. var i = 0;
  5792. for (i = 0; i < length2; i++) {
  5793. tmp[i] = array[start2 + i];
  5794. }
  5795. var cursor1 = start1 + length1 - 1;
  5796. var cursor2 = length2 - 1;
  5797. var dest = start2 + length2 - 1;
  5798. var customCursor = 0;
  5799. var customDest = 0;
  5800. array[dest--] = array[cursor1--];
  5801. if (--length1 === 0) {
  5802. customCursor = dest - (length2 - 1);
  5803. for (i = 0; i < length2; i++) {
  5804. array[customCursor + i] = tmp[i];
  5805. }
  5806. return;
  5807. }
  5808. if (length2 === 1) {
  5809. dest -= length1;
  5810. cursor1 -= length1;
  5811. customDest = dest + 1;
  5812. customCursor = cursor1 + 1;
  5813. for (i = length1 - 1; i >= 0; i--) {
  5814. array[customDest + i] = array[customCursor + i];
  5815. }
  5816. array[dest] = tmp[cursor2];
  5817. return;
  5818. }
  5819. var _minGallop = minGallop;
  5820. while (true) {
  5821. var count1 = 0;
  5822. var count2 = 0;
  5823. var exit = false;
  5824. do {
  5825. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5826. array[dest--] = array[cursor1--];
  5827. count1++;
  5828. count2 = 0;
  5829. if (--length1 === 0) {
  5830. exit = true;
  5831. break;
  5832. }
  5833. }
  5834. else {
  5835. array[dest--] = tmp[cursor2--];
  5836. count2++;
  5837. count1 = 0;
  5838. if (--length2 === 1) {
  5839. exit = true;
  5840. break;
  5841. }
  5842. }
  5843. } while ((count1 | count2) < _minGallop);
  5844. if (exit) {
  5845. break;
  5846. }
  5847. do {
  5848. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5849. if (count1 !== 0) {
  5850. dest -= count1;
  5851. cursor1 -= count1;
  5852. length1 -= count1;
  5853. customDest = dest + 1;
  5854. customCursor = cursor1 + 1;
  5855. for (i = count1 - 1; i >= 0; i--) {
  5856. array[customDest + i] = array[customCursor + i];
  5857. }
  5858. if (length1 === 0) {
  5859. exit = true;
  5860. break;
  5861. }
  5862. }
  5863. array[dest--] = tmp[cursor2--];
  5864. if (--length2 === 1) {
  5865. exit = true;
  5866. break;
  5867. }
  5868. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5869. if (count2 !== 0) {
  5870. dest -= count2;
  5871. cursor2 -= count2;
  5872. length2 -= count2;
  5873. customDest = dest + 1;
  5874. customCursor = cursor2 + 1;
  5875. for (i = 0; i < count2; i++) {
  5876. array[customDest + i] = tmp[customCursor + i];
  5877. }
  5878. if (length2 <= 1) {
  5879. exit = true;
  5880. break;
  5881. }
  5882. }
  5883. array[dest--] = array[cursor1--];
  5884. if (--length1 === 0) {
  5885. exit = true;
  5886. break;
  5887. }
  5888. _minGallop--;
  5889. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5890. if (exit) {
  5891. break;
  5892. }
  5893. if (_minGallop < 0) {
  5894. _minGallop = 0;
  5895. }
  5896. _minGallop += 2;
  5897. }
  5898. minGallop = _minGallop;
  5899. if (minGallop < 1) {
  5900. minGallop = 1;
  5901. }
  5902. if (length2 === 1) {
  5903. dest -= length1;
  5904. cursor1 -= length1;
  5905. customDest = dest + 1;
  5906. customCursor = cursor1 + 1;
  5907. for (i = length1 - 1; i >= 0; i--) {
  5908. array[customDest + i] = array[customCursor + i];
  5909. }
  5910. array[dest] = tmp[cursor2];
  5911. }
  5912. else if (length2 === 0) {
  5913. throw new Error();
  5914. // throw new Error('mergeHigh preconditions were not respected');
  5915. }
  5916. else {
  5917. customCursor = dest - (length2 - 1);
  5918. for (i = 0; i < length2; i++) {
  5919. array[customCursor + i] = tmp[i];
  5920. }
  5921. }
  5922. }
  5923. this.mergeRuns = mergeRuns;
  5924. this.forceMergeRuns = forceMergeRuns;
  5925. this.pushRun = pushRun;
  5926. }
  5927. function sort(array, compare, lo, hi) {
  5928. if (!lo) {
  5929. lo = 0;
  5930. }
  5931. if (!hi) {
  5932. hi = array.length;
  5933. }
  5934. var remaining = hi - lo;
  5935. if (remaining < 2) {
  5936. return;
  5937. }
  5938. var runLength = 0;
  5939. if (remaining < DEFAULT_MIN_MERGE) {
  5940. runLength = makeAscendingRun(array, lo, hi, compare);
  5941. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5942. return;
  5943. }
  5944. var ts = new TimSort(array, compare);
  5945. var minRun = minRunLength(remaining);
  5946. do {
  5947. runLength = makeAscendingRun(array, lo, hi, compare);
  5948. if (runLength < minRun) {
  5949. var force = remaining;
  5950. if (force > minRun) {
  5951. force = minRun;
  5952. }
  5953. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5954. runLength = force;
  5955. }
  5956. ts.pushRun(lo, runLength);
  5957. ts.mergeRuns();
  5958. remaining -= runLength;
  5959. lo += runLength;
  5960. } while (remaining !== 0);
  5961. ts.forceMergeRuns();
  5962. }
  5963. // Use timsort because in most case elements are partially sorted
  5964. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5965. function shapeCompareFunc(a, b) {
  5966. if (a.zlevel === b.zlevel) {
  5967. if (a.z === b.z) {
  5968. // if (a.z2 === b.z2) {
  5969. // // FIXME Slow has renderidx compare
  5970. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5971. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5972. // return a.__renderidx - b.__renderidx;
  5973. // }
  5974. return a.z2 - b.z2;
  5975. }
  5976. return a.z - b.z;
  5977. }
  5978. return a.zlevel - b.zlevel;
  5979. }
  5980. /**
  5981. * 内容仓库 (M)
  5982. * @alias module:zrender/Storage
  5983. * @constructor
  5984. */
  5985. var Storage = function () { // jshint ignore:line
  5986. this._roots = [];
  5987. this._displayList = [];
  5988. this._displayListLen = 0;
  5989. };
  5990. Storage.prototype = {
  5991. constructor: Storage,
  5992. /**
  5993. * @param {Function} cb
  5994. *
  5995. */
  5996. traverse: function (cb, context) {
  5997. for (var i = 0; i < this._roots.length; i++) {
  5998. this._roots[i].traverse(cb, context);
  5999. }
  6000. },
  6001. /**
  6002. * 返回所有图形的绘制队列
  6003. * @param {boolean} [update=false] 是否在返回前更新该数组
  6004. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  6005. *
  6006. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  6007. * @return {Array.<module:zrender/graphic/Displayable>}
  6008. */
  6009. getDisplayList: function (update, includeIgnore) {
  6010. includeIgnore = includeIgnore || false;
  6011. if (update) {
  6012. this.updateDisplayList(includeIgnore);
  6013. }
  6014. return this._displayList;
  6015. },
  6016. /**
  6017. * 更新图形的绘制队列。
  6018. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  6019. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  6020. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  6021. */
  6022. updateDisplayList: function (includeIgnore) {
  6023. this._displayListLen = 0;
  6024. var roots = this._roots;
  6025. var displayList = this._displayList;
  6026. for (var i = 0, len = roots.length; i < len; i++) {
  6027. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  6028. }
  6029. displayList.length = this._displayListLen;
  6030. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  6031. },
  6032. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  6033. if (el.ignore && !includeIgnore) {
  6034. return;
  6035. }
  6036. el.beforeUpdate();
  6037. if (el.__dirty) {
  6038. el.update();
  6039. }
  6040. el.afterUpdate();
  6041. var userSetClipPath = el.clipPath;
  6042. if (userSetClipPath) {
  6043. // FIXME 效率影响
  6044. if (clipPaths) {
  6045. clipPaths = clipPaths.slice();
  6046. }
  6047. else {
  6048. clipPaths = [];
  6049. }
  6050. var currentClipPath = userSetClipPath;
  6051. var parentClipPath = el;
  6052. // Recursively add clip path
  6053. while (currentClipPath) {
  6054. // clipPath 的变换是基于使用这个 clipPath 的元素
  6055. currentClipPath.parent = parentClipPath;
  6056. currentClipPath.updateTransform();
  6057. clipPaths.push(currentClipPath);
  6058. parentClipPath = currentClipPath;
  6059. currentClipPath = currentClipPath.clipPath;
  6060. }
  6061. }
  6062. if (el.isGroup) {
  6063. var children = el._children;
  6064. for (var i = 0; i < children.length; i++) {
  6065. var child = children[i];
  6066. // Force to mark as dirty if group is dirty
  6067. // FIXME __dirtyPath ?
  6068. if (el.__dirty) {
  6069. child.__dirty = true;
  6070. }
  6071. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  6072. }
  6073. // Mark group clean here
  6074. el.__dirty = false;
  6075. }
  6076. else {
  6077. el.__clipPaths = clipPaths;
  6078. this._displayList[this._displayListLen++] = el;
  6079. }
  6080. },
  6081. /**
  6082. * 添加图形(Shape)或者组(Group)到根节点
  6083. * @param {module:zrender/Element} el
  6084. */
  6085. addRoot: function (el) {
  6086. if (el.__storage === this) {
  6087. return;
  6088. }
  6089. if (el instanceof Group) {
  6090. el.addChildrenToStorage(this);
  6091. }
  6092. this.addToStorage(el);
  6093. this._roots.push(el);
  6094. },
  6095. /**
  6096. * 删除指定的图形(Shape)或者组(Group)
  6097. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  6098. */
  6099. delRoot: function (el) {
  6100. if (el == null) {
  6101. // 不指定el清空
  6102. for (var i = 0; i < this._roots.length; i++) {
  6103. var root = this._roots[i];
  6104. if (root instanceof Group) {
  6105. root.delChildrenFromStorage(this);
  6106. }
  6107. }
  6108. this._roots = [];
  6109. this._displayList = [];
  6110. this._displayListLen = 0;
  6111. return;
  6112. }
  6113. if (el instanceof Array) {
  6114. for (var i = 0, l = el.length; i < l; i++) {
  6115. this.delRoot(el[i]);
  6116. }
  6117. return;
  6118. }
  6119. var idx = indexOf(this._roots, el);
  6120. if (idx >= 0) {
  6121. this.delFromStorage(el);
  6122. this._roots.splice(idx, 1);
  6123. if (el instanceof Group) {
  6124. el.delChildrenFromStorage(this);
  6125. }
  6126. }
  6127. },
  6128. addToStorage: function (el) {
  6129. if (el) {
  6130. el.__storage = this;
  6131. el.dirty(false);
  6132. }
  6133. return this;
  6134. },
  6135. delFromStorage: function (el) {
  6136. if (el) {
  6137. el.__storage = null;
  6138. }
  6139. return this;
  6140. },
  6141. /**
  6142. * 清空并且释放Storage
  6143. */
  6144. dispose: function () {
  6145. this._renderList =
  6146. this._roots = null;
  6147. },
  6148. displayableSortFunc: shapeCompareFunc
  6149. };
  6150. var SHADOW_PROPS = {
  6151. 'shadowBlur': 1,
  6152. 'shadowOffsetX': 1,
  6153. 'shadowOffsetY': 1,
  6154. 'textShadowBlur': 1,
  6155. 'textShadowOffsetX': 1,
  6156. 'textShadowOffsetY': 1,
  6157. 'textBoxShadowBlur': 1,
  6158. 'textBoxShadowOffsetX': 1,
  6159. 'textBoxShadowOffsetY': 1
  6160. };
  6161. var fixShadow = function (ctx, propName, value) {
  6162. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  6163. return value *= ctx.dpr;
  6164. }
  6165. return value;
  6166. };
  6167. var ContextCachedBy = {
  6168. NONE: 0,
  6169. STYLE_BIND: 1,
  6170. PLAIN_TEXT: 2
  6171. };
  6172. // Avoid confused with 0/false.
  6173. var WILL_BE_RESTORED = 9;
  6174. var STYLE_COMMON_PROPS = [
  6175. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  6176. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  6177. ];
  6178. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  6179. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  6180. var Style = function (opts) {
  6181. this.extendFrom(opts, false);
  6182. };
  6183. function createLinearGradient(ctx, obj, rect) {
  6184. var x = obj.x == null ? 0 : obj.x;
  6185. var x2 = obj.x2 == null ? 1 : obj.x2;
  6186. var y = obj.y == null ? 0 : obj.y;
  6187. var y2 = obj.y2 == null ? 0 : obj.y2;
  6188. if (!obj.global) {
  6189. x = x * rect.width + rect.x;
  6190. x2 = x2 * rect.width + rect.x;
  6191. y = y * rect.height + rect.y;
  6192. y2 = y2 * rect.height + rect.y;
  6193. }
  6194. // Fix NaN when rect is Infinity
  6195. x = isNaN(x) ? 0 : x;
  6196. x2 = isNaN(x2) ? 1 : x2;
  6197. y = isNaN(y) ? 0 : y;
  6198. y2 = isNaN(y2) ? 0 : y2;
  6199. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  6200. return canvasGradient;
  6201. }
  6202. function createRadialGradient(ctx, obj, rect) {
  6203. var width = rect.width;
  6204. var height = rect.height;
  6205. var min = Math.min(width, height);
  6206. var x = obj.x == null ? 0.5 : obj.x;
  6207. var y = obj.y == null ? 0.5 : obj.y;
  6208. var r = obj.r == null ? 0.5 : obj.r;
  6209. if (!obj.global) {
  6210. x = x * width + rect.x;
  6211. y = y * height + rect.y;
  6212. r = r * min;
  6213. }
  6214. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  6215. return canvasGradient;
  6216. }
  6217. Style.prototype = {
  6218. constructor: Style,
  6219. /**
  6220. * @type {string}
  6221. */
  6222. fill: '#000',
  6223. /**
  6224. * @type {string}
  6225. */
  6226. stroke: null,
  6227. /**
  6228. * @type {number}
  6229. */
  6230. opacity: 1,
  6231. /**
  6232. * @type {number}
  6233. */
  6234. fillOpacity: null,
  6235. /**
  6236. * @type {number}
  6237. */
  6238. strokeOpacity: null,
  6239. /**
  6240. * `true` is not supported.
  6241. * `false`/`null`/`undefined` are the same.
  6242. * `false` is used to remove lineDash in some
  6243. * case that `null`/`undefined` can not be set.
  6244. * (e.g., emphasis.lineStyle in echarts)
  6245. * @type {Array.<number>|boolean}
  6246. */
  6247. lineDash: null,
  6248. /**
  6249. * @type {number}
  6250. */
  6251. lineDashOffset: 0,
  6252. /**
  6253. * @type {number}
  6254. */
  6255. shadowBlur: 0,
  6256. /**
  6257. * @type {number}
  6258. */
  6259. shadowOffsetX: 0,
  6260. /**
  6261. * @type {number}
  6262. */
  6263. shadowOffsetY: 0,
  6264. /**
  6265. * @type {number}
  6266. */
  6267. lineWidth: 1,
  6268. /**
  6269. * If stroke ignore scale
  6270. * @type {Boolean}
  6271. */
  6272. strokeNoScale: false,
  6273. // Bounding rect text configuration
  6274. // Not affected by element transform
  6275. /**
  6276. * @type {string}
  6277. */
  6278. text: null,
  6279. /**
  6280. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  6281. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  6282. * So do not visit it directly in upper application (like echarts),
  6283. * but use `contain/text#makeFont` instead.
  6284. * @type {string}
  6285. */
  6286. font: null,
  6287. /**
  6288. * The same as font. Use font please.
  6289. * @deprecated
  6290. * @type {string}
  6291. */
  6292. textFont: null,
  6293. /**
  6294. * It helps merging respectively, rather than parsing an entire font string.
  6295. * @type {string}
  6296. */
  6297. fontStyle: null,
  6298. /**
  6299. * It helps merging respectively, rather than parsing an entire font string.
  6300. * @type {string}
  6301. */
  6302. fontWeight: null,
  6303. /**
  6304. * It helps merging respectively, rather than parsing an entire font string.
  6305. * Should be 12 but not '12px'.
  6306. * @type {number}
  6307. */
  6308. fontSize: null,
  6309. /**
  6310. * It helps merging respectively, rather than parsing an entire font string.
  6311. * @type {string}
  6312. */
  6313. fontFamily: null,
  6314. /**
  6315. * Reserved for special functinality, like 'hr'.
  6316. * @type {string}
  6317. */
  6318. textTag: null,
  6319. /**
  6320. * @type {string}
  6321. */
  6322. textFill: '#000',
  6323. /**
  6324. * @type {string}
  6325. */
  6326. textStroke: null,
  6327. /**
  6328. * @type {number}
  6329. */
  6330. textWidth: null,
  6331. /**
  6332. * Only for textBackground.
  6333. * @type {number}
  6334. */
  6335. textHeight: null,
  6336. /**
  6337. * textStroke may be set as some color as a default
  6338. * value in upper applicaion, where the default value
  6339. * of textStrokeWidth should be 0 to make sure that
  6340. * user can choose to do not use text stroke.
  6341. * @type {number}
  6342. */
  6343. textStrokeWidth: 0,
  6344. /**
  6345. * @type {number}
  6346. */
  6347. textLineHeight: null,
  6348. /**
  6349. * 'inside', 'left', 'right', 'top', 'bottom'
  6350. * [x, y]
  6351. * Based on x, y of rect.
  6352. * @type {string|Array.<number>}
  6353. * @default 'inside'
  6354. */
  6355. textPosition: 'inside',
  6356. /**
  6357. * If not specified, use the boundingRect of a `displayable`.
  6358. * @type {Object}
  6359. */
  6360. textRect: null,
  6361. /**
  6362. * [x, y]
  6363. * @type {Array.<number>}
  6364. */
  6365. textOffset: null,
  6366. /**
  6367. * @type {string}
  6368. */
  6369. textAlign: null,
  6370. /**
  6371. * @type {string}
  6372. */
  6373. textVerticalAlign: null,
  6374. /**
  6375. * @type {number}
  6376. */
  6377. textDistance: 5,
  6378. /**
  6379. * @type {string}
  6380. */
  6381. textShadowColor: 'transparent',
  6382. /**
  6383. * @type {number}
  6384. */
  6385. textShadowBlur: 0,
  6386. /**
  6387. * @type {number}
  6388. */
  6389. textShadowOffsetX: 0,
  6390. /**
  6391. * @type {number}
  6392. */
  6393. textShadowOffsetY: 0,
  6394. /**
  6395. * @type {string}
  6396. */
  6397. textBoxShadowColor: 'transparent',
  6398. /**
  6399. * @type {number}
  6400. */
  6401. textBoxShadowBlur: 0,
  6402. /**
  6403. * @type {number}
  6404. */
  6405. textBoxShadowOffsetX: 0,
  6406. /**
  6407. * @type {number}
  6408. */
  6409. textBoxShadowOffsetY: 0,
  6410. /**
  6411. * Whether transform text.
  6412. * Only available in Path and Image element,
  6413. * where the text is called as `RectText`.
  6414. * @type {boolean}
  6415. */
  6416. transformText: false,
  6417. /**
  6418. * Text rotate around position of Path or Image.
  6419. * The origin of the rotation can be specified by `textOrigin`.
  6420. * Only available in Path and Image element,
  6421. * where the text is called as `RectText`.
  6422. */
  6423. textRotation: 0,
  6424. /**
  6425. * Text origin of text rotation.
  6426. * Useful in the case like label rotation of circular symbol.
  6427. * Only available in Path and Image element, where the text is called
  6428. * as `RectText` and the element is called as "host element".
  6429. * The value can be:
  6430. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6431. * base on the left-top corner of the rect of its host element.
  6432. * + If specified as a string `center`, it is the center of the rect of
  6433. * its host element.
  6434. * + By default, this origin is the `textPosition`.
  6435. * @type {string|Array.<number>}
  6436. */
  6437. textOrigin: null,
  6438. /**
  6439. * @type {string}
  6440. */
  6441. textBackgroundColor: null,
  6442. /**
  6443. * @type {string}
  6444. */
  6445. textBorderColor: null,
  6446. /**
  6447. * @type {number}
  6448. */
  6449. textBorderWidth: 0,
  6450. /**
  6451. * @type {number}
  6452. */
  6453. textBorderRadius: 0,
  6454. /**
  6455. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6456. * @type {number|Array.<number>}
  6457. */
  6458. textPadding: null,
  6459. /**
  6460. * Text styles for rich text.
  6461. * @type {Object}
  6462. */
  6463. rich: null,
  6464. /**
  6465. * {outerWidth, outerHeight, ellipsis, placeholder}
  6466. * @type {Object}
  6467. */
  6468. truncate: null,
  6469. /**
  6470. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6471. * @type {string}
  6472. */
  6473. blend: null,
  6474. /**
  6475. * @param {CanvasRenderingContext2D} ctx
  6476. */
  6477. bind: function (ctx, el, prevEl) {
  6478. var style = this;
  6479. var prevStyle = prevEl && prevEl.style;
  6480. // If no prevStyle, it means first draw.
  6481. // Only apply cache if the last time cachced by this function.
  6482. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6483. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6484. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6485. var prop = STYLE_COMMON_PROPS[i];
  6486. var styleName = prop[0];
  6487. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6488. // FIXME Invalid property value will cause style leak from previous element.
  6489. ctx[styleName] =
  6490. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6491. }
  6492. }
  6493. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6494. ctx.fillStyle = style.fill;
  6495. }
  6496. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6497. ctx.strokeStyle = style.stroke;
  6498. }
  6499. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6500. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6501. }
  6502. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6503. ctx.globalCompositeOperation = style.blend || 'source-over';
  6504. }
  6505. if (this.hasStroke()) {
  6506. var lineWidth = style.lineWidth;
  6507. ctx.lineWidth = lineWidth / (
  6508. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6509. );
  6510. }
  6511. },
  6512. hasFill: function () {
  6513. var fill = this.fill;
  6514. return fill != null && fill !== 'none';
  6515. },
  6516. hasStroke: function () {
  6517. var stroke = this.stroke;
  6518. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6519. },
  6520. /**
  6521. * Extend from other style
  6522. * @param {zrender/graphic/Style} otherStyle
  6523. * @param {boolean} overwrite true: overwrirte any way.
  6524. * false: overwrite only when !target.hasOwnProperty
  6525. * others: overwrite when property is not null/undefined.
  6526. */
  6527. extendFrom: function (otherStyle, overwrite) {
  6528. if (otherStyle) {
  6529. for (var name in otherStyle) {
  6530. if (otherStyle.hasOwnProperty(name)
  6531. && (overwrite === true
  6532. || (
  6533. overwrite === false
  6534. ? !this.hasOwnProperty(name)
  6535. : otherStyle[name] != null
  6536. )
  6537. )
  6538. ) {
  6539. this[name] = otherStyle[name];
  6540. }
  6541. }
  6542. }
  6543. },
  6544. /**
  6545. * Batch setting style with a given object
  6546. * @param {Object|string} obj
  6547. * @param {*} [obj]
  6548. */
  6549. set: function (obj, value) {
  6550. if (typeof obj === 'string') {
  6551. this[obj] = value;
  6552. }
  6553. else {
  6554. this.extendFrom(obj, true);
  6555. }
  6556. },
  6557. /**
  6558. * Clone
  6559. * @return {zrender/graphic/Style} [description]
  6560. */
  6561. clone: function () {
  6562. var newStyle = new this.constructor();
  6563. newStyle.extendFrom(this, true);
  6564. return newStyle;
  6565. },
  6566. getGradient: function (ctx, obj, rect) {
  6567. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6568. var canvasGradient = method(ctx, obj, rect);
  6569. var colorStops = obj.colorStops;
  6570. for (var i = 0; i < colorStops.length; i++) {
  6571. canvasGradient.addColorStop(
  6572. colorStops[i].offset, colorStops[i].color
  6573. );
  6574. }
  6575. return canvasGradient;
  6576. }
  6577. };
  6578. var styleProto = Style.prototype;
  6579. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6580. var prop = STYLE_COMMON_PROPS[i];
  6581. if (!(prop[0] in styleProto)) {
  6582. styleProto[prop[0]] = prop[1];
  6583. }
  6584. }
  6585. // Provide for others
  6586. Style.getGradient = styleProto.getGradient;
  6587. var Pattern = function (image, repeat) {
  6588. // Should do nothing more in this constructor. Because gradient can be
  6589. // declard by `color: {image: ...}`, where this constructor will not be called.
  6590. this.image = image;
  6591. this.repeat = repeat;
  6592. // Can be cloned
  6593. this.type = 'pattern';
  6594. };
  6595. Pattern.prototype.getCanvasPattern = function (ctx) {
  6596. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6597. };
  6598. /**
  6599. * @module zrender/Layer
  6600. * @author pissang(https://www.github.com/pissang)
  6601. */
  6602. function returnFalse() {
  6603. return false;
  6604. }
  6605. /**
  6606. * 创建dom
  6607. *
  6608. * @inner
  6609. * @param {string} id dom id 待用
  6610. * @param {Painter} painter painter instance
  6611. * @param {number} number
  6612. */
  6613. function createDom(id, painter, dpr) {
  6614. var newDom = createCanvas();
  6615. var width = painter.getWidth();
  6616. var height = painter.getHeight();
  6617. var newDomStyle = newDom.style;
  6618. if (newDomStyle) { // In node or some other non-browser environment
  6619. newDomStyle.position = 'absolute';
  6620. newDomStyle.left = 0;
  6621. newDomStyle.top = 0;
  6622. newDomStyle.width = width + 'px';
  6623. newDomStyle.height = height + 'px';
  6624. newDom.setAttribute('data-zr-dom-id', id);
  6625. }
  6626. newDom.width = width * dpr;
  6627. newDom.height = height * dpr;
  6628. return newDom;
  6629. }
  6630. /**
  6631. * @alias module:zrender/Layer
  6632. * @constructor
  6633. * @extends module:zrender/mixin/Transformable
  6634. * @param {string} id
  6635. * @param {module:zrender/Painter} painter
  6636. * @param {number} [dpr]
  6637. */
  6638. var Layer = function (id, painter, dpr) {
  6639. var dom;
  6640. dpr = dpr || devicePixelRatio;
  6641. if (typeof id === 'string') {
  6642. dom = createDom(id, painter, dpr);
  6643. }
  6644. // Not using isDom because in node it will return false
  6645. else if (isObject$1(id)) {
  6646. dom = id;
  6647. id = dom.id;
  6648. }
  6649. this.id = id;
  6650. this.dom = dom;
  6651. var domStyle = dom.style;
  6652. if (domStyle) { // Not in node
  6653. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6654. domStyle['-webkit-user-select'] = 'none';
  6655. domStyle['user-select'] = 'none';
  6656. domStyle['-webkit-touch-callout'] = 'none';
  6657. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6658. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6659. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6660. domStyle['border-width'] = 0;
  6661. }
  6662. this.domBack = null;
  6663. this.ctxBack = null;
  6664. this.painter = painter;
  6665. this.config = null;
  6666. // Configs
  6667. /**
  6668. * 每次清空画布的颜色
  6669. * @type {string}
  6670. * @default 0
  6671. */
  6672. this.clearColor = 0;
  6673. /**
  6674. * 是否开启动态模糊
  6675. * @type {boolean}
  6676. * @default false
  6677. */
  6678. this.motionBlur = false;
  6679. /**
  6680. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6681. * @type {number}
  6682. * @default 0.7
  6683. */
  6684. this.lastFrameAlpha = 0.7;
  6685. /**
  6686. * Layer dpr
  6687. * @type {number}
  6688. */
  6689. this.dpr = dpr;
  6690. };
  6691. Layer.prototype = {
  6692. constructor: Layer,
  6693. __dirty: true,
  6694. __used: false,
  6695. __drawIndex: 0,
  6696. __startIndex: 0,
  6697. __endIndex: 0,
  6698. incremental: false,
  6699. getElementCount: function () {
  6700. return this.__endIndex - this.__startIndex;
  6701. },
  6702. initContext: function () {
  6703. this.ctx = this.dom.getContext('2d');
  6704. this.ctx.dpr = this.dpr;
  6705. },
  6706. createBackBuffer: function () {
  6707. var dpr = this.dpr;
  6708. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6709. this.ctxBack = this.domBack.getContext('2d');
  6710. if (dpr !== 1) {
  6711. this.ctxBack.scale(dpr, dpr);
  6712. }
  6713. },
  6714. /**
  6715. * @param {number} width
  6716. * @param {number} height
  6717. */
  6718. resize: function (width, height) {
  6719. var dpr = this.dpr;
  6720. var dom = this.dom;
  6721. var domStyle = dom.style;
  6722. var domBack = this.domBack;
  6723. if (domStyle) {
  6724. domStyle.width = width + 'px';
  6725. domStyle.height = height + 'px';
  6726. }
  6727. dom.width = width * dpr;
  6728. dom.height = height * dpr;
  6729. if (domBack) {
  6730. domBack.width = width * dpr;
  6731. domBack.height = height * dpr;
  6732. if (dpr !== 1) {
  6733. this.ctxBack.scale(dpr, dpr);
  6734. }
  6735. }
  6736. },
  6737. /**
  6738. * 清空该层画布
  6739. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6740. * @param {Color} [clearColor]
  6741. */
  6742. clear: function (clearAll, clearColor) {
  6743. var dom = this.dom;
  6744. var ctx = this.ctx;
  6745. var width = dom.width;
  6746. var height = dom.height;
  6747. var clearColor = clearColor || this.clearColor;
  6748. var haveMotionBLur = this.motionBlur && !clearAll;
  6749. var lastFrameAlpha = this.lastFrameAlpha;
  6750. var dpr = this.dpr;
  6751. if (haveMotionBLur) {
  6752. if (!this.domBack) {
  6753. this.createBackBuffer();
  6754. }
  6755. this.ctxBack.globalCompositeOperation = 'copy';
  6756. this.ctxBack.drawImage(
  6757. dom, 0, 0,
  6758. width / dpr,
  6759. height / dpr
  6760. );
  6761. }
  6762. ctx.clearRect(0, 0, width, height);
  6763. if (clearColor && clearColor !== 'transparent') {
  6764. var clearColorGradientOrPattern;
  6765. // Gradient
  6766. if (clearColor.colorStops) {
  6767. // Cache canvas gradient
  6768. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6769. x: 0,
  6770. y: 0,
  6771. width: width,
  6772. height: height
  6773. });
  6774. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6775. }
  6776. // Pattern
  6777. else if (clearColor.image) {
  6778. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6779. }
  6780. ctx.save();
  6781. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6782. ctx.fillRect(0, 0, width, height);
  6783. ctx.restore();
  6784. }
  6785. if (haveMotionBLur) {
  6786. var domBack = this.domBack;
  6787. ctx.save();
  6788. ctx.globalAlpha = lastFrameAlpha;
  6789. ctx.drawImage(domBack, 0, 0, width, height);
  6790. ctx.restore();
  6791. }
  6792. }
  6793. };
  6794. var requestAnimationFrame = (
  6795. typeof window !== 'undefined'
  6796. && (
  6797. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6798. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6799. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6800. || window.mozRequestAnimationFrame
  6801. || window.webkitRequestAnimationFrame
  6802. )
  6803. ) || function (func) {
  6804. setTimeout(func, 16);
  6805. };
  6806. var globalImageCache = new LRU(50);
  6807. /**
  6808. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6809. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6810. */
  6811. function findExistImage(newImageOrSrc) {
  6812. if (typeof newImageOrSrc === 'string') {
  6813. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6814. return cachedImgObj && cachedImgObj.image;
  6815. }
  6816. else {
  6817. return newImageOrSrc;
  6818. }
  6819. }
  6820. /**
  6821. * Caution: User should cache loaded images, but not just count on LRU.
  6822. * Consider if required images more than LRU size, will dead loop occur?
  6823. *
  6824. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6825. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6826. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6827. * @param {Function} [cb] params: (image, cbPayload)
  6828. * @param {Object} [cbPayload] Payload on cb calling.
  6829. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6830. */
  6831. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6832. if (!newImageOrSrc) {
  6833. return image;
  6834. }
  6835. else if (typeof newImageOrSrc === 'string') {
  6836. // Image should not be loaded repeatly.
  6837. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6838. return image;
  6839. }
  6840. // Only when there is no existent image or existent image src
  6841. // is different, this method is responsible for load.
  6842. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6843. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6844. if (cachedImgObj) {
  6845. image = cachedImgObj.image;
  6846. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6847. }
  6848. else {
  6849. image = new Image();
  6850. image.onload = image.onerror = imageOnLoad;
  6851. globalImageCache.put(
  6852. newImageOrSrc,
  6853. image.__cachedImgObj = {
  6854. image: image,
  6855. pending: [pendingWrap]
  6856. }
  6857. );
  6858. image.src = image.__zrImageSrc = newImageOrSrc;
  6859. }
  6860. return image;
  6861. }
  6862. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6863. else {
  6864. return newImageOrSrc;
  6865. }
  6866. }
  6867. function imageOnLoad() {
  6868. var cachedImgObj = this.__cachedImgObj;
  6869. this.onload = this.onerror = this.__cachedImgObj = null;
  6870. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6871. var pendingWrap = cachedImgObj.pending[i];
  6872. var cb = pendingWrap.cb;
  6873. cb && cb(this, pendingWrap.cbPayload);
  6874. pendingWrap.hostEl.dirty();
  6875. }
  6876. cachedImgObj.pending.length = 0;
  6877. }
  6878. function isImageReady(image) {
  6879. return image && image.width && image.height;
  6880. }
  6881. var textWidthCache = {};
  6882. var textWidthCacheCounter = 0;
  6883. var TEXT_CACHE_MAX = 5000;
  6884. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6885. var DEFAULT_FONT$1 = '12px sans-serif';
  6886. // Avoid assign to an exported variable, for transforming to cjs.
  6887. var methods$1 = {};
  6888. function $override$1(name, fn) {
  6889. methods$1[name] = fn;
  6890. }
  6891. /**
  6892. * @public
  6893. * @param {string} text
  6894. * @param {string} font
  6895. * @return {number} width
  6896. */
  6897. function getWidth(text, font) {
  6898. font = font || DEFAULT_FONT$1;
  6899. var key = text + ':' + font;
  6900. if (textWidthCache[key]) {
  6901. return textWidthCache[key];
  6902. }
  6903. var textLines = (text + '').split('\n');
  6904. var width = 0;
  6905. for (var i = 0, l = textLines.length; i < l; i++) {
  6906. // textContain.measureText may be overrided in SVG or VML
  6907. width = Math.max(measureText(textLines[i], font).width, width);
  6908. }
  6909. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6910. textWidthCacheCounter = 0;
  6911. textWidthCache = {};
  6912. }
  6913. textWidthCacheCounter++;
  6914. textWidthCache[key] = width;
  6915. return width;
  6916. }
  6917. /**
  6918. * @public
  6919. * @param {string} text
  6920. * @param {string} font
  6921. * @param {string} [textAlign='left']
  6922. * @param {string} [textVerticalAlign='top']
  6923. * @param {Array.<number>} [textPadding]
  6924. * @param {Object} [rich]
  6925. * @param {Object} [truncate]
  6926. * @return {Object} {x, y, width, height, lineHeight}
  6927. */
  6928. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6929. return rich
  6930. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6931. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6932. }
  6933. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6934. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6935. var outerWidth = getWidth(text, font);
  6936. if (textPadding) {
  6937. outerWidth += textPadding[1] + textPadding[3];
  6938. }
  6939. var outerHeight = contentBlock.outerHeight;
  6940. var x = adjustTextX(0, outerWidth, textAlign);
  6941. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6942. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6943. rect.lineHeight = contentBlock.lineHeight;
  6944. return rect;
  6945. }
  6946. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6947. var contentBlock = parseRichText(text, {
  6948. rich: rich,
  6949. truncate: truncate,
  6950. font: font,
  6951. textAlign: textAlign,
  6952. textPadding: textPadding,
  6953. textLineHeight: textLineHeight
  6954. });
  6955. var outerWidth = contentBlock.outerWidth;
  6956. var outerHeight = contentBlock.outerHeight;
  6957. var x = adjustTextX(0, outerWidth, textAlign);
  6958. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6959. return new BoundingRect(x, y, outerWidth, outerHeight);
  6960. }
  6961. /**
  6962. * @public
  6963. * @param {number} x
  6964. * @param {number} width
  6965. * @param {string} [textAlign='left']
  6966. * @return {number} Adjusted x.
  6967. */
  6968. function adjustTextX(x, width, textAlign) {
  6969. // FIXME Right to left language
  6970. if (textAlign === 'right') {
  6971. x -= width;
  6972. }
  6973. else if (textAlign === 'center') {
  6974. x -= width / 2;
  6975. }
  6976. return x;
  6977. }
  6978. /**
  6979. * @public
  6980. * @param {number} y
  6981. * @param {number} height
  6982. * @param {string} [textVerticalAlign='top']
  6983. * @return {number} Adjusted y.
  6984. */
  6985. function adjustTextY(y, height, textVerticalAlign) {
  6986. if (textVerticalAlign === 'middle') {
  6987. y -= height / 2;
  6988. }
  6989. else if (textVerticalAlign === 'bottom') {
  6990. y -= height;
  6991. }
  6992. return y;
  6993. }
  6994. /**
  6995. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6996. * @public
  6997. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6998. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6999. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  7000. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  7001. */
  7002. function calculateTextPosition(out, style, rect) {
  7003. var textPosition = style.textPosition;
  7004. var distance = style.textDistance;
  7005. var x = rect.x;
  7006. var y = rect.y;
  7007. distance = distance || 0;
  7008. var height = rect.height;
  7009. var width = rect.width;
  7010. var halfHeight = height / 2;
  7011. var textAlign = 'left';
  7012. var textVerticalAlign = 'top';
  7013. switch (textPosition) {
  7014. case 'left':
  7015. x -= distance;
  7016. y += halfHeight;
  7017. textAlign = 'right';
  7018. textVerticalAlign = 'middle';
  7019. break;
  7020. case 'right':
  7021. x += distance + width;
  7022. y += halfHeight;
  7023. textVerticalAlign = 'middle';
  7024. break;
  7025. case 'top':
  7026. x += width / 2;
  7027. y -= distance;
  7028. textAlign = 'center';
  7029. textVerticalAlign = 'bottom';
  7030. break;
  7031. case 'bottom':
  7032. x += width / 2;
  7033. y += height + distance;
  7034. textAlign = 'center';
  7035. break;
  7036. case 'inside':
  7037. x += width / 2;
  7038. y += halfHeight;
  7039. textAlign = 'center';
  7040. textVerticalAlign = 'middle';
  7041. break;
  7042. case 'insideLeft':
  7043. x += distance;
  7044. y += halfHeight;
  7045. textVerticalAlign = 'middle';
  7046. break;
  7047. case 'insideRight':
  7048. x += width - distance;
  7049. y += halfHeight;
  7050. textAlign = 'right';
  7051. textVerticalAlign = 'middle';
  7052. break;
  7053. case 'insideTop':
  7054. x += width / 2;
  7055. y += distance;
  7056. textAlign = 'center';
  7057. break;
  7058. case 'insideBottom':
  7059. x += width / 2;
  7060. y += height - distance;
  7061. textAlign = 'center';
  7062. textVerticalAlign = 'bottom';
  7063. break;
  7064. case 'insideTopLeft':
  7065. x += distance;
  7066. y += distance;
  7067. break;
  7068. case 'insideTopRight':
  7069. x += width - distance;
  7070. y += distance;
  7071. textAlign = 'right';
  7072. break;
  7073. case 'insideBottomLeft':
  7074. x += distance;
  7075. y += height - distance;
  7076. textVerticalAlign = 'bottom';
  7077. break;
  7078. case 'insideBottomRight':
  7079. x += width - distance;
  7080. y += height - distance;
  7081. textAlign = 'right';
  7082. textVerticalAlign = 'bottom';
  7083. break;
  7084. }
  7085. out = out || {};
  7086. out.x = x;
  7087. out.y = y;
  7088. out.textAlign = textAlign;
  7089. out.textVerticalAlign = textVerticalAlign;
  7090. return out;
  7091. }
  7092. /**
  7093. * To be removed. But still do not remove in case that some one has imported it.
  7094. * @deprecated
  7095. * @public
  7096. * @param {stirng} textPosition
  7097. * @param {Object} rect {x, y, width, height}
  7098. * @param {number} distance
  7099. * @return {Object} {x, y, textAlign, textVerticalAlign}
  7100. */
  7101. /**
  7102. * Show ellipsis if overflow.
  7103. *
  7104. * @public
  7105. * @param {string} text
  7106. * @param {string} containerWidth
  7107. * @param {string} font
  7108. * @param {number} [ellipsis='...']
  7109. * @param {Object} [options]
  7110. * @param {number} [options.maxIterations=3]
  7111. * @param {number} [options.minChar=0] If truncate result are less
  7112. * then minChar, ellipsis will not show, which is
  7113. * better for user hint in some cases.
  7114. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  7115. * @return {string}
  7116. */
  7117. function truncateText(text, containerWidth, font, ellipsis, options) {
  7118. if (!containerWidth) {
  7119. return '';
  7120. }
  7121. var textLines = (text + '').split('\n');
  7122. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  7123. // FIXME
  7124. // It is not appropriate that every line has '...' when truncate multiple lines.
  7125. for (var i = 0, len = textLines.length; i < len; i++) {
  7126. textLines[i] = truncateSingleLine(textLines[i], options);
  7127. }
  7128. return textLines.join('\n');
  7129. }
  7130. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  7131. options = extend({}, options);
  7132. options.font = font;
  7133. var ellipsis = retrieve2(ellipsis, '...');
  7134. options.maxIterations = retrieve2(options.maxIterations, 2);
  7135. var minChar = options.minChar = retrieve2(options.minChar, 0);
  7136. // FIXME
  7137. // Other languages?
  7138. options.cnCharWidth = getWidth('国', font);
  7139. // FIXME
  7140. // Consider proportional font?
  7141. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  7142. options.placeholder = retrieve2(options.placeholder, '');
  7143. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  7144. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  7145. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  7146. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  7147. contentWidth -= ascCharWidth;
  7148. }
  7149. var ellipsisWidth = getWidth(ellipsis, font);
  7150. if (ellipsisWidth > contentWidth) {
  7151. ellipsis = '';
  7152. ellipsisWidth = 0;
  7153. }
  7154. contentWidth = containerWidth - ellipsisWidth;
  7155. options.ellipsis = ellipsis;
  7156. options.ellipsisWidth = ellipsisWidth;
  7157. options.contentWidth = contentWidth;
  7158. options.containerWidth = containerWidth;
  7159. return options;
  7160. }
  7161. function truncateSingleLine(textLine, options) {
  7162. var containerWidth = options.containerWidth;
  7163. var font = options.font;
  7164. var contentWidth = options.contentWidth;
  7165. if (!containerWidth) {
  7166. return '';
  7167. }
  7168. var lineWidth = getWidth(textLine, font);
  7169. if (lineWidth <= containerWidth) {
  7170. return textLine;
  7171. }
  7172. for (var j = 0; ; j++) {
  7173. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  7174. textLine += options.ellipsis;
  7175. break;
  7176. }
  7177. var subLength = j === 0
  7178. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  7179. : lineWidth > 0
  7180. ? Math.floor(textLine.length * contentWidth / lineWidth)
  7181. : 0;
  7182. textLine = textLine.substr(0, subLength);
  7183. lineWidth = getWidth(textLine, font);
  7184. }
  7185. if (textLine === '') {
  7186. textLine = options.placeholder;
  7187. }
  7188. return textLine;
  7189. }
  7190. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  7191. var width = 0;
  7192. var i = 0;
  7193. for (var len = text.length; i < len && width < contentWidth; i++) {
  7194. var charCode = text.charCodeAt(i);
  7195. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  7196. }
  7197. return i;
  7198. }
  7199. /**
  7200. * @public
  7201. * @param {string} font
  7202. * @return {number} line height
  7203. */
  7204. function getLineHeight(font) {
  7205. // FIXME A rough approach.
  7206. return getWidth('国', font);
  7207. }
  7208. /**
  7209. * @public
  7210. * @param {string} text
  7211. * @param {string} font
  7212. * @return {Object} width
  7213. */
  7214. function measureText(text, font) {
  7215. return methods$1.measureText(text, font);
  7216. }
  7217. // Avoid assign to an exported variable, for transforming to cjs.
  7218. methods$1.measureText = function (text, font) {
  7219. var ctx = getContext();
  7220. ctx.font = font || DEFAULT_FONT$1;
  7221. return ctx.measureText(text);
  7222. };
  7223. /**
  7224. * @public
  7225. * @param {string} text
  7226. * @param {string} font
  7227. * @param {Object} [truncate]
  7228. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  7229. * Notice: for performance, do not calculate outerWidth util needed.
  7230. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  7231. * Thus we can simply comparing the `input` text to determin whether the result changed,
  7232. * without travel the result `lines`.
  7233. */
  7234. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  7235. text != null && (text += '');
  7236. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  7237. var lines = text ? text.split('\n') : [];
  7238. var height = lines.length * lineHeight;
  7239. var outerHeight = height;
  7240. var canCacheByTextString = true;
  7241. if (padding) {
  7242. outerHeight += padding[0] + padding[2];
  7243. }
  7244. if (text && truncate) {
  7245. canCacheByTextString = false;
  7246. var truncOuterHeight = truncate.outerHeight;
  7247. var truncOuterWidth = truncate.outerWidth;
  7248. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  7249. text = '';
  7250. lines = [];
  7251. }
  7252. else if (truncOuterWidth != null) {
  7253. var options = prepareTruncateOptions(
  7254. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  7255. font,
  7256. truncate.ellipsis,
  7257. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  7258. );
  7259. // FIXME
  7260. // It is not appropriate that every line has '...' when truncate multiple lines.
  7261. for (var i = 0, len = lines.length; i < len; i++) {
  7262. lines[i] = truncateSingleLine(lines[i], options);
  7263. }
  7264. }
  7265. }
  7266. return {
  7267. lines: lines,
  7268. height: height,
  7269. outerHeight: outerHeight,
  7270. lineHeight: lineHeight,
  7271. canCacheByTextString: canCacheByTextString
  7272. };
  7273. }
  7274. /**
  7275. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  7276. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  7277. *
  7278. * @public
  7279. * @param {string} text
  7280. * @param {Object} style
  7281. * @return {Object} block
  7282. * {
  7283. * width,
  7284. * height,
  7285. * lines: [{
  7286. * lineHeight,
  7287. * width,
  7288. * tokens: [[{
  7289. * styleName,
  7290. * text,
  7291. * width, // include textPadding
  7292. * height, // include textPadding
  7293. * textWidth, // pure text width
  7294. * textHeight, // pure text height
  7295. * lineHeihgt,
  7296. * font,
  7297. * textAlign,
  7298. * textVerticalAlign
  7299. * }], [...], ...]
  7300. * }, ...]
  7301. * }
  7302. * If styleName is undefined, it is plain text.
  7303. */
  7304. function parseRichText(text, style) {
  7305. var contentBlock = {lines: [], width: 0, height: 0};
  7306. text != null && (text += '');
  7307. if (!text) {
  7308. return contentBlock;
  7309. }
  7310. var lastIndex = STYLE_REG.lastIndex = 0;
  7311. var result;
  7312. while ((result = STYLE_REG.exec(text)) != null) {
  7313. var matchedIndex = result.index;
  7314. if (matchedIndex > lastIndex) {
  7315. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  7316. }
  7317. pushTokens(contentBlock, result[2], result[1]);
  7318. lastIndex = STYLE_REG.lastIndex;
  7319. }
  7320. if (lastIndex < text.length) {
  7321. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  7322. }
  7323. var lines = contentBlock.lines;
  7324. var contentHeight = 0;
  7325. var contentWidth = 0;
  7326. // For `textWidth: 100%`
  7327. var pendingList = [];
  7328. var stlPadding = style.textPadding;
  7329. var truncate = style.truncate;
  7330. var truncateWidth = truncate && truncate.outerWidth;
  7331. var truncateHeight = truncate && truncate.outerHeight;
  7332. if (stlPadding) {
  7333. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  7334. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  7335. }
  7336. // Calculate layout info of tokens.
  7337. for (var i = 0; i < lines.length; i++) {
  7338. var line = lines[i];
  7339. var lineHeight = 0;
  7340. var lineWidth = 0;
  7341. for (var j = 0; j < line.tokens.length; j++) {
  7342. var token = line.tokens[j];
  7343. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  7344. // textPadding should not inherit from style.
  7345. var textPadding = token.textPadding = tokenStyle.textPadding;
  7346. // textFont has been asigned to font by `normalizeStyle`.
  7347. var font = token.font = tokenStyle.font || style.font;
  7348. // textHeight can be used when textVerticalAlign is specified in token.
  7349. var tokenHeight = token.textHeight = retrieve2(
  7350. // textHeight should not be inherited, consider it can be specified
  7351. // as box height of the block.
  7352. tokenStyle.textHeight, getLineHeight(font)
  7353. );
  7354. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  7355. token.height = tokenHeight;
  7356. token.lineHeight = retrieve3(
  7357. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  7358. );
  7359. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  7360. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  7361. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  7362. return {lines: [], width: 0, height: 0};
  7363. }
  7364. token.textWidth = getWidth(token.text, font);
  7365. var tokenWidth = tokenStyle.textWidth;
  7366. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  7367. // Percent width, can be `100%`, can be used in drawing separate
  7368. // line when box width is needed to be auto.
  7369. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7370. token.percentWidth = tokenWidth;
  7371. pendingList.push(token);
  7372. tokenWidth = 0;
  7373. // Do not truncate in this case, because there is no user case
  7374. // and it is too complicated.
  7375. }
  7376. else {
  7377. if (tokenWidthNotSpecified) {
  7378. tokenWidth = token.textWidth;
  7379. // FIXME: If image is not loaded and textWidth is not specified, calling
  7380. // `getBoundingRect()` will not get correct result.
  7381. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7382. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7383. // Use cases:
  7384. // (1) If image is not loaded, it will be loaded at render phase and call
  7385. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7386. // image, and then the right size will be calculated here at the next tick.
  7387. // See `graphic/helper/text.js`.
  7388. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7389. // use `imageHelper.findExistImage` to find cached image.
  7390. // `imageHelper.findExistImage` will always be called here before
  7391. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7392. // which ensures that image will not be rendered before correct size calcualted.
  7393. if (bgImg) {
  7394. bgImg = findExistImage(bgImg);
  7395. if (isImageReady(bgImg)) {
  7396. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7397. }
  7398. }
  7399. }
  7400. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7401. tokenWidth += paddingW;
  7402. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7403. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7404. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7405. token.text = '';
  7406. token.textWidth = tokenWidth = 0;
  7407. }
  7408. else {
  7409. token.text = truncateText(
  7410. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7411. {minChar: truncate.minChar}
  7412. );
  7413. token.textWidth = getWidth(token.text, font);
  7414. tokenWidth = token.textWidth + paddingW;
  7415. }
  7416. }
  7417. }
  7418. lineWidth += (token.width = tokenWidth);
  7419. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7420. }
  7421. line.width = lineWidth;
  7422. line.lineHeight = lineHeight;
  7423. contentHeight += lineHeight;
  7424. contentWidth = Math.max(contentWidth, lineWidth);
  7425. }
  7426. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7427. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7428. if (stlPadding) {
  7429. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7430. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7431. }
  7432. for (var i = 0; i < pendingList.length; i++) {
  7433. var token = pendingList[i];
  7434. var percentWidth = token.percentWidth;
  7435. // Should not base on outerWidth, because token can not be placed out of padding.
  7436. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7437. }
  7438. return contentBlock;
  7439. }
  7440. function pushTokens(block, str, styleName) {
  7441. var isEmptyStr = str === '';
  7442. var strs = str.split('\n');
  7443. var lines = block.lines;
  7444. for (var i = 0; i < strs.length; i++) {
  7445. var text = strs[i];
  7446. var token = {
  7447. styleName: styleName,
  7448. text: text,
  7449. isLineHolder: !text && !isEmptyStr
  7450. };
  7451. // The first token should be appended to the last line.
  7452. if (!i) {
  7453. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7454. // Consider cases:
  7455. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7456. // (which is a placeholder) should be replaced by new token.
  7457. // (2) A image backage, where token likes {a|}.
  7458. // (3) A redundant '' will affect textAlign in line.
  7459. // (4) tokens with the same tplName should not be merged, because
  7460. // they should be displayed in different box (with border and padding).
  7461. var tokensLen = tokens.length;
  7462. (tokensLen === 1 && tokens[0].isLineHolder)
  7463. ? (tokens[0] = token)
  7464. // Consider text is '', only insert when it is the "lineHolder" or
  7465. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7466. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7467. }
  7468. // Other tokens always start a new line.
  7469. else {
  7470. // If there is '', insert it as a placeholder.
  7471. lines.push({tokens: [token]});
  7472. }
  7473. }
  7474. }
  7475. function makeFont(style) {
  7476. // FIXME in node-canvas fontWeight is before fontStyle
  7477. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7478. var font = (style.fontSize || style.fontFamily) && [
  7479. style.fontStyle,
  7480. style.fontWeight,
  7481. (style.fontSize || 12) + 'px',
  7482. // If font properties are defined, `fontFamily` should not be ignored.
  7483. style.fontFamily || 'sans-serif'
  7484. ].join(' ');
  7485. return font && trim(font) || style.textFont || style.font;
  7486. }
  7487. /**
  7488. * @param {Object} ctx
  7489. * @param {Object} shape
  7490. * @param {number} shape.x
  7491. * @param {number} shape.y
  7492. * @param {number} shape.width
  7493. * @param {number} shape.height
  7494. * @param {number} shape.r
  7495. */
  7496. function buildPath(ctx, shape) {
  7497. var x = shape.x;
  7498. var y = shape.y;
  7499. var width = shape.width;
  7500. var height = shape.height;
  7501. var r = shape.r;
  7502. var r1;
  7503. var r2;
  7504. var r3;
  7505. var r4;
  7506. // Convert width and height to positive for better borderRadius
  7507. if (width < 0) {
  7508. x = x + width;
  7509. width = -width;
  7510. }
  7511. if (height < 0) {
  7512. y = y + height;
  7513. height = -height;
  7514. }
  7515. if (typeof r === 'number') {
  7516. r1 = r2 = r3 = r4 = r;
  7517. }
  7518. else if (r instanceof Array) {
  7519. if (r.length === 1) {
  7520. r1 = r2 = r3 = r4 = r[0];
  7521. }
  7522. else if (r.length === 2) {
  7523. r1 = r3 = r[0];
  7524. r2 = r4 = r[1];
  7525. }
  7526. else if (r.length === 3) {
  7527. r1 = r[0];
  7528. r2 = r4 = r[1];
  7529. r3 = r[2];
  7530. }
  7531. else {
  7532. r1 = r[0];
  7533. r2 = r[1];
  7534. r3 = r[2];
  7535. r4 = r[3];
  7536. }
  7537. }
  7538. else {
  7539. r1 = r2 = r3 = r4 = 0;
  7540. }
  7541. var total;
  7542. if (r1 + r2 > width) {
  7543. total = r1 + r2;
  7544. r1 *= width / total;
  7545. r2 *= width / total;
  7546. }
  7547. if (r3 + r4 > width) {
  7548. total = r3 + r4;
  7549. r3 *= width / total;
  7550. r4 *= width / total;
  7551. }
  7552. if (r2 + r3 > height) {
  7553. total = r2 + r3;
  7554. r2 *= height / total;
  7555. r3 *= height / total;
  7556. }
  7557. if (r1 + r4 > height) {
  7558. total = r1 + r4;
  7559. r1 *= height / total;
  7560. r4 *= height / total;
  7561. }
  7562. ctx.moveTo(x + r1, y);
  7563. ctx.lineTo(x + width - r2, y);
  7564. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7565. ctx.lineTo(x + width, y + height - r3);
  7566. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7567. ctx.lineTo(x + r4, y + height);
  7568. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7569. ctx.lineTo(x, y + r1);
  7570. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7571. }
  7572. var DEFAULT_FONT = DEFAULT_FONT$1;
  7573. // TODO: Have not support 'start', 'end' yet.
  7574. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7575. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7576. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7577. // the default value of shadowColor is `'transparent'`.
  7578. var SHADOW_STYLE_COMMON_PROPS = [
  7579. ['textShadowBlur', 'shadowBlur', 0],
  7580. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7581. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7582. ['textShadowColor', 'shadowColor', 'transparent']
  7583. ];
  7584. var _tmpTextPositionResult = {};
  7585. var _tmpBoxPositionResult = {};
  7586. /**
  7587. * @param {module:zrender/graphic/Style} style
  7588. * @return {module:zrender/graphic/Style} The input style.
  7589. */
  7590. function normalizeTextStyle(style) {
  7591. normalizeStyle(style);
  7592. each$1(style.rich, normalizeStyle);
  7593. return style;
  7594. }
  7595. function normalizeStyle(style) {
  7596. if (style) {
  7597. style.font = makeFont(style);
  7598. var textAlign = style.textAlign;
  7599. textAlign === 'middle' && (textAlign = 'center');
  7600. style.textAlign = (
  7601. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7602. ) ? textAlign : 'left';
  7603. // Compatible with textBaseline.
  7604. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7605. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7606. style.textVerticalAlign = (
  7607. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7608. ) ? textVerticalAlign : 'top';
  7609. var textPadding = style.textPadding;
  7610. if (textPadding) {
  7611. style.textPadding = normalizeCssArray(style.textPadding);
  7612. }
  7613. }
  7614. }
  7615. /**
  7616. * @param {CanvasRenderingContext2D} ctx
  7617. * @param {string} text
  7618. * @param {module:zrender/graphic/Style} style
  7619. * @param {Object|boolean} [rect] {x, y, width, height}
  7620. * If set false, rect text is not used.
  7621. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7622. */
  7623. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7624. style.rich
  7625. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7626. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7627. }
  7628. // Avoid setting to ctx according to prevEl if possible for
  7629. // performance in scenarios of large amount text.
  7630. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7631. 'use strict';
  7632. var needDrawBg = needDrawBackground(style);
  7633. var prevStyle;
  7634. var checkCache = false;
  7635. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7636. // Only take and check cache for `Text` el, but not RectText.
  7637. if (prevEl !== WILL_BE_RESTORED) {
  7638. if (prevEl) {
  7639. prevStyle = prevEl.style;
  7640. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7641. }
  7642. // Prevent from using cache in `Style::bind`, because of the case:
  7643. // ctx property is modified by other properties than `Style::bind`
  7644. // used, and Style::bind is called next.
  7645. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7646. }
  7647. // Since this will be restored, prevent from using these props to check cache in the next
  7648. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7649. else if (cachedByMe) {
  7650. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7651. }
  7652. var styleFont = style.font || DEFAULT_FONT;
  7653. // PENDING
  7654. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7655. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7656. // But layer save/restore needed to be considered.
  7657. // if (styleFont !== ctx.__fontCache) {
  7658. // ctx.font = styleFont;
  7659. // if (prevEl !== WILL_BE_RESTORED) {
  7660. // ctx.__fontCache = styleFont;
  7661. // }
  7662. // }
  7663. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7664. ctx.font = styleFont;
  7665. }
  7666. // Use the final font from context-2d, because the final
  7667. // font might not be the style.font when it is illegal.
  7668. // But get `ctx.font` might be time consuming.
  7669. var computedFont = hostEl.__computedFont;
  7670. if (hostEl.__styleFont !== styleFont) {
  7671. hostEl.__styleFont = styleFont;
  7672. computedFont = hostEl.__computedFont = ctx.font;
  7673. }
  7674. var textPadding = style.textPadding;
  7675. var textLineHeight = style.textLineHeight;
  7676. var contentBlock = hostEl.__textCotentBlock;
  7677. if (!contentBlock || hostEl.__dirtyText) {
  7678. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7679. text, computedFont, textPadding, textLineHeight, style.truncate
  7680. );
  7681. }
  7682. var outerHeight = contentBlock.outerHeight;
  7683. var textLines = contentBlock.lines;
  7684. var lineHeight = contentBlock.lineHeight;
  7685. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7686. var baseX = boxPos.baseX;
  7687. var baseY = boxPos.baseY;
  7688. var textAlign = boxPos.textAlign || 'left';
  7689. var textVerticalAlign = boxPos.textVerticalAlign;
  7690. // Origin of textRotation should be the base point of text drawing.
  7691. applyTextRotation(ctx, style, rect, baseX, baseY);
  7692. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7693. var textX = baseX;
  7694. var textY = boxY;
  7695. if (needDrawBg || textPadding) {
  7696. // Consider performance, do not call getTextWidth util necessary.
  7697. var textWidth = getWidth(text, computedFont);
  7698. var outerWidth = textWidth;
  7699. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7700. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7701. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7702. if (textPadding) {
  7703. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7704. textY += textPadding[0];
  7705. }
  7706. }
  7707. // Always set textAlign and textBase line, because it is difficute to calculate
  7708. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7709. // font set happened.
  7710. ctx.textAlign = textAlign;
  7711. // Force baseline to be "middle". Otherwise, if using "top", the
  7712. // text will offset downward a little bit in font "Microsoft YaHei".
  7713. ctx.textBaseline = 'middle';
  7714. // Set text opacity
  7715. ctx.globalAlpha = style.opacity || 1;
  7716. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7717. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7718. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7719. var styleProp = propItem[0];
  7720. var ctxProp = propItem[1];
  7721. var val = style[styleProp];
  7722. if (!checkCache || val !== prevStyle[styleProp]) {
  7723. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7724. }
  7725. }
  7726. // `textBaseline` is set as 'middle'.
  7727. textY += lineHeight / 2;
  7728. var textStrokeWidth = style.textStrokeWidth;
  7729. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7730. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7731. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7732. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7733. var textFill = getFill(style.textFill);
  7734. if (textStroke) {
  7735. if (strokeWidthChanged) {
  7736. ctx.lineWidth = textStrokeWidth;
  7737. }
  7738. if (strokeChanged) {
  7739. ctx.strokeStyle = textStroke;
  7740. }
  7741. }
  7742. if (textFill) {
  7743. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7744. ctx.fillStyle = textFill;
  7745. }
  7746. }
  7747. // Optimize simply, in most cases only one line exists.
  7748. if (textLines.length === 1) {
  7749. // Fill after stroke so the outline will not cover the main part.
  7750. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7751. textFill && ctx.fillText(textLines[0], textX, textY);
  7752. }
  7753. else {
  7754. for (var i = 0; i < textLines.length; i++) {
  7755. // Fill after stroke so the outline will not cover the main part.
  7756. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7757. textFill && ctx.fillText(textLines[i], textX, textY);
  7758. textY += lineHeight;
  7759. }
  7760. }
  7761. }
  7762. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7763. // Do not do cache for rich text because of the complexity.
  7764. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7765. if (prevEl !== WILL_BE_RESTORED) {
  7766. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7767. }
  7768. var contentBlock = hostEl.__textCotentBlock;
  7769. if (!contentBlock || hostEl.__dirtyText) {
  7770. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7771. }
  7772. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7773. }
  7774. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7775. var contentWidth = contentBlock.width;
  7776. var outerWidth = contentBlock.outerWidth;
  7777. var outerHeight = contentBlock.outerHeight;
  7778. var textPadding = style.textPadding;
  7779. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7780. var baseX = boxPos.baseX;
  7781. var baseY = boxPos.baseY;
  7782. var textAlign = boxPos.textAlign;
  7783. var textVerticalAlign = boxPos.textVerticalAlign;
  7784. // Origin of textRotation should be the base point of text drawing.
  7785. applyTextRotation(ctx, style, rect, baseX, baseY);
  7786. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7787. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7788. var xLeft = boxX;
  7789. var lineTop = boxY;
  7790. if (textPadding) {
  7791. xLeft += textPadding[3];
  7792. lineTop += textPadding[0];
  7793. }
  7794. var xRight = xLeft + contentWidth;
  7795. needDrawBackground(style) && drawBackground(
  7796. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7797. );
  7798. for (var i = 0; i < contentBlock.lines.length; i++) {
  7799. var line = contentBlock.lines[i];
  7800. var tokens = line.tokens;
  7801. var tokenCount = tokens.length;
  7802. var lineHeight = line.lineHeight;
  7803. var usedWidth = line.width;
  7804. var leftIndex = 0;
  7805. var lineXLeft = xLeft;
  7806. var lineXRight = xRight;
  7807. var rightIndex = tokenCount - 1;
  7808. var token;
  7809. while (
  7810. leftIndex < tokenCount
  7811. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7812. ) {
  7813. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7814. usedWidth -= token.width;
  7815. lineXLeft += token.width;
  7816. leftIndex++;
  7817. }
  7818. while (
  7819. rightIndex >= 0
  7820. && (token = tokens[rightIndex], token.textAlign === 'right')
  7821. ) {
  7822. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7823. usedWidth -= token.width;
  7824. lineXRight -= token.width;
  7825. rightIndex--;
  7826. }
  7827. // The other tokens are placed as textAlign 'center' if there is enough space.
  7828. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7829. while (leftIndex <= rightIndex) {
  7830. token = tokens[leftIndex];
  7831. // Consider width specified by user, use 'center' rather than 'left'.
  7832. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7833. lineXLeft += token.width;
  7834. leftIndex++;
  7835. }
  7836. lineTop += lineHeight;
  7837. }
  7838. }
  7839. function applyTextRotation(ctx, style, rect, x, y) {
  7840. // textRotation only apply in RectText.
  7841. if (rect && style.textRotation) {
  7842. var origin = style.textOrigin;
  7843. if (origin === 'center') {
  7844. x = rect.width / 2 + rect.x;
  7845. y = rect.height / 2 + rect.y;
  7846. }
  7847. else if (origin) {
  7848. x = origin[0] + rect.x;
  7849. y = origin[1] + rect.y;
  7850. }
  7851. ctx.translate(x, y);
  7852. // Positive: anticlockwise
  7853. ctx.rotate(-style.textRotation);
  7854. ctx.translate(-x, -y);
  7855. }
  7856. }
  7857. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7858. var tokenStyle = style.rich[token.styleName] || {};
  7859. tokenStyle.text = token.text;
  7860. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7861. // the bias of "Microsoft YaHei".
  7862. var textVerticalAlign = token.textVerticalAlign;
  7863. var y = lineTop + lineHeight / 2;
  7864. if (textVerticalAlign === 'top') {
  7865. y = lineTop + token.height / 2;
  7866. }
  7867. else if (textVerticalAlign === 'bottom') {
  7868. y = lineTop + lineHeight - token.height / 2;
  7869. }
  7870. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7871. hostEl,
  7872. ctx,
  7873. tokenStyle,
  7874. textAlign === 'right'
  7875. ? x - token.width
  7876. : textAlign === 'center'
  7877. ? x - token.width / 2
  7878. : x,
  7879. y - token.height / 2,
  7880. token.width,
  7881. token.height
  7882. );
  7883. var textPadding = token.textPadding;
  7884. if (textPadding) {
  7885. x = getTextXForPadding(x, textAlign, textPadding);
  7886. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7887. }
  7888. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7889. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7890. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7891. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7892. setCtx(ctx, 'textAlign', textAlign);
  7893. // Force baseline to be "middle". Otherwise, if using "top", the
  7894. // text will offset downward a little bit in font "Microsoft YaHei".
  7895. setCtx(ctx, 'textBaseline', 'middle');
  7896. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7897. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7898. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7899. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7900. // Fill after stroke so the outline will not cover the main part.
  7901. if (textStroke) {
  7902. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7903. setCtx(ctx, 'strokeStyle', textStroke);
  7904. ctx.strokeText(token.text, x, y);
  7905. }
  7906. if (textFill) {
  7907. setCtx(ctx, 'fillStyle', textFill);
  7908. ctx.fillText(token.text, x, y);
  7909. }
  7910. }
  7911. function needDrawBackground(style) {
  7912. return !!(
  7913. style.textBackgroundColor
  7914. || (style.textBorderWidth && style.textBorderColor)
  7915. );
  7916. }
  7917. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7918. // shape: {x, y, width, height}
  7919. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7920. var textBackgroundColor = style.textBackgroundColor;
  7921. var textBorderWidth = style.textBorderWidth;
  7922. var textBorderColor = style.textBorderColor;
  7923. var isPlainBg = isString(textBackgroundColor);
  7924. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7925. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7926. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7927. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7928. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7929. ctx.beginPath();
  7930. var textBorderRadius = style.textBorderRadius;
  7931. if (!textBorderRadius) {
  7932. ctx.rect(x, y, width, height);
  7933. }
  7934. else {
  7935. buildPath(ctx, {
  7936. x: x, y: y, width: width, height: height, r: textBorderRadius
  7937. });
  7938. }
  7939. ctx.closePath();
  7940. }
  7941. if (isPlainBg) {
  7942. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7943. if (style.fillOpacity != null) {
  7944. var originalGlobalAlpha = ctx.globalAlpha;
  7945. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7946. ctx.fill();
  7947. ctx.globalAlpha = originalGlobalAlpha;
  7948. }
  7949. else {
  7950. ctx.fill();
  7951. }
  7952. }
  7953. else if (isObject$1(textBackgroundColor)) {
  7954. var image = textBackgroundColor.image;
  7955. image = createOrUpdateImage(
  7956. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7957. );
  7958. if (image && isImageReady(image)) {
  7959. ctx.drawImage(image, x, y, width, height);
  7960. }
  7961. }
  7962. if (textBorderWidth && textBorderColor) {
  7963. setCtx(ctx, 'lineWidth', textBorderWidth);
  7964. setCtx(ctx, 'strokeStyle', textBorderColor);
  7965. if (style.strokeOpacity != null) {
  7966. var originalGlobalAlpha = ctx.globalAlpha;
  7967. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7968. ctx.stroke();
  7969. ctx.globalAlpha = originalGlobalAlpha;
  7970. }
  7971. else {
  7972. ctx.stroke();
  7973. }
  7974. }
  7975. }
  7976. function onBgImageLoaded(image, textBackgroundColor) {
  7977. // Replace image, so that `contain/text.js#parseRichText`
  7978. // will get correct result in next tick.
  7979. textBackgroundColor.image = image;
  7980. }
  7981. function getBoxPosition(out, hostEl, style, rect) {
  7982. var baseX = style.x || 0;
  7983. var baseY = style.y || 0;
  7984. var textAlign = style.textAlign;
  7985. var textVerticalAlign = style.textVerticalAlign;
  7986. // Text position represented by coord
  7987. if (rect) {
  7988. var textPosition = style.textPosition;
  7989. if (textPosition instanceof Array) {
  7990. // Percent
  7991. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7992. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7993. }
  7994. else {
  7995. var res = (hostEl && hostEl.calculateTextPosition)
  7996. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7997. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7998. baseX = res.x;
  7999. baseY = res.y;
  8000. // Default align and baseline when has textPosition
  8001. textAlign = textAlign || res.textAlign;
  8002. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  8003. }
  8004. // textOffset is only support in RectText, otherwise
  8005. // we have to adjust boundingRect for textOffset.
  8006. var textOffset = style.textOffset;
  8007. if (textOffset) {
  8008. baseX += textOffset[0];
  8009. baseY += textOffset[1];
  8010. }
  8011. }
  8012. out = out || {};
  8013. out.baseX = baseX;
  8014. out.baseY = baseY;
  8015. out.textAlign = textAlign;
  8016. out.textVerticalAlign = textVerticalAlign;
  8017. return out;
  8018. }
  8019. function setCtx(ctx, prop, value) {
  8020. ctx[prop] = fixShadow(ctx, prop, value);
  8021. return ctx[prop];
  8022. }
  8023. /**
  8024. * @param {string} [stroke] If specified, do not check style.textStroke.
  8025. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  8026. * @param {number} style
  8027. */
  8028. function getStroke(stroke, lineWidth) {
  8029. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  8030. ? null
  8031. // TODO pattern and gradient?
  8032. : (stroke.image || stroke.colorStops)
  8033. ? '#000'
  8034. : stroke;
  8035. }
  8036. function getFill(fill) {
  8037. return (fill == null || fill === 'none')
  8038. ? null
  8039. // TODO pattern and gradient?
  8040. : (fill.image || fill.colorStops)
  8041. ? '#000'
  8042. : fill;
  8043. }
  8044. function parsePercent(value, maxValue) {
  8045. if (typeof value === 'string') {
  8046. if (value.lastIndexOf('%') >= 0) {
  8047. return parseFloat(value) / 100 * maxValue;
  8048. }
  8049. return parseFloat(value);
  8050. }
  8051. return value;
  8052. }
  8053. function getTextXForPadding(x, textAlign, textPadding) {
  8054. return textAlign === 'right'
  8055. ? (x - textPadding[1])
  8056. : textAlign === 'center'
  8057. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  8058. : (x + textPadding[3]);
  8059. }
  8060. /**
  8061. * @param {string} text
  8062. * @param {module:zrender/Style} style
  8063. * @return {boolean}
  8064. */
  8065. function needDrawText(text, style) {
  8066. return text != null
  8067. && (text
  8068. || style.textBackgroundColor
  8069. || (style.textBorderWidth && style.textBorderColor)
  8070. || style.textPadding
  8071. );
  8072. }
  8073. /**
  8074. * Mixin for drawing text in a element bounding rect
  8075. * @module zrender/mixin/RectText
  8076. */
  8077. var tmpRect$1 = new BoundingRect();
  8078. var RectText = function () {};
  8079. RectText.prototype = {
  8080. constructor: RectText,
  8081. /**
  8082. * Draw text in a rect with specified position.
  8083. * @param {CanvasRenderingContext2D} ctx
  8084. * @param {Object} rect Displayable rect
  8085. */
  8086. drawRectText: function (ctx, rect) {
  8087. var style = this.style;
  8088. rect = style.textRect || rect;
  8089. // Optimize, avoid normalize every time.
  8090. this.__dirty && normalizeTextStyle(style, true);
  8091. var text = style.text;
  8092. // Convert to string
  8093. text != null && (text += '');
  8094. if (!needDrawText(text, style)) {
  8095. return;
  8096. }
  8097. // FIXME
  8098. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  8099. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  8100. // text propably break the cache for its host elements.
  8101. ctx.save();
  8102. // Transform rect to view space
  8103. var transform = this.transform;
  8104. if (!style.transformText) {
  8105. if (transform) {
  8106. tmpRect$1.copy(rect);
  8107. tmpRect$1.applyTransform(transform);
  8108. rect = tmpRect$1;
  8109. }
  8110. }
  8111. else {
  8112. this.setTransform(ctx);
  8113. }
  8114. // transformText and textRotation can not be used at the same time.
  8115. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  8116. ctx.restore();
  8117. }
  8118. };
  8119. /**
  8120. * Base class of all displayable graphic objects
  8121. * @module zrender/graphic/Displayable
  8122. */
  8123. /**
  8124. * @alias module:zrender/graphic/Displayable
  8125. * @extends module:zrender/Element
  8126. * @extends module:zrender/graphic/mixin/RectText
  8127. */
  8128. function Displayable(opts) {
  8129. opts = opts || {};
  8130. Element.call(this, opts);
  8131. // Extend properties
  8132. for (var name in opts) {
  8133. if (
  8134. opts.hasOwnProperty(name)
  8135. && name !== 'style'
  8136. ) {
  8137. this[name] = opts[name];
  8138. }
  8139. }
  8140. /**
  8141. * @type {module:zrender/graphic/Style}
  8142. */
  8143. this.style = new Style(opts.style, this);
  8144. this._rect = null;
  8145. // Shapes for cascade clipping.
  8146. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  8147. // because it is easy to only using null to check whether clipPaths changed.
  8148. this.__clipPaths = null;
  8149. // FIXME Stateful must be mixined after style is setted
  8150. // Stateful.call(this, opts);
  8151. }
  8152. Displayable.prototype = {
  8153. constructor: Displayable,
  8154. type: 'displayable',
  8155. /**
  8156. * Dirty flag. From which painter will determine if this displayable object needs brush.
  8157. * @name module:zrender/graphic/Displayable#__dirty
  8158. * @type {boolean}
  8159. */
  8160. __dirty: true,
  8161. /**
  8162. * Whether the displayable object is visible. when it is true, the displayable object
  8163. * is not drawn, but the mouse event can still trigger the object.
  8164. * @name module:/zrender/graphic/Displayable#invisible
  8165. * @type {boolean}
  8166. * @default false
  8167. */
  8168. invisible: false,
  8169. /**
  8170. * @name module:/zrender/graphic/Displayable#z
  8171. * @type {number}
  8172. * @default 0
  8173. */
  8174. z: 0,
  8175. /**
  8176. * @name module:/zrender/graphic/Displayable#z
  8177. * @type {number}
  8178. * @default 0
  8179. */
  8180. z2: 0,
  8181. /**
  8182. * The z level determines the displayable object can be drawn in which layer canvas.
  8183. * @name module:/zrender/graphic/Displayable#zlevel
  8184. * @type {number}
  8185. * @default 0
  8186. */
  8187. zlevel: 0,
  8188. /**
  8189. * Whether it can be dragged.
  8190. * @name module:/zrender/graphic/Displayable#draggable
  8191. * @type {boolean}
  8192. * @default false
  8193. */
  8194. draggable: false,
  8195. /**
  8196. * Whether is it dragging.
  8197. * @name module:/zrender/graphic/Displayable#draggable
  8198. * @type {boolean}
  8199. * @default false
  8200. */
  8201. dragging: false,
  8202. /**
  8203. * Whether to respond to mouse events.
  8204. * @name module:/zrender/graphic/Displayable#silent
  8205. * @type {boolean}
  8206. * @default false
  8207. */
  8208. silent: false,
  8209. /**
  8210. * If enable culling
  8211. * @type {boolean}
  8212. * @default false
  8213. */
  8214. culling: false,
  8215. /**
  8216. * Mouse cursor when hovered
  8217. * @name module:/zrender/graphic/Displayable#cursor
  8218. * @type {string}
  8219. */
  8220. cursor: 'pointer',
  8221. /**
  8222. * If hover area is bounding rect
  8223. * @name module:/zrender/graphic/Displayable#rectHover
  8224. * @type {string}
  8225. */
  8226. rectHover: false,
  8227. /**
  8228. * Render the element progressively when the value >= 0,
  8229. * usefull for large data.
  8230. * @type {boolean}
  8231. */
  8232. progressive: false,
  8233. /**
  8234. * @type {boolean}
  8235. */
  8236. incremental: false,
  8237. /**
  8238. * Scale ratio for global scale.
  8239. * @type {boolean}
  8240. */
  8241. globalScaleRatio: 1,
  8242. beforeBrush: function (ctx) {},
  8243. afterBrush: function (ctx) {},
  8244. /**
  8245. * Graphic drawing method.
  8246. * @param {CanvasRenderingContext2D} ctx
  8247. */
  8248. // Interface
  8249. brush: function (ctx, prevEl) {},
  8250. /**
  8251. * Get the minimum bounding box.
  8252. * @return {module:zrender/core/BoundingRect}
  8253. */
  8254. // Interface
  8255. getBoundingRect: function () {},
  8256. /**
  8257. * If displayable element contain coord x, y
  8258. * @param {number} x
  8259. * @param {number} y
  8260. * @return {boolean}
  8261. */
  8262. contain: function (x, y) {
  8263. return this.rectContain(x, y);
  8264. },
  8265. /**
  8266. * @param {Function} cb
  8267. * @param {} context
  8268. */
  8269. traverse: function (cb, context) {
  8270. cb.call(context, this);
  8271. },
  8272. /**
  8273. * If bounding rect of element contain coord x, y
  8274. * @param {number} x
  8275. * @param {number} y
  8276. * @return {boolean}
  8277. */
  8278. rectContain: function (x, y) {
  8279. var coord = this.transformCoordToLocal(x, y);
  8280. var rect = this.getBoundingRect();
  8281. return rect.contain(coord[0], coord[1]);
  8282. },
  8283. /**
  8284. * Mark displayable element dirty and refresh next frame
  8285. */
  8286. dirty: function () {
  8287. this.__dirty = this.__dirtyText = true;
  8288. this._rect = null;
  8289. this.__zr && this.__zr.refresh();
  8290. },
  8291. /**
  8292. * If displayable object binded any event
  8293. * @return {boolean}
  8294. */
  8295. // TODO, events bound by bind
  8296. // isSilent: function () {
  8297. // return !(
  8298. // this.hoverable || this.draggable
  8299. // || this.onmousemove || this.onmouseover || this.onmouseout
  8300. // || this.onmousedown || this.onmouseup || this.onclick
  8301. // || this.ondragenter || this.ondragover || this.ondragleave
  8302. // || this.ondrop
  8303. // );
  8304. // },
  8305. /**
  8306. * Alias for animate('style')
  8307. * @param {boolean} loop
  8308. */
  8309. animateStyle: function (loop) {
  8310. return this.animate('style', loop);
  8311. },
  8312. attrKV: function (key, value) {
  8313. if (key !== 'style') {
  8314. Element.prototype.attrKV.call(this, key, value);
  8315. }
  8316. else {
  8317. this.style.set(value);
  8318. }
  8319. },
  8320. /**
  8321. * @param {Object|string} key
  8322. * @param {*} value
  8323. */
  8324. setStyle: function (key, value) {
  8325. this.style.set(key, value);
  8326. this.dirty(false);
  8327. return this;
  8328. },
  8329. /**
  8330. * Use given style object
  8331. * @param {Object} obj
  8332. */
  8333. useStyle: function (obj) {
  8334. this.style = new Style(obj, this);
  8335. this.dirty(false);
  8336. return this;
  8337. },
  8338. /**
  8339. * The string value of `textPosition` needs to be calculated to a real postion.
  8340. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  8341. * by default. See `contain/text.js#calculateTextPosition` for more details.
  8342. * But some coutom shapes like "pin", "flag" have center that is not exactly
  8343. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  8344. * for those shapes. It will be called if the `style.textPosition` is a string.
  8345. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  8346. * be responsible for creating one.
  8347. * @param {module:zrender/graphic/Style} style
  8348. * @param {Object} rect {x, y, width, height}
  8349. * @return {Obejct} out The same as the input out.
  8350. * {
  8351. * x: number. mandatory.
  8352. * y: number. mandatory.
  8353. * textAlign: string. optional. use style.textAlign by default.
  8354. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  8355. * }
  8356. */
  8357. calculateTextPosition: null
  8358. };
  8359. inherits(Displayable, Element);
  8360. mixin(Displayable, RectText);
  8361. /**
  8362. * @alias zrender/graphic/Image
  8363. * @extends module:zrender/graphic/Displayable
  8364. * @constructor
  8365. * @param {Object} opts
  8366. */
  8367. function ZImage(opts) {
  8368. Displayable.call(this, opts);
  8369. }
  8370. ZImage.prototype = {
  8371. constructor: ZImage,
  8372. type: 'image',
  8373. brush: function (ctx, prevEl) {
  8374. var style = this.style;
  8375. var src = style.image;
  8376. // Must bind each time
  8377. style.bind(ctx, this, prevEl);
  8378. var image = this._image = createOrUpdateImage(
  8379. src,
  8380. this._image,
  8381. this,
  8382. this.onload
  8383. );
  8384. if (!image || !isImageReady(image)) {
  8385. return;
  8386. }
  8387. // 图片已经加载完成
  8388. // if (image.nodeName.toUpperCase() == 'IMG') {
  8389. // if (!image.complete) {
  8390. // return;
  8391. // }
  8392. // }
  8393. // Else is canvas
  8394. var x = style.x || 0;
  8395. var y = style.y || 0;
  8396. var width = style.width;
  8397. var height = style.height;
  8398. var aspect = image.width / image.height;
  8399. if (width == null && height != null) {
  8400. // Keep image/height ratio
  8401. width = height * aspect;
  8402. }
  8403. else if (height == null && width != null) {
  8404. height = width / aspect;
  8405. }
  8406. else if (width == null && height == null) {
  8407. width = image.width;
  8408. height = image.height;
  8409. }
  8410. // 设置transform
  8411. this.setTransform(ctx);
  8412. if (style.sWidth && style.sHeight) {
  8413. var sx = style.sx || 0;
  8414. var sy = style.sy || 0;
  8415. ctx.drawImage(
  8416. image,
  8417. sx, sy, style.sWidth, style.sHeight,
  8418. x, y, width, height
  8419. );
  8420. }
  8421. else if (style.sx && style.sy) {
  8422. var sx = style.sx;
  8423. var sy = style.sy;
  8424. var sWidth = width - sx;
  8425. var sHeight = height - sy;
  8426. ctx.drawImage(
  8427. image,
  8428. sx, sy, sWidth, sHeight,
  8429. x, y, width, height
  8430. );
  8431. }
  8432. else {
  8433. ctx.drawImage(image, x, y, width, height);
  8434. }
  8435. // Draw rect text
  8436. if (style.text != null) {
  8437. // Only restore transform when needs draw text.
  8438. this.restoreTransform(ctx);
  8439. this.drawRectText(ctx, this.getBoundingRect());
  8440. }
  8441. },
  8442. getBoundingRect: function () {
  8443. var style = this.style;
  8444. if (!this._rect) {
  8445. this._rect = new BoundingRect(
  8446. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8447. );
  8448. }
  8449. return this._rect;
  8450. }
  8451. };
  8452. inherits(ZImage, Displayable);
  8453. var HOVER_LAYER_ZLEVEL = 1e5;
  8454. var CANVAS_ZLEVEL = 314159;
  8455. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8456. var INCREMENTAL_INC = 0.001;
  8457. function parseInt10(val) {
  8458. return parseInt(val, 10);
  8459. }
  8460. function isLayerValid(layer) {
  8461. if (!layer) {
  8462. return false;
  8463. }
  8464. if (layer.__builtin__) {
  8465. return true;
  8466. }
  8467. if (typeof (layer.resize) !== 'function'
  8468. || typeof (layer.refresh) !== 'function'
  8469. ) {
  8470. return false;
  8471. }
  8472. return true;
  8473. }
  8474. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8475. var viewRect = new BoundingRect(0, 0, 0, 0);
  8476. function isDisplayableCulled(el, width, height) {
  8477. tmpRect.copy(el.getBoundingRect());
  8478. if (el.transform) {
  8479. tmpRect.applyTransform(el.transform);
  8480. }
  8481. viewRect.width = width;
  8482. viewRect.height = height;
  8483. return !tmpRect.intersect(viewRect);
  8484. }
  8485. function isClipPathChanged(clipPaths, prevClipPaths) {
  8486. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8487. if (clipPaths === prevClipPaths) {
  8488. return false;
  8489. }
  8490. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8491. return true;
  8492. }
  8493. for (var i = 0; i < clipPaths.length; i++) {
  8494. if (clipPaths[i] !== prevClipPaths[i]) {
  8495. return true;
  8496. }
  8497. }
  8498. return false;
  8499. }
  8500. function doClip(clipPaths, ctx) {
  8501. for (var i = 0; i < clipPaths.length; i++) {
  8502. var clipPath = clipPaths[i];
  8503. clipPath.setTransform(ctx);
  8504. ctx.beginPath();
  8505. clipPath.buildPath(ctx, clipPath.shape);
  8506. ctx.clip();
  8507. // Transform back
  8508. clipPath.restoreTransform(ctx);
  8509. }
  8510. }
  8511. function createRoot(width, height) {
  8512. var domRoot = document.createElement('div');
  8513. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8514. domRoot.style.cssText = [
  8515. 'position:relative',
  8516. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8517. // dom does not act as expected) when some of the parent dom has
  8518. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8519. // the canvas is not at the top part of the page.
  8520. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8521. // this `overflow:hidden` to avoid the bug.
  8522. // 'overflow:hidden',
  8523. 'width:' + width + 'px',
  8524. 'height:' + height + 'px',
  8525. 'padding:0',
  8526. 'margin:0',
  8527. 'border-width:0'
  8528. ].join(';') + ';';
  8529. return domRoot;
  8530. }
  8531. /**
  8532. * @alias module:zrender/Painter
  8533. * @constructor
  8534. * @param {HTMLElement} root 绘图容器
  8535. * @param {module:zrender/Storage} storage
  8536. * @param {Object} opts
  8537. */
  8538. var Painter = function (root, storage, opts) {
  8539. this.type = 'canvas';
  8540. // In node environment using node-canvas
  8541. var singleCanvas = !root.nodeName // In node ?
  8542. || root.nodeName.toUpperCase() === 'CANVAS';
  8543. this._opts = opts = extend({}, opts || {});
  8544. /**
  8545. * @type {number}
  8546. */
  8547. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8548. /**
  8549. * @type {boolean}
  8550. * @private
  8551. */
  8552. this._singleCanvas = singleCanvas;
  8553. /**
  8554. * 绘图容器
  8555. * @type {HTMLElement}
  8556. */
  8557. this.root = root;
  8558. var rootStyle = root.style;
  8559. if (rootStyle) {
  8560. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8561. rootStyle['-webkit-user-select'] =
  8562. rootStyle['user-select'] =
  8563. rootStyle['-webkit-touch-callout'] = 'none';
  8564. root.innerHTML = '';
  8565. }
  8566. /**
  8567. * @type {module:zrender/Storage}
  8568. */
  8569. this.storage = storage;
  8570. /**
  8571. * @type {Array.<number>}
  8572. * @private
  8573. */
  8574. var zlevelList = this._zlevelList = [];
  8575. /**
  8576. * @type {Object.<string, module:zrender/Layer>}
  8577. * @private
  8578. */
  8579. var layers = this._layers = {};
  8580. /**
  8581. * @type {Object.<string, Object>}
  8582. * @private
  8583. */
  8584. this._layerConfig = {};
  8585. /**
  8586. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8587. */
  8588. this._needsManuallyCompositing = false;
  8589. if (!singleCanvas) {
  8590. this._width = this._getSize(0);
  8591. this._height = this._getSize(1);
  8592. var domRoot = this._domRoot = createRoot(
  8593. this._width, this._height
  8594. );
  8595. root.appendChild(domRoot);
  8596. }
  8597. else {
  8598. var width = root.width;
  8599. var height = root.height;
  8600. if (opts.width != null) {
  8601. width = opts.width;
  8602. }
  8603. if (opts.height != null) {
  8604. height = opts.height;
  8605. }
  8606. this.dpr = opts.devicePixelRatio || 1;
  8607. // Use canvas width and height directly
  8608. root.width = width * this.dpr;
  8609. root.height = height * this.dpr;
  8610. this._width = width;
  8611. this._height = height;
  8612. // Create layer if only one given canvas
  8613. // Device can be specified to create a high dpi image.
  8614. var mainLayer = new Layer(root, this, this.dpr);
  8615. mainLayer.__builtin__ = true;
  8616. mainLayer.initContext();
  8617. // FIXME Use canvas width and height
  8618. // mainLayer.resize(width, height);
  8619. layers[CANVAS_ZLEVEL] = mainLayer;
  8620. mainLayer.zlevel = CANVAS_ZLEVEL;
  8621. // Not use common zlevel.
  8622. zlevelList.push(CANVAS_ZLEVEL);
  8623. this._domRoot = root;
  8624. }
  8625. /**
  8626. * @type {module:zrender/Layer}
  8627. * @private
  8628. */
  8629. this._hoverlayer = null;
  8630. this._hoverElements = [];
  8631. };
  8632. Painter.prototype = {
  8633. constructor: Painter,
  8634. getType: function () {
  8635. return 'canvas';
  8636. },
  8637. /**
  8638. * If painter use a single canvas
  8639. * @return {boolean}
  8640. */
  8641. isSingleCanvas: function () {
  8642. return this._singleCanvas;
  8643. },
  8644. /**
  8645. * @return {HTMLDivElement}
  8646. */
  8647. getViewportRoot: function () {
  8648. return this._domRoot;
  8649. },
  8650. getViewportRootOffset: function () {
  8651. var viewportRoot = this.getViewportRoot();
  8652. if (viewportRoot) {
  8653. return {
  8654. offsetLeft: viewportRoot.offsetLeft || 0,
  8655. offsetTop: viewportRoot.offsetTop || 0
  8656. };
  8657. }
  8658. },
  8659. /**
  8660. * 刷新
  8661. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8662. */
  8663. refresh: function (paintAll) {
  8664. var list = this.storage.getDisplayList(true);
  8665. var zlevelList = this._zlevelList;
  8666. this._redrawId = Math.random();
  8667. this._paintList(list, paintAll, this._redrawId);
  8668. // Paint custum layers
  8669. for (var i = 0; i < zlevelList.length; i++) {
  8670. var z = zlevelList[i];
  8671. var layer = this._layers[z];
  8672. if (!layer.__builtin__ && layer.refresh) {
  8673. var clearColor = i === 0 ? this._backgroundColor : null;
  8674. layer.refresh(clearColor);
  8675. }
  8676. }
  8677. this.refreshHover();
  8678. return this;
  8679. },
  8680. addHover: function (el, hoverStyle) {
  8681. if (el.__hoverMir) {
  8682. return;
  8683. }
  8684. var elMirror = new el.constructor({
  8685. style: el.style,
  8686. shape: el.shape,
  8687. z: el.z,
  8688. z2: el.z2,
  8689. silent: el.silent
  8690. });
  8691. elMirror.__from = el;
  8692. el.__hoverMir = elMirror;
  8693. hoverStyle && elMirror.setStyle(hoverStyle);
  8694. this._hoverElements.push(elMirror);
  8695. return elMirror;
  8696. },
  8697. removeHover: function (el) {
  8698. var elMirror = el.__hoverMir;
  8699. var hoverElements = this._hoverElements;
  8700. var idx = indexOf(hoverElements, elMirror);
  8701. if (idx >= 0) {
  8702. hoverElements.splice(idx, 1);
  8703. }
  8704. el.__hoverMir = null;
  8705. },
  8706. clearHover: function (el) {
  8707. var hoverElements = this._hoverElements;
  8708. for (var i = 0; i < hoverElements.length; i++) {
  8709. var from = hoverElements[i].__from;
  8710. if (from) {
  8711. from.__hoverMir = null;
  8712. }
  8713. }
  8714. hoverElements.length = 0;
  8715. },
  8716. refreshHover: function () {
  8717. var hoverElements = this._hoverElements;
  8718. var len = hoverElements.length;
  8719. var hoverLayer = this._hoverlayer;
  8720. hoverLayer && hoverLayer.clear();
  8721. if (!len) {
  8722. return;
  8723. }
  8724. sort(hoverElements, this.storage.displayableSortFunc);
  8725. // Use a extream large zlevel
  8726. // FIXME?
  8727. if (!hoverLayer) {
  8728. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8729. }
  8730. var scope = {};
  8731. hoverLayer.ctx.save();
  8732. for (var i = 0; i < len;) {
  8733. var el = hoverElements[i];
  8734. var originalEl = el.__from;
  8735. // Original el is removed
  8736. // PENDING
  8737. if (!(originalEl && originalEl.__zr)) {
  8738. hoverElements.splice(i, 1);
  8739. originalEl.__hoverMir = null;
  8740. len--;
  8741. continue;
  8742. }
  8743. i++;
  8744. // Use transform
  8745. // FIXME style and shape ?
  8746. if (!originalEl.invisible) {
  8747. el.transform = originalEl.transform;
  8748. el.invTransform = originalEl.invTransform;
  8749. el.__clipPaths = originalEl.__clipPaths;
  8750. // el.
  8751. this._doPaintEl(el, hoverLayer, true, scope);
  8752. }
  8753. }
  8754. hoverLayer.ctx.restore();
  8755. },
  8756. getHoverLayer: function () {
  8757. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8758. },
  8759. _paintList: function (list, paintAll, redrawId) {
  8760. if (this._redrawId !== redrawId) {
  8761. return;
  8762. }
  8763. paintAll = paintAll || false;
  8764. this._updateLayerStatus(list);
  8765. var finished = this._doPaintList(list, paintAll);
  8766. if (this._needsManuallyCompositing) {
  8767. this._compositeManually();
  8768. }
  8769. if (!finished) {
  8770. var self = this;
  8771. requestAnimationFrame(function () {
  8772. self._paintList(list, paintAll, redrawId);
  8773. });
  8774. }
  8775. },
  8776. _compositeManually: function () {
  8777. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8778. var width = this._domRoot.width;
  8779. var height = this._domRoot.height;
  8780. ctx.clearRect(0, 0, width, height);
  8781. // PENDING, If only builtin layer?
  8782. this.eachBuiltinLayer(function (layer) {
  8783. if (layer.virtual) {
  8784. ctx.drawImage(layer.dom, 0, 0, width, height);
  8785. }
  8786. });
  8787. },
  8788. _doPaintList: function (list, paintAll) {
  8789. var layerList = [];
  8790. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8791. var zlevel = this._zlevelList[zi];
  8792. var layer = this._layers[zlevel];
  8793. if (layer.__builtin__
  8794. && layer !== this._hoverlayer
  8795. && (layer.__dirty || paintAll)
  8796. ) {
  8797. layerList.push(layer);
  8798. }
  8799. }
  8800. var finished = true;
  8801. for (var k = 0; k < layerList.length; k++) {
  8802. var layer = layerList[k];
  8803. var ctx = layer.ctx;
  8804. var scope = {};
  8805. ctx.save();
  8806. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8807. var useTimer = !paintAll && layer.incremental && Date.now;
  8808. var startTime = useTimer && Date.now();
  8809. var clearColor = layer.zlevel === this._zlevelList[0]
  8810. ? this._backgroundColor : null;
  8811. // All elements in this layer are cleared.
  8812. if (layer.__startIndex === layer.__endIndex) {
  8813. layer.clear(false, clearColor);
  8814. }
  8815. else if (start === layer.__startIndex) {
  8816. var firstEl = list[start];
  8817. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8818. layer.clear(false, clearColor);
  8819. }
  8820. }
  8821. if (start === -1) {
  8822. console.error('For some unknown reason. drawIndex is -1');
  8823. start = layer.__startIndex;
  8824. }
  8825. for (var i = start; i < layer.__endIndex; i++) {
  8826. var el = list[i];
  8827. this._doPaintEl(el, layer, paintAll, scope);
  8828. el.__dirty = el.__dirtyText = false;
  8829. if (useTimer) {
  8830. // Date.now can be executed in 13,025,305 ops/second.
  8831. var dTime = Date.now() - startTime;
  8832. // Give 15 millisecond to draw.
  8833. // The rest elements will be drawn in the next frame.
  8834. if (dTime > 15) {
  8835. break;
  8836. }
  8837. }
  8838. }
  8839. layer.__drawIndex = i;
  8840. if (layer.__drawIndex < layer.__endIndex) {
  8841. finished = false;
  8842. }
  8843. if (scope.prevElClipPaths) {
  8844. // Needs restore the state. If last drawn element is in the clipping area.
  8845. ctx.restore();
  8846. }
  8847. ctx.restore();
  8848. }
  8849. if (env$1.wxa) {
  8850. // Flush for weixin application
  8851. each$1(this._layers, function (layer) {
  8852. if (layer && layer.ctx && layer.ctx.draw) {
  8853. layer.ctx.draw();
  8854. }
  8855. });
  8856. }
  8857. return finished;
  8858. },
  8859. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8860. var ctx = currentLayer.ctx;
  8861. var m = el.transform;
  8862. if (
  8863. (currentLayer.__dirty || forcePaint)
  8864. // Ignore invisible element
  8865. && !el.invisible
  8866. // Ignore transparent element
  8867. && el.style.opacity !== 0
  8868. // Ignore scale 0 element, in some environment like node-canvas
  8869. // Draw a scale 0 element can cause all following draw wrong
  8870. // And setTransform with scale 0 will cause set back transform failed.
  8871. && !(m && !m[0] && !m[3])
  8872. // Ignore culled element
  8873. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8874. ) {
  8875. var clipPaths = el.__clipPaths;
  8876. var prevElClipPaths = scope.prevElClipPaths;
  8877. // Optimize when clipping on group with several elements
  8878. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8879. // If has previous clipping state, restore from it
  8880. if (prevElClipPaths) {
  8881. ctx.restore();
  8882. scope.prevElClipPaths = null;
  8883. // Reset prevEl since context has been restored
  8884. scope.prevEl = null;
  8885. }
  8886. // New clipping state
  8887. if (clipPaths) {
  8888. ctx.save();
  8889. doClip(clipPaths, ctx);
  8890. scope.prevElClipPaths = clipPaths;
  8891. }
  8892. }
  8893. el.beforeBrush && el.beforeBrush(ctx);
  8894. el.brush(ctx, scope.prevEl || null);
  8895. scope.prevEl = el;
  8896. el.afterBrush && el.afterBrush(ctx);
  8897. }
  8898. },
  8899. /**
  8900. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8901. * @param {number} zlevel
  8902. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8903. * @return {module:zrender/Layer}
  8904. */
  8905. getLayer: function (zlevel, virtual) {
  8906. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8907. zlevel = CANVAS_ZLEVEL;
  8908. }
  8909. var layer = this._layers[zlevel];
  8910. if (!layer) {
  8911. // Create a new layer
  8912. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8913. layer.zlevel = zlevel;
  8914. layer.__builtin__ = true;
  8915. if (this._layerConfig[zlevel]) {
  8916. merge(layer, this._layerConfig[zlevel], true);
  8917. }
  8918. // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  8919. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  8920. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  8921. }
  8922. if (virtual) {
  8923. layer.virtual = virtual;
  8924. }
  8925. this.insertLayer(zlevel, layer);
  8926. // Context is created after dom inserted to document
  8927. // Or excanvas will get 0px clientWidth and clientHeight
  8928. layer.initContext();
  8929. }
  8930. return layer;
  8931. },
  8932. insertLayer: function (zlevel, layer) {
  8933. var layersMap = this._layers;
  8934. var zlevelList = this._zlevelList;
  8935. var len = zlevelList.length;
  8936. var prevLayer = null;
  8937. var i = -1;
  8938. var domRoot = this._domRoot;
  8939. if (layersMap[zlevel]) {
  8940. logError$1('ZLevel ' + zlevel + ' has been used already');
  8941. return;
  8942. }
  8943. // Check if is a valid layer
  8944. if (!isLayerValid(layer)) {
  8945. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8946. return;
  8947. }
  8948. if (len > 0 && zlevel > zlevelList[0]) {
  8949. for (i = 0; i < len - 1; i++) {
  8950. if (
  8951. zlevelList[i] < zlevel
  8952. && zlevelList[i + 1] > zlevel
  8953. ) {
  8954. break;
  8955. }
  8956. }
  8957. prevLayer = layersMap[zlevelList[i]];
  8958. }
  8959. zlevelList.splice(i + 1, 0, zlevel);
  8960. layersMap[zlevel] = layer;
  8961. // Vitual layer will not directly show on the screen.
  8962. // (It can be a WebGL layer and assigned to a ZImage element)
  8963. // But it still under management of zrender.
  8964. if (!layer.virtual) {
  8965. if (prevLayer) {
  8966. var prevDom = prevLayer.dom;
  8967. if (prevDom.nextSibling) {
  8968. domRoot.insertBefore(
  8969. layer.dom,
  8970. prevDom.nextSibling
  8971. );
  8972. }
  8973. else {
  8974. domRoot.appendChild(layer.dom);
  8975. }
  8976. }
  8977. else {
  8978. if (domRoot.firstChild) {
  8979. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8980. }
  8981. else {
  8982. domRoot.appendChild(layer.dom);
  8983. }
  8984. }
  8985. }
  8986. },
  8987. // Iterate each layer
  8988. eachLayer: function (cb, context) {
  8989. var zlevelList = this._zlevelList;
  8990. var z;
  8991. var i;
  8992. for (i = 0; i < zlevelList.length; i++) {
  8993. z = zlevelList[i];
  8994. cb.call(context, this._layers[z], z);
  8995. }
  8996. },
  8997. // Iterate each buildin layer
  8998. eachBuiltinLayer: function (cb, context) {
  8999. var zlevelList = this._zlevelList;
  9000. var layer;
  9001. var z;
  9002. var i;
  9003. for (i = 0; i < zlevelList.length; i++) {
  9004. z = zlevelList[i];
  9005. layer = this._layers[z];
  9006. if (layer.__builtin__) {
  9007. cb.call(context, layer, z);
  9008. }
  9009. }
  9010. },
  9011. // Iterate each other layer except buildin layer
  9012. eachOtherLayer: function (cb, context) {
  9013. var zlevelList = this._zlevelList;
  9014. var layer;
  9015. var z;
  9016. var i;
  9017. for (i = 0; i < zlevelList.length; i++) {
  9018. z = zlevelList[i];
  9019. layer = this._layers[z];
  9020. if (!layer.__builtin__) {
  9021. cb.call(context, layer, z);
  9022. }
  9023. }
  9024. },
  9025. /**
  9026. * 获取所有已创建的层
  9027. * @param {Array.<module:zrender/Layer>} [prevLayer]
  9028. */
  9029. getLayers: function () {
  9030. return this._layers;
  9031. },
  9032. _updateLayerStatus: function (list) {
  9033. this.eachBuiltinLayer(function (layer, z) {
  9034. layer.__dirty = layer.__used = false;
  9035. });
  9036. function updatePrevLayer(idx) {
  9037. if (prevLayer) {
  9038. if (prevLayer.__endIndex !== idx) {
  9039. prevLayer.__dirty = true;
  9040. }
  9041. prevLayer.__endIndex = idx;
  9042. }
  9043. }
  9044. if (this._singleCanvas) {
  9045. for (var i = 1; i < list.length; i++) {
  9046. var el = list[i];
  9047. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  9048. this._needsManuallyCompositing = true;
  9049. break;
  9050. }
  9051. }
  9052. }
  9053. var prevLayer = null;
  9054. var incrementalLayerCount = 0;
  9055. var prevZlevel;
  9056. for (var i = 0; i < list.length; i++) {
  9057. var el = list[i];
  9058. var zlevel = el.zlevel;
  9059. var layer;
  9060. if (prevZlevel !== zlevel) {
  9061. prevZlevel = zlevel;
  9062. incrementalLayerCount = 0;
  9063. }
  9064. // TODO Not use magic number on zlevel.
  9065. // Each layer with increment element can be separated to 3 layers.
  9066. // (Other Element drawn after incremental element)
  9067. // -----------------zlevel + EL_AFTER_INCREMENTAL_INC--------------------
  9068. // (Incremental element)
  9069. // ----------------------zlevel + INCREMENTAL_INC------------------------
  9070. // (Element drawn before incremental element)
  9071. // --------------------------------zlevel--------------------------------
  9072. if (el.incremental) {
  9073. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  9074. layer.incremental = true;
  9075. incrementalLayerCount = 1;
  9076. }
  9077. else {
  9078. layer = this.getLayer(
  9079. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  9080. this._needsManuallyCompositing
  9081. );
  9082. }
  9083. if (!layer.__builtin__) {
  9084. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  9085. }
  9086. if (layer !== prevLayer) {
  9087. layer.__used = true;
  9088. if (layer.__startIndex !== i) {
  9089. layer.__dirty = true;
  9090. }
  9091. layer.__startIndex = i;
  9092. if (!layer.incremental) {
  9093. layer.__drawIndex = i;
  9094. }
  9095. else {
  9096. // Mark layer draw index needs to update.
  9097. layer.__drawIndex = -1;
  9098. }
  9099. updatePrevLayer(i);
  9100. prevLayer = layer;
  9101. }
  9102. if (el.__dirty) {
  9103. layer.__dirty = true;
  9104. if (layer.incremental && layer.__drawIndex < 0) {
  9105. // Start draw from the first dirty element.
  9106. layer.__drawIndex = i;
  9107. }
  9108. }
  9109. }
  9110. updatePrevLayer(i);
  9111. this.eachBuiltinLayer(function (layer, z) {
  9112. // Used in last frame but not in this frame. Needs clear
  9113. if (!layer.__used && layer.getElementCount() > 0) {
  9114. layer.__dirty = true;
  9115. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  9116. }
  9117. // For incremental layer. In case start index changed and no elements are dirty.
  9118. if (layer.__dirty && layer.__drawIndex < 0) {
  9119. layer.__drawIndex = layer.__startIndex;
  9120. }
  9121. });
  9122. },
  9123. /**
  9124. * 清除hover层外所有内容
  9125. */
  9126. clear: function () {
  9127. this.eachBuiltinLayer(this._clearLayer);
  9128. return this;
  9129. },
  9130. _clearLayer: function (layer) {
  9131. layer.clear();
  9132. },
  9133. setBackgroundColor: function (backgroundColor) {
  9134. this._backgroundColor = backgroundColor;
  9135. },
  9136. /**
  9137. * 修改指定zlevel的绘制参数
  9138. *
  9139. * @param {string} zlevel
  9140. * @param {Object} config 配置对象
  9141. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  9142. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  9143. * @param {number} [config.lastFrameAlpha=0.7]
  9144. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  9145. */
  9146. configLayer: function (zlevel, config) {
  9147. if (config) {
  9148. var layerConfig = this._layerConfig;
  9149. if (!layerConfig[zlevel]) {
  9150. layerConfig[zlevel] = config;
  9151. }
  9152. else {
  9153. merge(layerConfig[zlevel], config, true);
  9154. }
  9155. for (var i = 0; i < this._zlevelList.length; i++) {
  9156. var _zlevel = this._zlevelList[i];
  9157. // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  9158. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  9159. var layer = this._layers[_zlevel];
  9160. merge(layer, layerConfig[zlevel], true);
  9161. }
  9162. }
  9163. }
  9164. },
  9165. /**
  9166. * 删除指定层
  9167. * @param {number} zlevel 层所在的zlevel
  9168. */
  9169. delLayer: function (zlevel) {
  9170. var layers = this._layers;
  9171. var zlevelList = this._zlevelList;
  9172. var layer = layers[zlevel];
  9173. if (!layer) {
  9174. return;
  9175. }
  9176. layer.dom.parentNode.removeChild(layer.dom);
  9177. delete layers[zlevel];
  9178. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  9179. },
  9180. /**
  9181. * 区域大小变化后重绘
  9182. */
  9183. resize: function (width, height) {
  9184. if (!this._domRoot.style) { // Maybe in node or worker
  9185. if (width == null || height == null) {
  9186. return;
  9187. }
  9188. this._width = width;
  9189. this._height = height;
  9190. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  9191. }
  9192. else {
  9193. var domRoot = this._domRoot;
  9194. // FIXME Why ?
  9195. domRoot.style.display = 'none';
  9196. // Save input w/h
  9197. var opts = this._opts;
  9198. width != null && (opts.width = width);
  9199. height != null && (opts.height = height);
  9200. width = this._getSize(0);
  9201. height = this._getSize(1);
  9202. domRoot.style.display = '';
  9203. // 优化没有实际改变的resize
  9204. if (this._width !== width || height !== this._height) {
  9205. domRoot.style.width = width + 'px';
  9206. domRoot.style.height = height + 'px';
  9207. for (var id in this._layers) {
  9208. if (this._layers.hasOwnProperty(id)) {
  9209. this._layers[id].resize(width, height);
  9210. }
  9211. }
  9212. each$1(this._progressiveLayers, function (layer) {
  9213. layer.resize(width, height);
  9214. });
  9215. this.refresh(true);
  9216. }
  9217. this._width = width;
  9218. this._height = height;
  9219. }
  9220. return this;
  9221. },
  9222. /**
  9223. * 清除单独的一个层
  9224. * @param {number} zlevel
  9225. */
  9226. clearLayer: function (zlevel) {
  9227. var layer = this._layers[zlevel];
  9228. if (layer) {
  9229. layer.clear();
  9230. }
  9231. },
  9232. /**
  9233. * 释放
  9234. */
  9235. dispose: function () {
  9236. this.root.innerHTML = '';
  9237. this.root =
  9238. this.storage =
  9239. this._domRoot =
  9240. this._layers = null;
  9241. },
  9242. /**
  9243. * Get canvas which has all thing rendered
  9244. * @param {Object} opts
  9245. * @param {string} [opts.backgroundColor]
  9246. * @param {number} [opts.pixelRatio]
  9247. */
  9248. getRenderedCanvas: function (opts) {
  9249. opts = opts || {};
  9250. if (this._singleCanvas && !this._compositeManually) {
  9251. return this._layers[CANVAS_ZLEVEL].dom;
  9252. }
  9253. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  9254. imageLayer.initContext();
  9255. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  9256. if (opts.pixelRatio <= this.dpr) {
  9257. this.refresh();
  9258. var width = imageLayer.dom.width;
  9259. var height = imageLayer.dom.height;
  9260. var ctx = imageLayer.ctx;
  9261. this.eachLayer(function (layer) {
  9262. if (layer.__builtin__) {
  9263. ctx.drawImage(layer.dom, 0, 0, width, height);
  9264. }
  9265. else if (layer.renderToCanvas) {
  9266. imageLayer.ctx.save();
  9267. layer.renderToCanvas(imageLayer.ctx);
  9268. imageLayer.ctx.restore();
  9269. }
  9270. });
  9271. }
  9272. else {
  9273. // PENDING, echarts-gl and incremental rendering.
  9274. var scope = {};
  9275. var displayList = this.storage.getDisplayList(true);
  9276. for (var i = 0; i < displayList.length; i++) {
  9277. var el = displayList[i];
  9278. this._doPaintEl(el, imageLayer, true, scope);
  9279. }
  9280. }
  9281. return imageLayer.dom;
  9282. },
  9283. /**
  9284. * 获取绘图区域宽度
  9285. */
  9286. getWidth: function () {
  9287. return this._width;
  9288. },
  9289. /**
  9290. * 获取绘图区域高度
  9291. */
  9292. getHeight: function () {
  9293. return this._height;
  9294. },
  9295. _getSize: function (whIdx) {
  9296. var opts = this._opts;
  9297. var wh = ['width', 'height'][whIdx];
  9298. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  9299. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  9300. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  9301. if (opts[wh] != null && opts[wh] !== 'auto') {
  9302. return parseFloat(opts[wh]);
  9303. }
  9304. var root = this.root;
  9305. // IE8 does not support getComputedStyle, but it use VML.
  9306. var stl = document.defaultView.getComputedStyle(root);
  9307. return (
  9308. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  9309. - (parseInt10(stl[plt]) || 0)
  9310. - (parseInt10(stl[prb]) || 0)
  9311. ) | 0;
  9312. },
  9313. pathToImage: function (path, dpr) {
  9314. dpr = dpr || this.dpr;
  9315. var canvas = document.createElement('canvas');
  9316. var ctx = canvas.getContext('2d');
  9317. var rect = path.getBoundingRect();
  9318. var style = path.style;
  9319. var shadowBlurSize = style.shadowBlur * dpr;
  9320. var shadowOffsetX = style.shadowOffsetX * dpr;
  9321. var shadowOffsetY = style.shadowOffsetY * dpr;
  9322. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  9323. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  9324. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  9325. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  9326. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  9327. var width = rect.width + leftMargin + rightMargin;
  9328. var height = rect.height + topMargin + bottomMargin;
  9329. canvas.width = width * dpr;
  9330. canvas.height = height * dpr;
  9331. ctx.scale(dpr, dpr);
  9332. ctx.clearRect(0, 0, width, height);
  9333. ctx.dpr = dpr;
  9334. var pathTransform = {
  9335. position: path.position,
  9336. rotation: path.rotation,
  9337. scale: path.scale
  9338. };
  9339. path.position = [leftMargin - rect.x, topMargin - rect.y];
  9340. path.rotation = 0;
  9341. path.scale = [1, 1];
  9342. path.updateTransform();
  9343. if (path) {
  9344. path.brush(ctx);
  9345. }
  9346. var ImageShape = ZImage;
  9347. var imgShape = new ImageShape({
  9348. style: {
  9349. x: 0,
  9350. y: 0,
  9351. image: canvas
  9352. }
  9353. });
  9354. if (pathTransform.position != null) {
  9355. imgShape.position = path.position = pathTransform.position;
  9356. }
  9357. if (pathTransform.rotation != null) {
  9358. imgShape.rotation = path.rotation = pathTransform.rotation;
  9359. }
  9360. if (pathTransform.scale != null) {
  9361. imgShape.scale = path.scale = pathTransform.scale;
  9362. }
  9363. return imgShape;
  9364. }
  9365. };
  9366. /**
  9367. * Animation main class, dispatch and manage all animation controllers
  9368. *
  9369. * @module zrender/animation/Animation
  9370. * @author pissang(https://github.com/pissang)
  9371. */
  9372. // TODO Additive animation
  9373. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  9374. // https://developer.apple.com/videos/wwdc2014/#236
  9375. /**
  9376. * @typedef {Object} IZRenderStage
  9377. * @property {Function} update
  9378. */
  9379. /**
  9380. * @alias module:zrender/animation/Animation
  9381. * @constructor
  9382. * @param {Object} [options]
  9383. * @param {Function} [options.onframe]
  9384. * @param {IZRenderStage} [options.stage]
  9385. * @example
  9386. * var animation = new Animation();
  9387. * var obj = {
  9388. * x: 100,
  9389. * y: 100
  9390. * };
  9391. * animation.animate(node.position)
  9392. * .when(1000, {
  9393. * x: 500,
  9394. * y: 500
  9395. * })
  9396. * .when(2000, {
  9397. * x: 100,
  9398. * y: 100
  9399. * })
  9400. * .start('spline');
  9401. */
  9402. var Animation = function (options) {
  9403. options = options || {};
  9404. this.stage = options.stage || {};
  9405. this.onframe = options.onframe || function () {};
  9406. // private properties
  9407. this._clips = [];
  9408. this._running = false;
  9409. this._time;
  9410. this._pausedTime;
  9411. this._pauseStart;
  9412. this._paused = false;
  9413. Eventful.call(this);
  9414. };
  9415. Animation.prototype = {
  9416. constructor: Animation,
  9417. /**
  9418. * Add clip
  9419. * @param {module:zrender/animation/Clip} clip
  9420. */
  9421. addClip: function (clip) {
  9422. this._clips.push(clip);
  9423. },
  9424. /**
  9425. * Add animator
  9426. * @param {module:zrender/animation/Animator} animator
  9427. */
  9428. addAnimator: function (animator) {
  9429. animator.animation = this;
  9430. var clips = animator.getClips();
  9431. for (var i = 0; i < clips.length; i++) {
  9432. this.addClip(clips[i]);
  9433. }
  9434. },
  9435. /**
  9436. * Delete animation clip
  9437. * @param {module:zrender/animation/Clip} clip
  9438. */
  9439. removeClip: function (clip) {
  9440. var idx = indexOf(this._clips, clip);
  9441. if (idx >= 0) {
  9442. this._clips.splice(idx, 1);
  9443. }
  9444. },
  9445. /**
  9446. * Delete animation clip
  9447. * @param {module:zrender/animation/Animator} animator
  9448. */
  9449. removeAnimator: function (animator) {
  9450. var clips = animator.getClips();
  9451. for (var i = 0; i < clips.length; i++) {
  9452. this.removeClip(clips[i]);
  9453. }
  9454. animator.animation = null;
  9455. },
  9456. _update: function () {
  9457. var time = new Date().getTime() - this._pausedTime;
  9458. var delta = time - this._time;
  9459. var clips = this._clips;
  9460. var len = clips.length;
  9461. var deferredEvents = [];
  9462. var deferredClips = [];
  9463. for (var i = 0; i < len; i++) {
  9464. var clip = clips[i];
  9465. var e = clip.step(time, delta);
  9466. // Throw out the events need to be called after
  9467. // stage.update, like destroy
  9468. if (e) {
  9469. deferredEvents.push(e);
  9470. deferredClips.push(clip);
  9471. }
  9472. }
  9473. // Remove the finished clip
  9474. for (var i = 0; i < len;) {
  9475. if (clips[i]._needsRemove) {
  9476. clips[i] = clips[len - 1];
  9477. clips.pop();
  9478. len--;
  9479. }
  9480. else {
  9481. i++;
  9482. }
  9483. }
  9484. len = deferredEvents.length;
  9485. for (var i = 0; i < len; i++) {
  9486. deferredClips[i].fire(deferredEvents[i]);
  9487. }
  9488. this._time = time;
  9489. this.onframe(delta);
  9490. // 'frame' should be triggered before stage, because upper application
  9491. // depends on the sequence (e.g., echarts-stream and finish
  9492. // event judge)
  9493. this.trigger('frame', delta);
  9494. if (this.stage.update) {
  9495. this.stage.update();
  9496. }
  9497. },
  9498. _startLoop: function () {
  9499. var self = this;
  9500. this._running = true;
  9501. function step() {
  9502. if (self._running) {
  9503. requestAnimationFrame(step);
  9504. !self._paused && self._update();
  9505. }
  9506. }
  9507. requestAnimationFrame(step);
  9508. },
  9509. /**
  9510. * Start animation.
  9511. */
  9512. start: function () {
  9513. this._time = new Date().getTime();
  9514. this._pausedTime = 0;
  9515. this._startLoop();
  9516. },
  9517. /**
  9518. * Stop animation.
  9519. */
  9520. stop: function () {
  9521. this._running = false;
  9522. },
  9523. /**
  9524. * Pause animation.
  9525. */
  9526. pause: function () {
  9527. if (!this._paused) {
  9528. this._pauseStart = new Date().getTime();
  9529. this._paused = true;
  9530. }
  9531. },
  9532. /**
  9533. * Resume animation.
  9534. */
  9535. resume: function () {
  9536. if (this._paused) {
  9537. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9538. this._paused = false;
  9539. }
  9540. },
  9541. /**
  9542. * Clear animation.
  9543. */
  9544. clear: function () {
  9545. this._clips = [];
  9546. },
  9547. /**
  9548. * Whether animation finished.
  9549. */
  9550. isFinished: function () {
  9551. return !this._clips.length;
  9552. },
  9553. /**
  9554. * Creat animator for a target, whose props can be animated.
  9555. *
  9556. * @param {Object} target
  9557. * @param {Object} options
  9558. * @param {boolean} [options.loop=false] Whether loop animation.
  9559. * @param {Function} [options.getter=null] Get value from target.
  9560. * @param {Function} [options.setter=null] Set value to target.
  9561. * @return {module:zrender/animation/Animation~Animator}
  9562. */
  9563. // TODO Gap
  9564. animate: function (target, options) {
  9565. options = options || {};
  9566. var animator = new Animator(
  9567. target,
  9568. options.loop,
  9569. options.getter,
  9570. options.setter
  9571. );
  9572. this.addAnimator(animator);
  9573. return animator;
  9574. }
  9575. };
  9576. mixin(Animation, Eventful);
  9577. /* global document */
  9578. var TOUCH_CLICK_DELAY = 300;
  9579. var globalEventSupported = env$1.domSupported;
  9580. var localNativeListenerNames = (function () {
  9581. var mouseHandlerNames = [
  9582. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9583. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9584. ];
  9585. var touchHandlerNames = [
  9586. 'touchstart', 'touchend', 'touchmove'
  9587. ];
  9588. var pointerEventNameMap = {
  9589. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9590. };
  9591. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9592. var nm = name.replace('mouse', 'pointer');
  9593. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9594. });
  9595. return {
  9596. mouse: mouseHandlerNames,
  9597. touch: touchHandlerNames,
  9598. pointer: pointerHandlerNames
  9599. };
  9600. })();
  9601. var globalNativeListenerNames = {
  9602. mouse: ['mousemove', 'mouseup'],
  9603. pointer: ['pointermove', 'pointerup']
  9604. };
  9605. function eventNameFix(name) {
  9606. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9607. }
  9608. function isPointerFromTouch(event) {
  9609. var pointerType = event.pointerType;
  9610. return pointerType === 'pen' || pointerType === 'touch';
  9611. }
  9612. // function useMSGuesture(handlerProxy, event) {
  9613. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9614. // }
  9615. // function onMSGestureChange(proxy, event) {
  9616. // if (event.translationX || event.translationY) {
  9617. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9618. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9619. // }
  9620. // if (event.scale !== 1) {
  9621. // event.pinchX = event.offsetX;
  9622. // event.pinchY = event.offsetY;
  9623. // event.pinchScale = event.scale;
  9624. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9625. // }
  9626. // }
  9627. /**
  9628. * Prevent mouse event from being dispatched after Touch Events action
  9629. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9630. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9631. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9632. * Result: Blocking Mouse Events for 700ms.
  9633. *
  9634. * @param {DOMHandlerScope} scope
  9635. */
  9636. function setTouchTimer(scope) {
  9637. scope.touching = true;
  9638. if (scope.touchTimer != null) {
  9639. clearTimeout(scope.touchTimer);
  9640. scope.touchTimer = null;
  9641. }
  9642. scope.touchTimer = setTimeout(function () {
  9643. scope.touching = false;
  9644. scope.touchTimer = null;
  9645. }, 700);
  9646. }
  9647. // Mark touch, which is useful in distinguish touch and
  9648. // mouse event in upper applicatoin.
  9649. function markTouch(event) {
  9650. event && (event.zrByTouch = true);
  9651. }
  9652. // function markTriggeredFromLocal(event) {
  9653. // event && (event.__zrIsFromLocal = true);
  9654. // }
  9655. // function isTriggeredFromLocal(instance, event) {
  9656. // return !!(event && event.__zrIsFromLocal);
  9657. // }
  9658. function normalizeGlobalEvent(instance, event) {
  9659. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9660. // handlers of the upper applications. Set `true` to force calculate them.
  9661. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9662. }
  9663. /**
  9664. * Detect whether the given el is in `painterRoot`.
  9665. */
  9666. function isLocalEl(instance, el) {
  9667. var elTmp = el;
  9668. var isLocal = false;
  9669. while (elTmp && elTmp.nodeType !== 9
  9670. && !(
  9671. isLocal = elTmp.domBelongToZr
  9672. || (elTmp !== el && elTmp === instance.painterRoot)
  9673. )
  9674. ) {
  9675. elTmp = elTmp.parentNode;
  9676. }
  9677. return isLocal;
  9678. }
  9679. /**
  9680. * Make a fake event but not change the original event,
  9681. * becuase the global event probably be used by other
  9682. * listeners not belonging to zrender.
  9683. * @class
  9684. */
  9685. function FakeGlobalEvent(instance, event) {
  9686. this.type = event.type;
  9687. this.target = this.currentTarget = instance.dom;
  9688. this.pointerType = event.pointerType;
  9689. // Necessray for the force calculation of zrX, zrY
  9690. this.clientX = event.clientX;
  9691. this.clientY = event.clientY;
  9692. // Because we do not mount global listeners to touch events,
  9693. // we do not copy `targetTouches` and `changedTouches` here.
  9694. }
  9695. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9696. // we make the default methods on the event do nothing,
  9697. // otherwise it is dangerous. See more details in
  9698. // [Drag outside] in `Handler.js`.
  9699. fakeGlobalEventProto.stopPropagation =
  9700. fakeGlobalEventProto.stopImmediatePropagation =
  9701. fakeGlobalEventProto.preventDefault = noop;
  9702. /**
  9703. * Local DOM Handlers
  9704. * @this {HandlerProxy}
  9705. */
  9706. var localDOMHandlers = {
  9707. mousedown: function (event) {
  9708. event = normalizeEvent(this.dom, event);
  9709. this._mayPointerCapture = [event.zrX, event.zrY];
  9710. this.trigger('mousedown', event);
  9711. },
  9712. mousemove: function (event) {
  9713. event = normalizeEvent(this.dom, event);
  9714. var downPoint = this._mayPointerCapture;
  9715. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9716. togglePointerCapture(this, true);
  9717. }
  9718. this.trigger('mousemove', event);
  9719. },
  9720. mouseup: function (event) {
  9721. event = normalizeEvent(this.dom, event);
  9722. togglePointerCapture(this, false);
  9723. this.trigger('mouseup', event);
  9724. },
  9725. mouseout: function (event) {
  9726. event = normalizeEvent(this.dom, event);
  9727. // Similarly to the browser did on `document` and touch event,
  9728. // `globalout` will be delayed to final pointer cature release.
  9729. if (this._pointerCapturing) {
  9730. event.zrEventControl = 'no_globalout';
  9731. }
  9732. // There might be some doms created by upper layer application
  9733. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9734. // dom created by echarts), where 'globalout' event should not
  9735. // be triggered when mouse enters these doms. (But 'mouseout'
  9736. // should be triggered at the original hovered element as usual).
  9737. var element = event.toElement || event.relatedTarget;
  9738. event.zrIsToLocalDOM = isLocalEl(this, element);
  9739. this.trigger('mouseout', event);
  9740. },
  9741. touchstart: function (event) {
  9742. // Default mouse behaviour should not be disabled here.
  9743. // For example, page may needs to be slided.
  9744. event = normalizeEvent(this.dom, event);
  9745. markTouch(event);
  9746. this._lastTouchMoment = new Date();
  9747. this.handler.processGesture(event, 'start');
  9748. // For consistent event listener for both touch device and mouse device,
  9749. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9750. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9751. // `mousedown`.
  9752. localDOMHandlers.mousemove.call(this, event);
  9753. localDOMHandlers.mousedown.call(this, event);
  9754. },
  9755. touchmove: function (event) {
  9756. event = normalizeEvent(this.dom, event);
  9757. markTouch(event);
  9758. this.handler.processGesture(event, 'change');
  9759. // Mouse move should always be triggered no matter whether
  9760. // there is gestrue event, because mouse move and pinch may
  9761. // be used at the same time.
  9762. localDOMHandlers.mousemove.call(this, event);
  9763. },
  9764. touchend: function (event) {
  9765. event = normalizeEvent(this.dom, event);
  9766. markTouch(event);
  9767. this.handler.processGesture(event, 'end');
  9768. localDOMHandlers.mouseup.call(this, event);
  9769. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9770. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9771. // we can conveniently implement "hover style" in both PC and touch device just
  9772. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9773. // to remove "hover style" on an element, without any additional code for
  9774. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9775. // style" will remain for user view)
  9776. // click event should always be triggered no matter whether
  9777. // there is gestrue event. System click can not be prevented.
  9778. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9779. localDOMHandlers.click.call(this, event);
  9780. }
  9781. },
  9782. pointerdown: function (event) {
  9783. localDOMHandlers.mousedown.call(this, event);
  9784. // if (useMSGuesture(this, event)) {
  9785. // this._msGesture.addPointer(event.pointerId);
  9786. // }
  9787. },
  9788. pointermove: function (event) {
  9789. // FIXME
  9790. // pointermove is so sensitive that it always triggered when
  9791. // tap(click) on touch screen, which affect some judgement in
  9792. // upper application. So, we dont support mousemove on MS touch
  9793. // device yet.
  9794. if (!isPointerFromTouch(event)) {
  9795. localDOMHandlers.mousemove.call(this, event);
  9796. }
  9797. },
  9798. pointerup: function (event) {
  9799. localDOMHandlers.mouseup.call(this, event);
  9800. },
  9801. pointerout: function (event) {
  9802. // pointerout will be triggered when tap on touch screen
  9803. // (IE11+/Edge on MS Surface) after click event triggered,
  9804. // which is inconsistent with the mousout behavior we defined
  9805. // in touchend. So we unify them.
  9806. // (check localDOMHandlers.touchend for detailed explanation)
  9807. if (!isPointerFromTouch(event)) {
  9808. localDOMHandlers.mouseout.call(this, event);
  9809. }
  9810. }
  9811. };
  9812. /**
  9813. * Othere DOM UI Event handlers for zr dom.
  9814. * @this {HandlerProxy}
  9815. */
  9816. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9817. localDOMHandlers[name] = function (event) {
  9818. event = normalizeEvent(this.dom, event);
  9819. this.trigger(name, event);
  9820. };
  9821. });
  9822. /**
  9823. * DOM UI Event handlers for global page.
  9824. *
  9825. * [Caution]:
  9826. * those handlers should both support in capture phase and bubble phase!
  9827. *
  9828. * @this {HandlerProxy}
  9829. */
  9830. var globalDOMHandlers = {
  9831. pointermove: function (event) {
  9832. // FIXME
  9833. // pointermove is so sensitive that it always triggered when
  9834. // tap(click) on touch screen, which affect some judgement in
  9835. // upper application. So, we dont support mousemove on MS touch
  9836. // device yet.
  9837. if (!isPointerFromTouch(event)) {
  9838. globalDOMHandlers.mousemove.call(this, event);
  9839. }
  9840. },
  9841. pointerup: function (event) {
  9842. globalDOMHandlers.mouseup.call(this, event);
  9843. },
  9844. mousemove: function (event) {
  9845. this.trigger('mousemove', event);
  9846. },
  9847. mouseup: function (event) {
  9848. var pointerCaptureReleasing = this._pointerCapturing;
  9849. togglePointerCapture(this, false);
  9850. this.trigger('mouseup', event);
  9851. if (pointerCaptureReleasing) {
  9852. event.zrEventControl = 'only_globalout';
  9853. this.trigger('mouseout', event);
  9854. }
  9855. }
  9856. };
  9857. /**
  9858. * @param {HandlerProxy} instance
  9859. * @param {DOMHandlerScope} scope
  9860. */
  9861. function mountLocalDOMEventListeners(instance, scope) {
  9862. var domHandlers = scope.domHandlers;
  9863. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9864. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9865. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9866. // at the same time.
  9867. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9868. // screen, which do not occurs in pointer event.
  9869. // So we use pointer event to both detect touch gesture and mouse behavior.
  9870. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9871. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9872. // markTriggeredFromLocal(event);
  9873. domHandlers[nativeEventName].call(instance, event);
  9874. });
  9875. });
  9876. // FIXME
  9877. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9878. // which does not prevent defuault behavior occasionally (which may cause view port
  9879. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9880. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9881. // touch screen. And we only support click behavior on MS touch screen now.
  9882. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9883. // We dont support touch on IE on win7.
  9884. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9885. // if (typeof MSGesture === 'function') {
  9886. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9887. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9888. // }
  9889. }
  9890. else {
  9891. if (env$1.touchEventsSupported) {
  9892. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9893. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9894. // markTriggeredFromLocal(event);
  9895. domHandlers[nativeEventName].call(instance, event);
  9896. setTouchTimer(scope);
  9897. });
  9898. });
  9899. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9900. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9901. }
  9902. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9903. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9904. // mouse event can not be handle in those devices.
  9905. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9906. // mouseevent after touch event triggered, see `setTouchTimer`.
  9907. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9908. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9909. event = getNativeEvent(event);
  9910. if (!scope.touching) {
  9911. // markTriggeredFromLocal(event);
  9912. domHandlers[nativeEventName].call(instance, event);
  9913. }
  9914. });
  9915. });
  9916. }
  9917. }
  9918. /**
  9919. * @param {HandlerProxy} instance
  9920. * @param {DOMHandlerScope} scope
  9921. */
  9922. function mountGlobalDOMEventListeners(instance, scope) {
  9923. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9924. if (env$1.pointerEventsSupported) {
  9925. each$1(globalNativeListenerNames.pointer, mount);
  9926. }
  9927. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9928. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9929. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9930. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9931. else if (!env$1.touchEventsSupported) {
  9932. each$1(globalNativeListenerNames.mouse, mount);
  9933. }
  9934. function mount(nativeEventName) {
  9935. function nativeEventListener(event) {
  9936. event = getNativeEvent(event);
  9937. // See the reason in [Drag outside] in `Handler.js`
  9938. // This checking supports both `useCapture` or not.
  9939. // PENDING: if there is performance issue in some devices,
  9940. // we probably can not use `useCapture` and change a easier
  9941. // to judes whether local (mark).
  9942. if (!isLocalEl(instance, event.target)) {
  9943. event = normalizeGlobalEvent(instance, event);
  9944. scope.domHandlers[nativeEventName].call(instance, event);
  9945. }
  9946. }
  9947. mountSingleDOMEventListener(
  9948. scope, nativeEventName, nativeEventListener,
  9949. {capture: true} // See [Drag Outside] in `Handler.js`
  9950. );
  9951. }
  9952. }
  9953. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9954. scope.mounted[nativeEventName] = listener;
  9955. scope.listenerOpts[nativeEventName] = opt;
  9956. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9957. }
  9958. function unmountDOMEventListeners(scope) {
  9959. var mounted = scope.mounted;
  9960. for (var nativeEventName in mounted) {
  9961. if (mounted.hasOwnProperty(nativeEventName)) {
  9962. removeEventListener(
  9963. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9964. scope.listenerOpts[nativeEventName]
  9965. );
  9966. }
  9967. }
  9968. scope.mounted = {};
  9969. }
  9970. /**
  9971. * See [Drag Outside] in `Handler.js`.
  9972. * @implement
  9973. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9974. * `true`: start to capture pointer if it is not capturing.
  9975. * `false`: end the capture if it is capturing.
  9976. */
  9977. function togglePointerCapture(instance, isPointerCapturing) {
  9978. instance._mayPointerCapture = null;
  9979. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9980. instance._pointerCapturing = isPointerCapturing;
  9981. var globalHandlerScope = instance._globalHandlerScope;
  9982. isPointerCapturing
  9983. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9984. : unmountDOMEventListeners(globalHandlerScope);
  9985. }
  9986. }
  9987. /**
  9988. * @inner
  9989. * @class
  9990. */
  9991. function DOMHandlerScope(domTarget, domHandlers) {
  9992. this.domTarget = domTarget;
  9993. this.domHandlers = domHandlers;
  9994. // Key: eventName, value: mounted handler funcitons.
  9995. // Used for unmount.
  9996. this.mounted = {};
  9997. this.listenerOpts = {};
  9998. this.touchTimer = null;
  9999. this.touching = false;
  10000. }
  10001. /**
  10002. * @public
  10003. * @class
  10004. */
  10005. function HandlerDomProxy(dom, painterRoot) {
  10006. Eventful.call(this);
  10007. this.dom = dom;
  10008. this.painterRoot = painterRoot;
  10009. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  10010. if (globalEventSupported) {
  10011. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  10012. }
  10013. /**
  10014. * @type {boolean}
  10015. */
  10016. this._pointerCapturing = false;
  10017. /**
  10018. * @type {Array.<number>} [x, y] or null.
  10019. */
  10020. this._mayPointerCapture = null;
  10021. mountLocalDOMEventListeners(this, this._localHandlerScope);
  10022. }
  10023. var handlerDomProxyProto = HandlerDomProxy.prototype;
  10024. handlerDomProxyProto.dispose = function () {
  10025. unmountDOMEventListeners(this._localHandlerScope);
  10026. if (globalEventSupported) {
  10027. unmountDOMEventListeners(this._globalHandlerScope);
  10028. }
  10029. };
  10030. handlerDomProxyProto.setCursor = function (cursorStyle) {
  10031. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  10032. };
  10033. mixin(HandlerDomProxy, Eventful);
  10034. /*!
  10035. * ZRender, a high performance 2d drawing library.
  10036. *
  10037. * Copyright (c) 2013, Baidu Inc.
  10038. * All rights reserved.
  10039. *
  10040. * LICENSE
  10041. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  10042. */
  10043. var useVML = !env$1.canvasSupported;
  10044. var painterCtors = {
  10045. canvas: Painter
  10046. };
  10047. var instances$1 = {}; // ZRender实例map索引
  10048. /**
  10049. * @type {string}
  10050. */
  10051. var version$1 = '4.3.2';
  10052. /**
  10053. * Initializing a zrender instance
  10054. * @param {HTMLElement} dom
  10055. * @param {Object} [opts]
  10056. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  10057. * @param {number} [opts.devicePixelRatio]
  10058. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10059. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10060. * @return {module:zrender/ZRender}
  10061. */
  10062. function init$1(dom, opts) {
  10063. var zr = new ZRender(guid(), dom, opts);
  10064. instances$1[zr.id] = zr;
  10065. return zr;
  10066. }
  10067. /**
  10068. * Dispose zrender instance
  10069. * @param {module:zrender/ZRender} zr
  10070. */
  10071. function dispose$1(zr) {
  10072. if (zr) {
  10073. zr.dispose();
  10074. }
  10075. else {
  10076. for (var key in instances$1) {
  10077. if (instances$1.hasOwnProperty(key)) {
  10078. instances$1[key].dispose();
  10079. }
  10080. }
  10081. instances$1 = {};
  10082. }
  10083. return this;
  10084. }
  10085. /**
  10086. * Get zrender instance by id
  10087. * @param {string} id zrender instance id
  10088. * @return {module:zrender/ZRender}
  10089. */
  10090. function getInstance(id) {
  10091. return instances$1[id];
  10092. }
  10093. function registerPainter(name, Ctor) {
  10094. painterCtors[name] = Ctor;
  10095. }
  10096. function delInstance(id) {
  10097. delete instances$1[id];
  10098. }
  10099. /**
  10100. * @module zrender/ZRender
  10101. */
  10102. /**
  10103. * @constructor
  10104. * @alias module:zrender/ZRender
  10105. * @param {string} id
  10106. * @param {HTMLElement} dom
  10107. * @param {Object} opts
  10108. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  10109. * @param {number} [opts.devicePixelRatio]
  10110. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  10111. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  10112. */
  10113. var ZRender = function (id, dom, opts) {
  10114. opts = opts || {};
  10115. /**
  10116. * @type {HTMLDomElement}
  10117. */
  10118. this.dom = dom;
  10119. /**
  10120. * @type {string}
  10121. */
  10122. this.id = id;
  10123. var self = this;
  10124. var storage = new Storage();
  10125. var rendererType = opts.renderer;
  10126. // TODO WebGL
  10127. if (useVML) {
  10128. if (!painterCtors.vml) {
  10129. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  10130. }
  10131. rendererType = 'vml';
  10132. }
  10133. else if (!rendererType || !painterCtors[rendererType]) {
  10134. rendererType = 'canvas';
  10135. }
  10136. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  10137. this.storage = storage;
  10138. this.painter = painter;
  10139. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  10140. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  10141. /**
  10142. * @type {module:zrender/animation/Animation}
  10143. */
  10144. this.animation = new Animation({
  10145. stage: {
  10146. update: bind(this.flush, this)
  10147. }
  10148. });
  10149. this.animation.start();
  10150. /**
  10151. * @type {boolean}
  10152. * @private
  10153. */
  10154. this._needsRefresh;
  10155. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  10156. // FIXME 有点ugly
  10157. var oldDelFromStorage = storage.delFromStorage;
  10158. var oldAddToStorage = storage.addToStorage;
  10159. storage.delFromStorage = function (el) {
  10160. oldDelFromStorage.call(storage, el);
  10161. el && el.removeSelfFromZr(self);
  10162. };
  10163. storage.addToStorage = function (el) {
  10164. oldAddToStorage.call(storage, el);
  10165. el.addSelfToZr(self);
  10166. };
  10167. };
  10168. ZRender.prototype = {
  10169. constructor: ZRender,
  10170. /**
  10171. * 获取实例唯一标识
  10172. * @return {string}
  10173. */
  10174. getId: function () {
  10175. return this.id;
  10176. },
  10177. /**
  10178. * 添加元素
  10179. * @param {module:zrender/Element} el
  10180. */
  10181. add: function (el) {
  10182. this.storage.addRoot(el);
  10183. this._needsRefresh = true;
  10184. },
  10185. /**
  10186. * 删除元素
  10187. * @param {module:zrender/Element} el
  10188. */
  10189. remove: function (el) {
  10190. this.storage.delRoot(el);
  10191. this._needsRefresh = true;
  10192. },
  10193. /**
  10194. * Change configuration of layer
  10195. * @param {string} zLevel
  10196. * @param {Object} config
  10197. * @param {string} [config.clearColor=0] Clear color
  10198. * @param {string} [config.motionBlur=false] If enable motion blur
  10199. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  10200. */
  10201. configLayer: function (zLevel, config) {
  10202. if (this.painter.configLayer) {
  10203. this.painter.configLayer(zLevel, config);
  10204. }
  10205. this._needsRefresh = true;
  10206. },
  10207. /**
  10208. * Set background color
  10209. * @param {string} backgroundColor
  10210. */
  10211. setBackgroundColor: function (backgroundColor) {
  10212. if (this.painter.setBackgroundColor) {
  10213. this.painter.setBackgroundColor(backgroundColor);
  10214. }
  10215. this._needsRefresh = true;
  10216. },
  10217. /**
  10218. * Repaint the canvas immediately
  10219. */
  10220. refreshImmediately: function () {
  10221. // var start = new Date();
  10222. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  10223. // Or it will cause zrender refreshes again and again.
  10224. this._needsRefresh = this._needsRefreshHover = false;
  10225. this.painter.refresh();
  10226. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  10227. this._needsRefresh = this._needsRefreshHover = false;
  10228. // var end = new Date();
  10229. // var log = document.getElementById('log');
  10230. // if (log) {
  10231. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  10232. // }
  10233. },
  10234. /**
  10235. * Mark and repaint the canvas in the next frame of browser
  10236. */
  10237. refresh: function () {
  10238. this._needsRefresh = true;
  10239. },
  10240. /**
  10241. * Perform all refresh
  10242. */
  10243. flush: function () {
  10244. var triggerRendered;
  10245. if (this._needsRefresh) {
  10246. triggerRendered = true;
  10247. this.refreshImmediately();
  10248. }
  10249. if (this._needsRefreshHover) {
  10250. triggerRendered = true;
  10251. this.refreshHoverImmediately();
  10252. }
  10253. triggerRendered && this.trigger('rendered');
  10254. },
  10255. /**
  10256. * Add element to hover layer
  10257. * @param {module:zrender/Element} el
  10258. * @param {Object} style
  10259. */
  10260. addHover: function (el, style) {
  10261. if (this.painter.addHover) {
  10262. var elMirror = this.painter.addHover(el, style);
  10263. this.refreshHover();
  10264. return elMirror;
  10265. }
  10266. },
  10267. /**
  10268. * Add element from hover layer
  10269. * @param {module:zrender/Element} el
  10270. */
  10271. removeHover: function (el) {
  10272. if (this.painter.removeHover) {
  10273. this.painter.removeHover(el);
  10274. this.refreshHover();
  10275. }
  10276. },
  10277. /**
  10278. * Clear all hover elements in hover layer
  10279. * @param {module:zrender/Element} el
  10280. */
  10281. clearHover: function () {
  10282. if (this.painter.clearHover) {
  10283. this.painter.clearHover();
  10284. this.refreshHover();
  10285. }
  10286. },
  10287. /**
  10288. * Refresh hover in next frame
  10289. */
  10290. refreshHover: function () {
  10291. this._needsRefreshHover = true;
  10292. },
  10293. /**
  10294. * Refresh hover immediately
  10295. */
  10296. refreshHoverImmediately: function () {
  10297. this._needsRefreshHover = false;
  10298. this.painter.refreshHover && this.painter.refreshHover();
  10299. },
  10300. /**
  10301. * Resize the canvas.
  10302. * Should be invoked when container size is changed
  10303. * @param {Object} [opts]
  10304. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10305. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10306. */
  10307. resize: function (opts) {
  10308. opts = opts || {};
  10309. this.painter.resize(opts.width, opts.height);
  10310. this.handler.resize();
  10311. },
  10312. /**
  10313. * Stop and clear all animation immediately
  10314. */
  10315. clearAnimation: function () {
  10316. this.animation.clear();
  10317. },
  10318. /**
  10319. * Get container width
  10320. */
  10321. getWidth: function () {
  10322. return this.painter.getWidth();
  10323. },
  10324. /**
  10325. * Get container height
  10326. */
  10327. getHeight: function () {
  10328. return this.painter.getHeight();
  10329. },
  10330. /**
  10331. * Export the canvas as Base64 URL
  10332. * @param {string} type
  10333. * @param {string} [backgroundColor='#fff']
  10334. * @return {string} Base64 URL
  10335. */
  10336. // toDataURL: function(type, backgroundColor) {
  10337. // return this.painter.getRenderedCanvas({
  10338. // backgroundColor: backgroundColor
  10339. // }).toDataURL(type);
  10340. // },
  10341. /**
  10342. * Converting a path to image.
  10343. * It has much better performance of drawing image rather than drawing a vector path.
  10344. * @param {module:zrender/graphic/Path} e
  10345. * @param {number} width
  10346. * @param {number} height
  10347. */
  10348. pathToImage: function (e, dpr) {
  10349. return this.painter.pathToImage(e, dpr);
  10350. },
  10351. /**
  10352. * Set default cursor
  10353. * @param {string} [cursorStyle='default'] 例如 crosshair
  10354. */
  10355. setCursorStyle: function (cursorStyle) {
  10356. this.handler.setCursorStyle(cursorStyle);
  10357. },
  10358. /**
  10359. * Find hovered element
  10360. * @param {number} x
  10361. * @param {number} y
  10362. * @return {Object} {target, topTarget}
  10363. */
  10364. findHover: function (x, y) {
  10365. return this.handler.findHover(x, y);
  10366. },
  10367. /**
  10368. * Bind event
  10369. *
  10370. * @param {string} eventName Event name
  10371. * @param {Function} eventHandler Handler function
  10372. * @param {Object} [context] Context object
  10373. */
  10374. on: function (eventName, eventHandler, context) {
  10375. this.handler.on(eventName, eventHandler, context);
  10376. },
  10377. /**
  10378. * Unbind event
  10379. * @param {string} eventName Event name
  10380. * @param {Function} [eventHandler] Handler function
  10381. */
  10382. off: function (eventName, eventHandler) {
  10383. this.handler.off(eventName, eventHandler);
  10384. },
  10385. /**
  10386. * Trigger event manually
  10387. *
  10388. * @param {string} eventName Event name
  10389. * @param {event=} event Event object
  10390. */
  10391. trigger: function (eventName, event) {
  10392. this.handler.trigger(eventName, event);
  10393. },
  10394. /**
  10395. * Clear all objects and the canvas.
  10396. */
  10397. clear: function () {
  10398. this.storage.delRoot();
  10399. this.painter.clear();
  10400. },
  10401. /**
  10402. * Dispose self.
  10403. */
  10404. dispose: function () {
  10405. this.animation.stop();
  10406. this.clear();
  10407. this.storage.dispose();
  10408. this.painter.dispose();
  10409. this.handler.dispose();
  10410. this.animation =
  10411. this.storage =
  10412. this.painter =
  10413. this.handler = null;
  10414. delInstance(this.id);
  10415. }
  10416. };
  10417. var zrender = (Object.freeze || Object)({
  10418. version: version$1,
  10419. init: init$1,
  10420. dispose: dispose$1,
  10421. getInstance: getInstance,
  10422. registerPainter: registerPainter
  10423. });
  10424. /*
  10425. * Licensed to the Apache Software Foundation (ASF) under one
  10426. * or more contributor license agreements. See the NOTICE file
  10427. * distributed with this work for additional information
  10428. * regarding copyright ownership. The ASF licenses this file
  10429. * to you under the Apache License, Version 2.0 (the
  10430. * "License"); you may not use this file except in compliance
  10431. * with the License. You may obtain a copy of the License at
  10432. *
  10433. * http://www.apache.org/licenses/LICENSE-2.0
  10434. *
  10435. * Unless required by applicable law or agreed to in writing,
  10436. * software distributed under the License is distributed on an
  10437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10438. * KIND, either express or implied. See the License for the
  10439. * specific language governing permissions and limitations
  10440. * under the License.
  10441. */
  10442. var each$2 = each$1;
  10443. var isObject$2 = isObject$1;
  10444. var isArray$1 = isArray;
  10445. /**
  10446. * Make the name displayable. But we should
  10447. * make sure it is not duplicated with user
  10448. * specified name, so use '\0';
  10449. */
  10450. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  10451. /**
  10452. * If value is not array, then translate it to array.
  10453. * @param {*} value
  10454. * @return {Array} [value] or value
  10455. */
  10456. function normalizeToArray(value) {
  10457. return value instanceof Array
  10458. ? value
  10459. : value == null
  10460. ? []
  10461. : [value];
  10462. }
  10463. /**
  10464. * Sync default option between normal and emphasis like `position` and `show`
  10465. * In case some one will write code like
  10466. * label: {
  10467. * show: false,
  10468. * position: 'outside',
  10469. * fontSize: 18
  10470. * },
  10471. * emphasis: {
  10472. * label: { show: true }
  10473. * }
  10474. * @param {Object} opt
  10475. * @param {string} key
  10476. * @param {Array.<string>} subOpts
  10477. */
  10478. function defaultEmphasis(opt, key, subOpts) {
  10479. // Caution: performance sensitive.
  10480. if (opt) {
  10481. opt[key] = opt[key] || {};
  10482. opt.emphasis = opt.emphasis || {};
  10483. opt.emphasis[key] = opt.emphasis[key] || {};
  10484. // Default emphasis option from normal
  10485. for (var i = 0, len = subOpts.length; i < len; i++) {
  10486. var subOptName = subOpts[i];
  10487. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  10488. && opt[key].hasOwnProperty(subOptName)
  10489. ) {
  10490. opt.emphasis[key][subOptName] = opt[key][subOptName];
  10491. }
  10492. }
  10493. }
  10494. }
  10495. var TEXT_STYLE_OPTIONS = [
  10496. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10497. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  10498. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  10499. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  10500. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  10501. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  10502. ];
  10503. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  10504. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  10505. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10506. // // FIXME: deprecated, check and remove it.
  10507. // 'textStyle'
  10508. // ]);
  10509. /**
  10510. * The method do not ensure performance.
  10511. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10512. * This helper method retieves value from data.
  10513. * @param {string|number|Date|Array|Object} dataItem
  10514. * @return {number|string|Date|Array.<number|string|Date>}
  10515. */
  10516. function getDataItemValue(dataItem) {
  10517. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  10518. ? dataItem.value : dataItem;
  10519. }
  10520. /**
  10521. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10522. * This helper method determine if dataItem has extra option besides value
  10523. * @param {string|number|Date|Array|Object} dataItem
  10524. */
  10525. function isDataItemOption(dataItem) {
  10526. return isObject$2(dataItem)
  10527. && !(dataItem instanceof Array);
  10528. // // markLine data can be array
  10529. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  10530. }
  10531. /**
  10532. * Mapping to exists for merge.
  10533. *
  10534. * @public
  10535. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  10536. * @param {Object|Array.<Object>} newCptOptions
  10537. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10538. * index of which is the same as exists.
  10539. */
  10540. function mappingToExists(exists, newCptOptions) {
  10541. // Mapping by the order by original option (but not order of
  10542. // new option) in merge mode. Because we should ensure
  10543. // some specified index (like xAxisIndex) is consistent with
  10544. // original option, which is easy to understand, espatially in
  10545. // media query. And in most case, merge option is used to
  10546. // update partial option but not be expected to change order.
  10547. newCptOptions = (newCptOptions || []).slice();
  10548. var result = map(exists || [], function (obj, index) {
  10549. return {exist: obj};
  10550. });
  10551. // Mapping by id or name if specified.
  10552. each$2(newCptOptions, function (cptOption, index) {
  10553. if (!isObject$2(cptOption)) {
  10554. return;
  10555. }
  10556. // id has highest priority.
  10557. for (var i = 0; i < result.length; i++) {
  10558. if (!result[i].option // Consider name: two map to one.
  10559. && cptOption.id != null
  10560. && result[i].exist.id === cptOption.id + ''
  10561. ) {
  10562. result[i].option = cptOption;
  10563. newCptOptions[index] = null;
  10564. return;
  10565. }
  10566. }
  10567. for (var i = 0; i < result.length; i++) {
  10568. var exist = result[i].exist;
  10569. if (!result[i].option // Consider name: two map to one.
  10570. // Can not match when both ids exist but different.
  10571. && (exist.id == null || cptOption.id == null)
  10572. && cptOption.name != null
  10573. && !isIdInner(cptOption)
  10574. && !isIdInner(exist)
  10575. && exist.name === cptOption.name + ''
  10576. ) {
  10577. result[i].option = cptOption;
  10578. newCptOptions[index] = null;
  10579. return;
  10580. }
  10581. }
  10582. });
  10583. // Otherwise mapping by index.
  10584. each$2(newCptOptions, function (cptOption, index) {
  10585. if (!isObject$2(cptOption)) {
  10586. return;
  10587. }
  10588. var i = 0;
  10589. for (; i < result.length; i++) {
  10590. var exist = result[i].exist;
  10591. if (!result[i].option
  10592. // Existing model that already has id should be able to
  10593. // mapped to (because after mapping performed model may
  10594. // be assigned with a id, whish should not affect next
  10595. // mapping), except those has inner id.
  10596. && !isIdInner(exist)
  10597. // Caution:
  10598. // Do not overwrite id. But name can be overwritten,
  10599. // because axis use name as 'show label text'.
  10600. // 'exist' always has id and name and we dont
  10601. // need to check it.
  10602. && cptOption.id == null
  10603. ) {
  10604. result[i].option = cptOption;
  10605. break;
  10606. }
  10607. }
  10608. if (i >= result.length) {
  10609. result.push({option: cptOption});
  10610. }
  10611. });
  10612. return result;
  10613. }
  10614. /**
  10615. * Make id and name for mapping result (result of mappingToExists)
  10616. * into `keyInfo` field.
  10617. *
  10618. * @public
  10619. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10620. * which order is the same as exists.
  10621. * @return {Array.<Object>} The input.
  10622. */
  10623. function makeIdAndName(mapResult) {
  10624. // We use this id to hash component models and view instances
  10625. // in echarts. id can be specified by user, or auto generated.
  10626. // The id generation rule ensures new view instance are able
  10627. // to mapped to old instance when setOption are called in
  10628. // no-merge mode. So we generate model id by name and plus
  10629. // type in view id.
  10630. // name can be duplicated among components, which is convenient
  10631. // to specify multi components (like series) by one name.
  10632. // Ensure that each id is distinct.
  10633. var idMap = createHashMap();
  10634. each$2(mapResult, function (item, index) {
  10635. var existCpt = item.exist;
  10636. existCpt && idMap.set(existCpt.id, item);
  10637. });
  10638. each$2(mapResult, function (item, index) {
  10639. var opt = item.option;
  10640. assert$1(
  10641. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10642. 'id duplicates: ' + (opt && opt.id)
  10643. );
  10644. opt && opt.id != null && idMap.set(opt.id, item);
  10645. !item.keyInfo && (item.keyInfo = {});
  10646. });
  10647. // Make name and id.
  10648. each$2(mapResult, function (item, index) {
  10649. var existCpt = item.exist;
  10650. var opt = item.option;
  10651. var keyInfo = item.keyInfo;
  10652. if (!isObject$2(opt)) {
  10653. return;
  10654. }
  10655. // name can be overwitten. Consider case: axis.name = '20km'.
  10656. // But id generated by name will not be changed, which affect
  10657. // only in that case: setOption with 'not merge mode' and view
  10658. // instance will be recreated, which can be accepted.
  10659. keyInfo.name = opt.name != null
  10660. ? opt.name + ''
  10661. : existCpt
  10662. ? existCpt.name
  10663. // Avoid diffferent series has the same name,
  10664. // because name may be used like in color pallet.
  10665. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10666. if (existCpt) {
  10667. keyInfo.id = existCpt.id;
  10668. }
  10669. else if (opt.id != null) {
  10670. keyInfo.id = opt.id + '';
  10671. }
  10672. else {
  10673. // Consider this situatoin:
  10674. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10675. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10676. // Series with the same name between optionA and optionB
  10677. // should be mapped.
  10678. var idNum = 0;
  10679. do {
  10680. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10681. }
  10682. while (idMap.get(keyInfo.id));
  10683. }
  10684. idMap.set(keyInfo.id, item);
  10685. });
  10686. }
  10687. function isNameSpecified(componentModel) {
  10688. var name = componentModel.name;
  10689. // Is specified when `indexOf` get -1 or > 0.
  10690. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10691. }
  10692. /**
  10693. * @public
  10694. * @param {Object} cptOption
  10695. * @return {boolean}
  10696. */
  10697. function isIdInner(cptOption) {
  10698. return isObject$2(cptOption)
  10699. && cptOption.id
  10700. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10701. }
  10702. /**
  10703. * A helper for removing duplicate items between batchA and batchB,
  10704. * and in themselves, and categorize by series.
  10705. *
  10706. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10707. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10708. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10709. */
  10710. /**
  10711. * @param {module:echarts/data/List} data
  10712. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10713. * each of which can be Array or primary type.
  10714. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10715. */
  10716. function queryDataIndex(data, payload) {
  10717. if (payload.dataIndexInside != null) {
  10718. return payload.dataIndexInside;
  10719. }
  10720. else if (payload.dataIndex != null) {
  10721. return isArray(payload.dataIndex)
  10722. ? map(payload.dataIndex, function (value) {
  10723. return data.indexOfRawIndex(value);
  10724. })
  10725. : data.indexOfRawIndex(payload.dataIndex);
  10726. }
  10727. else if (payload.name != null) {
  10728. return isArray(payload.name)
  10729. ? map(payload.name, function (value) {
  10730. return data.indexOfName(value);
  10731. })
  10732. : data.indexOfName(payload.name);
  10733. }
  10734. }
  10735. /**
  10736. * Enable property storage to any host object.
  10737. * Notice: Serialization is not supported.
  10738. *
  10739. * For example:
  10740. * var inner = zrUitl.makeInner();
  10741. *
  10742. * function some1(hostObj) {
  10743. * inner(hostObj).someProperty = 1212;
  10744. * ...
  10745. * }
  10746. * function some2() {
  10747. * var fields = inner(this);
  10748. * fields.someProperty1 = 1212;
  10749. * fields.someProperty2 = 'xx';
  10750. * ...
  10751. * }
  10752. *
  10753. * @return {Function}
  10754. */
  10755. function makeInner() {
  10756. // Consider different scope by es module import.
  10757. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10758. return function (hostObj) {
  10759. return hostObj[key] || (hostObj[key] = {});
  10760. };
  10761. }
  10762. var innerUniqueIndex = 0;
  10763. /**
  10764. * @param {module:echarts/model/Global} ecModel
  10765. * @param {string|Object} finder
  10766. * If string, e.g., 'geo', means {geoIndex: 0}.
  10767. * If Object, could contain some of these properties below:
  10768. * {
  10769. * seriesIndex, seriesId, seriesName,
  10770. * geoIndex, geoId, geoName,
  10771. * bmapIndex, bmapId, bmapName,
  10772. * xAxisIndex, xAxisId, xAxisName,
  10773. * yAxisIndex, yAxisId, yAxisName,
  10774. * gridIndex, gridId, gridName,
  10775. * ... (can be extended)
  10776. * }
  10777. * Each properties can be number|string|Array.<number>|Array.<string>
  10778. * For example, a finder could be
  10779. * {
  10780. * seriesIndex: 3,
  10781. * geoId: ['aa', 'cc'],
  10782. * gridName: ['xx', 'rr']
  10783. * }
  10784. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10785. * If nothing or null/undefined specified, return nothing.
  10786. * @param {Object} [opt]
  10787. * @param {string} [opt.defaultMainType]
  10788. * @param {Array.<string>} [opt.includeMainTypes]
  10789. * @return {Object} result like:
  10790. * {
  10791. * seriesModels: [seriesModel1, seriesModel2],
  10792. * seriesModel: seriesModel1, // The first model
  10793. * geoModels: [geoModel1, geoModel2],
  10794. * geoModel: geoModel1, // The first model
  10795. * ...
  10796. * }
  10797. */
  10798. function parseFinder(ecModel, finder, opt) {
  10799. if (isString(finder)) {
  10800. var obj = {};
  10801. obj[finder + 'Index'] = 0;
  10802. finder = obj;
  10803. }
  10804. var defaultMainType = opt && opt.defaultMainType;
  10805. if (defaultMainType
  10806. && !has(finder, defaultMainType + 'Index')
  10807. && !has(finder, defaultMainType + 'Id')
  10808. && !has(finder, defaultMainType + 'Name')
  10809. ) {
  10810. finder[defaultMainType + 'Index'] = 0;
  10811. }
  10812. var result = {};
  10813. each$2(finder, function (value, key) {
  10814. var value = finder[key];
  10815. // Exclude 'dataIndex' and other illgal keys.
  10816. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10817. result[key] = value;
  10818. return;
  10819. }
  10820. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10821. var mainType = parsedKey[1];
  10822. var queryType = (parsedKey[2] || '').toLowerCase();
  10823. if (!mainType
  10824. || !queryType
  10825. || value == null
  10826. || (queryType === 'index' && value === 'none')
  10827. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10828. ) {
  10829. return;
  10830. }
  10831. var queryParam = {mainType: mainType};
  10832. if (queryType !== 'index' || value !== 'all') {
  10833. queryParam[queryType] = value;
  10834. }
  10835. var models = ecModel.queryComponents(queryParam);
  10836. result[mainType + 'Models'] = models;
  10837. result[mainType + 'Model'] = models[0];
  10838. });
  10839. return result;
  10840. }
  10841. function has(obj, prop) {
  10842. return obj && obj.hasOwnProperty(prop);
  10843. }
  10844. function setAttribute(dom, key, value) {
  10845. dom.setAttribute
  10846. ? dom.setAttribute(key, value)
  10847. : (dom[key] = value);
  10848. }
  10849. function getAttribute(dom, key) {
  10850. return dom.getAttribute
  10851. ? dom.getAttribute(key)
  10852. : dom[key];
  10853. }
  10854. function getTooltipRenderMode(renderModeOption) {
  10855. if (renderModeOption === 'auto') {
  10856. // Using html when `document` exists, use richText otherwise
  10857. return env$1.domSupported ? 'html' : 'richText';
  10858. }
  10859. else {
  10860. return renderModeOption || 'html';
  10861. }
  10862. }
  10863. /**
  10864. * Group a list by key.
  10865. *
  10866. * @param {Array} array
  10867. * @param {Function} getKey
  10868. * param {*} Array item
  10869. * return {string} key
  10870. * @return {Object} Result
  10871. * {Array}: keys,
  10872. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10873. */
  10874. /*
  10875. * Licensed to the Apache Software Foundation (ASF) under one
  10876. * or more contributor license agreements. See the NOTICE file
  10877. * distributed with this work for additional information
  10878. * regarding copyright ownership. The ASF licenses this file
  10879. * to you under the Apache License, Version 2.0 (the
  10880. * "License"); you may not use this file except in compliance
  10881. * with the License. You may obtain a copy of the License at
  10882. *
  10883. * http://www.apache.org/licenses/LICENSE-2.0
  10884. *
  10885. * Unless required by applicable law or agreed to in writing,
  10886. * software distributed under the License is distributed on an
  10887. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10888. * KIND, either express or implied. See the License for the
  10889. * specific language governing permissions and limitations
  10890. * under the License.
  10891. */
  10892. var TYPE_DELIMITER = '.';
  10893. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10894. /**
  10895. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10896. * @public
  10897. */
  10898. function parseClassType$1(componentType) {
  10899. var ret = {main: '', sub: ''};
  10900. if (componentType) {
  10901. componentType = componentType.split(TYPE_DELIMITER);
  10902. ret.main = componentType[0] || '';
  10903. ret.sub = componentType[1] || '';
  10904. }
  10905. return ret;
  10906. }
  10907. /**
  10908. * @public
  10909. */
  10910. function checkClassType(componentType) {
  10911. assert$1(
  10912. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10913. 'componentType "' + componentType + '" illegal'
  10914. );
  10915. }
  10916. /**
  10917. * @public
  10918. */
  10919. function enableClassExtend(RootClass, mandatoryMethods) {
  10920. RootClass.$constructor = RootClass;
  10921. RootClass.extend = function (proto) {
  10922. if (__DEV__) {
  10923. each$1(mandatoryMethods, function (method) {
  10924. if (!proto[method]) {
  10925. console.warn(
  10926. 'Method `' + method + '` should be implemented'
  10927. + (proto.type ? ' in ' + proto.type : '') + '.'
  10928. );
  10929. }
  10930. });
  10931. }
  10932. var superClass = this;
  10933. var ExtendedClass = function () {
  10934. if (!proto.$constructor) {
  10935. superClass.apply(this, arguments);
  10936. }
  10937. else {
  10938. proto.$constructor.apply(this, arguments);
  10939. }
  10940. };
  10941. extend(ExtendedClass.prototype, proto);
  10942. ExtendedClass.extend = this.extend;
  10943. ExtendedClass.superCall = superCall;
  10944. ExtendedClass.superApply = superApply;
  10945. inherits(ExtendedClass, this);
  10946. ExtendedClass.superClass = superClass;
  10947. return ExtendedClass;
  10948. };
  10949. }
  10950. var classBase = 0;
  10951. /**
  10952. * Can not use instanceof, consider different scope by
  10953. * cross domain or es module import in ec extensions.
  10954. * Mount a method "isInstance()" to Clz.
  10955. */
  10956. function enableClassCheck(Clz) {
  10957. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10958. Clz.prototype[classAttr] = true;
  10959. if (__DEV__) {
  10960. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10961. }
  10962. Clz.isInstance = function (obj) {
  10963. return !!(obj && obj[classAttr]);
  10964. };
  10965. }
  10966. // superCall should have class info, which can not be fetch from 'this'.
  10967. // Consider this case:
  10968. // class A has method f,
  10969. // class B inherits class A, overrides method f, f call superApply('f'),
  10970. // class C inherits class B, do not overrides method f,
  10971. // then when method of class C is called, dead loop occured.
  10972. function superCall(context, methodName) {
  10973. var args = slice(arguments, 2);
  10974. return this.superClass.prototype[methodName].apply(context, args);
  10975. }
  10976. function superApply(context, methodName, args) {
  10977. return this.superClass.prototype[methodName].apply(context, args);
  10978. }
  10979. /**
  10980. * @param {Object} entity
  10981. * @param {Object} options
  10982. * @param {boolean} [options.registerWhenExtend]
  10983. * @public
  10984. */
  10985. function enableClassManagement(entity, options) {
  10986. options = options || {};
  10987. /**
  10988. * Component model classes
  10989. * key: componentType,
  10990. * value:
  10991. * componentClass, when componentType is 'xxx'
  10992. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10993. * @type {Object}
  10994. */
  10995. var storage = {};
  10996. entity.registerClass = function (Clazz, componentType) {
  10997. if (componentType) {
  10998. checkClassType(componentType);
  10999. componentType = parseClassType$1(componentType);
  11000. if (!componentType.sub) {
  11001. if (__DEV__) {
  11002. if (storage[componentType.main]) {
  11003. console.warn(componentType.main + ' exists.');
  11004. }
  11005. }
  11006. storage[componentType.main] = Clazz;
  11007. }
  11008. else if (componentType.sub !== IS_CONTAINER) {
  11009. var container = makeContainer(componentType);
  11010. container[componentType.sub] = Clazz;
  11011. }
  11012. }
  11013. return Clazz;
  11014. };
  11015. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  11016. var Clazz = storage[componentMainType];
  11017. if (Clazz && Clazz[IS_CONTAINER]) {
  11018. Clazz = subType ? Clazz[subType] : null;
  11019. }
  11020. if (throwWhenNotFound && !Clazz) {
  11021. throw new Error(
  11022. !subType
  11023. ? componentMainType + '.' + 'type should be specified.'
  11024. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  11025. );
  11026. }
  11027. return Clazz;
  11028. };
  11029. entity.getClassesByMainType = function (componentType) {
  11030. componentType = parseClassType$1(componentType);
  11031. var result = [];
  11032. var obj = storage[componentType.main];
  11033. if (obj && obj[IS_CONTAINER]) {
  11034. each$1(obj, function (o, type) {
  11035. type !== IS_CONTAINER && result.push(o);
  11036. });
  11037. }
  11038. else {
  11039. result.push(obj);
  11040. }
  11041. return result;
  11042. };
  11043. entity.hasClass = function (componentType) {
  11044. // Just consider componentType.main.
  11045. componentType = parseClassType$1(componentType);
  11046. return !!storage[componentType.main];
  11047. };
  11048. /**
  11049. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  11050. */
  11051. entity.getAllClassMainTypes = function () {
  11052. var types = [];
  11053. each$1(storage, function (obj, type) {
  11054. types.push(type);
  11055. });
  11056. return types;
  11057. };
  11058. /**
  11059. * If a main type is container and has sub types
  11060. * @param {string} mainType
  11061. * @return {boolean}
  11062. */
  11063. entity.hasSubTypes = function (componentType) {
  11064. componentType = parseClassType$1(componentType);
  11065. var obj = storage[componentType.main];
  11066. return obj && obj[IS_CONTAINER];
  11067. };
  11068. entity.parseClassType = parseClassType$1;
  11069. function makeContainer(componentType) {
  11070. var container = storage[componentType.main];
  11071. if (!container || !container[IS_CONTAINER]) {
  11072. container = storage[componentType.main] = {};
  11073. container[IS_CONTAINER] = true;
  11074. }
  11075. return container;
  11076. }
  11077. if (options.registerWhenExtend) {
  11078. var originalExtend = entity.extend;
  11079. if (originalExtend) {
  11080. entity.extend = function (proto) {
  11081. var ExtendedClass = originalExtend.call(this, proto);
  11082. return entity.registerClass(ExtendedClass, proto.type);
  11083. };
  11084. }
  11085. }
  11086. return entity;
  11087. }
  11088. /**
  11089. * @param {string|Array.<string>} properties
  11090. */
  11091. /*
  11092. * Licensed to the Apache Software Foundation (ASF) under one
  11093. * or more contributor license agreements. See the NOTICE file
  11094. * distributed with this work for additional information
  11095. * regarding copyright ownership. The ASF licenses this file
  11096. * to you under the Apache License, Version 2.0 (the
  11097. * "License"); you may not use this file except in compliance
  11098. * with the License. You may obtain a copy of the License at
  11099. *
  11100. * http://www.apache.org/licenses/LICENSE-2.0
  11101. *
  11102. * Unless required by applicable law or agreed to in writing,
  11103. * software distributed under the License is distributed on an
  11104. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11105. * KIND, either express or implied. See the License for the
  11106. * specific language governing permissions and limitations
  11107. * under the License.
  11108. */
  11109. // TODO Parse shadow style
  11110. // TODO Only shallow path support
  11111. var makeStyleMapper = function (properties) {
  11112. // Normalize
  11113. for (var i = 0; i < properties.length; i++) {
  11114. if (!properties[i][1]) {
  11115. properties[i][1] = properties[i][0];
  11116. }
  11117. }
  11118. return function (model, excludes, includes) {
  11119. var style = {};
  11120. for (var i = 0; i < properties.length; i++) {
  11121. var propName = properties[i][1];
  11122. if ((excludes && indexOf(excludes, propName) >= 0)
  11123. || (includes && indexOf(includes, propName) < 0)
  11124. ) {
  11125. continue;
  11126. }
  11127. var val = model.getShallow(propName);
  11128. if (val != null) {
  11129. style[properties[i][0]] = val;
  11130. }
  11131. }
  11132. return style;
  11133. };
  11134. };
  11135. /*
  11136. * Licensed to the Apache Software Foundation (ASF) under one
  11137. * or more contributor license agreements. See the NOTICE file
  11138. * distributed with this work for additional information
  11139. * regarding copyright ownership. The ASF licenses this file
  11140. * to you under the Apache License, Version 2.0 (the
  11141. * "License"); you may not use this file except in compliance
  11142. * with the License. You may obtain a copy of the License at
  11143. *
  11144. * http://www.apache.org/licenses/LICENSE-2.0
  11145. *
  11146. * Unless required by applicable law or agreed to in writing,
  11147. * software distributed under the License is distributed on an
  11148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11149. * KIND, either express or implied. See the License for the
  11150. * specific language governing permissions and limitations
  11151. * under the License.
  11152. */
  11153. var getLineStyle = makeStyleMapper(
  11154. [
  11155. ['lineWidth', 'width'],
  11156. ['stroke', 'color'],
  11157. ['opacity'],
  11158. ['shadowBlur'],
  11159. ['shadowOffsetX'],
  11160. ['shadowOffsetY'],
  11161. ['shadowColor']
  11162. ]
  11163. );
  11164. var lineStyleMixin = {
  11165. getLineStyle: function (excludes) {
  11166. var style = getLineStyle(this, excludes);
  11167. // Always set lineDash whether dashed, otherwise we can not
  11168. // erase the previous style when assigning to el.style.
  11169. style.lineDash = this.getLineDash(style.lineWidth);
  11170. return style;
  11171. },
  11172. getLineDash: function (lineWidth) {
  11173. if (lineWidth == null) {
  11174. lineWidth = 1;
  11175. }
  11176. var lineType = this.get('type');
  11177. var dotSize = Math.max(lineWidth, 2);
  11178. var dashSize = lineWidth * 4;
  11179. return (lineType === 'solid' || lineType == null)
  11180. // Use `false` but not `null` for the solid line here, because `null` might be
  11181. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  11182. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  11183. // `lineDash` gotten form the latter one is not able to erase that from the former
  11184. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  11185. ? false
  11186. : lineType === 'dashed'
  11187. ? [dashSize, dashSize]
  11188. : [dotSize, dotSize];
  11189. }
  11190. };
  11191. /*
  11192. * Licensed to the Apache Software Foundation (ASF) under one
  11193. * or more contributor license agreements. See the NOTICE file
  11194. * distributed with this work for additional information
  11195. * regarding copyright ownership. The ASF licenses this file
  11196. * to you under the Apache License, Version 2.0 (the
  11197. * "License"); you may not use this file except in compliance
  11198. * with the License. You may obtain a copy of the License at
  11199. *
  11200. * http://www.apache.org/licenses/LICENSE-2.0
  11201. *
  11202. * Unless required by applicable law or agreed to in writing,
  11203. * software distributed under the License is distributed on an
  11204. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11205. * KIND, either express or implied. See the License for the
  11206. * specific language governing permissions and limitations
  11207. * under the License.
  11208. */
  11209. var getAreaStyle = makeStyleMapper(
  11210. [
  11211. ['fill', 'color'],
  11212. ['shadowBlur'],
  11213. ['shadowOffsetX'],
  11214. ['shadowOffsetY'],
  11215. ['opacity'],
  11216. ['shadowColor']
  11217. ]
  11218. );
  11219. var areaStyleMixin = {
  11220. getAreaStyle: function (excludes, includes) {
  11221. return getAreaStyle(this, excludes, includes);
  11222. }
  11223. };
  11224. /**
  11225. * 曲线辅助模块
  11226. * @module zrender/core/curve
  11227. * @author pissang(https://www.github.com/pissang)
  11228. */
  11229. var mathPow = Math.pow;
  11230. var mathSqrt$2 = Math.sqrt;
  11231. var EPSILON$1 = 1e-8;
  11232. var EPSILON_NUMERIC = 1e-4;
  11233. var THREE_SQRT = mathSqrt$2(3);
  11234. var ONE_THIRD = 1 / 3;
  11235. // 临时变量
  11236. var _v0 = create();
  11237. var _v1 = create();
  11238. var _v2 = create();
  11239. function isAroundZero(val) {
  11240. return val > -EPSILON$1 && val < EPSILON$1;
  11241. }
  11242. function isNotAroundZero$1(val) {
  11243. return val > EPSILON$1 || val < -EPSILON$1;
  11244. }
  11245. /**
  11246. * 计算三次贝塞尔值
  11247. * @memberOf module:zrender/core/curve
  11248. * @param {number} p0
  11249. * @param {number} p1
  11250. * @param {number} p2
  11251. * @param {number} p3
  11252. * @param {number} t
  11253. * @return {number}
  11254. */
  11255. function cubicAt(p0, p1, p2, p3, t) {
  11256. var onet = 1 - t;
  11257. return onet * onet * (onet * p0 + 3 * t * p1)
  11258. + t * t * (t * p3 + 3 * onet * p2);
  11259. }
  11260. /**
  11261. * 计算三次贝塞尔导数值
  11262. * @memberOf module:zrender/core/curve
  11263. * @param {number} p0
  11264. * @param {number} p1
  11265. * @param {number} p2
  11266. * @param {number} p3
  11267. * @param {number} t
  11268. * @return {number}
  11269. */
  11270. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  11271. var onet = 1 - t;
  11272. return 3 * (
  11273. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  11274. + (p3 - p2) * t * t
  11275. );
  11276. }
  11277. /**
  11278. * 计算三次贝塞尔方程根,使用盛金公式
  11279. * @memberOf module:zrender/core/curve
  11280. * @param {number} p0
  11281. * @param {number} p1
  11282. * @param {number} p2
  11283. * @param {number} p3
  11284. * @param {number} val
  11285. * @param {Array.<number>} roots
  11286. * @return {number} 有效根数目
  11287. */
  11288. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  11289. // Evaluate roots of cubic functions
  11290. var a = p3 + 3 * (p1 - p2) - p0;
  11291. var b = 3 * (p2 - p1 * 2 + p0);
  11292. var c = 3 * (p1 - p0);
  11293. var d = p0 - val;
  11294. var A = b * b - 3 * a * c;
  11295. var B = b * c - 9 * a * d;
  11296. var C = c * c - 3 * b * d;
  11297. var n = 0;
  11298. if (isAroundZero(A) && isAroundZero(B)) {
  11299. if (isAroundZero(b)) {
  11300. roots[0] = 0;
  11301. }
  11302. else {
  11303. var t1 = -c / b; //t1, t2, t3, b is not zero
  11304. if (t1 >= 0 && t1 <= 1) {
  11305. roots[n++] = t1;
  11306. }
  11307. }
  11308. }
  11309. else {
  11310. var disc = B * B - 4 * A * C;
  11311. if (isAroundZero(disc)) {
  11312. var K = B / A;
  11313. var t1 = -b / a + K; // t1, a is not zero
  11314. var t2 = -K / 2; // t2, t3
  11315. if (t1 >= 0 && t1 <= 1) {
  11316. roots[n++] = t1;
  11317. }
  11318. if (t2 >= 0 && t2 <= 1) {
  11319. roots[n++] = t2;
  11320. }
  11321. }
  11322. else if (disc > 0) {
  11323. var discSqrt = mathSqrt$2(disc);
  11324. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  11325. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  11326. if (Y1 < 0) {
  11327. Y1 = -mathPow(-Y1, ONE_THIRD);
  11328. }
  11329. else {
  11330. Y1 = mathPow(Y1, ONE_THIRD);
  11331. }
  11332. if (Y2 < 0) {
  11333. Y2 = -mathPow(-Y2, ONE_THIRD);
  11334. }
  11335. else {
  11336. Y2 = mathPow(Y2, ONE_THIRD);
  11337. }
  11338. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  11339. if (t1 >= 0 && t1 <= 1) {
  11340. roots[n++] = t1;
  11341. }
  11342. }
  11343. else {
  11344. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  11345. var theta = Math.acos(T) / 3;
  11346. var ASqrt = mathSqrt$2(A);
  11347. var tmp = Math.cos(theta);
  11348. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  11349. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  11350. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  11351. if (t1 >= 0 && t1 <= 1) {
  11352. roots[n++] = t1;
  11353. }
  11354. if (t2 >= 0 && t2 <= 1) {
  11355. roots[n++] = t2;
  11356. }
  11357. if (t3 >= 0 && t3 <= 1) {
  11358. roots[n++] = t3;
  11359. }
  11360. }
  11361. }
  11362. return n;
  11363. }
  11364. /**
  11365. * 计算三次贝塞尔方程极限值的位置
  11366. * @memberOf module:zrender/core/curve
  11367. * @param {number} p0
  11368. * @param {number} p1
  11369. * @param {number} p2
  11370. * @param {number} p3
  11371. * @param {Array.<number>} extrema
  11372. * @return {number} 有效数目
  11373. */
  11374. function cubicExtrema(p0, p1, p2, p3, extrema) {
  11375. var b = 6 * p2 - 12 * p1 + 6 * p0;
  11376. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  11377. var c = 3 * p1 - 3 * p0;
  11378. var n = 0;
  11379. if (isAroundZero(a)) {
  11380. if (isNotAroundZero$1(b)) {
  11381. var t1 = -c / b;
  11382. if (t1 >= 0 && t1 <= 1) {
  11383. extrema[n++] = t1;
  11384. }
  11385. }
  11386. }
  11387. else {
  11388. var disc = b * b - 4 * a * c;
  11389. if (isAroundZero(disc)) {
  11390. extrema[0] = -b / (2 * a);
  11391. }
  11392. else if (disc > 0) {
  11393. var discSqrt = mathSqrt$2(disc);
  11394. var t1 = (-b + discSqrt) / (2 * a);
  11395. var t2 = (-b - discSqrt) / (2 * a);
  11396. if (t1 >= 0 && t1 <= 1) {
  11397. extrema[n++] = t1;
  11398. }
  11399. if (t2 >= 0 && t2 <= 1) {
  11400. extrema[n++] = t2;
  11401. }
  11402. }
  11403. }
  11404. return n;
  11405. }
  11406. /**
  11407. * 细分三次贝塞尔曲线
  11408. * @memberOf module:zrender/core/curve
  11409. * @param {number} p0
  11410. * @param {number} p1
  11411. * @param {number} p2
  11412. * @param {number} p3
  11413. * @param {number} t
  11414. * @param {Array.<number>} out
  11415. */
  11416. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  11417. var p01 = (p1 - p0) * t + p0;
  11418. var p12 = (p2 - p1) * t + p1;
  11419. var p23 = (p3 - p2) * t + p2;
  11420. var p012 = (p12 - p01) * t + p01;
  11421. var p123 = (p23 - p12) * t + p12;
  11422. var p0123 = (p123 - p012) * t + p012;
  11423. // Seg0
  11424. out[0] = p0;
  11425. out[1] = p01;
  11426. out[2] = p012;
  11427. out[3] = p0123;
  11428. // Seg1
  11429. out[4] = p0123;
  11430. out[5] = p123;
  11431. out[6] = p23;
  11432. out[7] = p3;
  11433. }
  11434. /**
  11435. * 投射点到三次贝塞尔曲线上,返回投射距离。
  11436. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11437. * @param {number} x0
  11438. * @param {number} y0
  11439. * @param {number} x1
  11440. * @param {number} y1
  11441. * @param {number} x2
  11442. * @param {number} y2
  11443. * @param {number} x3
  11444. * @param {number} y3
  11445. * @param {number} x
  11446. * @param {number} y
  11447. * @param {Array.<number>} [out] 投射点
  11448. * @return {number}
  11449. */
  11450. function cubicProjectPoint(
  11451. x0, y0, x1, y1, x2, y2, x3, y3,
  11452. x, y, out
  11453. ) {
  11454. // http://pomax.github.io/bezierinfo/#projections
  11455. var t;
  11456. var interval = 0.005;
  11457. var d = Infinity;
  11458. var prev;
  11459. var next;
  11460. var d1;
  11461. var d2;
  11462. _v0[0] = x;
  11463. _v0[1] = y;
  11464. // 先粗略估计一下可能的最小距离的 t 值
  11465. // PENDING
  11466. for (var _t = 0; _t < 1; _t += 0.05) {
  11467. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  11468. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  11469. d1 = distSquare(_v0, _v1);
  11470. if (d1 < d) {
  11471. t = _t;
  11472. d = d1;
  11473. }
  11474. }
  11475. d = Infinity;
  11476. // At most 32 iteration
  11477. for (var i = 0; i < 32; i++) {
  11478. if (interval < EPSILON_NUMERIC) {
  11479. break;
  11480. }
  11481. prev = t - interval;
  11482. next = t + interval;
  11483. // t - interval
  11484. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  11485. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  11486. d1 = distSquare(_v1, _v0);
  11487. if (prev >= 0 && d1 < d) {
  11488. t = prev;
  11489. d = d1;
  11490. }
  11491. else {
  11492. // t + interval
  11493. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  11494. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  11495. d2 = distSquare(_v2, _v0);
  11496. if (next <= 1 && d2 < d) {
  11497. t = next;
  11498. d = d2;
  11499. }
  11500. else {
  11501. interval *= 0.5;
  11502. }
  11503. }
  11504. }
  11505. // t
  11506. if (out) {
  11507. out[0] = cubicAt(x0, x1, x2, x3, t);
  11508. out[1] = cubicAt(y0, y1, y2, y3, t);
  11509. }
  11510. // console.log(interval, i);
  11511. return mathSqrt$2(d);
  11512. }
  11513. /**
  11514. * 计算二次方贝塞尔值
  11515. * @param {number} p0
  11516. * @param {number} p1
  11517. * @param {number} p2
  11518. * @param {number} t
  11519. * @return {number}
  11520. */
  11521. function quadraticAt(p0, p1, p2, t) {
  11522. var onet = 1 - t;
  11523. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  11524. }
  11525. /**
  11526. * 计算二次方贝塞尔导数值
  11527. * @param {number} p0
  11528. * @param {number} p1
  11529. * @param {number} p2
  11530. * @param {number} t
  11531. * @return {number}
  11532. */
  11533. function quadraticDerivativeAt(p0, p1, p2, t) {
  11534. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  11535. }
  11536. /**
  11537. * 计算二次方贝塞尔方程根
  11538. * @param {number} p0
  11539. * @param {number} p1
  11540. * @param {number} p2
  11541. * @param {number} t
  11542. * @param {Array.<number>} roots
  11543. * @return {number} 有效根数目
  11544. */
  11545. function quadraticRootAt(p0, p1, p2, val, roots) {
  11546. var a = p0 - 2 * p1 + p2;
  11547. var b = 2 * (p1 - p0);
  11548. var c = p0 - val;
  11549. var n = 0;
  11550. if (isAroundZero(a)) {
  11551. if (isNotAroundZero$1(b)) {
  11552. var t1 = -c / b;
  11553. if (t1 >= 0 && t1 <= 1) {
  11554. roots[n++] = t1;
  11555. }
  11556. }
  11557. }
  11558. else {
  11559. var disc = b * b - 4 * a * c;
  11560. if (isAroundZero(disc)) {
  11561. var t1 = -b / (2 * a);
  11562. if (t1 >= 0 && t1 <= 1) {
  11563. roots[n++] = t1;
  11564. }
  11565. }
  11566. else if (disc > 0) {
  11567. var discSqrt = mathSqrt$2(disc);
  11568. var t1 = (-b + discSqrt) / (2 * a);
  11569. var t2 = (-b - discSqrt) / (2 * a);
  11570. if (t1 >= 0 && t1 <= 1) {
  11571. roots[n++] = t1;
  11572. }
  11573. if (t2 >= 0 && t2 <= 1) {
  11574. roots[n++] = t2;
  11575. }
  11576. }
  11577. }
  11578. return n;
  11579. }
  11580. /**
  11581. * 计算二次贝塞尔方程极限值
  11582. * @memberOf module:zrender/core/curve
  11583. * @param {number} p0
  11584. * @param {number} p1
  11585. * @param {number} p2
  11586. * @return {number}
  11587. */
  11588. function quadraticExtremum(p0, p1, p2) {
  11589. var divider = p0 + p2 - 2 * p1;
  11590. if (divider === 0) {
  11591. // p1 is center of p0 and p2
  11592. return 0.5;
  11593. }
  11594. else {
  11595. return (p0 - p1) / divider;
  11596. }
  11597. }
  11598. /**
  11599. * 细分二次贝塞尔曲线
  11600. * @memberOf module:zrender/core/curve
  11601. * @param {number} p0
  11602. * @param {number} p1
  11603. * @param {number} p2
  11604. * @param {number} t
  11605. * @param {Array.<number>} out
  11606. */
  11607. function quadraticSubdivide(p0, p1, p2, t, out) {
  11608. var p01 = (p1 - p0) * t + p0;
  11609. var p12 = (p2 - p1) * t + p1;
  11610. var p012 = (p12 - p01) * t + p01;
  11611. // Seg0
  11612. out[0] = p0;
  11613. out[1] = p01;
  11614. out[2] = p012;
  11615. // Seg1
  11616. out[3] = p012;
  11617. out[4] = p12;
  11618. out[5] = p2;
  11619. }
  11620. /**
  11621. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11622. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11623. * @param {number} x0
  11624. * @param {number} y0
  11625. * @param {number} x1
  11626. * @param {number} y1
  11627. * @param {number} x2
  11628. * @param {number} y2
  11629. * @param {number} x
  11630. * @param {number} y
  11631. * @param {Array.<number>} out 投射点
  11632. * @return {number}
  11633. */
  11634. function quadraticProjectPoint(
  11635. x0, y0, x1, y1, x2, y2,
  11636. x, y, out
  11637. ) {
  11638. // http://pomax.github.io/bezierinfo/#projections
  11639. var t;
  11640. var interval = 0.005;
  11641. var d = Infinity;
  11642. _v0[0] = x;
  11643. _v0[1] = y;
  11644. // 先粗略估计一下可能的最小距离的 t 值
  11645. // PENDING
  11646. for (var _t = 0; _t < 1; _t += 0.05) {
  11647. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11648. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11649. var d1 = distSquare(_v0, _v1);
  11650. if (d1 < d) {
  11651. t = _t;
  11652. d = d1;
  11653. }
  11654. }
  11655. d = Infinity;
  11656. // At most 32 iteration
  11657. for (var i = 0; i < 32; i++) {
  11658. if (interval < EPSILON_NUMERIC) {
  11659. break;
  11660. }
  11661. var prev = t - interval;
  11662. var next = t + interval;
  11663. // t - interval
  11664. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11665. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11666. var d1 = distSquare(_v1, _v0);
  11667. if (prev >= 0 && d1 < d) {
  11668. t = prev;
  11669. d = d1;
  11670. }
  11671. else {
  11672. // t + interval
  11673. _v2[0] = quadraticAt(x0, x1, x2, next);
  11674. _v2[1] = quadraticAt(y0, y1, y2, next);
  11675. var d2 = distSquare(_v2, _v0);
  11676. if (next <= 1 && d2 < d) {
  11677. t = next;
  11678. d = d2;
  11679. }
  11680. else {
  11681. interval *= 0.5;
  11682. }
  11683. }
  11684. }
  11685. // t
  11686. if (out) {
  11687. out[0] = quadraticAt(x0, x1, x2, t);
  11688. out[1] = quadraticAt(y0, y1, y2, t);
  11689. }
  11690. // console.log(interval, i);
  11691. return mathSqrt$2(d);
  11692. }
  11693. /**
  11694. * @author Yi Shen(https://github.com/pissang)
  11695. */
  11696. var mathMin$3 = Math.min;
  11697. var mathMax$3 = Math.max;
  11698. var mathSin$2 = Math.sin;
  11699. var mathCos$2 = Math.cos;
  11700. var PI2 = Math.PI * 2;
  11701. var start = create();
  11702. var end = create();
  11703. var extremity = create();
  11704. /**
  11705. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11706. * @module zrender/core/bbox
  11707. * @param {Array<Object>} points 顶点数组
  11708. * @param {number} min
  11709. * @param {number} max
  11710. */
  11711. function fromPoints(points, min$$1, max$$1) {
  11712. if (points.length === 0) {
  11713. return;
  11714. }
  11715. var p = points[0];
  11716. var left = p[0];
  11717. var right = p[0];
  11718. var top = p[1];
  11719. var bottom = p[1];
  11720. var i;
  11721. for (i = 1; i < points.length; i++) {
  11722. p = points[i];
  11723. left = mathMin$3(left, p[0]);
  11724. right = mathMax$3(right, p[0]);
  11725. top = mathMin$3(top, p[1]);
  11726. bottom = mathMax$3(bottom, p[1]);
  11727. }
  11728. min$$1[0] = left;
  11729. min$$1[1] = top;
  11730. max$$1[0] = right;
  11731. max$$1[1] = bottom;
  11732. }
  11733. /**
  11734. * @memberOf module:zrender/core/bbox
  11735. * @param {number} x0
  11736. * @param {number} y0
  11737. * @param {number} x1
  11738. * @param {number} y1
  11739. * @param {Array.<number>} min
  11740. * @param {Array.<number>} max
  11741. */
  11742. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11743. min$$1[0] = mathMin$3(x0, x1);
  11744. min$$1[1] = mathMin$3(y0, y1);
  11745. max$$1[0] = mathMax$3(x0, x1);
  11746. max$$1[1] = mathMax$3(y0, y1);
  11747. }
  11748. var xDim = [];
  11749. var yDim = [];
  11750. /**
  11751. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11752. * @memberOf module:zrender/core/bbox
  11753. * @param {number} x0
  11754. * @param {number} y0
  11755. * @param {number} x1
  11756. * @param {number} y1
  11757. * @param {number} x2
  11758. * @param {number} y2
  11759. * @param {number} x3
  11760. * @param {number} y3
  11761. * @param {Array.<number>} min
  11762. * @param {Array.<number>} max
  11763. */
  11764. function fromCubic(
  11765. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11766. ) {
  11767. var cubicExtrema$$1 = cubicExtrema;
  11768. var cubicAt$$1 = cubicAt;
  11769. var i;
  11770. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11771. min$$1[0] = Infinity;
  11772. min$$1[1] = Infinity;
  11773. max$$1[0] = -Infinity;
  11774. max$$1[1] = -Infinity;
  11775. for (i = 0; i < n; i++) {
  11776. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11777. min$$1[0] = mathMin$3(x, min$$1[0]);
  11778. max$$1[0] = mathMax$3(x, max$$1[0]);
  11779. }
  11780. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11781. for (i = 0; i < n; i++) {
  11782. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11783. min$$1[1] = mathMin$3(y, min$$1[1]);
  11784. max$$1[1] = mathMax$3(y, max$$1[1]);
  11785. }
  11786. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11787. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11788. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11789. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11790. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11791. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11792. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11793. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11794. }
  11795. /**
  11796. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11797. * @memberOf module:zrender/core/bbox
  11798. * @param {number} x0
  11799. * @param {number} y0
  11800. * @param {number} x1
  11801. * @param {number} y1
  11802. * @param {number} x2
  11803. * @param {number} y2
  11804. * @param {Array.<number>} min
  11805. * @param {Array.<number>} max
  11806. */
  11807. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11808. var quadraticExtremum$$1 = quadraticExtremum;
  11809. var quadraticAt$$1 = quadraticAt;
  11810. // Find extremities, where derivative in x dim or y dim is zero
  11811. var tx =
  11812. mathMax$3(
  11813. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11814. );
  11815. var ty =
  11816. mathMax$3(
  11817. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11818. );
  11819. var x = quadraticAt$$1(x0, x1, x2, tx);
  11820. var y = quadraticAt$$1(y0, y1, y2, ty);
  11821. min$$1[0] = mathMin$3(x0, x2, x);
  11822. min$$1[1] = mathMin$3(y0, y2, y);
  11823. max$$1[0] = mathMax$3(x0, x2, x);
  11824. max$$1[1] = mathMax$3(y0, y2, y);
  11825. }
  11826. /**
  11827. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11828. * @method
  11829. * @memberOf module:zrender/core/bbox
  11830. * @param {number} x
  11831. * @param {number} y
  11832. * @param {number} rx
  11833. * @param {number} ry
  11834. * @param {number} startAngle
  11835. * @param {number} endAngle
  11836. * @param {number} anticlockwise
  11837. * @param {Array.<number>} min
  11838. * @param {Array.<number>} max
  11839. */
  11840. function fromArc(
  11841. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11842. ) {
  11843. var vec2Min = min;
  11844. var vec2Max = max;
  11845. var diff = Math.abs(startAngle - endAngle);
  11846. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11847. // Is a circle
  11848. min$$1[0] = x - rx;
  11849. min$$1[1] = y - ry;
  11850. max$$1[0] = x + rx;
  11851. max$$1[1] = y + ry;
  11852. return;
  11853. }
  11854. start[0] = mathCos$2(startAngle) * rx + x;
  11855. start[1] = mathSin$2(startAngle) * ry + y;
  11856. end[0] = mathCos$2(endAngle) * rx + x;
  11857. end[1] = mathSin$2(endAngle) * ry + y;
  11858. vec2Min(min$$1, start, end);
  11859. vec2Max(max$$1, start, end);
  11860. // Thresh to [0, Math.PI * 2]
  11861. startAngle = startAngle % (PI2);
  11862. if (startAngle < 0) {
  11863. startAngle = startAngle + PI2;
  11864. }
  11865. endAngle = endAngle % (PI2);
  11866. if (endAngle < 0) {
  11867. endAngle = endAngle + PI2;
  11868. }
  11869. if (startAngle > endAngle && !anticlockwise) {
  11870. endAngle += PI2;
  11871. }
  11872. else if (startAngle < endAngle && anticlockwise) {
  11873. startAngle += PI2;
  11874. }
  11875. if (anticlockwise) {
  11876. var tmp = endAngle;
  11877. endAngle = startAngle;
  11878. startAngle = tmp;
  11879. }
  11880. // var number = 0;
  11881. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11882. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11883. if (angle > startAngle) {
  11884. extremity[0] = mathCos$2(angle) * rx + x;
  11885. extremity[1] = mathSin$2(angle) * ry + y;
  11886. vec2Min(min$$1, extremity, min$$1);
  11887. vec2Max(max$$1, extremity, max$$1);
  11888. }
  11889. }
  11890. }
  11891. /**
  11892. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11893. * 可以用于 isInsidePath 判断以及获取boundingRect
  11894. *
  11895. * @module zrender/core/PathProxy
  11896. * @author Yi Shen (http://www.github.com/pissang)
  11897. */
  11898. // TODO getTotalLength, getPointAtLength
  11899. /* global Float32Array */
  11900. var CMD = {
  11901. M: 1,
  11902. L: 2,
  11903. C: 3,
  11904. Q: 4,
  11905. A: 5,
  11906. Z: 6,
  11907. // Rect
  11908. R: 7
  11909. };
  11910. // var CMD_MEM_SIZE = {
  11911. // M: 3,
  11912. // L: 3,
  11913. // C: 7,
  11914. // Q: 5,
  11915. // A: 9,
  11916. // R: 5,
  11917. // Z: 1
  11918. // };
  11919. var min$1 = [];
  11920. var max$1 = [];
  11921. var min2 = [];
  11922. var max2 = [];
  11923. var mathMin$2 = Math.min;
  11924. var mathMax$2 = Math.max;
  11925. var mathCos$1 = Math.cos;
  11926. var mathSin$1 = Math.sin;
  11927. var mathSqrt$1 = Math.sqrt;
  11928. var mathAbs = Math.abs;
  11929. var hasTypedArray = typeof Float32Array !== 'undefined';
  11930. /**
  11931. * @alias module:zrender/core/PathProxy
  11932. * @constructor
  11933. */
  11934. var PathProxy = function (notSaveData) {
  11935. this._saveData = !(notSaveData || false);
  11936. if (this._saveData) {
  11937. /**
  11938. * Path data. Stored as flat array
  11939. * @type {Array.<Object>}
  11940. */
  11941. this.data = [];
  11942. }
  11943. this._ctx = null;
  11944. };
  11945. /**
  11946. * 快速计算Path包围盒(并不是最小包围盒)
  11947. * @return {Object}
  11948. */
  11949. PathProxy.prototype = {
  11950. constructor: PathProxy,
  11951. _xi: 0,
  11952. _yi: 0,
  11953. _x0: 0,
  11954. _y0: 0,
  11955. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11956. _ux: 0,
  11957. _uy: 0,
  11958. _len: 0,
  11959. _lineDash: null,
  11960. _dashOffset: 0,
  11961. _dashIdx: 0,
  11962. _dashSum: 0,
  11963. /**
  11964. * @readOnly
  11965. */
  11966. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11967. // Compat. Previously there is no segmentIgnoreThreshold.
  11968. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11969. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11970. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11971. },
  11972. getContext: function () {
  11973. return this._ctx;
  11974. },
  11975. /**
  11976. * @param {CanvasRenderingContext2D} ctx
  11977. * @return {module:zrender/core/PathProxy}
  11978. */
  11979. beginPath: function (ctx) {
  11980. this._ctx = ctx;
  11981. ctx && ctx.beginPath();
  11982. ctx && (this.dpr = ctx.dpr);
  11983. // Reset
  11984. if (this._saveData) {
  11985. this._len = 0;
  11986. }
  11987. if (this._lineDash) {
  11988. this._lineDash = null;
  11989. this._dashOffset = 0;
  11990. }
  11991. return this;
  11992. },
  11993. /**
  11994. * @param {number} x
  11995. * @param {number} y
  11996. * @return {module:zrender/core/PathProxy}
  11997. */
  11998. moveTo: function (x, y) {
  11999. this.addData(CMD.M, x, y);
  12000. this._ctx && this._ctx.moveTo(x, y);
  12001. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  12002. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  12003. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  12004. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  12005. this._x0 = x;
  12006. this._y0 = y;
  12007. this._xi = x;
  12008. this._yi = y;
  12009. return this;
  12010. },
  12011. /**
  12012. * @param {number} x
  12013. * @param {number} y
  12014. * @return {module:zrender/core/PathProxy}
  12015. */
  12016. lineTo: function (x, y) {
  12017. var exceedUnit = mathAbs(x - this._xi) > this._ux
  12018. || mathAbs(y - this._yi) > this._uy
  12019. // Force draw the first segment
  12020. || this._len < 5;
  12021. this.addData(CMD.L, x, y);
  12022. if (this._ctx && exceedUnit) {
  12023. this._needsDash() ? this._dashedLineTo(x, y)
  12024. : this._ctx.lineTo(x, y);
  12025. }
  12026. if (exceedUnit) {
  12027. this._xi = x;
  12028. this._yi = y;
  12029. }
  12030. return this;
  12031. },
  12032. /**
  12033. * @param {number} x1
  12034. * @param {number} y1
  12035. * @param {number} x2
  12036. * @param {number} y2
  12037. * @param {number} x3
  12038. * @param {number} y3
  12039. * @return {module:zrender/core/PathProxy}
  12040. */
  12041. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  12042. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  12043. if (this._ctx) {
  12044. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  12045. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  12046. }
  12047. this._xi = x3;
  12048. this._yi = y3;
  12049. return this;
  12050. },
  12051. /**
  12052. * @param {number} x1
  12053. * @param {number} y1
  12054. * @param {number} x2
  12055. * @param {number} y2
  12056. * @return {module:zrender/core/PathProxy}
  12057. */
  12058. quadraticCurveTo: function (x1, y1, x2, y2) {
  12059. this.addData(CMD.Q, x1, y1, x2, y2);
  12060. if (this._ctx) {
  12061. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  12062. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  12063. }
  12064. this._xi = x2;
  12065. this._yi = y2;
  12066. return this;
  12067. },
  12068. /**
  12069. * @param {number} cx
  12070. * @param {number} cy
  12071. * @param {number} r
  12072. * @param {number} startAngle
  12073. * @param {number} endAngle
  12074. * @param {boolean} anticlockwise
  12075. * @return {module:zrender/core/PathProxy}
  12076. */
  12077. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  12078. this.addData(
  12079. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  12080. );
  12081. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  12082. this._xi = mathCos$1(endAngle) * r + cx;
  12083. this._yi = mathSin$1(endAngle) * r + cy;
  12084. return this;
  12085. },
  12086. // TODO
  12087. arcTo: function (x1, y1, x2, y2, radius) {
  12088. if (this._ctx) {
  12089. this._ctx.arcTo(x1, y1, x2, y2, radius);
  12090. }
  12091. return this;
  12092. },
  12093. // TODO
  12094. rect: function (x, y, w, h) {
  12095. this._ctx && this._ctx.rect(x, y, w, h);
  12096. this.addData(CMD.R, x, y, w, h);
  12097. return this;
  12098. },
  12099. /**
  12100. * @return {module:zrender/core/PathProxy}
  12101. */
  12102. closePath: function () {
  12103. this.addData(CMD.Z);
  12104. var ctx = this._ctx;
  12105. var x0 = this._x0;
  12106. var y0 = this._y0;
  12107. if (ctx) {
  12108. this._needsDash() && this._dashedLineTo(x0, y0);
  12109. ctx.closePath();
  12110. }
  12111. this._xi = x0;
  12112. this._yi = y0;
  12113. return this;
  12114. },
  12115. /**
  12116. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  12117. * stroke 同样
  12118. * @param {CanvasRenderingContext2D} ctx
  12119. * @return {module:zrender/core/PathProxy}
  12120. */
  12121. fill: function (ctx) {
  12122. ctx && ctx.fill();
  12123. this.toStatic();
  12124. },
  12125. /**
  12126. * @param {CanvasRenderingContext2D} ctx
  12127. * @return {module:zrender/core/PathProxy}
  12128. */
  12129. stroke: function (ctx) {
  12130. ctx && ctx.stroke();
  12131. this.toStatic();
  12132. },
  12133. /**
  12134. * 必须在其它绘制命令前调用
  12135. * Must be invoked before all other path drawing methods
  12136. * @return {module:zrender/core/PathProxy}
  12137. */
  12138. setLineDash: function (lineDash) {
  12139. if (lineDash instanceof Array) {
  12140. this._lineDash = lineDash;
  12141. this._dashIdx = 0;
  12142. var lineDashSum = 0;
  12143. for (var i = 0; i < lineDash.length; i++) {
  12144. lineDashSum += lineDash[i];
  12145. }
  12146. this._dashSum = lineDashSum;
  12147. }
  12148. return this;
  12149. },
  12150. /**
  12151. * 必须在其它绘制命令前调用
  12152. * Must be invoked before all other path drawing methods
  12153. * @return {module:zrender/core/PathProxy}
  12154. */
  12155. setLineDashOffset: function (offset) {
  12156. this._dashOffset = offset;
  12157. return this;
  12158. },
  12159. /**
  12160. *
  12161. * @return {boolean}
  12162. */
  12163. len: function () {
  12164. return this._len;
  12165. },
  12166. /**
  12167. * 直接设置 Path 数据
  12168. */
  12169. setData: function (data) {
  12170. var len$$1 = data.length;
  12171. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  12172. this.data = new Float32Array(len$$1);
  12173. }
  12174. for (var i = 0; i < len$$1; i++) {
  12175. this.data[i] = data[i];
  12176. }
  12177. this._len = len$$1;
  12178. },
  12179. /**
  12180. * 添加子路径
  12181. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  12182. */
  12183. appendPath: function (path) {
  12184. if (!(path instanceof Array)) {
  12185. path = [path];
  12186. }
  12187. var len$$1 = path.length;
  12188. var appendSize = 0;
  12189. var offset = this._len;
  12190. for (var i = 0; i < len$$1; i++) {
  12191. appendSize += path[i].len();
  12192. }
  12193. if (hasTypedArray && (this.data instanceof Float32Array)) {
  12194. this.data = new Float32Array(offset + appendSize);
  12195. }
  12196. for (var i = 0; i < len$$1; i++) {
  12197. var appendPathData = path[i].data;
  12198. for (var k = 0; k < appendPathData.length; k++) {
  12199. this.data[offset++] = appendPathData[k];
  12200. }
  12201. }
  12202. this._len = offset;
  12203. },
  12204. /**
  12205. * 填充 Path 数据。
  12206. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  12207. */
  12208. addData: function (cmd) {
  12209. if (!this._saveData) {
  12210. return;
  12211. }
  12212. var data = this.data;
  12213. if (this._len + arguments.length > data.length) {
  12214. // 因为之前的数组已经转换成静态的 Float32Array
  12215. // 所以不够用时需要扩展一个新的动态数组
  12216. this._expandData();
  12217. data = this.data;
  12218. }
  12219. for (var i = 0; i < arguments.length; i++) {
  12220. data[this._len++] = arguments[i];
  12221. }
  12222. this._prevCmd = cmd;
  12223. },
  12224. _expandData: function () {
  12225. // Only if data is Float32Array
  12226. if (!(this.data instanceof Array)) {
  12227. var newData = [];
  12228. for (var i = 0; i < this._len; i++) {
  12229. newData[i] = this.data[i];
  12230. }
  12231. this.data = newData;
  12232. }
  12233. },
  12234. /**
  12235. * If needs js implemented dashed line
  12236. * @return {boolean}
  12237. * @private
  12238. */
  12239. _needsDash: function () {
  12240. return this._lineDash;
  12241. },
  12242. _dashedLineTo: function (x1, y1) {
  12243. var dashSum = this._dashSum;
  12244. var offset = this._dashOffset;
  12245. var lineDash = this._lineDash;
  12246. var ctx = this._ctx;
  12247. var x0 = this._xi;
  12248. var y0 = this._yi;
  12249. var dx = x1 - x0;
  12250. var dy = y1 - y0;
  12251. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  12252. var x = x0;
  12253. var y = y0;
  12254. var dash;
  12255. var nDash = lineDash.length;
  12256. var idx;
  12257. dx /= dist$$1;
  12258. dy /= dist$$1;
  12259. if (offset < 0) {
  12260. // Convert to positive offset
  12261. offset = dashSum + offset;
  12262. }
  12263. offset %= dashSum;
  12264. x -= offset * dx;
  12265. y -= offset * dy;
  12266. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  12267. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  12268. idx = this._dashIdx;
  12269. dash = lineDash[idx];
  12270. x += dx * dash;
  12271. y += dy * dash;
  12272. this._dashIdx = (idx + 1) % nDash;
  12273. // Skip positive offset
  12274. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  12275. continue;
  12276. }
  12277. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  12278. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  12279. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  12280. );
  12281. }
  12282. // Offset for next lineTo
  12283. dx = x - x1;
  12284. dy = y - y1;
  12285. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12286. },
  12287. // Not accurate dashed line to
  12288. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  12289. var dashSum = this._dashSum;
  12290. var offset = this._dashOffset;
  12291. var lineDash = this._lineDash;
  12292. var ctx = this._ctx;
  12293. var x0 = this._xi;
  12294. var y0 = this._yi;
  12295. var t;
  12296. var dx;
  12297. var dy;
  12298. var cubicAt$$1 = cubicAt;
  12299. var bezierLen = 0;
  12300. var idx = this._dashIdx;
  12301. var nDash = lineDash.length;
  12302. var x;
  12303. var y;
  12304. var tmpLen = 0;
  12305. if (offset < 0) {
  12306. // Convert to positive offset
  12307. offset = dashSum + offset;
  12308. }
  12309. offset %= dashSum;
  12310. // Bezier approx length
  12311. for (t = 0; t < 1; t += 0.1) {
  12312. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  12313. - cubicAt$$1(x0, x1, x2, x3, t);
  12314. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  12315. - cubicAt$$1(y0, y1, y2, y3, t);
  12316. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  12317. }
  12318. // Find idx after add offset
  12319. for (; idx < nDash; idx++) {
  12320. tmpLen += lineDash[idx];
  12321. if (tmpLen > offset) {
  12322. break;
  12323. }
  12324. }
  12325. t = (tmpLen - offset) / bezierLen;
  12326. while (t <= 1) {
  12327. x = cubicAt$$1(x0, x1, x2, x3, t);
  12328. y = cubicAt$$1(y0, y1, y2, y3, t);
  12329. // Use line to approximate dashed bezier
  12330. // Bad result if dash is long
  12331. idx % 2 ? ctx.moveTo(x, y)
  12332. : ctx.lineTo(x, y);
  12333. t += lineDash[idx] / bezierLen;
  12334. idx = (idx + 1) % nDash;
  12335. }
  12336. // Finish the last segment and calculate the new offset
  12337. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  12338. dx = x3 - x;
  12339. dy = y3 - y;
  12340. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12341. },
  12342. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  12343. // Convert quadratic to cubic using degree elevation
  12344. var x3 = x2;
  12345. var y3 = y2;
  12346. x2 = (x2 + 2 * x1) / 3;
  12347. y2 = (y2 + 2 * y1) / 3;
  12348. x1 = (this._xi + 2 * x1) / 3;
  12349. y1 = (this._yi + 2 * y1) / 3;
  12350. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  12351. },
  12352. /**
  12353. * 转成静态的 Float32Array 减少堆内存占用
  12354. * Convert dynamic array to static Float32Array
  12355. */
  12356. toStatic: function () {
  12357. var data = this.data;
  12358. if (data instanceof Array) {
  12359. data.length = this._len;
  12360. if (hasTypedArray) {
  12361. this.data = new Float32Array(data);
  12362. }
  12363. }
  12364. },
  12365. /**
  12366. * @return {module:zrender/core/BoundingRect}
  12367. */
  12368. getBoundingRect: function () {
  12369. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  12370. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  12371. var data = this.data;
  12372. var xi = 0;
  12373. var yi = 0;
  12374. var x0 = 0;
  12375. var y0 = 0;
  12376. for (var i = 0; i < data.length;) {
  12377. var cmd = data[i++];
  12378. if (i === 1) {
  12379. // 如果第一个命令是 L, C, Q
  12380. // 则 previous point 同绘制命令的第一个 point
  12381. //
  12382. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12383. xi = data[i];
  12384. yi = data[i + 1];
  12385. x0 = xi;
  12386. y0 = yi;
  12387. }
  12388. switch (cmd) {
  12389. case CMD.M:
  12390. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12391. // 在 closePath 的时候使用
  12392. x0 = data[i++];
  12393. y0 = data[i++];
  12394. xi = x0;
  12395. yi = y0;
  12396. min2[0] = x0;
  12397. min2[1] = y0;
  12398. max2[0] = x0;
  12399. max2[1] = y0;
  12400. break;
  12401. case CMD.L:
  12402. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  12403. xi = data[i++];
  12404. yi = data[i++];
  12405. break;
  12406. case CMD.C:
  12407. fromCubic(
  12408. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12409. min2, max2
  12410. );
  12411. xi = data[i++];
  12412. yi = data[i++];
  12413. break;
  12414. case CMD.Q:
  12415. fromQuadratic(
  12416. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  12417. min2, max2
  12418. );
  12419. xi = data[i++];
  12420. yi = data[i++];
  12421. break;
  12422. case CMD.A:
  12423. // TODO Arc 判断的开销比较大
  12424. var cx = data[i++];
  12425. var cy = data[i++];
  12426. var rx = data[i++];
  12427. var ry = data[i++];
  12428. var startAngle = data[i++];
  12429. var endAngle = data[i++] + startAngle;
  12430. // TODO Arc 旋转
  12431. i += 1;
  12432. var anticlockwise = 1 - data[i++];
  12433. if (i === 1) {
  12434. // 直接使用 arc 命令
  12435. // 第一个命令起点还未定义
  12436. x0 = mathCos$1(startAngle) * rx + cx;
  12437. y0 = mathSin$1(startAngle) * ry + cy;
  12438. }
  12439. fromArc(
  12440. cx, cy, rx, ry, startAngle, endAngle,
  12441. anticlockwise, min2, max2
  12442. );
  12443. xi = mathCos$1(endAngle) * rx + cx;
  12444. yi = mathSin$1(endAngle) * ry + cy;
  12445. break;
  12446. case CMD.R:
  12447. x0 = xi = data[i++];
  12448. y0 = yi = data[i++];
  12449. var width = data[i++];
  12450. var height = data[i++];
  12451. // Use fromLine
  12452. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  12453. break;
  12454. case CMD.Z:
  12455. xi = x0;
  12456. yi = y0;
  12457. break;
  12458. }
  12459. // Union
  12460. min(min$1, min$1, min2);
  12461. max(max$1, max$1, max2);
  12462. }
  12463. // No data
  12464. if (i === 0) {
  12465. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  12466. }
  12467. return new BoundingRect(
  12468. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  12469. );
  12470. },
  12471. /**
  12472. * Rebuild path from current data
  12473. * Rebuild path will not consider javascript implemented line dash.
  12474. * @param {CanvasRenderingContext2D} ctx
  12475. */
  12476. rebuildPath: function (ctx) {
  12477. var d = this.data;
  12478. var x0;
  12479. var y0;
  12480. var xi;
  12481. var yi;
  12482. var x;
  12483. var y;
  12484. var ux = this._ux;
  12485. var uy = this._uy;
  12486. var len$$1 = this._len;
  12487. for (var i = 0; i < len$$1;) {
  12488. var cmd = d[i++];
  12489. if (i === 1) {
  12490. // 如果第一个命令是 L, C, Q
  12491. // 则 previous point 同绘制命令的第一个 point
  12492. //
  12493. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12494. xi = d[i];
  12495. yi = d[i + 1];
  12496. x0 = xi;
  12497. y0 = yi;
  12498. }
  12499. switch (cmd) {
  12500. case CMD.M:
  12501. x0 = xi = d[i++];
  12502. y0 = yi = d[i++];
  12503. ctx.moveTo(xi, yi);
  12504. break;
  12505. case CMD.L:
  12506. x = d[i++];
  12507. y = d[i++];
  12508. // Not draw too small seg between
  12509. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  12510. ctx.lineTo(x, y);
  12511. xi = x;
  12512. yi = y;
  12513. }
  12514. break;
  12515. case CMD.C:
  12516. ctx.bezierCurveTo(
  12517. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  12518. );
  12519. xi = d[i - 2];
  12520. yi = d[i - 1];
  12521. break;
  12522. case CMD.Q:
  12523. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  12524. xi = d[i - 2];
  12525. yi = d[i - 1];
  12526. break;
  12527. case CMD.A:
  12528. var cx = d[i++];
  12529. var cy = d[i++];
  12530. var rx = d[i++];
  12531. var ry = d[i++];
  12532. var theta = d[i++];
  12533. var dTheta = d[i++];
  12534. var psi = d[i++];
  12535. var fs = d[i++];
  12536. var r = (rx > ry) ? rx : ry;
  12537. var scaleX = (rx > ry) ? 1 : rx / ry;
  12538. var scaleY = (rx > ry) ? ry / rx : 1;
  12539. var isEllipse = Math.abs(rx - ry) > 1e-3;
  12540. var endAngle = theta + dTheta;
  12541. if (isEllipse) {
  12542. ctx.translate(cx, cy);
  12543. ctx.rotate(psi);
  12544. ctx.scale(scaleX, scaleY);
  12545. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  12546. ctx.scale(1 / scaleX, 1 / scaleY);
  12547. ctx.rotate(-psi);
  12548. ctx.translate(-cx, -cy);
  12549. }
  12550. else {
  12551. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  12552. }
  12553. if (i === 1) {
  12554. // 直接使用 arc 命令
  12555. // 第一个命令起点还未定义
  12556. x0 = mathCos$1(theta) * rx + cx;
  12557. y0 = mathSin$1(theta) * ry + cy;
  12558. }
  12559. xi = mathCos$1(endAngle) * rx + cx;
  12560. yi = mathSin$1(endAngle) * ry + cy;
  12561. break;
  12562. case CMD.R:
  12563. x0 = xi = d[i];
  12564. y0 = yi = d[i + 1];
  12565. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  12566. break;
  12567. case CMD.Z:
  12568. ctx.closePath();
  12569. xi = x0;
  12570. yi = y0;
  12571. }
  12572. }
  12573. }
  12574. };
  12575. PathProxy.CMD = CMD;
  12576. /**
  12577. * 线段包含判断
  12578. * @param {number} x0
  12579. * @param {number} y0
  12580. * @param {number} x1
  12581. * @param {number} y1
  12582. * @param {number} lineWidth
  12583. * @param {number} x
  12584. * @param {number} y
  12585. * @return {boolean}
  12586. */
  12587. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  12588. if (lineWidth === 0) {
  12589. return false;
  12590. }
  12591. var _l = lineWidth;
  12592. var _a = 0;
  12593. var _b = x0;
  12594. // Quick reject
  12595. if (
  12596. (y > y0 + _l && y > y1 + _l)
  12597. || (y < y0 - _l && y < y1 - _l)
  12598. || (x > x0 + _l && x > x1 + _l)
  12599. || (x < x0 - _l && x < x1 - _l)
  12600. ) {
  12601. return false;
  12602. }
  12603. if (x0 !== x1) {
  12604. _a = (y0 - y1) / (x0 - x1);
  12605. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12606. }
  12607. else {
  12608. return Math.abs(x - x0) <= _l / 2;
  12609. }
  12610. var tmp = _a * x - y + _b;
  12611. var _s = tmp * tmp / (_a * _a + 1);
  12612. return _s <= _l / 2 * _l / 2;
  12613. }
  12614. /**
  12615. * 三次贝塞尔曲线描边包含判断
  12616. * @param {number} x0
  12617. * @param {number} y0
  12618. * @param {number} x1
  12619. * @param {number} y1
  12620. * @param {number} x2
  12621. * @param {number} y2
  12622. * @param {number} x3
  12623. * @param {number} y3
  12624. * @param {number} lineWidth
  12625. * @param {number} x
  12626. * @param {number} y
  12627. * @return {boolean}
  12628. */
  12629. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12630. if (lineWidth === 0) {
  12631. return false;
  12632. }
  12633. var _l = lineWidth;
  12634. // Quick reject
  12635. if (
  12636. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12637. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12638. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12639. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12640. ) {
  12641. return false;
  12642. }
  12643. var d = cubicProjectPoint(
  12644. x0, y0, x1, y1, x2, y2, x3, y3,
  12645. x, y, null
  12646. );
  12647. return d <= _l / 2;
  12648. }
  12649. /**
  12650. * 二次贝塞尔曲线描边包含判断
  12651. * @param {number} x0
  12652. * @param {number} y0
  12653. * @param {number} x1
  12654. * @param {number} y1
  12655. * @param {number} x2
  12656. * @param {number} y2
  12657. * @param {number} lineWidth
  12658. * @param {number} x
  12659. * @param {number} y
  12660. * @return {boolean}
  12661. */
  12662. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12663. if (lineWidth === 0) {
  12664. return false;
  12665. }
  12666. var _l = lineWidth;
  12667. // Quick reject
  12668. if (
  12669. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12670. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12671. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12672. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12673. ) {
  12674. return false;
  12675. }
  12676. var d = quadraticProjectPoint(
  12677. x0, y0, x1, y1, x2, y2,
  12678. x, y, null
  12679. );
  12680. return d <= _l / 2;
  12681. }
  12682. var PI2$3 = Math.PI * 2;
  12683. function normalizeRadian(angle) {
  12684. angle %= PI2$3;
  12685. if (angle < 0) {
  12686. angle += PI2$3;
  12687. }
  12688. return angle;
  12689. }
  12690. var PI2$2 = Math.PI * 2;
  12691. /**
  12692. * 圆弧描边包含判断
  12693. * @param {number} cx
  12694. * @param {number} cy
  12695. * @param {number} r
  12696. * @param {number} startAngle
  12697. * @param {number} endAngle
  12698. * @param {boolean} anticlockwise
  12699. * @param {number} lineWidth
  12700. * @param {number} x
  12701. * @param {number} y
  12702. * @return {Boolean}
  12703. */
  12704. function containStroke$4(
  12705. cx, cy, r, startAngle, endAngle, anticlockwise,
  12706. lineWidth, x, y
  12707. ) {
  12708. if (lineWidth === 0) {
  12709. return false;
  12710. }
  12711. var _l = lineWidth;
  12712. x -= cx;
  12713. y -= cy;
  12714. var d = Math.sqrt(x * x + y * y);
  12715. if ((d - _l > r) || (d + _l < r)) {
  12716. return false;
  12717. }
  12718. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12719. // Is a circle
  12720. return true;
  12721. }
  12722. if (anticlockwise) {
  12723. var tmp = startAngle;
  12724. startAngle = normalizeRadian(endAngle);
  12725. endAngle = normalizeRadian(tmp);
  12726. }
  12727. else {
  12728. startAngle = normalizeRadian(startAngle);
  12729. endAngle = normalizeRadian(endAngle);
  12730. }
  12731. if (startAngle > endAngle) {
  12732. endAngle += PI2$2;
  12733. }
  12734. var angle = Math.atan2(y, x);
  12735. if (angle < 0) {
  12736. angle += PI2$2;
  12737. }
  12738. return (angle >= startAngle && angle <= endAngle)
  12739. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12740. }
  12741. function windingLine(x0, y0, x1, y1, x, y) {
  12742. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12743. return 0;
  12744. }
  12745. // Ignore horizontal line
  12746. if (y1 === y0) {
  12747. return 0;
  12748. }
  12749. var dir = y1 < y0 ? 1 : -1;
  12750. var t = (y - y0) / (y1 - y0);
  12751. // Avoid winding error when intersection point is the connect point of two line of polygon
  12752. if (t === 1 || t === 0) {
  12753. dir = y1 < y0 ? 0.5 : -0.5;
  12754. }
  12755. var x_ = t * (x1 - x0) + x0;
  12756. // If (x, y) on the line, considered as "contain".
  12757. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12758. }
  12759. var CMD$1 = PathProxy.CMD;
  12760. var PI2$1 = Math.PI * 2;
  12761. var EPSILON$2 = 1e-4;
  12762. function isAroundEqual(a, b) {
  12763. return Math.abs(a - b) < EPSILON$2;
  12764. }
  12765. // 临时数组
  12766. var roots = [-1, -1, -1];
  12767. var extrema = [-1, -1];
  12768. function swapExtrema() {
  12769. var tmp = extrema[0];
  12770. extrema[0] = extrema[1];
  12771. extrema[1] = tmp;
  12772. }
  12773. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12774. // Quick reject
  12775. if (
  12776. (y > y0 && y > y1 && y > y2 && y > y3)
  12777. || (y < y0 && y < y1 && y < y2 && y < y3)
  12778. ) {
  12779. return 0;
  12780. }
  12781. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12782. if (nRoots === 0) {
  12783. return 0;
  12784. }
  12785. else {
  12786. var w = 0;
  12787. var nExtrema = -1;
  12788. var y0_;
  12789. var y1_;
  12790. for (var i = 0; i < nRoots; i++) {
  12791. var t = roots[i];
  12792. // Avoid winding error when intersection point is the connect point of two line of polygon
  12793. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12794. var x_ = cubicAt(x0, x1, x2, x3, t);
  12795. if (x_ < x) { // Quick reject
  12796. continue;
  12797. }
  12798. if (nExtrema < 0) {
  12799. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12800. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12801. swapExtrema();
  12802. }
  12803. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12804. if (nExtrema > 1) {
  12805. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12806. }
  12807. }
  12808. if (nExtrema === 2) {
  12809. // 分成三段单调函数
  12810. if (t < extrema[0]) {
  12811. w += y0_ < y0 ? unit : -unit;
  12812. }
  12813. else if (t < extrema[1]) {
  12814. w += y1_ < y0_ ? unit : -unit;
  12815. }
  12816. else {
  12817. w += y3 < y1_ ? unit : -unit;
  12818. }
  12819. }
  12820. else {
  12821. // 分成两段单调函数
  12822. if (t < extrema[0]) {
  12823. w += y0_ < y0 ? unit : -unit;
  12824. }
  12825. else {
  12826. w += y3 < y0_ ? unit : -unit;
  12827. }
  12828. }
  12829. }
  12830. return w;
  12831. }
  12832. }
  12833. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12834. // Quick reject
  12835. if (
  12836. (y > y0 && y > y1 && y > y2)
  12837. || (y < y0 && y < y1 && y < y2)
  12838. ) {
  12839. return 0;
  12840. }
  12841. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12842. if (nRoots === 0) {
  12843. return 0;
  12844. }
  12845. else {
  12846. var t = quadraticExtremum(y0, y1, y2);
  12847. if (t >= 0 && t <= 1) {
  12848. var w = 0;
  12849. var y_ = quadraticAt(y0, y1, y2, t);
  12850. for (var i = 0; i < nRoots; i++) {
  12851. // Remove one endpoint.
  12852. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12853. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12854. if (x_ < x) { // Quick reject
  12855. continue;
  12856. }
  12857. if (roots[i] < t) {
  12858. w += y_ < y0 ? unit : -unit;
  12859. }
  12860. else {
  12861. w += y2 < y_ ? unit : -unit;
  12862. }
  12863. }
  12864. return w;
  12865. }
  12866. else {
  12867. // Remove one endpoint.
  12868. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12869. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12870. if (x_ < x) { // Quick reject
  12871. return 0;
  12872. }
  12873. return y2 < y0 ? unit : -unit;
  12874. }
  12875. }
  12876. }
  12877. // TODO
  12878. // Arc 旋转
  12879. function windingArc(
  12880. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12881. ) {
  12882. y -= cy;
  12883. if (y > r || y < -r) {
  12884. return 0;
  12885. }
  12886. var tmp = Math.sqrt(r * r - y * y);
  12887. roots[0] = -tmp;
  12888. roots[1] = tmp;
  12889. var diff = Math.abs(startAngle - endAngle);
  12890. if (diff < 1e-4) {
  12891. return 0;
  12892. }
  12893. if (diff % PI2$1 < 1e-4) {
  12894. // Is a circle
  12895. startAngle = 0;
  12896. endAngle = PI2$1;
  12897. var dir = anticlockwise ? 1 : -1;
  12898. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12899. return dir;
  12900. }
  12901. else {
  12902. return 0;
  12903. }
  12904. }
  12905. if (anticlockwise) {
  12906. var tmp = startAngle;
  12907. startAngle = normalizeRadian(endAngle);
  12908. endAngle = normalizeRadian(tmp);
  12909. }
  12910. else {
  12911. startAngle = normalizeRadian(startAngle);
  12912. endAngle = normalizeRadian(endAngle);
  12913. }
  12914. if (startAngle > endAngle) {
  12915. endAngle += PI2$1;
  12916. }
  12917. var w = 0;
  12918. for (var i = 0; i < 2; i++) {
  12919. var x_ = roots[i];
  12920. if (x_ + cx > x) {
  12921. var angle = Math.atan2(y, x_);
  12922. var dir = anticlockwise ? 1 : -1;
  12923. if (angle < 0) {
  12924. angle = PI2$1 + angle;
  12925. }
  12926. if (
  12927. (angle >= startAngle && angle <= endAngle)
  12928. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12929. ) {
  12930. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12931. dir = -dir;
  12932. }
  12933. w += dir;
  12934. }
  12935. }
  12936. }
  12937. return w;
  12938. }
  12939. function containPath(data, lineWidth, isStroke, x, y) {
  12940. var w = 0;
  12941. var xi = 0;
  12942. var yi = 0;
  12943. var x0 = 0;
  12944. var y0 = 0;
  12945. for (var i = 0; i < data.length;) {
  12946. var cmd = data[i++];
  12947. // Begin a new subpath
  12948. if (cmd === CMD$1.M && i > 1) {
  12949. // Close previous subpath
  12950. if (!isStroke) {
  12951. w += windingLine(xi, yi, x0, y0, x, y);
  12952. }
  12953. // 如果被任何一个 subpath 包含
  12954. // if (w !== 0) {
  12955. // return true;
  12956. // }
  12957. }
  12958. if (i === 1) {
  12959. // 如果第一个命令是 L, C, Q
  12960. // 则 previous point 同绘制命令的第一个 point
  12961. //
  12962. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12963. xi = data[i];
  12964. yi = data[i + 1];
  12965. x0 = xi;
  12966. y0 = yi;
  12967. }
  12968. switch (cmd) {
  12969. case CMD$1.M:
  12970. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12971. // 在 closePath 的时候使用
  12972. x0 = data[i++];
  12973. y0 = data[i++];
  12974. xi = x0;
  12975. yi = y0;
  12976. break;
  12977. case CMD$1.L:
  12978. if (isStroke) {
  12979. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12980. return true;
  12981. }
  12982. }
  12983. else {
  12984. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12985. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12986. }
  12987. xi = data[i++];
  12988. yi = data[i++];
  12989. break;
  12990. case CMD$1.C:
  12991. if (isStroke) {
  12992. if (containStroke$2(xi, yi,
  12993. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12994. lineWidth, x, y
  12995. )) {
  12996. return true;
  12997. }
  12998. }
  12999. else {
  13000. w += windingCubic(
  13001. xi, yi,
  13002. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  13003. x, y
  13004. ) || 0;
  13005. }
  13006. xi = data[i++];
  13007. yi = data[i++];
  13008. break;
  13009. case CMD$1.Q:
  13010. if (isStroke) {
  13011. if (containStroke$3(xi, yi,
  13012. data[i++], data[i++], data[i], data[i + 1],
  13013. lineWidth, x, y
  13014. )) {
  13015. return true;
  13016. }
  13017. }
  13018. else {
  13019. w += windingQuadratic(
  13020. xi, yi,
  13021. data[i++], data[i++], data[i], data[i + 1],
  13022. x, y
  13023. ) || 0;
  13024. }
  13025. xi = data[i++];
  13026. yi = data[i++];
  13027. break;
  13028. case CMD$1.A:
  13029. // TODO Arc 判断的开销比较大
  13030. var cx = data[i++];
  13031. var cy = data[i++];
  13032. var rx = data[i++];
  13033. var ry = data[i++];
  13034. var theta = data[i++];
  13035. var dTheta = data[i++];
  13036. // TODO Arc 旋转
  13037. i += 1;
  13038. var anticlockwise = 1 - data[i++];
  13039. var x1 = Math.cos(theta) * rx + cx;
  13040. var y1 = Math.sin(theta) * ry + cy;
  13041. // 不是直接使用 arc 命令
  13042. if (i > 1) {
  13043. w += windingLine(xi, yi, x1, y1, x, y);
  13044. }
  13045. else {
  13046. // 第一个命令起点还未定义
  13047. x0 = x1;
  13048. y0 = y1;
  13049. }
  13050. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  13051. var _x = (x - cx) * ry / rx + cx;
  13052. if (isStroke) {
  13053. if (containStroke$4(
  13054. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13055. lineWidth, _x, y
  13056. )) {
  13057. return true;
  13058. }
  13059. }
  13060. else {
  13061. w += windingArc(
  13062. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13063. _x, y
  13064. );
  13065. }
  13066. xi = Math.cos(theta + dTheta) * rx + cx;
  13067. yi = Math.sin(theta + dTheta) * ry + cy;
  13068. break;
  13069. case CMD$1.R:
  13070. x0 = xi = data[i++];
  13071. y0 = yi = data[i++];
  13072. var width = data[i++];
  13073. var height = data[i++];
  13074. var x1 = x0 + width;
  13075. var y1 = y0 + height;
  13076. if (isStroke) {
  13077. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  13078. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  13079. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  13080. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  13081. ) {
  13082. return true;
  13083. }
  13084. }
  13085. else {
  13086. // FIXME Clockwise ?
  13087. w += windingLine(x1, y0, x1, y1, x, y);
  13088. w += windingLine(x0, y1, x0, y0, x, y);
  13089. }
  13090. break;
  13091. case CMD$1.Z:
  13092. if (isStroke) {
  13093. if (containStroke$1(
  13094. xi, yi, x0, y0, lineWidth, x, y
  13095. )) {
  13096. return true;
  13097. }
  13098. }
  13099. else {
  13100. // Close a subpath
  13101. w += windingLine(xi, yi, x0, y0, x, y);
  13102. // 如果被任何一个 subpath 包含
  13103. // FIXME subpaths may overlap
  13104. // if (w !== 0) {
  13105. // return true;
  13106. // }
  13107. }
  13108. xi = x0;
  13109. yi = y0;
  13110. break;
  13111. }
  13112. }
  13113. if (!isStroke && !isAroundEqual(yi, y0)) {
  13114. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  13115. }
  13116. return w !== 0;
  13117. }
  13118. function contain(pathData, x, y) {
  13119. return containPath(pathData, 0, false, x, y);
  13120. }
  13121. function containStroke(pathData, lineWidth, x, y) {
  13122. return containPath(pathData, lineWidth, true, x, y);
  13123. }
  13124. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  13125. var abs = Math.abs;
  13126. var pathProxyForDraw = new PathProxy(true);
  13127. /**
  13128. * @alias module:zrender/graphic/Path
  13129. * @extends module:zrender/graphic/Displayable
  13130. * @constructor
  13131. * @param {Object} opts
  13132. */
  13133. function Path(opts) {
  13134. Displayable.call(this, opts);
  13135. /**
  13136. * @type {module:zrender/core/PathProxy}
  13137. * @readOnly
  13138. */
  13139. this.path = null;
  13140. }
  13141. Path.prototype = {
  13142. constructor: Path,
  13143. type: 'path',
  13144. __dirtyPath: true,
  13145. strokeContainThreshold: 5,
  13146. // This item default to be false. But in map series in echarts,
  13147. // in order to improve performance, it should be set to true,
  13148. // so the shorty segment won't draw.
  13149. segmentIgnoreThreshold: 0,
  13150. /**
  13151. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  13152. * @type {boolean}
  13153. */
  13154. subPixelOptimize: false,
  13155. brush: function (ctx, prevEl) {
  13156. var style = this.style;
  13157. var path = this.path || pathProxyForDraw;
  13158. var hasStroke = style.hasStroke();
  13159. var hasFill = style.hasFill();
  13160. var fill = style.fill;
  13161. var stroke = style.stroke;
  13162. var hasFillGradient = hasFill && !!(fill.colorStops);
  13163. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  13164. var hasFillPattern = hasFill && !!(fill.image);
  13165. var hasStrokePattern = hasStroke && !!(stroke.image);
  13166. style.bind(ctx, this, prevEl);
  13167. this.setTransform(ctx);
  13168. if (this.__dirty) {
  13169. var rect;
  13170. // Update gradient because bounding rect may changed
  13171. if (hasFillGradient) {
  13172. rect = rect || this.getBoundingRect();
  13173. this._fillGradient = style.getGradient(ctx, fill, rect);
  13174. }
  13175. if (hasStrokeGradient) {
  13176. rect = rect || this.getBoundingRect();
  13177. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  13178. }
  13179. }
  13180. // Use the gradient or pattern
  13181. if (hasFillGradient) {
  13182. // PENDING If may have affect the state
  13183. ctx.fillStyle = this._fillGradient;
  13184. }
  13185. else if (hasFillPattern) {
  13186. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  13187. }
  13188. if (hasStrokeGradient) {
  13189. ctx.strokeStyle = this._strokeGradient;
  13190. }
  13191. else if (hasStrokePattern) {
  13192. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  13193. }
  13194. var lineDash = style.lineDash;
  13195. var lineDashOffset = style.lineDashOffset;
  13196. var ctxLineDash = !!ctx.setLineDash;
  13197. // Update path sx, sy
  13198. var scale = this.getGlobalScale();
  13199. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  13200. // Proxy context
  13201. // Rebuild path in following 2 cases
  13202. // 1. Path is dirty
  13203. // 2. Path needs javascript implemented lineDash stroking.
  13204. // In this case, lineDash information will not be saved in PathProxy
  13205. if (this.__dirtyPath
  13206. || (lineDash && !ctxLineDash && hasStroke)
  13207. ) {
  13208. path.beginPath(ctx);
  13209. // Setting line dash before build path
  13210. if (lineDash && !ctxLineDash) {
  13211. path.setLineDash(lineDash);
  13212. path.setLineDashOffset(lineDashOffset);
  13213. }
  13214. this.buildPath(path, this.shape, false);
  13215. // Clear path dirty flag
  13216. if (this.path) {
  13217. this.__dirtyPath = false;
  13218. }
  13219. }
  13220. else {
  13221. // Replay path building
  13222. ctx.beginPath();
  13223. this.path.rebuildPath(ctx);
  13224. }
  13225. if (hasFill) {
  13226. if (style.fillOpacity != null) {
  13227. var originalGlobalAlpha = ctx.globalAlpha;
  13228. ctx.globalAlpha = style.fillOpacity * style.opacity;
  13229. path.fill(ctx);
  13230. ctx.globalAlpha = originalGlobalAlpha;
  13231. }
  13232. else {
  13233. path.fill(ctx);
  13234. }
  13235. }
  13236. if (lineDash && ctxLineDash) {
  13237. ctx.setLineDash(lineDash);
  13238. ctx.lineDashOffset = lineDashOffset;
  13239. }
  13240. if (hasStroke) {
  13241. if (style.strokeOpacity != null) {
  13242. var originalGlobalAlpha = ctx.globalAlpha;
  13243. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  13244. path.stroke(ctx);
  13245. ctx.globalAlpha = originalGlobalAlpha;
  13246. }
  13247. else {
  13248. path.stroke(ctx);
  13249. }
  13250. }
  13251. if (lineDash && ctxLineDash) {
  13252. // PENDING
  13253. // Remove lineDash
  13254. ctx.setLineDash([]);
  13255. }
  13256. // Draw rect text
  13257. if (style.text != null) {
  13258. // Only restore transform when needs draw text.
  13259. this.restoreTransform(ctx);
  13260. this.drawRectText(ctx, this.getBoundingRect());
  13261. }
  13262. },
  13263. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  13264. // Like in circle
  13265. buildPath: function (ctx, shapeCfg, inBundle) {},
  13266. createPathProxy: function () {
  13267. this.path = new PathProxy();
  13268. },
  13269. getBoundingRect: function () {
  13270. var rect = this._rect;
  13271. var style = this.style;
  13272. var needsUpdateRect = !rect;
  13273. if (needsUpdateRect) {
  13274. var path = this.path;
  13275. if (!path) {
  13276. // Create path on demand.
  13277. path = this.path = new PathProxy();
  13278. }
  13279. if (this.__dirtyPath) {
  13280. path.beginPath();
  13281. this.buildPath(path, this.shape, false);
  13282. }
  13283. rect = path.getBoundingRect();
  13284. }
  13285. this._rect = rect;
  13286. if (style.hasStroke()) {
  13287. // Needs update rect with stroke lineWidth when
  13288. // 1. Element changes scale or lineWidth
  13289. // 2. Shape is changed
  13290. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  13291. if (this.__dirty || needsUpdateRect) {
  13292. rectWithStroke.copy(rect);
  13293. // FIXME Must after updateTransform
  13294. var w = style.lineWidth;
  13295. // PENDING, Min line width is needed when line is horizontal or vertical
  13296. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13297. // Only add extra hover lineWidth when there are no fill
  13298. if (!style.hasFill()) {
  13299. w = Math.max(w, this.strokeContainThreshold || 4);
  13300. }
  13301. // Consider line width
  13302. // Line scale can't be 0;
  13303. if (lineScale > 1e-10) {
  13304. rectWithStroke.width += w / lineScale;
  13305. rectWithStroke.height += w / lineScale;
  13306. rectWithStroke.x -= w / lineScale / 2;
  13307. rectWithStroke.y -= w / lineScale / 2;
  13308. }
  13309. }
  13310. // Return rect with stroke
  13311. return rectWithStroke;
  13312. }
  13313. return rect;
  13314. },
  13315. contain: function (x, y) {
  13316. var localPos = this.transformCoordToLocal(x, y);
  13317. var rect = this.getBoundingRect();
  13318. var style = this.style;
  13319. x = localPos[0];
  13320. y = localPos[1];
  13321. if (rect.contain(x, y)) {
  13322. var pathData = this.path.data;
  13323. if (style.hasStroke()) {
  13324. var lineWidth = style.lineWidth;
  13325. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13326. // Line scale can't be 0;
  13327. if (lineScale > 1e-10) {
  13328. // Only add extra hover lineWidth when there are no fill
  13329. if (!style.hasFill()) {
  13330. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  13331. }
  13332. if (containStroke(
  13333. pathData, lineWidth / lineScale, x, y
  13334. )) {
  13335. return true;
  13336. }
  13337. }
  13338. }
  13339. if (style.hasFill()) {
  13340. return contain(pathData, x, y);
  13341. }
  13342. }
  13343. return false;
  13344. },
  13345. /**
  13346. * @param {boolean} dirtyPath
  13347. */
  13348. dirty: function (dirtyPath) {
  13349. if (dirtyPath == null) {
  13350. dirtyPath = true;
  13351. }
  13352. // Only mark dirty, not mark clean
  13353. if (dirtyPath) {
  13354. this.__dirtyPath = dirtyPath;
  13355. this._rect = null;
  13356. }
  13357. this.__dirty = this.__dirtyText = true;
  13358. this.__zr && this.__zr.refresh();
  13359. // Used as a clipping path
  13360. if (this.__clipTarget) {
  13361. this.__clipTarget.dirty();
  13362. }
  13363. },
  13364. /**
  13365. * Alias for animate('shape')
  13366. * @param {boolean} loop
  13367. */
  13368. animateShape: function (loop) {
  13369. return this.animate('shape', loop);
  13370. },
  13371. // Overwrite attrKV
  13372. attrKV: function (key, value) {
  13373. // FIXME
  13374. if (key === 'shape') {
  13375. this.setShape(value);
  13376. this.__dirtyPath = true;
  13377. this._rect = null;
  13378. }
  13379. else {
  13380. Displayable.prototype.attrKV.call(this, key, value);
  13381. }
  13382. },
  13383. /**
  13384. * @param {Object|string} key
  13385. * @param {*} value
  13386. */
  13387. setShape: function (key, value) {
  13388. var shape = this.shape;
  13389. // Path from string may not have shape
  13390. if (shape) {
  13391. if (isObject$1(key)) {
  13392. for (var name in key) {
  13393. if (key.hasOwnProperty(name)) {
  13394. shape[name] = key[name];
  13395. }
  13396. }
  13397. }
  13398. else {
  13399. shape[key] = value;
  13400. }
  13401. this.dirty(true);
  13402. }
  13403. return this;
  13404. },
  13405. getLineScale: function () {
  13406. var m = this.transform;
  13407. // Get the line scale.
  13408. // Determinant of `m` means how much the area is enlarged by the
  13409. // transformation. So its square root can be used as a scale factor
  13410. // for width.
  13411. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  13412. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  13413. : 1;
  13414. }
  13415. };
  13416. /**
  13417. * 扩展一个 Path element, 比如星形,圆等。
  13418. * Extend a path element
  13419. * @param {Object} props
  13420. * @param {string} props.type Path type
  13421. * @param {Function} props.init Initialize
  13422. * @param {Function} props.buildPath Overwrite buildPath method
  13423. * @param {Object} [props.style] Extended default style config
  13424. * @param {Object} [props.shape] Extended default shape config
  13425. */
  13426. Path.extend = function (defaults$$1) {
  13427. var Sub = function (opts) {
  13428. Path.call(this, opts);
  13429. if (defaults$$1.style) {
  13430. // Extend default style
  13431. this.style.extendFrom(defaults$$1.style, false);
  13432. }
  13433. // Extend default shape
  13434. var defaultShape = defaults$$1.shape;
  13435. if (defaultShape) {
  13436. this.shape = this.shape || {};
  13437. var thisShape = this.shape;
  13438. for (var name in defaultShape) {
  13439. if (
  13440. !thisShape.hasOwnProperty(name)
  13441. && defaultShape.hasOwnProperty(name)
  13442. ) {
  13443. thisShape[name] = defaultShape[name];
  13444. }
  13445. }
  13446. }
  13447. defaults$$1.init && defaults$$1.init.call(this, opts);
  13448. };
  13449. inherits(Sub, Path);
  13450. // FIXME 不能 extend position, rotation 等引用对象
  13451. for (var name in defaults$$1) {
  13452. // Extending prototype values and methods
  13453. if (name !== 'style' && name !== 'shape') {
  13454. Sub.prototype[name] = defaults$$1[name];
  13455. }
  13456. }
  13457. return Sub;
  13458. };
  13459. inherits(Path, Displayable);
  13460. var CMD$2 = PathProxy.CMD;
  13461. var points = [[], [], []];
  13462. var mathSqrt$3 = Math.sqrt;
  13463. var mathAtan2 = Math.atan2;
  13464. var transformPath = function (path, m) {
  13465. var data = path.data;
  13466. var cmd;
  13467. var nPoint;
  13468. var i;
  13469. var j;
  13470. var k;
  13471. var p;
  13472. var M = CMD$2.M;
  13473. var C = CMD$2.C;
  13474. var L = CMD$2.L;
  13475. var R = CMD$2.R;
  13476. var A = CMD$2.A;
  13477. var Q = CMD$2.Q;
  13478. for (i = 0, j = 0; i < data.length;) {
  13479. cmd = data[i++];
  13480. j = i;
  13481. nPoint = 0;
  13482. switch (cmd) {
  13483. case M:
  13484. nPoint = 1;
  13485. break;
  13486. case L:
  13487. nPoint = 1;
  13488. break;
  13489. case C:
  13490. nPoint = 3;
  13491. break;
  13492. case Q:
  13493. nPoint = 2;
  13494. break;
  13495. case A:
  13496. var x = m[4];
  13497. var y = m[5];
  13498. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  13499. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  13500. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13501. // cx
  13502. data[i] *= sx;
  13503. data[i++] += x;
  13504. // cy
  13505. data[i] *= sy;
  13506. data[i++] += y;
  13507. // Scale rx and ry
  13508. // FIXME Assume psi is 0 here
  13509. data[i++] *= sx;
  13510. data[i++] *= sy;
  13511. // Start angle
  13512. data[i++] += angle;
  13513. // end angle
  13514. data[i++] += angle;
  13515. // FIXME psi
  13516. i += 2;
  13517. j = i;
  13518. break;
  13519. case R:
  13520. // x0, y0
  13521. p[0] = data[i++];
  13522. p[1] = data[i++];
  13523. applyTransform(p, p, m);
  13524. data[j++] = p[0];
  13525. data[j++] = p[1];
  13526. // x1, y1
  13527. p[0] += data[i++];
  13528. p[1] += data[i++];
  13529. applyTransform(p, p, m);
  13530. data[j++] = p[0];
  13531. data[j++] = p[1];
  13532. }
  13533. for (k = 0; k < nPoint; k++) {
  13534. var p = points[k];
  13535. p[0] = data[i++];
  13536. p[1] = data[i++];
  13537. applyTransform(p, p, m);
  13538. // Write back
  13539. data[j++] = p[0];
  13540. data[j++] = p[1];
  13541. }
  13542. }
  13543. };
  13544. // command chars
  13545. // var cc = [
  13546. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  13547. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  13548. // ];
  13549. var mathSqrt = Math.sqrt;
  13550. var mathSin = Math.sin;
  13551. var mathCos = Math.cos;
  13552. var PI = Math.PI;
  13553. var vMag = function (v) {
  13554. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13555. };
  13556. var vRatio = function (u, v) {
  13557. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13558. };
  13559. var vAngle = function (u, v) {
  13560. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13561. * Math.acos(vRatio(u, v));
  13562. };
  13563. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13564. var psi = psiDeg * (PI / 180.0);
  13565. var xp = mathCos(psi) * (x1 - x2) / 2.0
  13566. + mathSin(psi) * (y1 - y2) / 2.0;
  13567. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  13568. + mathCos(psi) * (y1 - y2) / 2.0;
  13569. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13570. if (lambda > 1) {
  13571. rx *= mathSqrt(lambda);
  13572. ry *= mathSqrt(lambda);
  13573. }
  13574. var f = (fa === fs ? -1 : 1)
  13575. * mathSqrt((((rx * rx) * (ry * ry))
  13576. - ((rx * rx) * (yp * yp))
  13577. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13578. + (ry * ry) * (xp * xp))
  13579. ) || 0;
  13580. var cxp = f * rx * yp / ry;
  13581. var cyp = f * -ry * xp / rx;
  13582. var cx = (x1 + x2) / 2.0
  13583. + mathCos(psi) * cxp
  13584. - mathSin(psi) * cyp;
  13585. var cy = (y1 + y2) / 2.0
  13586. + mathSin(psi) * cxp
  13587. + mathCos(psi) * cyp;
  13588. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  13589. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  13590. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  13591. var dTheta = vAngle(u, v);
  13592. if (vRatio(u, v) <= -1) {
  13593. dTheta = PI;
  13594. }
  13595. if (vRatio(u, v) >= 1) {
  13596. dTheta = 0;
  13597. }
  13598. if (fs === 0 && dTheta > 0) {
  13599. dTheta = dTheta - 2 * PI;
  13600. }
  13601. if (fs === 1 && dTheta < 0) {
  13602. dTheta = dTheta + 2 * PI;
  13603. }
  13604. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13605. }
  13606. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13607. // Consider case:
  13608. // (1) delimiter can be comma or space, where continuous commas
  13609. // or spaces should be seen as one comma.
  13610. // (2) value can be like:
  13611. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13612. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13613. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13614. // var valueSplitReg = /[\s,]+/;
  13615. function createPathProxyFromString(data) {
  13616. if (!data) {
  13617. return new PathProxy();
  13618. }
  13619. // var data = data.replace(/-/g, ' -')
  13620. // .replace(/ /g, ' ')
  13621. // .replace(/ /g, ',')
  13622. // .replace(/,,/g, ',');
  13623. // var n;
  13624. // create pipes so that we can split the data
  13625. // for (n = 0; n < cc.length; n++) {
  13626. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13627. // }
  13628. // data = data.replace(/-/g, ',-');
  13629. // create array
  13630. // var arr = cs.split('|');
  13631. // init context point
  13632. var cpx = 0;
  13633. var cpy = 0;
  13634. var subpathX = cpx;
  13635. var subpathY = cpy;
  13636. var prevCmd;
  13637. var path = new PathProxy();
  13638. var CMD = PathProxy.CMD;
  13639. // commandReg.lastIndex = 0;
  13640. // var cmdResult;
  13641. // while ((cmdResult = commandReg.exec(data)) != null) {
  13642. // var cmdStr = cmdResult[1];
  13643. // var cmdContent = cmdResult[2];
  13644. var cmdList = data.match(commandReg);
  13645. for (var l = 0; l < cmdList.length; l++) {
  13646. var cmdText = cmdList[l];
  13647. var cmdStr = cmdText.charAt(0);
  13648. var cmd;
  13649. // String#split is faster a little bit than String#replace or RegExp#exec.
  13650. // var p = cmdContent.split(valueSplitReg);
  13651. // var pLen = 0;
  13652. // for (var i = 0; i < p.length; i++) {
  13653. // // '' and other invalid str => NaN
  13654. // var val = parseFloat(p[i]);
  13655. // !isNaN(val) && (p[pLen++] = val);
  13656. // }
  13657. var p = cmdText.match(numberReg) || [];
  13658. var pLen = p.length;
  13659. for (var i = 0; i < pLen; i++) {
  13660. p[i] = parseFloat(p[i]);
  13661. }
  13662. var off = 0;
  13663. while (off < pLen) {
  13664. var ctlPtx;
  13665. var ctlPty;
  13666. var rx;
  13667. var ry;
  13668. var psi;
  13669. var fa;
  13670. var fs;
  13671. var x1 = cpx;
  13672. var y1 = cpy;
  13673. // convert l, H, h, V, and v to L
  13674. switch (cmdStr) {
  13675. case 'l':
  13676. cpx += p[off++];
  13677. cpy += p[off++];
  13678. cmd = CMD.L;
  13679. path.addData(cmd, cpx, cpy);
  13680. break;
  13681. case 'L':
  13682. cpx = p[off++];
  13683. cpy = p[off++];
  13684. cmd = CMD.L;
  13685. path.addData(cmd, cpx, cpy);
  13686. break;
  13687. case 'm':
  13688. cpx += p[off++];
  13689. cpy += p[off++];
  13690. cmd = CMD.M;
  13691. path.addData(cmd, cpx, cpy);
  13692. subpathX = cpx;
  13693. subpathY = cpy;
  13694. cmdStr = 'l';
  13695. break;
  13696. case 'M':
  13697. cpx = p[off++];
  13698. cpy = p[off++];
  13699. cmd = CMD.M;
  13700. path.addData(cmd, cpx, cpy);
  13701. subpathX = cpx;
  13702. subpathY = cpy;
  13703. cmdStr = 'L';
  13704. break;
  13705. case 'h':
  13706. cpx += p[off++];
  13707. cmd = CMD.L;
  13708. path.addData(cmd, cpx, cpy);
  13709. break;
  13710. case 'H':
  13711. cpx = p[off++];
  13712. cmd = CMD.L;
  13713. path.addData(cmd, cpx, cpy);
  13714. break;
  13715. case 'v':
  13716. cpy += p[off++];
  13717. cmd = CMD.L;
  13718. path.addData(cmd, cpx, cpy);
  13719. break;
  13720. case 'V':
  13721. cpy = p[off++];
  13722. cmd = CMD.L;
  13723. path.addData(cmd, cpx, cpy);
  13724. break;
  13725. case 'C':
  13726. cmd = CMD.C;
  13727. path.addData(
  13728. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13729. );
  13730. cpx = p[off - 2];
  13731. cpy = p[off - 1];
  13732. break;
  13733. case 'c':
  13734. cmd = CMD.C;
  13735. path.addData(
  13736. cmd,
  13737. p[off++] + cpx, p[off++] + cpy,
  13738. p[off++] + cpx, p[off++] + cpy,
  13739. p[off++] + cpx, p[off++] + cpy
  13740. );
  13741. cpx += p[off - 2];
  13742. cpy += p[off - 1];
  13743. break;
  13744. case 'S':
  13745. ctlPtx = cpx;
  13746. ctlPty = cpy;
  13747. var len = path.len();
  13748. var pathData = path.data;
  13749. if (prevCmd === CMD.C) {
  13750. ctlPtx += cpx - pathData[len - 4];
  13751. ctlPty += cpy - pathData[len - 3];
  13752. }
  13753. cmd = CMD.C;
  13754. x1 = p[off++];
  13755. y1 = p[off++];
  13756. cpx = p[off++];
  13757. cpy = p[off++];
  13758. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13759. break;
  13760. case 's':
  13761. ctlPtx = cpx;
  13762. ctlPty = cpy;
  13763. var len = path.len();
  13764. var pathData = path.data;
  13765. if (prevCmd === CMD.C) {
  13766. ctlPtx += cpx - pathData[len - 4];
  13767. ctlPty += cpy - pathData[len - 3];
  13768. }
  13769. cmd = CMD.C;
  13770. x1 = cpx + p[off++];
  13771. y1 = cpy + p[off++];
  13772. cpx += p[off++];
  13773. cpy += p[off++];
  13774. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13775. break;
  13776. case 'Q':
  13777. x1 = p[off++];
  13778. y1 = p[off++];
  13779. cpx = p[off++];
  13780. cpy = p[off++];
  13781. cmd = CMD.Q;
  13782. path.addData(cmd, x1, y1, cpx, cpy);
  13783. break;
  13784. case 'q':
  13785. x1 = p[off++] + cpx;
  13786. y1 = p[off++] + cpy;
  13787. cpx += p[off++];
  13788. cpy += p[off++];
  13789. cmd = CMD.Q;
  13790. path.addData(cmd, x1, y1, cpx, cpy);
  13791. break;
  13792. case 'T':
  13793. ctlPtx = cpx;
  13794. ctlPty = cpy;
  13795. var len = path.len();
  13796. var pathData = path.data;
  13797. if (prevCmd === CMD.Q) {
  13798. ctlPtx += cpx - pathData[len - 4];
  13799. ctlPty += cpy - pathData[len - 3];
  13800. }
  13801. cpx = p[off++];
  13802. cpy = p[off++];
  13803. cmd = CMD.Q;
  13804. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13805. break;
  13806. case 't':
  13807. ctlPtx = cpx;
  13808. ctlPty = cpy;
  13809. var len = path.len();
  13810. var pathData = path.data;
  13811. if (prevCmd === CMD.Q) {
  13812. ctlPtx += cpx - pathData[len - 4];
  13813. ctlPty += cpy - pathData[len - 3];
  13814. }
  13815. cpx += p[off++];
  13816. cpy += p[off++];
  13817. cmd = CMD.Q;
  13818. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13819. break;
  13820. case 'A':
  13821. rx = p[off++];
  13822. ry = p[off++];
  13823. psi = p[off++];
  13824. fa = p[off++];
  13825. fs = p[off++];
  13826. x1 = cpx, y1 = cpy;
  13827. cpx = p[off++];
  13828. cpy = p[off++];
  13829. cmd = CMD.A;
  13830. processArc(
  13831. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13832. );
  13833. break;
  13834. case 'a':
  13835. rx = p[off++];
  13836. ry = p[off++];
  13837. psi = p[off++];
  13838. fa = p[off++];
  13839. fs = p[off++];
  13840. x1 = cpx, y1 = cpy;
  13841. cpx += p[off++];
  13842. cpy += p[off++];
  13843. cmd = CMD.A;
  13844. processArc(
  13845. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13846. );
  13847. break;
  13848. }
  13849. }
  13850. if (cmdStr === 'z' || cmdStr === 'Z') {
  13851. cmd = CMD.Z;
  13852. path.addData(cmd);
  13853. // z may be in the middle of the path.
  13854. cpx = subpathX;
  13855. cpy = subpathY;
  13856. }
  13857. prevCmd = cmd;
  13858. }
  13859. path.toStatic();
  13860. return path;
  13861. }
  13862. // TODO Optimize double memory cost problem
  13863. function createPathOptions(str, opts) {
  13864. var pathProxy = createPathProxyFromString(str);
  13865. opts = opts || {};
  13866. opts.buildPath = function (path) {
  13867. if (path.setData) {
  13868. path.setData(pathProxy.data);
  13869. // Svg and vml renderer don't have context
  13870. var ctx = path.getContext();
  13871. if (ctx) {
  13872. path.rebuildPath(ctx);
  13873. }
  13874. }
  13875. else {
  13876. var ctx = path;
  13877. pathProxy.rebuildPath(ctx);
  13878. }
  13879. };
  13880. opts.applyTransform = function (m) {
  13881. transformPath(pathProxy, m);
  13882. this.dirty(true);
  13883. };
  13884. return opts;
  13885. }
  13886. /**
  13887. * Create a Path object from path string data
  13888. * http://www.w3.org/TR/SVG/paths.html#PathData
  13889. * @param {Object} opts Other options
  13890. */
  13891. function createFromString(str, opts) {
  13892. return new Path(createPathOptions(str, opts));
  13893. }
  13894. /**
  13895. * Create a Path class from path string data
  13896. * @param {string} str
  13897. * @param {Object} opts Other options
  13898. */
  13899. function extendFromString(str, opts) {
  13900. return Path.extend(createPathOptions(str, opts));
  13901. }
  13902. /**
  13903. * Merge multiple paths
  13904. */
  13905. // TODO Apply transform
  13906. // TODO stroke dash
  13907. // TODO Optimize double memory cost problem
  13908. function mergePath$1(pathEls, opts) {
  13909. var pathList = [];
  13910. var len = pathEls.length;
  13911. for (var i = 0; i < len; i++) {
  13912. var pathEl = pathEls[i];
  13913. if (!pathEl.path) {
  13914. pathEl.createPathProxy();
  13915. }
  13916. if (pathEl.__dirtyPath) {
  13917. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13918. }
  13919. pathList.push(pathEl.path);
  13920. }
  13921. var pathBundle = new Path(opts);
  13922. // Need path proxy.
  13923. pathBundle.createPathProxy();
  13924. pathBundle.buildPath = function (path) {
  13925. path.appendPath(pathList);
  13926. // Svg and vml renderer don't have context
  13927. var ctx = path.getContext();
  13928. if (ctx) {
  13929. path.rebuildPath(ctx);
  13930. }
  13931. };
  13932. return pathBundle;
  13933. }
  13934. /**
  13935. * @alias zrender/graphic/Text
  13936. * @extends module:zrender/graphic/Displayable
  13937. * @constructor
  13938. * @param {Object} opts
  13939. */
  13940. var Text = function (opts) { // jshint ignore:line
  13941. Displayable.call(this, opts);
  13942. };
  13943. Text.prototype = {
  13944. constructor: Text,
  13945. type: 'text',
  13946. brush: function (ctx, prevEl) {
  13947. var style = this.style;
  13948. // Optimize, avoid normalize every time.
  13949. this.__dirty && normalizeTextStyle(style, true);
  13950. // Use props with prefix 'text'.
  13951. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13952. style.shadowOffsetX = style.shadowOffsetY = null;
  13953. var text = style.text;
  13954. // Convert to string
  13955. text != null && (text += '');
  13956. // Do not apply style.bind in Text node. Because the real bind job
  13957. // is in textHelper.renderText, and performance of text render should
  13958. // be considered.
  13959. // style.bind(ctx, this, prevEl);
  13960. if (!needDrawText(text, style)) {
  13961. // The current el.style is not applied
  13962. // and should not be used as cache.
  13963. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13964. return;
  13965. }
  13966. this.setTransform(ctx);
  13967. renderText(this, ctx, text, style, null, prevEl);
  13968. this.restoreTransform(ctx);
  13969. },
  13970. getBoundingRect: function () {
  13971. var style = this.style;
  13972. // Optimize, avoid normalize every time.
  13973. this.__dirty && normalizeTextStyle(style, true);
  13974. if (!this._rect) {
  13975. var text = style.text;
  13976. text != null ? (text += '') : (text = '');
  13977. var rect = getBoundingRect(
  13978. style.text + '',
  13979. style.font,
  13980. style.textAlign,
  13981. style.textVerticalAlign,
  13982. style.textPadding,
  13983. style.textLineHeight,
  13984. style.rich
  13985. );
  13986. rect.x += style.x || 0;
  13987. rect.y += style.y || 0;
  13988. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13989. var w = style.textStrokeWidth;
  13990. rect.x -= w / 2;
  13991. rect.y -= w / 2;
  13992. rect.width += w;
  13993. rect.height += w;
  13994. }
  13995. this._rect = rect;
  13996. }
  13997. return this._rect;
  13998. }
  13999. };
  14000. inherits(Text, Displayable);
  14001. /**
  14002. * 圆形
  14003. * @module zrender/shape/Circle
  14004. */
  14005. var Circle = Path.extend({
  14006. type: 'circle',
  14007. shape: {
  14008. cx: 0,
  14009. cy: 0,
  14010. r: 0
  14011. },
  14012. buildPath: function (ctx, shape, inBundle) {
  14013. // Better stroking in ShapeBundle
  14014. // Always do it may have performence issue ( fill may be 2x more cost)
  14015. if (inBundle) {
  14016. ctx.moveTo(shape.cx + shape.r, shape.cy);
  14017. }
  14018. // else {
  14019. // if (ctx.allocate && !ctx.data.length) {
  14020. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  14021. // }
  14022. // }
  14023. // Better stroking in ShapeBundle
  14024. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  14025. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  14026. }
  14027. });
  14028. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  14029. // where exception "unexpected call to method or property access"
  14030. // might be thrown when calling ctx.fill or ctx.stroke after a path
  14031. // whose area size is zero is drawn and ctx.clip() is called and
  14032. // shadowBlur is set. See #4572, #3112, #5777.
  14033. // (e.g.,
  14034. // ctx.moveTo(10, 10);
  14035. // ctx.lineTo(20, 10);
  14036. // ctx.closePath();
  14037. // ctx.clip();
  14038. // ctx.shadowBlur = 10;
  14039. // ...
  14040. // ctx.fill();
  14041. // )
  14042. var shadowTemp = [
  14043. ['shadowBlur', 0],
  14044. ['shadowColor', '#000'],
  14045. ['shadowOffsetX', 0],
  14046. ['shadowOffsetY', 0]
  14047. ];
  14048. var fixClipWithShadow = function (orignalBrush) {
  14049. // version string can be: '11.0'
  14050. return (env$1.browser.ie && env$1.browser.version >= 11)
  14051. ? function () {
  14052. var clipPaths = this.__clipPaths;
  14053. var style = this.style;
  14054. var modified;
  14055. if (clipPaths) {
  14056. for (var i = 0; i < clipPaths.length; i++) {
  14057. var clipPath = clipPaths[i];
  14058. var shape = clipPath && clipPath.shape;
  14059. var type = clipPath && clipPath.type;
  14060. if (shape && (
  14061. (type === 'sector' && shape.startAngle === shape.endAngle)
  14062. || (type === 'rect' && (!shape.width || !shape.height))
  14063. )) {
  14064. for (var j = 0; j < shadowTemp.length; j++) {
  14065. // It is save to put shadowTemp static, because shadowTemp
  14066. // will be all modified each item brush called.
  14067. shadowTemp[j][2] = style[shadowTemp[j][0]];
  14068. style[shadowTemp[j][0]] = shadowTemp[j][1];
  14069. }
  14070. modified = true;
  14071. break;
  14072. }
  14073. }
  14074. }
  14075. orignalBrush.apply(this, arguments);
  14076. if (modified) {
  14077. for (var j = 0; j < shadowTemp.length; j++) {
  14078. style[shadowTemp[j][0]] = shadowTemp[j][2];
  14079. }
  14080. }
  14081. }
  14082. : orignalBrush;
  14083. };
  14084. /**
  14085. * 扇形
  14086. * @module zrender/graphic/shape/Sector
  14087. */
  14088. var Sector = Path.extend({
  14089. type: 'sector',
  14090. shape: {
  14091. cx: 0,
  14092. cy: 0,
  14093. r0: 0,
  14094. r: 0,
  14095. startAngle: 0,
  14096. endAngle: Math.PI * 2,
  14097. clockwise: true
  14098. },
  14099. brush: fixClipWithShadow(Path.prototype.brush),
  14100. buildPath: function (ctx, shape) {
  14101. var x = shape.cx;
  14102. var y = shape.cy;
  14103. var r0 = Math.max(shape.r0 || 0, 0);
  14104. var r = Math.max(shape.r, 0);
  14105. var startAngle = shape.startAngle;
  14106. var endAngle = shape.endAngle;
  14107. var clockwise = shape.clockwise;
  14108. var unitX = Math.cos(startAngle);
  14109. var unitY = Math.sin(startAngle);
  14110. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  14111. ctx.lineTo(unitX * r + x, unitY * r + y);
  14112. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14113. ctx.lineTo(
  14114. Math.cos(endAngle) * r0 + x,
  14115. Math.sin(endAngle) * r0 + y
  14116. );
  14117. if (r0 !== 0) {
  14118. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  14119. }
  14120. ctx.closePath();
  14121. }
  14122. });
  14123. /**
  14124. * 圆环
  14125. * @module zrender/graphic/shape/Ring
  14126. */
  14127. var Ring = Path.extend({
  14128. type: 'ring',
  14129. shape: {
  14130. cx: 0,
  14131. cy: 0,
  14132. r: 0,
  14133. r0: 0
  14134. },
  14135. buildPath: function (ctx, shape) {
  14136. var x = shape.cx;
  14137. var y = shape.cy;
  14138. var PI2 = Math.PI * 2;
  14139. ctx.moveTo(x + shape.r, y);
  14140. ctx.arc(x, y, shape.r, 0, PI2, false);
  14141. ctx.moveTo(x + shape.r0, y);
  14142. ctx.arc(x, y, shape.r0, 0, PI2, true);
  14143. }
  14144. });
  14145. /**
  14146. * Catmull-Rom spline 插值折线
  14147. * @module zrender/shape/util/smoothSpline
  14148. * @author pissang (https://www.github.com/pissang)
  14149. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14150. * errorrik (errorrik@gmail.com)
  14151. */
  14152. /**
  14153. * @inner
  14154. */
  14155. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  14156. var v0 = (p2 - p0) * 0.5;
  14157. var v1 = (p3 - p1) * 0.5;
  14158. return (2 * (p1 - p2) + v0 + v1) * t3
  14159. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  14160. + v0 * t + p1;
  14161. }
  14162. /**
  14163. * @alias module:zrender/shape/util/smoothSpline
  14164. * @param {Array} points 线段顶点数组
  14165. * @param {boolean} isLoop
  14166. * @return {Array}
  14167. */
  14168. var smoothSpline = function (points, isLoop) {
  14169. var len$$1 = points.length;
  14170. var ret = [];
  14171. var distance$$1 = 0;
  14172. for (var i = 1; i < len$$1; i++) {
  14173. distance$$1 += distance(points[i - 1], points[i]);
  14174. }
  14175. var segs = distance$$1 / 2;
  14176. segs = segs < len$$1 ? len$$1 : segs;
  14177. for (var i = 0; i < segs; i++) {
  14178. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  14179. var idx = Math.floor(pos);
  14180. var w = pos - idx;
  14181. var p0;
  14182. var p1 = points[idx % len$$1];
  14183. var p2;
  14184. var p3;
  14185. if (!isLoop) {
  14186. p0 = points[idx === 0 ? idx : idx - 1];
  14187. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  14188. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  14189. }
  14190. else {
  14191. p0 = points[(idx - 1 + len$$1) % len$$1];
  14192. p2 = points[(idx + 1) % len$$1];
  14193. p3 = points[(idx + 2) % len$$1];
  14194. }
  14195. var w2 = w * w;
  14196. var w3 = w * w2;
  14197. ret.push([
  14198. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  14199. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  14200. ]);
  14201. }
  14202. return ret;
  14203. };
  14204. /**
  14205. * 贝塞尔平滑曲线
  14206. * @module zrender/shape/util/smoothBezier
  14207. * @author pissang (https://www.github.com/pissang)
  14208. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14209. * errorrik (errorrik@gmail.com)
  14210. */
  14211. /**
  14212. * 贝塞尔平滑曲线
  14213. * @alias module:zrender/shape/util/smoothBezier
  14214. * @param {Array} points 线段顶点数组
  14215. * @param {number} smooth 平滑等级, 0-1
  14216. * @param {boolean} isLoop
  14217. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  14218. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  14219. * 整个折线的包围盒做一个并集用来约束控制点。
  14220. * @param {Array} 计算出来的控制点数组
  14221. */
  14222. var smoothBezier = function (points, smooth, isLoop, constraint) {
  14223. var cps = [];
  14224. var v = [];
  14225. var v1 = [];
  14226. var v2 = [];
  14227. var prevPoint;
  14228. var nextPoint;
  14229. var min$$1;
  14230. var max$$1;
  14231. if (constraint) {
  14232. min$$1 = [Infinity, Infinity];
  14233. max$$1 = [-Infinity, -Infinity];
  14234. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14235. min(min$$1, min$$1, points[i]);
  14236. max(max$$1, max$$1, points[i]);
  14237. }
  14238. // 与指定的包围盒做并集
  14239. min(min$$1, min$$1, constraint[0]);
  14240. max(max$$1, max$$1, constraint[1]);
  14241. }
  14242. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14243. var point = points[i];
  14244. if (isLoop) {
  14245. prevPoint = points[i ? i - 1 : len$$1 - 1];
  14246. nextPoint = points[(i + 1) % len$$1];
  14247. }
  14248. else {
  14249. if (i === 0 || i === len$$1 - 1) {
  14250. cps.push(clone$1(points[i]));
  14251. continue;
  14252. }
  14253. else {
  14254. prevPoint = points[i - 1];
  14255. nextPoint = points[i + 1];
  14256. }
  14257. }
  14258. sub(v, nextPoint, prevPoint);
  14259. // use degree to scale the handle length
  14260. scale(v, v, smooth);
  14261. var d0 = distance(point, prevPoint);
  14262. var d1 = distance(point, nextPoint);
  14263. var sum = d0 + d1;
  14264. if (sum !== 0) {
  14265. d0 /= sum;
  14266. d1 /= sum;
  14267. }
  14268. scale(v1, v, -d0);
  14269. scale(v2, v, d1);
  14270. var cp0 = add([], point, v1);
  14271. var cp1 = add([], point, v2);
  14272. if (constraint) {
  14273. max(cp0, cp0, min$$1);
  14274. min(cp0, cp0, max$$1);
  14275. max(cp1, cp1, min$$1);
  14276. min(cp1, cp1, max$$1);
  14277. }
  14278. cps.push(cp0);
  14279. cps.push(cp1);
  14280. }
  14281. if (isLoop) {
  14282. cps.push(cps.shift());
  14283. }
  14284. return cps;
  14285. };
  14286. function buildPath$1(ctx, shape, closePath) {
  14287. var points = shape.points;
  14288. var smooth = shape.smooth;
  14289. if (points && points.length >= 2) {
  14290. if (smooth && smooth !== 'spline') {
  14291. var controlPoints = smoothBezier(
  14292. points, smooth, closePath, shape.smoothConstraint
  14293. );
  14294. ctx.moveTo(points[0][0], points[0][1]);
  14295. var len = points.length;
  14296. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  14297. var cp1 = controlPoints[i * 2];
  14298. var cp2 = controlPoints[i * 2 + 1];
  14299. var p = points[(i + 1) % len];
  14300. ctx.bezierCurveTo(
  14301. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  14302. );
  14303. }
  14304. }
  14305. else {
  14306. if (smooth === 'spline') {
  14307. points = smoothSpline(points, closePath);
  14308. }
  14309. ctx.moveTo(points[0][0], points[0][1]);
  14310. for (var i = 1, l = points.length; i < l; i++) {
  14311. ctx.lineTo(points[i][0], points[i][1]);
  14312. }
  14313. }
  14314. closePath && ctx.closePath();
  14315. }
  14316. }
  14317. /**
  14318. * 多边形
  14319. * @module zrender/shape/Polygon
  14320. */
  14321. var Polygon = Path.extend({
  14322. type: 'polygon',
  14323. shape: {
  14324. points: null,
  14325. smooth: false,
  14326. smoothConstraint: null
  14327. },
  14328. buildPath: function (ctx, shape) {
  14329. buildPath$1(ctx, shape, true);
  14330. }
  14331. });
  14332. /**
  14333. * @module zrender/graphic/shape/Polyline
  14334. */
  14335. var Polyline = Path.extend({
  14336. type: 'polyline',
  14337. shape: {
  14338. points: null,
  14339. smooth: false,
  14340. smoothConstraint: null
  14341. },
  14342. style: {
  14343. stroke: '#000',
  14344. fill: null
  14345. },
  14346. buildPath: function (ctx, shape) {
  14347. buildPath$1(ctx, shape, false);
  14348. }
  14349. });
  14350. /**
  14351. * Sub-pixel optimize for canvas rendering, prevent from blur
  14352. * when rendering a thin vertical/horizontal line.
  14353. */
  14354. var round = Math.round;
  14355. /**
  14356. * Sub pixel optimize line for canvas
  14357. *
  14358. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14359. * `outputShape` and `inputShape` can be the same object.
  14360. * `outputShape` object can be used repeatly, because all of
  14361. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  14362. * @param {Object} [inputShape]
  14363. * @param {number} [inputShape.x1]
  14364. * @param {number} [inputShape.y1]
  14365. * @param {number} [inputShape.x2]
  14366. * @param {number} [inputShape.y2]
  14367. * @param {Object} [style]
  14368. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  14369. */
  14370. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  14371. if (!inputShape) {
  14372. return;
  14373. }
  14374. var x1 = inputShape.x1;
  14375. var x2 = inputShape.x2;
  14376. var y1 = inputShape.y1;
  14377. var y2 = inputShape.y2;
  14378. outputShape.x1 = x1;
  14379. outputShape.x2 = x2;
  14380. outputShape.y1 = y1;
  14381. outputShape.y2 = y2;
  14382. var lineWidth = style && style.lineWidth;
  14383. if (!lineWidth) {
  14384. return;
  14385. }
  14386. if (round(x1 * 2) === round(x2 * 2)) {
  14387. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  14388. }
  14389. if (round(y1 * 2) === round(y2 * 2)) {
  14390. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  14391. }
  14392. }
  14393. /**
  14394. * Sub pixel optimize rect for canvas
  14395. *
  14396. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14397. * `outputShape` and `inputShape` can be the same object.
  14398. * `outputShape` object can be used repeatly, because all of
  14399. * the `x`, `y`, `width`, `height` will be assigned in this method.
  14400. * @param {Object} [inputShape]
  14401. * @param {number} [inputShape.x]
  14402. * @param {number} [inputShape.y]
  14403. * @param {number} [inputShape.width]
  14404. * @param {number} [inputShape.height]
  14405. * @param {Object} [style]
  14406. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  14407. */
  14408. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  14409. if (!inputShape) {
  14410. return;
  14411. }
  14412. var originX = inputShape.x;
  14413. var originY = inputShape.y;
  14414. var originWidth = inputShape.width;
  14415. var originHeight = inputShape.height;
  14416. outputShape.x = originX;
  14417. outputShape.y = originY;
  14418. outputShape.width = originWidth;
  14419. outputShape.height = originHeight;
  14420. var lineWidth = style && style.lineWidth;
  14421. if (!lineWidth) {
  14422. return;
  14423. }
  14424. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  14425. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  14426. outputShape.width = Math.max(
  14427. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  14428. originWidth === 0 ? 0 : 1
  14429. );
  14430. outputShape.height = Math.max(
  14431. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  14432. originHeight === 0 ? 0 : 1
  14433. );
  14434. }
  14435. /**
  14436. * Sub pixel optimize for canvas
  14437. *
  14438. * @param {number} position Coordinate, such as x, y
  14439. * @param {number} lineWidth If `null`/`undefined`/`0`, do not optimize.
  14440. * @param {boolean=} positiveOrNegative Default false (negative).
  14441. * @return {number} Optimized position.
  14442. */
  14443. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  14444. if (!lineWidth) {
  14445. return position;
  14446. }
  14447. // Assure that (position + lineWidth / 2) is near integer edge,
  14448. // otherwise line will be fuzzy in canvas.
  14449. var doubledPosition = round(position * 2);
  14450. return (doubledPosition + round(lineWidth)) % 2 === 0
  14451. ? doubledPosition / 2
  14452. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14453. }
  14454. /**
  14455. * 矩形
  14456. * @module zrender/graphic/shape/Rect
  14457. */
  14458. // Avoid create repeatly.
  14459. var subPixelOptimizeOutputShape = {};
  14460. var Rect = Path.extend({
  14461. type: 'rect',
  14462. shape: {
  14463. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  14464. // r缩写为1 相当于 [1, 1, 1, 1]
  14465. // r缩写为[1] 相当于 [1, 1, 1, 1]
  14466. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  14467. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  14468. r: 0,
  14469. x: 0,
  14470. y: 0,
  14471. width: 0,
  14472. height: 0
  14473. },
  14474. buildPath: function (ctx, shape) {
  14475. var x;
  14476. var y;
  14477. var width;
  14478. var height;
  14479. if (this.subPixelOptimize) {
  14480. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  14481. x = subPixelOptimizeOutputShape.x;
  14482. y = subPixelOptimizeOutputShape.y;
  14483. width = subPixelOptimizeOutputShape.width;
  14484. height = subPixelOptimizeOutputShape.height;
  14485. subPixelOptimizeOutputShape.r = shape.r;
  14486. shape = subPixelOptimizeOutputShape;
  14487. }
  14488. else {
  14489. x = shape.x;
  14490. y = shape.y;
  14491. width = shape.width;
  14492. height = shape.height;
  14493. }
  14494. if (!shape.r) {
  14495. ctx.rect(x, y, width, height);
  14496. }
  14497. else {
  14498. buildPath(ctx, shape);
  14499. }
  14500. ctx.closePath();
  14501. return;
  14502. }
  14503. });
  14504. /**
  14505. * 直线
  14506. * @module zrender/graphic/shape/Line
  14507. */
  14508. // Avoid create repeatly.
  14509. var subPixelOptimizeOutputShape$1 = {};
  14510. var Line = Path.extend({
  14511. type: 'line',
  14512. shape: {
  14513. // Start point
  14514. x1: 0,
  14515. y1: 0,
  14516. // End point
  14517. x2: 0,
  14518. y2: 0,
  14519. percent: 1
  14520. },
  14521. style: {
  14522. stroke: '#000',
  14523. fill: null
  14524. },
  14525. buildPath: function (ctx, shape) {
  14526. var x1;
  14527. var y1;
  14528. var x2;
  14529. var y2;
  14530. if (this.subPixelOptimize) {
  14531. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  14532. x1 = subPixelOptimizeOutputShape$1.x1;
  14533. y1 = subPixelOptimizeOutputShape$1.y1;
  14534. x2 = subPixelOptimizeOutputShape$1.x2;
  14535. y2 = subPixelOptimizeOutputShape$1.y2;
  14536. }
  14537. else {
  14538. x1 = shape.x1;
  14539. y1 = shape.y1;
  14540. x2 = shape.x2;
  14541. y2 = shape.y2;
  14542. }
  14543. var percent = shape.percent;
  14544. if (percent === 0) {
  14545. return;
  14546. }
  14547. ctx.moveTo(x1, y1);
  14548. if (percent < 1) {
  14549. x2 = x1 * (1 - percent) + x2 * percent;
  14550. y2 = y1 * (1 - percent) + y2 * percent;
  14551. }
  14552. ctx.lineTo(x2, y2);
  14553. },
  14554. /**
  14555. * Get point at percent
  14556. * @param {number} percent
  14557. * @return {Array.<number>}
  14558. */
  14559. pointAt: function (p) {
  14560. var shape = this.shape;
  14561. return [
  14562. shape.x1 * (1 - p) + shape.x2 * p,
  14563. shape.y1 * (1 - p) + shape.y2 * p
  14564. ];
  14565. }
  14566. });
  14567. /**
  14568. * 贝塞尔曲线
  14569. * @module zrender/shape/BezierCurve
  14570. */
  14571. var out = [];
  14572. function someVectorAt(shape, t, isTangent) {
  14573. var cpx2 = shape.cpx2;
  14574. var cpy2 = shape.cpy2;
  14575. if (cpx2 === null || cpy2 === null) {
  14576. return [
  14577. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14578. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14579. ];
  14580. }
  14581. else {
  14582. return [
  14583. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14584. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14585. ];
  14586. }
  14587. }
  14588. var BezierCurve = Path.extend({
  14589. type: 'bezier-curve',
  14590. shape: {
  14591. x1: 0,
  14592. y1: 0,
  14593. x2: 0,
  14594. y2: 0,
  14595. cpx1: 0,
  14596. cpy1: 0,
  14597. // cpx2: 0,
  14598. // cpy2: 0
  14599. // Curve show percent, for animating
  14600. percent: 1
  14601. },
  14602. style: {
  14603. stroke: '#000',
  14604. fill: null
  14605. },
  14606. buildPath: function (ctx, shape) {
  14607. var x1 = shape.x1;
  14608. var y1 = shape.y1;
  14609. var x2 = shape.x2;
  14610. var y2 = shape.y2;
  14611. var cpx1 = shape.cpx1;
  14612. var cpy1 = shape.cpy1;
  14613. var cpx2 = shape.cpx2;
  14614. var cpy2 = shape.cpy2;
  14615. var percent = shape.percent;
  14616. if (percent === 0) {
  14617. return;
  14618. }
  14619. ctx.moveTo(x1, y1);
  14620. if (cpx2 == null || cpy2 == null) {
  14621. if (percent < 1) {
  14622. quadraticSubdivide(
  14623. x1, cpx1, x2, percent, out
  14624. );
  14625. cpx1 = out[1];
  14626. x2 = out[2];
  14627. quadraticSubdivide(
  14628. y1, cpy1, y2, percent, out
  14629. );
  14630. cpy1 = out[1];
  14631. y2 = out[2];
  14632. }
  14633. ctx.quadraticCurveTo(
  14634. cpx1, cpy1,
  14635. x2, y2
  14636. );
  14637. }
  14638. else {
  14639. if (percent < 1) {
  14640. cubicSubdivide(
  14641. x1, cpx1, cpx2, x2, percent, out
  14642. );
  14643. cpx1 = out[1];
  14644. cpx2 = out[2];
  14645. x2 = out[3];
  14646. cubicSubdivide(
  14647. y1, cpy1, cpy2, y2, percent, out
  14648. );
  14649. cpy1 = out[1];
  14650. cpy2 = out[2];
  14651. y2 = out[3];
  14652. }
  14653. ctx.bezierCurveTo(
  14654. cpx1, cpy1,
  14655. cpx2, cpy2,
  14656. x2, y2
  14657. );
  14658. }
  14659. },
  14660. /**
  14661. * Get point at percent
  14662. * @param {number} t
  14663. * @return {Array.<number>}
  14664. */
  14665. pointAt: function (t) {
  14666. return someVectorAt(this.shape, t, false);
  14667. },
  14668. /**
  14669. * Get tangent at percent
  14670. * @param {number} t
  14671. * @return {Array.<number>}
  14672. */
  14673. tangentAt: function (t) {
  14674. var p = someVectorAt(this.shape, t, true);
  14675. return normalize(p, p);
  14676. }
  14677. });
  14678. /**
  14679. * 圆弧
  14680. * @module zrender/graphic/shape/Arc
  14681. */
  14682. var Arc = Path.extend({
  14683. type: 'arc',
  14684. shape: {
  14685. cx: 0,
  14686. cy: 0,
  14687. r: 0,
  14688. startAngle: 0,
  14689. endAngle: Math.PI * 2,
  14690. clockwise: true
  14691. },
  14692. style: {
  14693. stroke: '#000',
  14694. fill: null
  14695. },
  14696. buildPath: function (ctx, shape) {
  14697. var x = shape.cx;
  14698. var y = shape.cy;
  14699. var r = Math.max(shape.r, 0);
  14700. var startAngle = shape.startAngle;
  14701. var endAngle = shape.endAngle;
  14702. var clockwise = shape.clockwise;
  14703. var unitX = Math.cos(startAngle);
  14704. var unitY = Math.sin(startAngle);
  14705. ctx.moveTo(unitX * r + x, unitY * r + y);
  14706. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14707. }
  14708. });
  14709. // CompoundPath to improve performance
  14710. var CompoundPath = Path.extend({
  14711. type: 'compound',
  14712. shape: {
  14713. paths: null
  14714. },
  14715. _updatePathDirty: function () {
  14716. var dirtyPath = this.__dirtyPath;
  14717. var paths = this.shape.paths;
  14718. for (var i = 0; i < paths.length; i++) {
  14719. // Mark as dirty if any subpath is dirty
  14720. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14721. }
  14722. this.__dirtyPath = dirtyPath;
  14723. this.__dirty = this.__dirty || dirtyPath;
  14724. },
  14725. beforeBrush: function () {
  14726. this._updatePathDirty();
  14727. var paths = this.shape.paths || [];
  14728. var scale = this.getGlobalScale();
  14729. // Update path scale
  14730. for (var i = 0; i < paths.length; i++) {
  14731. if (!paths[i].path) {
  14732. paths[i].createPathProxy();
  14733. }
  14734. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14735. }
  14736. },
  14737. buildPath: function (ctx, shape) {
  14738. var paths = shape.paths || [];
  14739. for (var i = 0; i < paths.length; i++) {
  14740. paths[i].buildPath(ctx, paths[i].shape, true);
  14741. }
  14742. },
  14743. afterBrush: function () {
  14744. var paths = this.shape.paths || [];
  14745. for (var i = 0; i < paths.length; i++) {
  14746. paths[i].__dirtyPath = false;
  14747. }
  14748. },
  14749. getBoundingRect: function () {
  14750. this._updatePathDirty();
  14751. return Path.prototype.getBoundingRect.call(this);
  14752. }
  14753. });
  14754. /**
  14755. * @param {Array.<Object>} colorStops
  14756. */
  14757. var Gradient = function (colorStops) {
  14758. this.colorStops = colorStops || [];
  14759. };
  14760. Gradient.prototype = {
  14761. constructor: Gradient,
  14762. addColorStop: function (offset, color) {
  14763. this.colorStops.push({
  14764. offset: offset,
  14765. color: color
  14766. });
  14767. }
  14768. };
  14769. /**
  14770. * x, y, x2, y2 are all percent from 0 to 1
  14771. * @param {number} [x=0]
  14772. * @param {number} [y=0]
  14773. * @param {number} [x2=1]
  14774. * @param {number} [y2=0]
  14775. * @param {Array.<Object>} colorStops
  14776. * @param {boolean} [globalCoord=false]
  14777. */
  14778. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14779. // Should do nothing more in this constructor. Because gradient can be
  14780. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14781. // this constructor will not be called.
  14782. this.x = x == null ? 0 : x;
  14783. this.y = y == null ? 0 : y;
  14784. this.x2 = x2 == null ? 1 : x2;
  14785. this.y2 = y2 == null ? 0 : y2;
  14786. // Can be cloned
  14787. this.type = 'linear';
  14788. // If use global coord
  14789. this.global = globalCoord || false;
  14790. Gradient.call(this, colorStops);
  14791. };
  14792. LinearGradient.prototype = {
  14793. constructor: LinearGradient
  14794. };
  14795. inherits(LinearGradient, Gradient);
  14796. /**
  14797. * x, y, r are all percent from 0 to 1
  14798. * @param {number} [x=0.5]
  14799. * @param {number} [y=0.5]
  14800. * @param {number} [r=0.5]
  14801. * @param {Array.<Object>} [colorStops]
  14802. * @param {boolean} [globalCoord=false]
  14803. */
  14804. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14805. // Should do nothing more in this constructor. Because gradient can be
  14806. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14807. // this constructor will not be called.
  14808. this.x = x == null ? 0.5 : x;
  14809. this.y = y == null ? 0.5 : y;
  14810. this.r = r == null ? 0.5 : r;
  14811. // Can be cloned
  14812. this.type = 'radial';
  14813. // If use global coord
  14814. this.global = globalCoord || false;
  14815. Gradient.call(this, colorStops);
  14816. };
  14817. RadialGradient.prototype = {
  14818. constructor: RadialGradient
  14819. };
  14820. inherits(RadialGradient, Gradient);
  14821. /**
  14822. * Displayable for incremental rendering. It will be rendered in a separate layer
  14823. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14824. * addDisplayables will render the added displayables incremetally.
  14825. *
  14826. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14827. */
  14828. // TODO Style override ?
  14829. function IncrementalDisplayble(opts) {
  14830. Displayable.call(this, opts);
  14831. this._displayables = [];
  14832. this._temporaryDisplayables = [];
  14833. this._cursor = 0;
  14834. this.notClear = true;
  14835. }
  14836. IncrementalDisplayble.prototype.incremental = true;
  14837. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14838. this._displayables = [];
  14839. this._temporaryDisplayables = [];
  14840. this._cursor = 0;
  14841. this.dirty();
  14842. this.notClear = false;
  14843. };
  14844. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14845. if (notPersistent) {
  14846. this._temporaryDisplayables.push(displayable);
  14847. }
  14848. else {
  14849. this._displayables.push(displayable);
  14850. }
  14851. this.dirty();
  14852. };
  14853. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14854. notPersistent = notPersistent || false;
  14855. for (var i = 0; i < displayables.length; i++) {
  14856. this.addDisplayable(displayables[i], notPersistent);
  14857. }
  14858. };
  14859. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14860. for (var i = this._cursor; i < this._displayables.length; i++) {
  14861. cb && cb(this._displayables[i]);
  14862. }
  14863. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14864. cb && cb(this._temporaryDisplayables[i]);
  14865. }
  14866. };
  14867. IncrementalDisplayble.prototype.update = function () {
  14868. this.updateTransform();
  14869. for (var i = this._cursor; i < this._displayables.length; i++) {
  14870. var displayable = this._displayables[i];
  14871. // PENDING
  14872. displayable.parent = this;
  14873. displayable.update();
  14874. displayable.parent = null;
  14875. }
  14876. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14877. var displayable = this._temporaryDisplayables[i];
  14878. // PENDING
  14879. displayable.parent = this;
  14880. displayable.update();
  14881. displayable.parent = null;
  14882. }
  14883. };
  14884. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14885. // Render persistant displayables.
  14886. for (var i = this._cursor; i < this._displayables.length; i++) {
  14887. var displayable = this._displayables[i];
  14888. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14889. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14890. displayable.afterBrush && displayable.afterBrush(ctx);
  14891. }
  14892. this._cursor = i;
  14893. // Render temporary displayables.
  14894. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14895. var displayable = this._temporaryDisplayables[i];
  14896. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14897. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14898. displayable.afterBrush && displayable.afterBrush(ctx);
  14899. }
  14900. this._temporaryDisplayables = [];
  14901. this.notClear = true;
  14902. };
  14903. var m = [];
  14904. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14905. if (!this._rect) {
  14906. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14907. for (var i = 0; i < this._displayables.length; i++) {
  14908. var displayable = this._displayables[i];
  14909. var childRect = displayable.getBoundingRect().clone();
  14910. if (displayable.needLocalTransform()) {
  14911. childRect.applyTransform(displayable.getLocalTransform(m));
  14912. }
  14913. rect.union(childRect);
  14914. }
  14915. this._rect = rect;
  14916. }
  14917. return this._rect;
  14918. };
  14919. IncrementalDisplayble.prototype.contain = function (x, y) {
  14920. var localPos = this.transformCoordToLocal(x, y);
  14921. var rect = this.getBoundingRect();
  14922. if (rect.contain(localPos[0], localPos[1])) {
  14923. for (var i = 0; i < this._displayables.length; i++) {
  14924. var displayable = this._displayables[i];
  14925. if (displayable.contain(x, y)) {
  14926. return true;
  14927. }
  14928. }
  14929. }
  14930. return false;
  14931. };
  14932. inherits(IncrementalDisplayble, Displayable);
  14933. /*
  14934. * Licensed to the Apache Software Foundation (ASF) under one
  14935. * or more contributor license agreements. See the NOTICE file
  14936. * distributed with this work for additional information
  14937. * regarding copyright ownership. The ASF licenses this file
  14938. * to you under the Apache License, Version 2.0 (the
  14939. * "License"); you may not use this file except in compliance
  14940. * with the License. You may obtain a copy of the License at
  14941. *
  14942. * http://www.apache.org/licenses/LICENSE-2.0
  14943. *
  14944. * Unless required by applicable law or agreed to in writing,
  14945. * software distributed under the License is distributed on an
  14946. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14947. * KIND, either express or implied. See the License for the
  14948. * specific language governing permissions and limitations
  14949. * under the License.
  14950. */
  14951. var mathMax$1 = Math.max;
  14952. var mathMin$1 = Math.min;
  14953. var EMPTY_OBJ = {};
  14954. var Z2_EMPHASIS_LIFT = 1;
  14955. // key: label model property nane, value: style property name.
  14956. var CACHED_LABEL_STYLE_PROPERTIES = {
  14957. color: 'textFill',
  14958. textBorderColor: 'textStroke',
  14959. textBorderWidth: 'textStrokeWidth'
  14960. };
  14961. var EMPHASIS = 'emphasis';
  14962. var NORMAL = 'normal';
  14963. // Reserve 0 as default.
  14964. var _highlightNextDigit = 1;
  14965. var _highlightKeyMap = {};
  14966. var _customShapeMap = {};
  14967. /**
  14968. * Extend shape with parameters
  14969. */
  14970. function extendShape(opts) {
  14971. return Path.extend(opts);
  14972. }
  14973. /**
  14974. * Extend path
  14975. */
  14976. function extendPath(pathData, opts) {
  14977. return extendFromString(pathData, opts);
  14978. }
  14979. /**
  14980. * Register a user defined shape.
  14981. * The shape class can be fetched by `getShapeClass`
  14982. * This method will overwrite the registered shapes, including
  14983. * the registered built-in shapes, if using the same `name`.
  14984. * The shape can be used in `custom series` and
  14985. * `graphic component` by declaring `{type: name}`.
  14986. *
  14987. * @param {string} name
  14988. * @param {Object} ShapeClass Can be generated by `extendShape`.
  14989. */
  14990. function registerShape(name, ShapeClass) {
  14991. _customShapeMap[name] = ShapeClass;
  14992. }
  14993. /**
  14994. * Find shape class registered by `registerShape`. Usually used in
  14995. * fetching user defined shape.
  14996. *
  14997. * [Caution]:
  14998. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14999. * to use user registered shapes.
  15000. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  15001. * `registerShape` by default. That enables users to get both built-in
  15002. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  15003. * the built-in shapes by using names like 'circle', 'rect' via calling
  15004. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  15005. * in case that it is overwritten by users, except that some features, like
  15006. * `custom series`, `graphic component`, do it deliberately.
  15007. *
  15008. * (2) In the features like `custom series`, `graphic component`, the user input
  15009. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  15010. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  15011. * are reserved names, that is, if some user register a shape named `'image'`,
  15012. * the shape will not be used. If we intending to add some more reserved names
  15013. * in feature, that might bring break changes (disable some existing user shape
  15014. * names). But that case probably rearly happen. So we dont make more mechanism
  15015. * to resolve this issue here.
  15016. *
  15017. * @param {string} name
  15018. * @return {Object} The shape class. If not found, return nothing.
  15019. */
  15020. function getShapeClass(name) {
  15021. if (_customShapeMap.hasOwnProperty(name)) {
  15022. return _customShapeMap[name];
  15023. }
  15024. }
  15025. /**
  15026. * Create a path element from path data string
  15027. * @param {string} pathData
  15028. * @param {Object} opts
  15029. * @param {module:zrender/core/BoundingRect} rect
  15030. * @param {string} [layout=cover] 'center' or 'cover'
  15031. */
  15032. function makePath(pathData, opts, rect, layout) {
  15033. var path = createFromString(pathData, opts);
  15034. if (rect) {
  15035. if (layout === 'center') {
  15036. rect = centerGraphic(rect, path.getBoundingRect());
  15037. }
  15038. resizePath(path, rect);
  15039. }
  15040. return path;
  15041. }
  15042. /**
  15043. * Create a image element from image url
  15044. * @param {string} imageUrl image url
  15045. * @param {Object} opts options
  15046. * @param {module:zrender/core/BoundingRect} rect constrain rect
  15047. * @param {string} [layout=cover] 'center' or 'cover'
  15048. */
  15049. function makeImage(imageUrl, rect, layout) {
  15050. var path = new ZImage({
  15051. style: {
  15052. image: imageUrl,
  15053. x: rect.x,
  15054. y: rect.y,
  15055. width: rect.width,
  15056. height: rect.height
  15057. },
  15058. onload: function (img) {
  15059. if (layout === 'center') {
  15060. var boundingRect = {
  15061. width: img.width,
  15062. height: img.height
  15063. };
  15064. path.setStyle(centerGraphic(rect, boundingRect));
  15065. }
  15066. }
  15067. });
  15068. return path;
  15069. }
  15070. /**
  15071. * Get position of centered element in bounding box.
  15072. *
  15073. * @param {Object} rect element local bounding box
  15074. * @param {Object} boundingRect constraint bounding box
  15075. * @return {Object} element position containing x, y, width, and height
  15076. */
  15077. function centerGraphic(rect, boundingRect) {
  15078. // Set rect to center, keep width / height ratio.
  15079. var aspect = boundingRect.width / boundingRect.height;
  15080. var width = rect.height * aspect;
  15081. var height;
  15082. if (width <= rect.width) {
  15083. height = rect.height;
  15084. }
  15085. else {
  15086. width = rect.width;
  15087. height = width / aspect;
  15088. }
  15089. var cx = rect.x + rect.width / 2;
  15090. var cy = rect.y + rect.height / 2;
  15091. return {
  15092. x: cx - width / 2,
  15093. y: cy - height / 2,
  15094. width: width,
  15095. height: height
  15096. };
  15097. }
  15098. var mergePath = mergePath$1;
  15099. /**
  15100. * Resize a path to fit the rect
  15101. * @param {module:zrender/graphic/Path} path
  15102. * @param {Object} rect
  15103. */
  15104. function resizePath(path, rect) {
  15105. if (!path.applyTransform) {
  15106. return;
  15107. }
  15108. var pathRect = path.getBoundingRect();
  15109. var m = pathRect.calculateTransform(rect);
  15110. path.applyTransform(m);
  15111. }
  15112. /**
  15113. * Sub pixel optimize line for canvas
  15114. *
  15115. * @param {Object} param
  15116. * @param {Object} [param.shape]
  15117. * @param {number} [param.shape.x1]
  15118. * @param {number} [param.shape.y1]
  15119. * @param {number} [param.shape.x2]
  15120. * @param {number} [param.shape.y2]
  15121. * @param {Object} [param.style]
  15122. * @param {number} [param.style.lineWidth]
  15123. * @return {Object} Modified param
  15124. */
  15125. function subPixelOptimizeLine(param) {
  15126. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  15127. return param;
  15128. }
  15129. /**
  15130. * Sub pixel optimize rect for canvas
  15131. *
  15132. * @param {Object} param
  15133. * @param {Object} [param.shape]
  15134. * @param {number} [param.shape.x]
  15135. * @param {number} [param.shape.y]
  15136. * @param {number} [param.shape.width]
  15137. * @param {number} [param.shape.height]
  15138. * @param {Object} [param.style]
  15139. * @param {number} [param.style.lineWidth]
  15140. * @return {Object} Modified param
  15141. */
  15142. function subPixelOptimizeRect(param) {
  15143. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  15144. return param;
  15145. }
  15146. /**
  15147. * Sub pixel optimize for canvas
  15148. *
  15149. * @param {number} position Coordinate, such as x, y
  15150. * @param {number} lineWidth Should be nonnegative integer.
  15151. * @param {boolean=} positiveOrNegative Default false (negative).
  15152. * @return {number} Optimized position.
  15153. */
  15154. var subPixelOptimize = subPixelOptimize$1;
  15155. function hasFillOrStroke(fillOrStroke) {
  15156. return fillOrStroke != null && fillOrStroke !== 'none';
  15157. }
  15158. // Most lifted color are duplicated.
  15159. var liftedColorMap = createHashMap();
  15160. var liftedColorCount = 0;
  15161. function liftColor(color) {
  15162. if (typeof color !== 'string') {
  15163. return color;
  15164. }
  15165. var liftedColor = liftedColorMap.get(color);
  15166. if (!liftedColor) {
  15167. liftedColor = lift(color, -0.1);
  15168. if (liftedColorCount < 10000) {
  15169. liftedColorMap.set(color, liftedColor);
  15170. liftedColorCount++;
  15171. }
  15172. }
  15173. return liftedColor;
  15174. }
  15175. function cacheElementStl(el) {
  15176. if (!el.__hoverStlDirty) {
  15177. return;
  15178. }
  15179. el.__hoverStlDirty = false;
  15180. var hoverStyle = el.__hoverStl;
  15181. if (!hoverStyle) {
  15182. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  15183. return;
  15184. }
  15185. var normalStyle = el.__cachedNormalStl = {};
  15186. el.__cachedNormalZ2 = el.z2;
  15187. var elStyle = el.style;
  15188. for (var name in hoverStyle) {
  15189. // See comment in `singleEnterEmphasis`.
  15190. if (hoverStyle[name] != null) {
  15191. normalStyle[name] = elStyle[name];
  15192. }
  15193. }
  15194. // Always cache fill and stroke to normalStyle for lifting color.
  15195. normalStyle.fill = elStyle.fill;
  15196. normalStyle.stroke = elStyle.stroke;
  15197. }
  15198. function singleEnterEmphasis(el) {
  15199. var hoverStl = el.__hoverStl;
  15200. if (!hoverStl || el.__highlighted) {
  15201. return;
  15202. }
  15203. var zr = el.__zr;
  15204. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  15205. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  15206. if (el.isGroup || (!zr && el.useHoverLayer)) {
  15207. return;
  15208. }
  15209. var elTarget = el;
  15210. var targetStyle = el.style;
  15211. if (useHoverLayer) {
  15212. elTarget = zr.addHover(el);
  15213. targetStyle = elTarget.style;
  15214. }
  15215. rollbackDefaultTextStyle(targetStyle);
  15216. if (!useHoverLayer) {
  15217. cacheElementStl(elTarget);
  15218. }
  15219. // styles can be:
  15220. // {
  15221. // label: {
  15222. // show: false,
  15223. // position: 'outside',
  15224. // fontSize: 18
  15225. // },
  15226. // emphasis: {
  15227. // label: {
  15228. // show: true
  15229. // }
  15230. // }
  15231. // },
  15232. // where properties of `emphasis` may not appear in `normal`. We previously use
  15233. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  15234. // But consider rich text and setOption in merge mode, it is impossible to cover
  15235. // all properties in merge. So we use merge mode when setting style here.
  15236. // But we choose the merge strategy that only properties that is not `null/undefined`.
  15237. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  15238. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  15239. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  15240. // style any more in `emphasis`. Users can both set properties directly on normal and
  15241. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  15242. targetStyle.extendFrom(hoverStl);
  15243. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  15244. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  15245. applyDefaultTextStyle(targetStyle);
  15246. if (!useHoverLayer) {
  15247. el.dirty(false);
  15248. el.z2 += Z2_EMPHASIS_LIFT;
  15249. }
  15250. }
  15251. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  15252. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  15253. targetStyle[prop] = liftColor(targetStyle[prop]);
  15254. }
  15255. }
  15256. function singleEnterNormal(el) {
  15257. var highlighted = el.__highlighted;
  15258. if (!highlighted) {
  15259. return;
  15260. }
  15261. el.__highlighted = false;
  15262. if (el.isGroup) {
  15263. return;
  15264. }
  15265. if (highlighted === 'layer') {
  15266. el.__zr && el.__zr.removeHover(el);
  15267. }
  15268. else {
  15269. var style = el.style;
  15270. var normalStl = el.__cachedNormalStl;
  15271. if (normalStl) {
  15272. rollbackDefaultTextStyle(style);
  15273. el.setStyle(normalStl);
  15274. applyDefaultTextStyle(style);
  15275. }
  15276. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  15277. // when `el` is on emphasis state. So here by comparing with 1, we try
  15278. // hard to make the bug case rare.
  15279. var normalZ2 = el.__cachedNormalZ2;
  15280. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  15281. el.z2 = normalZ2;
  15282. }
  15283. }
  15284. }
  15285. function traverseUpdate(el, updater, commonParam) {
  15286. // If root is group, also enter updater for `highDownOnUpdate`.
  15287. var fromState = NORMAL;
  15288. var toState = NORMAL;
  15289. var trigger;
  15290. // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  15291. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  15292. updater(el, commonParam);
  15293. el.__highlighted && (toState = EMPHASIS, trigger = true);
  15294. el.isGroup && el.traverse(function (child) {
  15295. !child.isGroup && updater(child, commonParam);
  15296. });
  15297. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  15298. }
  15299. /**
  15300. * Set hover style (namely "emphasis style") of element, based on the current
  15301. * style of the given `el`.
  15302. * This method should be called after all of the normal styles have been adopted
  15303. * to the `el`. See the reason on `setHoverStyle`.
  15304. *
  15305. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  15306. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  15307. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  15308. * Often used when item group has a label element and it's hoverStyle is different.
  15309. * @param {Object|boolean} [hoverStl] The specified hover style.
  15310. * If set as `false`, disable the hover style.
  15311. * Similarly, The `el.hoverStyle` can alse be set
  15312. * as `false` to disable the hover style.
  15313. * Otherwise, use the default hover style if not provided.
  15314. */
  15315. function setElementHoverStyle(el, hoverStl) {
  15316. // For performance consideration, it might be better to make the "hover style" only the
  15317. // difference properties from the "normal style", but not a entire copy of all styles.
  15318. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  15319. el.__hoverStlDirty = true;
  15320. // FIXME
  15321. // It is not completely right to save "normal"/"emphasis" flag on elements.
  15322. // It probably should be saved on `data` of series. Consider the cases:
  15323. // (1) A highlighted elements are moved out of the view port and re-enter
  15324. // again by dataZoom.
  15325. // (2) call `setOption` and replace elements totally when they are highlighted.
  15326. if (el.__highlighted) {
  15327. // Consider the case:
  15328. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  15329. // should be adapted to the `el`. Notice here new "normal styles" should have
  15330. // been set outside and the cached "normal style" is out of date.
  15331. el.__cachedNormalStl = null;
  15332. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  15333. // of this method. In most cases, `z2` is not set and hover style should be able
  15334. // to rollback. Of course, that would bring bug, but only in a rare case, see
  15335. // `doSingleLeaveHover` for details.
  15336. singleEnterNormal(el);
  15337. singleEnterEmphasis(el);
  15338. }
  15339. }
  15340. function onElementMouseOver(e) {
  15341. !shouldSilent(this, e)
  15342. // "emphasis" event highlight has higher priority than mouse highlight.
  15343. && !this.__highByOuter
  15344. && traverseUpdate(this, singleEnterEmphasis);
  15345. }
  15346. function onElementMouseOut(e) {
  15347. !shouldSilent(this, e)
  15348. // "emphasis" event highlight has higher priority than mouse highlight.
  15349. && !this.__highByOuter
  15350. && traverseUpdate(this, singleEnterNormal);
  15351. }
  15352. function onElementEmphasisEvent(highlightDigit) {
  15353. this.__highByOuter |= 1 << (highlightDigit || 0);
  15354. traverseUpdate(this, singleEnterEmphasis);
  15355. }
  15356. function onElementNormalEvent(highlightDigit) {
  15357. !(this.__highByOuter &= ~(1 << (highlightDigit || 0)))
  15358. && traverseUpdate(this, singleEnterNormal);
  15359. }
  15360. function shouldSilent(el, e) {
  15361. return el.__highDownSilentOnTouch && e.zrByTouch;
  15362. }
  15363. /**
  15364. * Set hover style (namely "emphasis style") of element,
  15365. * based on the current style of the given `el`.
  15366. *
  15367. * (1)
  15368. * **CONSTRAINTS** for this method:
  15369. * <A> This method MUST be called after all of the normal styles having been adopted
  15370. * to the `el`.
  15371. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  15372. * "normal style" having been set to the el.
  15373. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  15374. * a default hover style).
  15375. *
  15376. * The reason: this method treat the current style of the `el` as the "normal style"
  15377. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  15378. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  15379. * logic, where the el should shift from the original emphasis style to the new
  15380. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  15381. *
  15382. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  15383. * not found a better solution yet to fit the backward compatibility, performance and
  15384. * the current programming style.
  15385. *
  15386. * (2)
  15387. * Call the method for a "root" element once. Do not call it for each descendants.
  15388. * If the descendants elemenets of a group has itself hover style different from the
  15389. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  15390. * not call this method for them.
  15391. *
  15392. * (3) These input parameters can be set directly on `el`:
  15393. *
  15394. * @param {module:zrender/Element} el
  15395. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  15396. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  15397. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  15398. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  15399. */
  15400. function setHoverStyle(el, hoverStyle) {
  15401. setAsHighDownDispatcher(el, true);
  15402. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  15403. }
  15404. /**
  15405. * @param {module:zrender/Element} el
  15406. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  15407. * Since `setHoverStyle` has the constraint that it must be called after
  15408. * all of the normal style updated, `highDownOnUpdate` is not needed to
  15409. * trigger if both `fromState` and `toState` is 'normal', and needed to
  15410. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  15411. * to sync outside style settings to "emphasis" state.
  15412. * @this {string} This dispatcher `el`.
  15413. * @param {string} fromState Can be "normal" or "emphasis".
  15414. * `fromState` might equal to `toState`,
  15415. * for example, when this method is called when `el` is
  15416. * on "emphasis" state.
  15417. * @param {string} toState Can be "normal" or "emphasis".
  15418. *
  15419. * FIXME
  15420. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  15421. * Because it is not a complete solution. The update
  15422. * listener should not have been mount in element,
  15423. * and the normal/emphasis state should not have
  15424. * mantained on elements.
  15425. *
  15426. * @param {boolean} [el.highDownSilentOnTouch=false]
  15427. * In touch device, mouseover event will be trigger on touchstart event
  15428. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  15429. * conveniently use hoverStyle when tap on touch screen without additional
  15430. * code for compatibility.
  15431. * But if the chart/component has select feature, which usually also use
  15432. * hoverStyle, there might be conflict between 'select-highlight' and
  15433. * 'hover-highlight' especially when roam is enabled (see geo for example).
  15434. * In this case, `highDownSilentOnTouch` should be used to disable
  15435. * hover-highlight on touch device.
  15436. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  15437. */
  15438. function setAsHighDownDispatcher(el, asDispatcher) {
  15439. var disable = asDispatcher === false;
  15440. // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  15441. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  15442. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  15443. el.__highDownOnUpdate = el.highDownOnUpdate;
  15444. // Simple optimize, since this method might be
  15445. // called for each elements of a group in some cases.
  15446. if (!disable || el.__highDownDispatcher) {
  15447. var method = disable ? 'off' : 'on';
  15448. // Duplicated function will be auto-ignored, see Eventful.js.
  15449. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  15450. // Emphasis, normal can be triggered manually by API or other components like hover link.
  15451. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  15452. // Also keep previous record.
  15453. el.__highByOuter = el.__highByOuter || 0;
  15454. el.__highDownDispatcher = !disable;
  15455. }
  15456. }
  15457. /**
  15458. * @param {module:zrender/src/Element} el
  15459. * @return {boolean}
  15460. */
  15461. function isHighDownDispatcher(el) {
  15462. return !!(el && el.__highDownDispatcher);
  15463. }
  15464. /**
  15465. * Support hightlight/downplay record on each elements.
  15466. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  15467. * user triggerred hightlight/downplay should not conflict.
  15468. * Only all of the highlightDigit cleared, return to normal.
  15469. * @param {string} highlightKey
  15470. * @return {number} highlightDigit
  15471. */
  15472. function getHighlightDigit(highlightKey) {
  15473. var highlightDigit = _highlightKeyMap[highlightKey];
  15474. if (highlightDigit == null && _highlightNextDigit <= 32) {
  15475. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  15476. }
  15477. return highlightDigit;
  15478. }
  15479. /**
  15480. * See more info in `setTextStyleCommon`.
  15481. * @param {Object|module:zrender/graphic/Style} normalStyle
  15482. * @param {Object} emphasisStyle
  15483. * @param {module:echarts/model/Model} normalModel
  15484. * @param {module:echarts/model/Model} emphasisModel
  15485. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  15486. * @param {string|Function} [opt.defaultText]
  15487. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  15488. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15489. * @param {number} [opt.labelDataIndex] Fetch text by
  15490. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15491. * @param {number} [opt.labelDimIndex] Fetch text by
  15492. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15493. * @param {string} [opt.labelProp] Fetch text by
  15494. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15495. * @param {Object} [normalSpecified]
  15496. * @param {Object} [emphasisSpecified]
  15497. */
  15498. function setLabelStyle(
  15499. normalStyle, emphasisStyle,
  15500. normalModel, emphasisModel,
  15501. opt,
  15502. normalSpecified, emphasisSpecified
  15503. ) {
  15504. opt = opt || EMPTY_OBJ;
  15505. var labelFetcher = opt.labelFetcher;
  15506. var labelDataIndex = opt.labelDataIndex;
  15507. var labelDimIndex = opt.labelDimIndex;
  15508. var labelProp = opt.labelProp;
  15509. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  15510. // is not supported util someone requests.
  15511. var showNormal = normalModel.getShallow('show');
  15512. var showEmphasis = emphasisModel.getShallow('show');
  15513. // Consider performance, only fetch label when necessary.
  15514. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  15515. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  15516. var baseText;
  15517. if (showNormal || showEmphasis) {
  15518. if (labelFetcher) {
  15519. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, labelProp);
  15520. }
  15521. if (baseText == null) {
  15522. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  15523. }
  15524. }
  15525. var normalStyleText = showNormal ? baseText : null;
  15526. var emphasisStyleText = showEmphasis
  15527. ? retrieve2(
  15528. labelFetcher
  15529. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex, labelProp)
  15530. : null,
  15531. baseText
  15532. )
  15533. : null;
  15534. // Optimize: If style.text is null, text will not be drawn.
  15535. if (normalStyleText != null || emphasisStyleText != null) {
  15536. // Always set `textStyle` even if `normalStyle.text` is null, because default
  15537. // values have to be set on `normalStyle`.
  15538. // If we set default values on `emphasisStyle`, consider case:
  15539. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  15540. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  15541. // Then the 'red' will not work on emphasis.
  15542. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  15543. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  15544. }
  15545. normalStyle.text = normalStyleText;
  15546. emphasisStyle.text = emphasisStyleText;
  15547. }
  15548. /**
  15549. * Modify label style manually.
  15550. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  15551. *
  15552. * @param {module:zrender/src/Element} el
  15553. * @param {Object} [normalStyleProps] optional
  15554. * @param {Object} [emphasisStyleProps] optional
  15555. */
  15556. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  15557. var elStyle = el.style;
  15558. if (normalStyleProps) {
  15559. rollbackDefaultTextStyle(elStyle);
  15560. el.setStyle(normalStyleProps);
  15561. applyDefaultTextStyle(elStyle);
  15562. }
  15563. elStyle = el.__hoverStl;
  15564. if (emphasisStyleProps && elStyle) {
  15565. rollbackDefaultTextStyle(elStyle);
  15566. extend(elStyle, emphasisStyleProps);
  15567. applyDefaultTextStyle(elStyle);
  15568. }
  15569. }
  15570. /**
  15571. * Set basic textStyle properties.
  15572. * See more info in `setTextStyleCommon`.
  15573. * @param {Object|module:zrender/graphic/Style} textStyle
  15574. * @param {module:echarts/model/Model} model
  15575. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  15576. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  15577. * @param {boolean} [isEmphasis]
  15578. */
  15579. function setTextStyle(
  15580. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  15581. ) {
  15582. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  15583. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15584. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15585. return textStyle;
  15586. }
  15587. /**
  15588. * Set text option in the style.
  15589. * See more info in `setTextStyleCommon`.
  15590. * @deprecated
  15591. * @param {Object} textStyle
  15592. * @param {module:echarts/model/Model} labelModel
  15593. * @param {string|boolean} defaultColor Default text color.
  15594. * If set as false, it will be processed as a emphasis style.
  15595. */
  15596. function setText(textStyle, labelModel, defaultColor) {
  15597. var opt = {isRectText: true};
  15598. var isEmphasis;
  15599. if (defaultColor === false) {
  15600. isEmphasis = true;
  15601. }
  15602. else {
  15603. // Support setting color as 'auto' to get visual color.
  15604. opt.autoColor = defaultColor;
  15605. }
  15606. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  15607. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15608. }
  15609. /**
  15610. * The uniform entry of set text style, that is, retrieve style definitions
  15611. * from `model` and set to `textStyle` object.
  15612. *
  15613. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15614. * properties will be set. (Consider the states of normal and emphasis and
  15615. * default value can be adopted, merge would make the logic too complicated
  15616. * to manage.)
  15617. *
  15618. * The `textStyle` object can either be a plain object or an instance of
  15619. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  15620. * After this mothod called, the `textStyle` object can then be used in
  15621. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  15622. *
  15623. * Default value will be adopted and `insideRollbackOpt` will be created.
  15624. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  15625. *
  15626. * opt: {
  15627. * disableBox: boolean, Whether diable drawing box of block (outer most).
  15628. * isRectText: boolean,
  15629. * autoColor: string, specify a color when color is 'auto',
  15630. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  15631. * If autoColor specified, it is used as default textFill.
  15632. * useInsideStyle:
  15633. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  15634. * if `textFill` is not specified.
  15635. * `false`: Do not use inside style.
  15636. * `null/undefined`: use inside style if `isRectText` is true and
  15637. * `textFill` is not specified and textPosition contains `'inside'`.
  15638. * forceRich: boolean
  15639. * }
  15640. */
  15641. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  15642. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15643. opt = opt || EMPTY_OBJ;
  15644. if (opt.isRectText) {
  15645. var textPosition;
  15646. if (opt.getTextPosition) {
  15647. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  15648. }
  15649. else {
  15650. textPosition = textStyleModel.getShallow('position')
  15651. || (isEmphasis ? null : 'inside');
  15652. // 'outside' is not a valid zr textPostion value, but used
  15653. // in bar series, and magric type should be considered.
  15654. textPosition === 'outside' && (textPosition = 'top');
  15655. }
  15656. textStyle.textPosition = textPosition;
  15657. textStyle.textOffset = textStyleModel.getShallow('offset');
  15658. var labelRotate = textStyleModel.getShallow('rotate');
  15659. labelRotate != null && (labelRotate *= Math.PI / 180);
  15660. textStyle.textRotation = labelRotate;
  15661. textStyle.textDistance = retrieve2(
  15662. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  15663. );
  15664. }
  15665. var ecModel = textStyleModel.ecModel;
  15666. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15667. // Consider case:
  15668. // {
  15669. // data: [{
  15670. // value: 12,
  15671. // label: {
  15672. // rich: {
  15673. // // no 'a' here but using parent 'a'.
  15674. // }
  15675. // }
  15676. // }],
  15677. // rich: {
  15678. // a: { ... }
  15679. // }
  15680. // }
  15681. var richItemNames = getRichItemNames(textStyleModel);
  15682. var richResult;
  15683. if (richItemNames) {
  15684. richResult = {};
  15685. for (var name in richItemNames) {
  15686. if (richItemNames.hasOwnProperty(name)) {
  15687. // Cascade is supported in rich.
  15688. var richTextStyle = textStyleModel.getModel(['rich', name]);
  15689. // In rich, never `disableBox`.
  15690. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15691. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15692. // That might confuses users. So probably we should put `textStyleModel` as the
  15693. // root ancestor of the `richTextStyle`. But that would be a break change.
  15694. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  15695. }
  15696. }
  15697. }
  15698. textStyle.rich = richResult;
  15699. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  15700. if (opt.forceRich && !opt.textStyle) {
  15701. opt.textStyle = {};
  15702. }
  15703. return textStyle;
  15704. }
  15705. // Consider case:
  15706. // {
  15707. // data: [{
  15708. // value: 12,
  15709. // label: {
  15710. // rich: {
  15711. // // no 'a' here but using parent 'a'.
  15712. // }
  15713. // }
  15714. // }],
  15715. // rich: {
  15716. // a: { ... }
  15717. // }
  15718. // }
  15719. function getRichItemNames(textStyleModel) {
  15720. // Use object to remove duplicated names.
  15721. var richItemNameMap;
  15722. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15723. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15724. if (rich) {
  15725. richItemNameMap = richItemNameMap || {};
  15726. for (var name in rich) {
  15727. if (rich.hasOwnProperty(name)) {
  15728. richItemNameMap[name] = 1;
  15729. }
  15730. }
  15731. }
  15732. textStyleModel = textStyleModel.parentModel;
  15733. }
  15734. return richItemNameMap;
  15735. }
  15736. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15737. // In merge mode, default value should not be given.
  15738. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15739. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15740. || globalTextStyle.color;
  15741. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15742. || globalTextStyle.textBorderColor;
  15743. textStyle.textStrokeWidth = retrieve2(
  15744. textStyleModel.getShallow('textBorderWidth'),
  15745. globalTextStyle.textBorderWidth
  15746. );
  15747. if (!isEmphasis) {
  15748. if (isBlock) {
  15749. textStyle.insideRollbackOpt = opt;
  15750. applyDefaultTextStyle(textStyle);
  15751. }
  15752. // Set default finally.
  15753. if (textStyle.textFill == null) {
  15754. textStyle.textFill = opt.autoColor;
  15755. }
  15756. }
  15757. // Do not use `getFont` here, because merge should be supported, where
  15758. // part of these properties may be changed in emphasis style, and the
  15759. // others should remain their original value got from normal style.
  15760. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15761. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15762. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15763. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15764. textStyle.textAlign = textStyleModel.getShallow('align');
  15765. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15766. || textStyleModel.getShallow('baseline');
  15767. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15768. textStyle.textWidth = textStyleModel.getShallow('width');
  15769. textStyle.textHeight = textStyleModel.getShallow('height');
  15770. textStyle.textTag = textStyleModel.getShallow('tag');
  15771. if (!isBlock || !opt.disableBox) {
  15772. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15773. textStyle.textPadding = textStyleModel.getShallow('padding');
  15774. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15775. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15776. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15777. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15778. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15779. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15780. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15781. }
  15782. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15783. || globalTextStyle.textShadowColor;
  15784. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15785. || globalTextStyle.textShadowBlur;
  15786. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15787. || globalTextStyle.textShadowOffsetX;
  15788. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15789. || globalTextStyle.textShadowOffsetY;
  15790. }
  15791. function getAutoColor(color, opt) {
  15792. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15793. }
  15794. /**
  15795. * Give some default value to the input `textStyle` object, based on the current settings
  15796. * in this `textStyle` object.
  15797. *
  15798. * The Scenario:
  15799. * when text position is `inside` and `textFill` is not specified, we show
  15800. * text border by default for better view. But it should be considered that text position
  15801. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15802. * restore the style.
  15803. *
  15804. * Usage (& NOTICE):
  15805. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15806. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15807. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15808. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15809. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15810. */
  15811. function applyDefaultTextStyle(textStyle) {
  15812. var textPosition = textStyle.textPosition;
  15813. var opt = textStyle.insideRollbackOpt;
  15814. var insideRollback;
  15815. if (opt && textStyle.textFill == null) {
  15816. var autoColor = opt.autoColor;
  15817. var isRectText = opt.isRectText;
  15818. var useInsideStyle = opt.useInsideStyle;
  15819. var useInsideStyleCache = useInsideStyle !== false
  15820. && (useInsideStyle === true
  15821. || (isRectText
  15822. && textPosition
  15823. // textPosition can be [10, 30]
  15824. && typeof textPosition === 'string'
  15825. && textPosition.indexOf('inside') >= 0
  15826. )
  15827. );
  15828. var useAutoColorCache = !useInsideStyleCache && autoColor != null;
  15829. // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  15830. if (useInsideStyleCache || useAutoColorCache) {
  15831. insideRollback = {
  15832. textFill: textStyle.textFill,
  15833. textStroke: textStyle.textStroke,
  15834. textStrokeWidth: textStyle.textStrokeWidth
  15835. };
  15836. }
  15837. if (useInsideStyleCache) {
  15838. textStyle.textFill = '#fff';
  15839. // Consider text with #fff overflow its container.
  15840. if (textStyle.textStroke == null) {
  15841. textStyle.textStroke = autoColor;
  15842. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15843. }
  15844. }
  15845. if (useAutoColorCache) {
  15846. textStyle.textFill = autoColor;
  15847. }
  15848. }
  15849. // Always set `insideRollback`, so that the previous one can be cleared.
  15850. textStyle.insideRollback = insideRollback;
  15851. }
  15852. /**
  15853. * Consider the case: in a scatter,
  15854. * label: {
  15855. * normal: {position: 'inside'},
  15856. * emphasis: {position: 'top'}
  15857. * }
  15858. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15859. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15860. * should be retured to 'autoColor', but not keep '#fff'.
  15861. */
  15862. function rollbackDefaultTextStyle(style) {
  15863. var insideRollback = style.insideRollback;
  15864. if (insideRollback) {
  15865. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  15866. style.textFill = insideRollback.textFill;
  15867. style.textStroke = insideRollback.textStroke;
  15868. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15869. style.insideRollback = null;
  15870. }
  15871. }
  15872. function getFont(opt, ecModel) {
  15873. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15874. return trim([
  15875. // FIXME in node-canvas fontWeight is before fontStyle
  15876. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15877. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15878. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15879. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15880. ].join(' '));
  15881. }
  15882. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15883. if (typeof dataIndex === 'function') {
  15884. cb = dataIndex;
  15885. dataIndex = null;
  15886. }
  15887. // Do not check 'animation' property directly here. Consider this case:
  15888. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15889. // but its parent model (`seriesModel`) does.
  15890. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15891. if (animationEnabled) {
  15892. var postfix = isUpdate ? 'Update' : '';
  15893. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15894. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15895. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15896. if (typeof animationDelay === 'function') {
  15897. animationDelay = animationDelay(
  15898. dataIndex,
  15899. animatableModel.getAnimationDelayParams
  15900. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15901. : null
  15902. );
  15903. }
  15904. if (typeof duration === 'function') {
  15905. duration = duration(dataIndex);
  15906. }
  15907. duration > 0
  15908. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15909. : (el.stopAnimation(), el.attr(props), cb && cb());
  15910. }
  15911. else {
  15912. el.stopAnimation();
  15913. el.attr(props);
  15914. cb && cb();
  15915. }
  15916. }
  15917. /**
  15918. * Update graphic element properties with or without animation according to the
  15919. * configuration in series.
  15920. *
  15921. * Caution: this method will stop previous animation.
  15922. * So do not use this method to one element twice before
  15923. * animation starts, unless you know what you are doing.
  15924. *
  15925. * @param {module:zrender/Element} el
  15926. * @param {Object} props
  15927. * @param {module:echarts/model/Model} [animatableModel]
  15928. * @param {number} [dataIndex]
  15929. * @param {Function} [cb]
  15930. * @example
  15931. * graphic.updateProps(el, {
  15932. * position: [100, 100]
  15933. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15934. * // Or
  15935. * graphic.updateProps(el, {
  15936. * position: [100, 100]
  15937. * }, seriesModel, function () { console.log('Animation done!'); });
  15938. */
  15939. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15940. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15941. }
  15942. /**
  15943. * Init graphic element properties with or without animation according to the
  15944. * configuration in series.
  15945. *
  15946. * Caution: this method will stop previous animation.
  15947. * So do not use this method to one element twice before
  15948. * animation starts, unless you know what you are doing.
  15949. *
  15950. * @param {module:zrender/Element} el
  15951. * @param {Object} props
  15952. * @param {module:echarts/model/Model} [animatableModel]
  15953. * @param {number} [dataIndex]
  15954. * @param {Function} cb
  15955. */
  15956. function initProps(el, props, animatableModel, dataIndex, cb) {
  15957. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15958. }
  15959. /**
  15960. * Get transform matrix of target (param target),
  15961. * in coordinate of its ancestor (param ancestor)
  15962. *
  15963. * @param {module:zrender/mixin/Transformable} target
  15964. * @param {module:zrender/mixin/Transformable} [ancestor]
  15965. */
  15966. function getTransform(target, ancestor) {
  15967. var mat = identity([]);
  15968. while (target && target !== ancestor) {
  15969. mul$1(mat, target.getLocalTransform(), mat);
  15970. target = target.parent;
  15971. }
  15972. return mat;
  15973. }
  15974. /**
  15975. * Apply transform to an vertex.
  15976. * @param {Array.<number>} target [x, y]
  15977. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15978. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15979. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15980. * @param {boolean=} invert Whether use invert matrix.
  15981. * @return {Array.<number>} [x, y]
  15982. */
  15983. function applyTransform$1(target, transform, invert$$1) {
  15984. if (transform && !isArrayLike(transform)) {
  15985. transform = Transformable.getLocalTransform(transform);
  15986. }
  15987. if (invert$$1) {
  15988. transform = invert([], transform);
  15989. }
  15990. return applyTransform([], target, transform);
  15991. }
  15992. /**
  15993. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15994. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15995. * @param {boolean=} invert Whether use invert matrix.
  15996. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15997. */
  15998. function transformDirection(direction, transform, invert$$1) {
  15999. // Pick a base, ensure that transform result will not be (0, 0).
  16000. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  16001. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  16002. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  16003. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  16004. var vertex = [
  16005. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  16006. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  16007. ];
  16008. vertex = applyTransform$1(vertex, transform, invert$$1);
  16009. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  16010. ? (vertex[0] > 0 ? 'right' : 'left')
  16011. : (vertex[1] > 0 ? 'bottom' : 'top');
  16012. }
  16013. /**
  16014. * Apply group transition animation from g1 to g2.
  16015. * If no animatableModel, no animation.
  16016. */
  16017. function groupTransition(g1, g2, animatableModel, cb) {
  16018. if (!g1 || !g2) {
  16019. return;
  16020. }
  16021. function getElMap(g) {
  16022. var elMap = {};
  16023. g.traverse(function (el) {
  16024. if (!el.isGroup && el.anid) {
  16025. elMap[el.anid] = el;
  16026. }
  16027. });
  16028. return elMap;
  16029. }
  16030. function getAnimatableProps(el) {
  16031. var obj = {
  16032. position: clone$1(el.position),
  16033. rotation: el.rotation
  16034. };
  16035. if (el.shape) {
  16036. obj.shape = extend({}, el.shape);
  16037. }
  16038. return obj;
  16039. }
  16040. var elMap1 = getElMap(g1);
  16041. g2.traverse(function (el) {
  16042. if (!el.isGroup && el.anid) {
  16043. var oldEl = elMap1[el.anid];
  16044. if (oldEl) {
  16045. var newProp = getAnimatableProps(el);
  16046. el.attr(getAnimatableProps(oldEl));
  16047. updateProps(el, newProp, animatableModel, el.dataIndex);
  16048. }
  16049. // else {
  16050. // if (el.previousProps) {
  16051. // graphic.updateProps
  16052. // }
  16053. // }
  16054. }
  16055. });
  16056. }
  16057. /**
  16058. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  16059. * @param {Object} rect {x, y, width, height}
  16060. * @return {Array.<Array.<number>>} A new clipped points.
  16061. */
  16062. function clipPointsByRect(points, rect) {
  16063. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  16064. // and when element have border.
  16065. return map(points, function (point) {
  16066. var x = point[0];
  16067. x = mathMax$1(x, rect.x);
  16068. x = mathMin$1(x, rect.x + rect.width);
  16069. var y = point[1];
  16070. y = mathMax$1(y, rect.y);
  16071. y = mathMin$1(y, rect.y + rect.height);
  16072. return [x, y];
  16073. });
  16074. }
  16075. /**
  16076. * @param {Object} targetRect {x, y, width, height}
  16077. * @param {Object} rect {x, y, width, height}
  16078. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  16079. */
  16080. function clipRectByRect(targetRect, rect) {
  16081. var x = mathMax$1(targetRect.x, rect.x);
  16082. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  16083. var y = mathMax$1(targetRect.y, rect.y);
  16084. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  16085. // If the total rect is cliped, nothing, including the border,
  16086. // should be painted. So return undefined.
  16087. if (x2 >= x && y2 >= y) {
  16088. return {
  16089. x: x,
  16090. y: y,
  16091. width: x2 - x,
  16092. height: y2 - y
  16093. };
  16094. }
  16095. }
  16096. /**
  16097. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  16098. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  16099. * @param {Object} [rect] {x, y, width, height}
  16100. * @return {module:zrender/Element} Icon path or image element.
  16101. */
  16102. function createIcon(iconStr, opt, rect) {
  16103. opt = extend({rectHover: true}, opt);
  16104. var style = opt.style = {strokeNoScale: true};
  16105. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  16106. if (iconStr) {
  16107. return iconStr.indexOf('image://') === 0
  16108. ? (
  16109. style.image = iconStr.slice(8),
  16110. defaults(style, rect),
  16111. new ZImage(opt)
  16112. )
  16113. : (
  16114. makePath(
  16115. iconStr.replace('path://', ''),
  16116. opt,
  16117. rect,
  16118. 'center'
  16119. )
  16120. );
  16121. }
  16122. }
  16123. /**
  16124. * Return `true` if the given line (line `a`) and the given polygon
  16125. * are intersect.
  16126. * Note that we do not count colinear as intersect here because no
  16127. * requirement for that. We could do that if required in future.
  16128. *
  16129. * @param {number} a1x
  16130. * @param {number} a1y
  16131. * @param {number} a2x
  16132. * @param {number} a2y
  16133. * @param {Array.<Array.<number>>} points Points of the polygon.
  16134. * @return {boolean}
  16135. */
  16136. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  16137. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  16138. var p = points[i];
  16139. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  16140. return true;
  16141. }
  16142. p2 = p;
  16143. }
  16144. }
  16145. /**
  16146. * Return `true` if the given two lines (line `a` and line `b`)
  16147. * are intersect.
  16148. * Note that we do not count colinear as intersect here because no
  16149. * requirement for that. We could do that if required in future.
  16150. *
  16151. * @param {number} a1x
  16152. * @param {number} a1y
  16153. * @param {number} a2x
  16154. * @param {number} a2y
  16155. * @param {number} b1x
  16156. * @param {number} b1y
  16157. * @param {number} b2x
  16158. * @param {number} b2y
  16159. * @return {boolean}
  16160. */
  16161. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  16162. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  16163. var mx = a2x - a1x;
  16164. var my = a2y - a1y;
  16165. var nx = b2x - b1x;
  16166. var ny = b2y - b1y;
  16167. // `vec_m` and `vec_n` are parallel iff
  16168. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  16169. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  16170. if (nearZero(nmCrossProduct)) {
  16171. return false;
  16172. }
  16173. // `vec_m` and `vec_n` are intersect iff
  16174. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  16175. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  16176. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  16177. var b1a1x = a1x - b1x;
  16178. var b1a1y = a1y - b1y;
  16179. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  16180. if (q < 0 || q > 1) {
  16181. return false;
  16182. }
  16183. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  16184. if (p < 0 || p > 1) {
  16185. return false;
  16186. }
  16187. return true;
  16188. }
  16189. /**
  16190. * Cross product of 2-dimension vector.
  16191. */
  16192. function crossProduct2d(x1, y1, x2, y2) {
  16193. return x1 * y2 - x2 * y1;
  16194. }
  16195. function nearZero(val) {
  16196. return val <= (1e-6) && val >= -(1e-6);
  16197. }
  16198. // Register built-in shapes. These shapes might be overwirtten
  16199. // by users, although we do not recommend that.
  16200. registerShape('circle', Circle);
  16201. registerShape('sector', Sector);
  16202. registerShape('ring', Ring);
  16203. registerShape('polygon', Polygon);
  16204. registerShape('polyline', Polyline);
  16205. registerShape('rect', Rect);
  16206. registerShape('line', Line);
  16207. registerShape('bezierCurve', BezierCurve);
  16208. registerShape('arc', Arc);
  16209. var graphic = (Object.freeze || Object)({
  16210. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  16211. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  16212. extendShape: extendShape,
  16213. extendPath: extendPath,
  16214. registerShape: registerShape,
  16215. getShapeClass: getShapeClass,
  16216. makePath: makePath,
  16217. makeImage: makeImage,
  16218. mergePath: mergePath,
  16219. resizePath: resizePath,
  16220. subPixelOptimizeLine: subPixelOptimizeLine,
  16221. subPixelOptimizeRect: subPixelOptimizeRect,
  16222. subPixelOptimize: subPixelOptimize,
  16223. setElementHoverStyle: setElementHoverStyle,
  16224. setHoverStyle: setHoverStyle,
  16225. setAsHighDownDispatcher: setAsHighDownDispatcher,
  16226. isHighDownDispatcher: isHighDownDispatcher,
  16227. getHighlightDigit: getHighlightDigit,
  16228. setLabelStyle: setLabelStyle,
  16229. modifyLabelStyle: modifyLabelStyle,
  16230. setTextStyle: setTextStyle,
  16231. setText: setText,
  16232. getFont: getFont,
  16233. updateProps: updateProps,
  16234. initProps: initProps,
  16235. getTransform: getTransform,
  16236. applyTransform: applyTransform$1,
  16237. transformDirection: transformDirection,
  16238. groupTransition: groupTransition,
  16239. clipPointsByRect: clipPointsByRect,
  16240. clipRectByRect: clipRectByRect,
  16241. createIcon: createIcon,
  16242. linePolygonIntersect: linePolygonIntersect,
  16243. lineLineIntersect: lineLineIntersect,
  16244. Group: Group,
  16245. Image: ZImage,
  16246. Text: Text,
  16247. Circle: Circle,
  16248. Sector: Sector,
  16249. Ring: Ring,
  16250. Polygon: Polygon,
  16251. Polyline: Polyline,
  16252. Rect: Rect,
  16253. Line: Line,
  16254. BezierCurve: BezierCurve,
  16255. Arc: Arc,
  16256. IncrementalDisplayable: IncrementalDisplayble,
  16257. CompoundPath: CompoundPath,
  16258. LinearGradient: LinearGradient,
  16259. RadialGradient: RadialGradient,
  16260. BoundingRect: BoundingRect
  16261. });
  16262. /*
  16263. * Licensed to the Apache Software Foundation (ASF) under one
  16264. * or more contributor license agreements. See the NOTICE file
  16265. * distributed with this work for additional information
  16266. * regarding copyright ownership. The ASF licenses this file
  16267. * to you under the Apache License, Version 2.0 (the
  16268. * "License"); you may not use this file except in compliance
  16269. * with the License. You may obtain a copy of the License at
  16270. *
  16271. * http://www.apache.org/licenses/LICENSE-2.0
  16272. *
  16273. * Unless required by applicable law or agreed to in writing,
  16274. * software distributed under the License is distributed on an
  16275. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16276. * KIND, either express or implied. See the License for the
  16277. * specific language governing permissions and limitations
  16278. * under the License.
  16279. */
  16280. var PATH_COLOR = ['textStyle', 'color'];
  16281. var textStyleMixin = {
  16282. /**
  16283. * Get color property or get color from option.textStyle.color
  16284. * @param {boolean} [isEmphasis]
  16285. * @return {string}
  16286. */
  16287. getTextColor: function (isEmphasis) {
  16288. var ecModel = this.ecModel;
  16289. return this.getShallow('color')
  16290. || (
  16291. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  16292. );
  16293. },
  16294. /**
  16295. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  16296. * @return {string}
  16297. */
  16298. getFont: function () {
  16299. return getFont({
  16300. fontStyle: this.getShallow('fontStyle'),
  16301. fontWeight: this.getShallow('fontWeight'),
  16302. fontSize: this.getShallow('fontSize'),
  16303. fontFamily: this.getShallow('fontFamily')
  16304. }, this.ecModel);
  16305. },
  16306. getTextRect: function (text) {
  16307. return getBoundingRect(
  16308. text,
  16309. this.getFont(),
  16310. this.getShallow('align'),
  16311. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  16312. this.getShallow('padding'),
  16313. this.getShallow('lineHeight'),
  16314. this.getShallow('rich'),
  16315. this.getShallow('truncateText')
  16316. );
  16317. }
  16318. };
  16319. /*
  16320. * Licensed to the Apache Software Foundation (ASF) under one
  16321. * or more contributor license agreements. See the NOTICE file
  16322. * distributed with this work for additional information
  16323. * regarding copyright ownership. The ASF licenses this file
  16324. * to you under the Apache License, Version 2.0 (the
  16325. * "License"); you may not use this file except in compliance
  16326. * with the License. You may obtain a copy of the License at
  16327. *
  16328. * http://www.apache.org/licenses/LICENSE-2.0
  16329. *
  16330. * Unless required by applicable law or agreed to in writing,
  16331. * software distributed under the License is distributed on an
  16332. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16333. * KIND, either express or implied. See the License for the
  16334. * specific language governing permissions and limitations
  16335. * under the License.
  16336. */
  16337. var getItemStyle = makeStyleMapper(
  16338. [
  16339. ['fill', 'color'],
  16340. ['stroke', 'borderColor'],
  16341. ['lineWidth', 'borderWidth'],
  16342. ['opacity'],
  16343. ['shadowBlur'],
  16344. ['shadowOffsetX'],
  16345. ['shadowOffsetY'],
  16346. ['shadowColor'],
  16347. ['textPosition'],
  16348. ['textAlign']
  16349. ]
  16350. );
  16351. var itemStyleMixin = {
  16352. getItemStyle: function (excludes, includes) {
  16353. var style = getItemStyle(this, excludes, includes);
  16354. var lineDash = this.getBorderLineDash();
  16355. lineDash && (style.lineDash = lineDash);
  16356. return style;
  16357. },
  16358. getBorderLineDash: function () {
  16359. var lineType = this.get('borderType');
  16360. return (lineType === 'solid' || lineType == null) ? null
  16361. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  16362. }
  16363. };
  16364. /*
  16365. * Licensed to the Apache Software Foundation (ASF) under one
  16366. * or more contributor license agreements. See the NOTICE file
  16367. * distributed with this work for additional information
  16368. * regarding copyright ownership. The ASF licenses this file
  16369. * to you under the Apache License, Version 2.0 (the
  16370. * "License"); you may not use this file except in compliance
  16371. * with the License. You may obtain a copy of the License at
  16372. *
  16373. * http://www.apache.org/licenses/LICENSE-2.0
  16374. *
  16375. * Unless required by applicable law or agreed to in writing,
  16376. * software distributed under the License is distributed on an
  16377. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16378. * KIND, either express or implied. See the License for the
  16379. * specific language governing permissions and limitations
  16380. * under the License.
  16381. */
  16382. /**
  16383. * @module echarts/model/Model
  16384. */
  16385. var mixin$1 = mixin;
  16386. var inner = makeInner();
  16387. /**
  16388. * @alias module:echarts/model/Model
  16389. * @constructor
  16390. * @param {Object} [option]
  16391. * @param {module:echarts/model/Model} [parentModel]
  16392. * @param {module:echarts/model/Global} [ecModel]
  16393. */
  16394. function Model(option, parentModel, ecModel) {
  16395. /**
  16396. * @type {module:echarts/model/Model}
  16397. * @readOnly
  16398. */
  16399. this.parentModel = parentModel;
  16400. /**
  16401. * @type {module:echarts/model/Global}
  16402. * @readOnly
  16403. */
  16404. this.ecModel = ecModel;
  16405. /**
  16406. * @type {Object}
  16407. * @protected
  16408. */
  16409. this.option = option;
  16410. // Simple optimization
  16411. // if (this.init) {
  16412. // if (arguments.length <= 4) {
  16413. // this.init(option, parentModel, ecModel, extraOpt);
  16414. // }
  16415. // else {
  16416. // this.init.apply(this, arguments);
  16417. // }
  16418. // }
  16419. }
  16420. Model.prototype = {
  16421. constructor: Model,
  16422. /**
  16423. * Model 的初始化函数
  16424. * @param {Object} option
  16425. */
  16426. init: null,
  16427. /**
  16428. * 从新的 Option merge
  16429. */
  16430. mergeOption: function (option) {
  16431. merge(this.option, option, true);
  16432. },
  16433. /**
  16434. * @param {string|Array.<string>} path
  16435. * @param {boolean} [ignoreParent=false]
  16436. * @return {*}
  16437. */
  16438. get: function (path, ignoreParent) {
  16439. if (path == null) {
  16440. return this.option;
  16441. }
  16442. return doGet(
  16443. this.option,
  16444. this.parsePath(path),
  16445. !ignoreParent && getParent(this, path)
  16446. );
  16447. },
  16448. /**
  16449. * @param {string} key
  16450. * @param {boolean} [ignoreParent=false]
  16451. * @return {*}
  16452. */
  16453. getShallow: function (key, ignoreParent) {
  16454. var option = this.option;
  16455. var val = option == null ? option : option[key];
  16456. var parentModel = !ignoreParent && getParent(this, key);
  16457. if (val == null && parentModel) {
  16458. val = parentModel.getShallow(key);
  16459. }
  16460. return val;
  16461. },
  16462. /**
  16463. * @param {string|Array.<string>} [path]
  16464. * @param {module:echarts/model/Model} [parentModel]
  16465. * @return {module:echarts/model/Model}
  16466. */
  16467. getModel: function (path, parentModel) {
  16468. var obj = path == null
  16469. ? this.option
  16470. : doGet(this.option, path = this.parsePath(path));
  16471. var thisParentModel;
  16472. parentModel = parentModel || (
  16473. (thisParentModel = getParent(this, path))
  16474. && thisParentModel.getModel(path)
  16475. );
  16476. return new Model(obj, parentModel, this.ecModel);
  16477. },
  16478. /**
  16479. * If model has option
  16480. */
  16481. isEmpty: function () {
  16482. return this.option == null;
  16483. },
  16484. restoreData: function () {},
  16485. // Pending
  16486. clone: function () {
  16487. var Ctor = this.constructor;
  16488. return new Ctor(clone(this.option));
  16489. },
  16490. setReadOnly: function (properties) {
  16491. // clazzUtil.setReadOnly(this, properties);
  16492. },
  16493. // If path is null/undefined, return null/undefined.
  16494. parsePath: function (path) {
  16495. if (typeof path === 'string') {
  16496. path = path.split('.');
  16497. }
  16498. return path;
  16499. },
  16500. /**
  16501. * @param {Function} getParentMethod
  16502. * param {Array.<string>|string} path
  16503. * return {module:echarts/model/Model}
  16504. */
  16505. customizeGetParent: function (getParentMethod) {
  16506. inner(this).getParent = getParentMethod;
  16507. },
  16508. isAnimationEnabled: function () {
  16509. if (!env$1.node) {
  16510. if (this.option.animation != null) {
  16511. return !!this.option.animation;
  16512. }
  16513. else if (this.parentModel) {
  16514. return this.parentModel.isAnimationEnabled();
  16515. }
  16516. }
  16517. }
  16518. };
  16519. function doGet(obj, pathArr, parentModel) {
  16520. for (var i = 0; i < pathArr.length; i++) {
  16521. // Ignore empty
  16522. if (!pathArr[i]) {
  16523. continue;
  16524. }
  16525. // obj could be number/string/... (like 0)
  16526. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  16527. if (obj == null) {
  16528. break;
  16529. }
  16530. }
  16531. if (obj == null && parentModel) {
  16532. obj = parentModel.get(pathArr);
  16533. }
  16534. return obj;
  16535. }
  16536. // `path` can be null/undefined
  16537. function getParent(model, path) {
  16538. var getParentMethod = inner(model).getParent;
  16539. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  16540. }
  16541. // Enable Model.extend.
  16542. enableClassExtend(Model);
  16543. enableClassCheck(Model);
  16544. mixin$1(Model, lineStyleMixin);
  16545. mixin$1(Model, areaStyleMixin);
  16546. mixin$1(Model, textStyleMixin);
  16547. mixin$1(Model, itemStyleMixin);
  16548. /*
  16549. * Licensed to the Apache Software Foundation (ASF) under one
  16550. * or more contributor license agreements. See the NOTICE file
  16551. * distributed with this work for additional information
  16552. * regarding copyright ownership. The ASF licenses this file
  16553. * to you under the Apache License, Version 2.0 (the
  16554. * "License"); you may not use this file except in compliance
  16555. * with the License. You may obtain a copy of the License at
  16556. *
  16557. * http://www.apache.org/licenses/LICENSE-2.0
  16558. *
  16559. * Unless required by applicable law or agreed to in writing,
  16560. * software distributed under the License is distributed on an
  16561. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16562. * KIND, either express or implied. See the License for the
  16563. * specific language governing permissions and limitations
  16564. * under the License.
  16565. */
  16566. var base = 0;
  16567. /**
  16568. * @public
  16569. * @param {string} type
  16570. * @return {string}
  16571. */
  16572. function getUID(type) {
  16573. // Considering the case of crossing js context,
  16574. // use Math.random to make id as unique as possible.
  16575. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  16576. }
  16577. /**
  16578. * @inner
  16579. */
  16580. function enableSubTypeDefaulter(entity) {
  16581. var subTypeDefaulters = {};
  16582. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  16583. componentType = parseClassType$1(componentType);
  16584. subTypeDefaulters[componentType.main] = defaulter;
  16585. };
  16586. entity.determineSubType = function (componentType, option) {
  16587. var type = option.type;
  16588. if (!type) {
  16589. var componentTypeMain = parseClassType$1(componentType).main;
  16590. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16591. type = subTypeDefaulters[componentTypeMain](option);
  16592. }
  16593. }
  16594. return type;
  16595. };
  16596. return entity;
  16597. }
  16598. /**
  16599. * Topological travel on Activity Network (Activity On Vertices).
  16600. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16601. *
  16602. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16603. *
  16604. * If there is circle dependencey, Error will be thrown.
  16605. *
  16606. */
  16607. function enableTopologicalTravel(entity, dependencyGetter) {
  16608. /**
  16609. * @public
  16610. * @param {Array.<string>} targetNameList Target Component type list.
  16611. * Can be ['aa', 'bb', 'aa.xx']
  16612. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  16613. * @param {Function} callback Params: componentType, dependencies.
  16614. * @param {Object} context Scope of callback.
  16615. */
  16616. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16617. if (!targetNameList.length) {
  16618. return;
  16619. }
  16620. var result = makeDepndencyGraph(fullNameList);
  16621. var graph = result.graph;
  16622. var stack = result.noEntryList;
  16623. var targetNameSet = {};
  16624. each$1(targetNameList, function (name) {
  16625. targetNameSet[name] = true;
  16626. });
  16627. while (stack.length) {
  16628. var currComponentType = stack.pop();
  16629. var currVertex = graph[currComponentType];
  16630. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16631. if (isInTargetNameSet) {
  16632. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16633. delete targetNameSet[currComponentType];
  16634. }
  16635. each$1(
  16636. currVertex.successor,
  16637. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  16638. );
  16639. }
  16640. each$1(targetNameSet, function () {
  16641. throw new Error('Circle dependency may exists');
  16642. });
  16643. function removeEdge(succComponentType) {
  16644. graph[succComponentType].entryCount--;
  16645. if (graph[succComponentType].entryCount === 0) {
  16646. stack.push(succComponentType);
  16647. }
  16648. }
  16649. // Consider this case: legend depends on series, and we call
  16650. // chart.setOption({series: [...]}), where only series is in option.
  16651. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16652. // not be called, but only sereis.mergeOption is called. Thus legend
  16653. // have no chance to update its local record about series (like which
  16654. // name of series is available in legend).
  16655. function removeEdgeAndAdd(succComponentType) {
  16656. targetNameSet[succComponentType] = true;
  16657. removeEdge(succComponentType);
  16658. }
  16659. };
  16660. /**
  16661. * DepndencyGraph: {Object}
  16662. * key: conponentType,
  16663. * value: {
  16664. * successor: [conponentTypes...],
  16665. * originalDeps: [conponentTypes...],
  16666. * entryCount: {number}
  16667. * }
  16668. */
  16669. function makeDepndencyGraph(fullNameList) {
  16670. var graph = {};
  16671. var noEntryList = [];
  16672. each$1(fullNameList, function (name) {
  16673. var thisItem = createDependencyGraphItem(graph, name);
  16674. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16675. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16676. thisItem.entryCount = availableDeps.length;
  16677. if (thisItem.entryCount === 0) {
  16678. noEntryList.push(name);
  16679. }
  16680. each$1(availableDeps, function (dependentName) {
  16681. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16682. thisItem.predecessor.push(dependentName);
  16683. }
  16684. var thatItem = createDependencyGraphItem(graph, dependentName);
  16685. if (indexOf(thatItem.successor, dependentName) < 0) {
  16686. thatItem.successor.push(name);
  16687. }
  16688. });
  16689. });
  16690. return {graph: graph, noEntryList: noEntryList};
  16691. }
  16692. function createDependencyGraphItem(graph, name) {
  16693. if (!graph[name]) {
  16694. graph[name] = {predecessor: [], successor: []};
  16695. }
  16696. return graph[name];
  16697. }
  16698. function getAvailableDependencies(originalDeps, fullNameList) {
  16699. var availableDeps = [];
  16700. each$1(originalDeps, function (dep) {
  16701. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16702. });
  16703. return availableDeps;
  16704. }
  16705. }
  16706. /*
  16707. * Licensed to the Apache Software Foundation (ASF) under one
  16708. * or more contributor license agreements. See the NOTICE file
  16709. * distributed with this work for additional information
  16710. * regarding copyright ownership. The ASF licenses this file
  16711. * to you under the Apache License, Version 2.0 (the
  16712. * "License"); you may not use this file except in compliance
  16713. * with the License. You may obtain a copy of the License at
  16714. *
  16715. * http://www.apache.org/licenses/LICENSE-2.0
  16716. *
  16717. * Unless required by applicable law or agreed to in writing,
  16718. * software distributed under the License is distributed on an
  16719. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16720. * KIND, either express or implied. See the License for the
  16721. * specific language governing permissions and limitations
  16722. * under the License.
  16723. */
  16724. /*
  16725. * A third-party license is embeded for some of the code in this file:
  16726. * The method "quantile" was copied from "d3.js".
  16727. * (See more details in the comment of the method below.)
  16728. * The use of the source code of this file is also subject to the terms
  16729. * and consitions of the license of "d3.js" (BSD-3Clause, see
  16730. * </licenses/LICENSE-d3>).
  16731. */
  16732. var RADIAN_EPSILON = 1e-4;
  16733. function _trim(str) {
  16734. return str.replace(/^\s+|\s+$/g, '');
  16735. }
  16736. /**
  16737. * Linear mapping a value from domain to range
  16738. * @memberOf module:echarts/util/number
  16739. * @param {(number|Array.<number>)} val
  16740. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  16741. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  16742. * @param {boolean} clamp
  16743. * @return {(number|Array.<number>}
  16744. */
  16745. function linearMap(val, domain, range, clamp) {
  16746. var subDomain = domain[1] - domain[0];
  16747. var subRange = range[1] - range[0];
  16748. if (subDomain === 0) {
  16749. return subRange === 0
  16750. ? range[0]
  16751. : (range[0] + range[1]) / 2;
  16752. }
  16753. // Avoid accuracy problem in edge, such as
  16754. // 146.39 - 62.83 === 83.55999999999999.
  16755. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  16756. // It is a little verbose for efficiency considering this method
  16757. // is a hotspot.
  16758. if (clamp) {
  16759. if (subDomain > 0) {
  16760. if (val <= domain[0]) {
  16761. return range[0];
  16762. }
  16763. else if (val >= domain[1]) {
  16764. return range[1];
  16765. }
  16766. }
  16767. else {
  16768. if (val >= domain[0]) {
  16769. return range[0];
  16770. }
  16771. else if (val <= domain[1]) {
  16772. return range[1];
  16773. }
  16774. }
  16775. }
  16776. else {
  16777. if (val === domain[0]) {
  16778. return range[0];
  16779. }
  16780. if (val === domain[1]) {
  16781. return range[1];
  16782. }
  16783. }
  16784. return (val - domain[0]) / subDomain * subRange + range[0];
  16785. }
  16786. /**
  16787. * Convert a percent string to absolute number.
  16788. * Returns NaN if percent is not a valid string or number
  16789. * @memberOf module:echarts/util/number
  16790. * @param {string|number} percent
  16791. * @param {number} all
  16792. * @return {number}
  16793. */
  16794. function parsePercent$1(percent, all) {
  16795. switch (percent) {
  16796. case 'center':
  16797. case 'middle':
  16798. percent = '50%';
  16799. break;
  16800. case 'left':
  16801. case 'top':
  16802. percent = '0%';
  16803. break;
  16804. case 'right':
  16805. case 'bottom':
  16806. percent = '100%';
  16807. break;
  16808. }
  16809. if (typeof percent === 'string') {
  16810. if (_trim(percent).match(/%$/)) {
  16811. return parseFloat(percent) / 100 * all;
  16812. }
  16813. return parseFloat(percent);
  16814. }
  16815. return percent == null ? NaN : +percent;
  16816. }
  16817. /**
  16818. * (1) Fix rounding error of float numbers.
  16819. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16820. *
  16821. * @param {number} x
  16822. * @param {number} [precision]
  16823. * @param {boolean} [returnStr]
  16824. * @return {number|string}
  16825. */
  16826. function round$1(x, precision, returnStr) {
  16827. if (precision == null) {
  16828. precision = 10;
  16829. }
  16830. // Avoid range error
  16831. precision = Math.min(Math.max(0, precision), 20);
  16832. x = (+x).toFixed(precision);
  16833. return returnStr ? x : +x;
  16834. }
  16835. /**
  16836. * asc sort arr.
  16837. * The input arr will be modified.
  16838. *
  16839. * @param {Array} arr
  16840. * @return {Array} The input arr.
  16841. */
  16842. function asc(arr) {
  16843. arr.sort(function (a, b) {
  16844. return a - b;
  16845. });
  16846. return arr;
  16847. }
  16848. /**
  16849. * Get precision
  16850. * @param {number} val
  16851. */
  16852. function getPrecision(val) {
  16853. val = +val;
  16854. if (isNaN(val)) {
  16855. return 0;
  16856. }
  16857. // It is much faster than methods converting number to string as follows
  16858. // var tmp = val.toString();
  16859. // return tmp.length - 1 - tmp.indexOf('.');
  16860. // especially when precision is low
  16861. var e = 1;
  16862. var count = 0;
  16863. while (Math.round(val * e) / e !== val) {
  16864. e *= 10;
  16865. count++;
  16866. }
  16867. return count;
  16868. }
  16869. /**
  16870. * @param {string|number} val
  16871. * @return {number}
  16872. */
  16873. function getPrecisionSafe(val) {
  16874. var str = val.toString();
  16875. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16876. var eIndex = str.indexOf('e');
  16877. if (eIndex > 0) {
  16878. var precision = +str.slice(eIndex + 1);
  16879. return precision < 0 ? -precision : 0;
  16880. }
  16881. else {
  16882. var dotIndex = str.indexOf('.');
  16883. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16884. }
  16885. }
  16886. /**
  16887. * Minimal dicernible data precisioin according to a single pixel.
  16888. *
  16889. * @param {Array.<number>} dataExtent
  16890. * @param {Array.<number>} pixelExtent
  16891. * @return {number} precision
  16892. */
  16893. function getPixelPrecision(dataExtent, pixelExtent) {
  16894. var log = Math.log;
  16895. var LN10 = Math.LN10;
  16896. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16897. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16898. // toFixed() digits argument must be between 0 and 20.
  16899. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16900. return !isFinite(precision) ? 20 : precision;
  16901. }
  16902. /**
  16903. * Get a data of given precision, assuring the sum of percentages
  16904. * in valueList is 1.
  16905. * The largest remainer method is used.
  16906. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16907. *
  16908. * @param {Array.<number>} valueList a list of all data
  16909. * @param {number} idx index of the data to be processed in valueList
  16910. * @param {number} precision integer number showing digits of precision
  16911. * @return {number} percent ranging from 0 to 100
  16912. */
  16913. function getPercentWithPrecision(valueList, idx, precision) {
  16914. if (!valueList[idx]) {
  16915. return 0;
  16916. }
  16917. var sum = reduce(valueList, function (acc, val) {
  16918. return acc + (isNaN(val) ? 0 : val);
  16919. }, 0);
  16920. if (sum === 0) {
  16921. return 0;
  16922. }
  16923. var digits = Math.pow(10, precision);
  16924. var votesPerQuota = map(valueList, function (val) {
  16925. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16926. });
  16927. var targetSeats = digits * 100;
  16928. var seats = map(votesPerQuota, function (votes) {
  16929. // Assign automatic seats.
  16930. return Math.floor(votes);
  16931. });
  16932. var currentSum = reduce(seats, function (acc, val) {
  16933. return acc + val;
  16934. }, 0);
  16935. var remainder = map(votesPerQuota, function (votes, idx) {
  16936. return votes - seats[idx];
  16937. });
  16938. // Has remainding votes.
  16939. while (currentSum < targetSeats) {
  16940. // Find next largest remainder.
  16941. var max = Number.NEGATIVE_INFINITY;
  16942. var maxId = null;
  16943. for (var i = 0, len = remainder.length; i < len; ++i) {
  16944. if (remainder[i] > max) {
  16945. max = remainder[i];
  16946. maxId = i;
  16947. }
  16948. }
  16949. // Add a vote to max remainder.
  16950. ++seats[maxId];
  16951. remainder[maxId] = 0;
  16952. ++currentSum;
  16953. }
  16954. return seats[idx] / digits;
  16955. }
  16956. // Number.MAX_SAFE_INTEGER, ie do not support.
  16957. var MAX_SAFE_INTEGER = 9007199254740991;
  16958. /**
  16959. * To 0 - 2 * PI, considering negative radian.
  16960. * @param {number} radian
  16961. * @return {number}
  16962. */
  16963. function remRadian(radian) {
  16964. var pi2 = Math.PI * 2;
  16965. return (radian % pi2 + pi2) % pi2;
  16966. }
  16967. /**
  16968. * @param {type} radian
  16969. * @return {boolean}
  16970. */
  16971. function isRadianAroundZero(val) {
  16972. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16973. }
  16974. /* eslint-disable */
  16975. 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
  16976. /* eslint-enable */
  16977. /**
  16978. * @param {string|Date|number} value These values can be accepted:
  16979. * + An instance of Date, represent a time in its own time zone.
  16980. * + Or string in a subset of ISO 8601, only including:
  16981. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16982. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16983. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16984. * all of which will be treated as local time if time zone is not specified
  16985. * (see <https://momentjs.com/>).
  16986. * + Or other string format, including (all of which will be treated as loacal time):
  16987. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16988. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16989. * + a timestamp, which represent a time in UTC.
  16990. * @return {Date} date
  16991. */
  16992. function parseDate(value) {
  16993. if (value instanceof Date) {
  16994. return value;
  16995. }
  16996. else if (typeof value === 'string') {
  16997. // Different browsers parse date in different way, so we parse it manually.
  16998. // Some other issues:
  16999. // new Date('1970-01-01') is UTC,
  17000. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  17001. // See issue #3623
  17002. var match = TIME_REG.exec(value);
  17003. if (!match) {
  17004. // return Invalid Date.
  17005. return new Date(NaN);
  17006. }
  17007. // Use local time when no timezone offset specifed.
  17008. if (!match[8]) {
  17009. // match[n] can only be string or undefined.
  17010. // But take care of '12' + 1 => '121'.
  17011. return new Date(
  17012. +match[1],
  17013. +(match[2] || 1) - 1,
  17014. +match[3] || 1,
  17015. +match[4] || 0,
  17016. +(match[5] || 0),
  17017. +match[6] || 0,
  17018. +match[7] || 0
  17019. );
  17020. }
  17021. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  17022. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  17023. // For example, system timezone is set as "Time Zone: America/Toronto",
  17024. // then these code will get different result:
  17025. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  17026. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  17027. // So we should not use `new Date`, but use `Date.UTC`.
  17028. else {
  17029. var hour = +match[4] || 0;
  17030. if (match[8].toUpperCase() !== 'Z') {
  17031. hour -= match[8].slice(0, 3);
  17032. }
  17033. return new Date(Date.UTC(
  17034. +match[1],
  17035. +(match[2] || 1) - 1,
  17036. +match[3] || 1,
  17037. hour,
  17038. +(match[5] || 0),
  17039. +match[6] || 0,
  17040. +match[7] || 0
  17041. ));
  17042. }
  17043. }
  17044. else if (value == null) {
  17045. return new Date(NaN);
  17046. }
  17047. return new Date(Math.round(value));
  17048. }
  17049. /**
  17050. * Quantity of a number. e.g. 0.1, 1, 10, 100
  17051. *
  17052. * @param {number} val
  17053. * @return {number}
  17054. */
  17055. function quantity(val) {
  17056. return Math.pow(10, quantityExponent(val));
  17057. }
  17058. /**
  17059. * Exponent of the quantity of a number
  17060. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  17061. *
  17062. * @param {number} val non-negative value
  17063. * @return {number}
  17064. */
  17065. function quantityExponent(val) {
  17066. if (val === 0) {
  17067. return 0;
  17068. }
  17069. var exp = Math.floor(Math.log(val) / Math.LN10);
  17070. /**
  17071. * exp is expected to be the rounded-down result of the base-10 log of val.
  17072. * But due to the precision loss with Math.log(val), we need to restore it
  17073. * using 10^exp to make sure we can get val back from exp. #11249
  17074. */
  17075. if (val / Math.pow(10, exp) >= 10) {
  17076. exp++;
  17077. }
  17078. return exp;
  17079. }
  17080. /**
  17081. * find a “nice” number approximately equal to x. Round the number if round = true,
  17082. * take ceiling if round = false. The primary observation is that the “nicest”
  17083. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  17084. *
  17085. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  17086. *
  17087. * @param {number} val Non-negative value.
  17088. * @param {boolean} round
  17089. * @return {number}
  17090. */
  17091. function nice(val, round) {
  17092. var exponent = quantityExponent(val);
  17093. var exp10 = Math.pow(10, exponent);
  17094. var f = val / exp10; // 1 <= f < 10
  17095. var nf;
  17096. if (round) {
  17097. if (f < 1.5) {
  17098. nf = 1;
  17099. }
  17100. else if (f < 2.5) {
  17101. nf = 2;
  17102. }
  17103. else if (f < 4) {
  17104. nf = 3;
  17105. }
  17106. else if (f < 7) {
  17107. nf = 5;
  17108. }
  17109. else {
  17110. nf = 10;
  17111. }
  17112. }
  17113. else {
  17114. if (f < 1) {
  17115. nf = 1;
  17116. }
  17117. else if (f < 2) {
  17118. nf = 2;
  17119. }
  17120. else if (f < 3) {
  17121. nf = 3;
  17122. }
  17123. else if (f < 5) {
  17124. nf = 5;
  17125. }
  17126. else {
  17127. nf = 10;
  17128. }
  17129. }
  17130. val = nf * exp10;
  17131. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  17132. // 20 is the uppper bound of toFixed.
  17133. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  17134. }
  17135. /**
  17136. * This code was copied from "d3.js"
  17137. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  17138. * See the license statement at the head of this file.
  17139. * @param {Array.<number>} ascArr
  17140. */
  17141. function quantile(ascArr, p) {
  17142. var H = (ascArr.length - 1) * p + 1;
  17143. var h = Math.floor(H);
  17144. var v = +ascArr[h - 1];
  17145. var e = H - h;
  17146. return e ? v + e * (ascArr[h] - v) : v;
  17147. }
  17148. /**
  17149. * Order intervals asc, and split them when overlap.
  17150. * expect(numberUtil.reformIntervals([
  17151. * {interval: [18, 62], close: [1, 1]},
  17152. * {interval: [-Infinity, -70], close: [0, 0]},
  17153. * {interval: [-70, -26], close: [1, 1]},
  17154. * {interval: [-26, 18], close: [1, 1]},
  17155. * {interval: [62, 150], close: [1, 1]},
  17156. * {interval: [106, 150], close: [1, 1]},
  17157. * {interval: [150, Infinity], close: [0, 0]}
  17158. * ])).toEqual([
  17159. * {interval: [-Infinity, -70], close: [0, 0]},
  17160. * {interval: [-70, -26], close: [1, 1]},
  17161. * {interval: [-26, 18], close: [0, 1]},
  17162. * {interval: [18, 62], close: [0, 1]},
  17163. * {interval: [62, 150], close: [0, 1]},
  17164. * {interval: [150, Infinity], close: [0, 0]}
  17165. * ]);
  17166. * @param {Array.<Object>} list, where `close` mean open or close
  17167. * of the interval, and Infinity can be used.
  17168. * @return {Array.<Object>} The origin list, which has been reformed.
  17169. */
  17170. function reformIntervals(list) {
  17171. list.sort(function (a, b) {
  17172. return littleThan(a, b, 0) ? -1 : 1;
  17173. });
  17174. var curr = -Infinity;
  17175. var currClose = 1;
  17176. for (var i = 0; i < list.length;) {
  17177. var interval = list[i].interval;
  17178. var close = list[i].close;
  17179. for (var lg = 0; lg < 2; lg++) {
  17180. if (interval[lg] <= curr) {
  17181. interval[lg] = curr;
  17182. close[lg] = !lg ? 1 - currClose : 1;
  17183. }
  17184. curr = interval[lg];
  17185. currClose = close[lg];
  17186. }
  17187. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  17188. list.splice(i, 1);
  17189. }
  17190. else {
  17191. i++;
  17192. }
  17193. }
  17194. return list;
  17195. function littleThan(a, b, lg) {
  17196. return a.interval[lg] < b.interval[lg]
  17197. || (
  17198. a.interval[lg] === b.interval[lg]
  17199. && (
  17200. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  17201. || (!lg && littleThan(a, b, 1))
  17202. )
  17203. );
  17204. }
  17205. }
  17206. /**
  17207. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  17208. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  17209. * subtraction forces infinities to NaN
  17210. *
  17211. * @param {*} v
  17212. * @return {boolean}
  17213. */
  17214. function isNumeric(v) {
  17215. return v - parseFloat(v) >= 0;
  17216. }
  17217. var number = (Object.freeze || Object)({
  17218. linearMap: linearMap,
  17219. parsePercent: parsePercent$1,
  17220. round: round$1,
  17221. asc: asc,
  17222. getPrecision: getPrecision,
  17223. getPrecisionSafe: getPrecisionSafe,
  17224. getPixelPrecision: getPixelPrecision,
  17225. getPercentWithPrecision: getPercentWithPrecision,
  17226. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  17227. remRadian: remRadian,
  17228. isRadianAroundZero: isRadianAroundZero,
  17229. parseDate: parseDate,
  17230. quantity: quantity,
  17231. quantityExponent: quantityExponent,
  17232. nice: nice,
  17233. quantile: quantile,
  17234. reformIntervals: reformIntervals,
  17235. isNumeric: isNumeric
  17236. });
  17237. /*
  17238. * Licensed to the Apache Software Foundation (ASF) under one
  17239. * or more contributor license agreements. See the NOTICE file
  17240. * distributed with this work for additional information
  17241. * regarding copyright ownership. The ASF licenses this file
  17242. * to you under the Apache License, Version 2.0 (the
  17243. * "License"); you may not use this file except in compliance
  17244. * with the License. You may obtain a copy of the License at
  17245. *
  17246. * http://www.apache.org/licenses/LICENSE-2.0
  17247. *
  17248. * Unless required by applicable law or agreed to in writing,
  17249. * software distributed under the License is distributed on an
  17250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17251. * KIND, either express or implied. See the License for the
  17252. * specific language governing permissions and limitations
  17253. * under the License.
  17254. */
  17255. // import Text from 'zrender/src/graphic/Text';
  17256. /**
  17257. * add commas after every three numbers
  17258. * @param {string|number} x
  17259. * @return {string}
  17260. */
  17261. function addCommas(x) {
  17262. if (isNaN(x)) {
  17263. return '-';
  17264. }
  17265. x = (x + '').split('.');
  17266. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  17267. + (x.length > 1 ? ('.' + x[1]) : '');
  17268. }
  17269. /**
  17270. * @param {string} str
  17271. * @param {boolean} [upperCaseFirst=false]
  17272. * @return {string} str
  17273. */
  17274. function toCamelCase(str, upperCaseFirst) {
  17275. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  17276. return group1.toUpperCase();
  17277. });
  17278. if (upperCaseFirst && str) {
  17279. str = str.charAt(0).toUpperCase() + str.slice(1);
  17280. }
  17281. return str;
  17282. }
  17283. var normalizeCssArray$1 = normalizeCssArray;
  17284. var replaceReg = /([&<>"'])/g;
  17285. var replaceMap = {
  17286. '&': '&amp;',
  17287. '<': '&lt;',
  17288. '>': '&gt;',
  17289. '"': '&quot;',
  17290. '\'': '&#39;'
  17291. };
  17292. function encodeHTML(source) {
  17293. return source == null
  17294. ? ''
  17295. : (source + '').replace(replaceReg, function (str, c) {
  17296. return replaceMap[c];
  17297. });
  17298. }
  17299. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  17300. var wrapVar = function (varName, seriesIdx) {
  17301. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  17302. };
  17303. /**
  17304. * Template formatter
  17305. * @param {string} tpl
  17306. * @param {Array.<Object>|Object} paramsList
  17307. * @param {boolean} [encode=false]
  17308. * @return {string}
  17309. */
  17310. function formatTpl(tpl, paramsList, encode) {
  17311. if (!isArray(paramsList)) {
  17312. paramsList = [paramsList];
  17313. }
  17314. var seriesLen = paramsList.length;
  17315. if (!seriesLen) {
  17316. return '';
  17317. }
  17318. var $vars = paramsList[0].$vars || [];
  17319. for (var i = 0; i < $vars.length; i++) {
  17320. var alias = TPL_VAR_ALIAS[i];
  17321. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  17322. }
  17323. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  17324. for (var k = 0; k < $vars.length; k++) {
  17325. var val = paramsList[seriesIdx][$vars[k]];
  17326. tpl = tpl.replace(
  17327. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  17328. encode ? encodeHTML(val) : val
  17329. );
  17330. }
  17331. }
  17332. return tpl;
  17333. }
  17334. /**
  17335. * simple Template formatter
  17336. *
  17337. * @param {string} tpl
  17338. * @param {Object} param
  17339. * @param {boolean} [encode=false]
  17340. * @return {string}
  17341. */
  17342. function formatTplSimple(tpl, param, encode) {
  17343. each$1(param, function (value, key) {
  17344. tpl = tpl.replace(
  17345. '{' + key + '}',
  17346. encode ? encodeHTML(value) : value
  17347. );
  17348. });
  17349. return tpl;
  17350. }
  17351. /**
  17352. * @param {Object|string} [opt] If string, means color.
  17353. * @param {string} [opt.color]
  17354. * @param {string} [opt.extraCssText]
  17355. * @param {string} [opt.type='item'] 'item' or 'subItem'
  17356. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  17357. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  17358. * @return {string}
  17359. */
  17360. function getTooltipMarker(opt, extraCssText) {
  17361. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  17362. var color = opt.color;
  17363. var type = opt.type;
  17364. var extraCssText = opt.extraCssText;
  17365. var renderMode = opt.renderMode || 'html';
  17366. var markerId = opt.markerId || 'X';
  17367. if (!color) {
  17368. return '';
  17369. }
  17370. if (renderMode === 'html') {
  17371. return type === 'subItem'
  17372. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  17373. + 'border-radius:4px;width:4px;height:4px;background-color:'
  17374. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  17375. : '<span style="display:inline-block;margin-right:5px;'
  17376. + 'border-radius:10px;width:10px;height:10px;background-color:'
  17377. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  17378. }
  17379. else {
  17380. // Space for rich element marker
  17381. return {
  17382. renderMode: renderMode,
  17383. content: '{marker' + markerId + '|} ',
  17384. style: {
  17385. color: color
  17386. }
  17387. };
  17388. }
  17389. }
  17390. function pad(str, len) {
  17391. str += '';
  17392. return '0000'.substr(0, len - str.length) + str;
  17393. }
  17394. /**
  17395. * ISO Date format
  17396. * @param {string} tpl
  17397. * @param {number} value
  17398. * @param {boolean} [isUTC=false] Default in local time.
  17399. * see `module:echarts/scale/Time`
  17400. * and `module:echarts/util/number#parseDate`.
  17401. * @inner
  17402. */
  17403. function formatTime(tpl, value, isUTC) {
  17404. if (tpl === 'week'
  17405. || tpl === 'month'
  17406. || tpl === 'quarter'
  17407. || tpl === 'half-year'
  17408. || tpl === 'year'
  17409. ) {
  17410. tpl = 'MM-dd\nyyyy';
  17411. }
  17412. var date = parseDate(value);
  17413. var utc = isUTC ? 'UTC' : '';
  17414. var y = date['get' + utc + 'FullYear']();
  17415. var M = date['get' + utc + 'Month']() + 1;
  17416. var d = date['get' + utc + 'Date']();
  17417. var h = date['get' + utc + 'Hours']();
  17418. var m = date['get' + utc + 'Minutes']();
  17419. var s = date['get' + utc + 'Seconds']();
  17420. var S = date['get' + utc + 'Milliseconds']();
  17421. tpl = tpl.replace('MM', pad(M, 2))
  17422. .replace('M', M)
  17423. .replace('yyyy', y)
  17424. .replace('yy', y % 100)
  17425. .replace('dd', pad(d, 2))
  17426. .replace('d', d)
  17427. .replace('hh', pad(h, 2))
  17428. .replace('h', h)
  17429. .replace('mm', pad(m, 2))
  17430. .replace('m', m)
  17431. .replace('ss', pad(s, 2))
  17432. .replace('s', s)
  17433. .replace('SSS', pad(S, 3));
  17434. return tpl;
  17435. }
  17436. /**
  17437. * Capital first
  17438. * @param {string} str
  17439. * @return {string}
  17440. */
  17441. function capitalFirst(str) {
  17442. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  17443. }
  17444. var truncateText$1 = truncateText;
  17445. /**
  17446. * @public
  17447. * @param {Object} opt
  17448. * @param {string} opt.text
  17449. * @param {string} opt.font
  17450. * @param {string} [opt.textAlign='left']
  17451. * @param {string} [opt.textVerticalAlign='top']
  17452. * @param {Array.<number>} [opt.textPadding]
  17453. * @param {number} [opt.textLineHeight]
  17454. * @param {Object} [opt.rich]
  17455. * @param {Object} [opt.truncate]
  17456. * @return {Object} {x, y, width, height, lineHeight}
  17457. */
  17458. function getTextBoundingRect(opt) {
  17459. return getBoundingRect(
  17460. opt.text,
  17461. opt.font,
  17462. opt.textAlign,
  17463. opt.textVerticalAlign,
  17464. opt.textPadding,
  17465. opt.textLineHeight,
  17466. opt.rich,
  17467. opt.truncate
  17468. );
  17469. }
  17470. /**
  17471. * @deprecated
  17472. * the `textLineHeight` was added later.
  17473. * For backward compatiblility, put it as the last parameter.
  17474. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  17475. */
  17476. function getTextRect(
  17477. text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight
  17478. ) {
  17479. return getBoundingRect(
  17480. text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate
  17481. );
  17482. }
  17483. /**
  17484. * open new tab
  17485. * @param {string} link url
  17486. * @param {string} target blank or self
  17487. */
  17488. function windowOpen(link, target) {
  17489. if (target === '_blank' || target === 'blank') {
  17490. var blank = window.open();
  17491. blank.opener = null;
  17492. blank.location = link;
  17493. }
  17494. else {
  17495. window.open(link, target);
  17496. }
  17497. }
  17498. var format = (Object.freeze || Object)({
  17499. addCommas: addCommas,
  17500. toCamelCase: toCamelCase,
  17501. normalizeCssArray: normalizeCssArray$1,
  17502. encodeHTML: encodeHTML,
  17503. formatTpl: formatTpl,
  17504. formatTplSimple: formatTplSimple,
  17505. getTooltipMarker: getTooltipMarker,
  17506. formatTime: formatTime,
  17507. capitalFirst: capitalFirst,
  17508. truncateText: truncateText$1,
  17509. getTextBoundingRect: getTextBoundingRect,
  17510. getTextRect: getTextRect,
  17511. windowOpen: windowOpen
  17512. });
  17513. /*
  17514. * Licensed to the Apache Software Foundation (ASF) under one
  17515. * or more contributor license agreements. See the NOTICE file
  17516. * distributed with this work for additional information
  17517. * regarding copyright ownership. The ASF licenses this file
  17518. * to you under the Apache License, Version 2.0 (the
  17519. * "License"); you may not use this file except in compliance
  17520. * with the License. You may obtain a copy of the License at
  17521. *
  17522. * http://www.apache.org/licenses/LICENSE-2.0
  17523. *
  17524. * Unless required by applicable law or agreed to in writing,
  17525. * software distributed under the License is distributed on an
  17526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17527. * KIND, either express or implied. See the License for the
  17528. * specific language governing permissions and limitations
  17529. * under the License.
  17530. */
  17531. // Layout helpers for each component positioning
  17532. var each$3 = each$1;
  17533. /**
  17534. * @public
  17535. */
  17536. var LOCATION_PARAMS = [
  17537. 'left', 'right', 'top', 'bottom', 'width', 'height'
  17538. ];
  17539. /**
  17540. * @public
  17541. */
  17542. var HV_NAMES = [
  17543. ['width', 'left', 'right'],
  17544. ['height', 'top', 'bottom']
  17545. ];
  17546. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  17547. var x = 0;
  17548. var y = 0;
  17549. if (maxWidth == null) {
  17550. maxWidth = Infinity;
  17551. }
  17552. if (maxHeight == null) {
  17553. maxHeight = Infinity;
  17554. }
  17555. var currentLineMaxSize = 0;
  17556. group.eachChild(function (child, idx) {
  17557. var position = child.position;
  17558. var rect = child.getBoundingRect();
  17559. var nextChild = group.childAt(idx + 1);
  17560. var nextChildRect = nextChild && nextChild.getBoundingRect();
  17561. var nextX;
  17562. var nextY;
  17563. if (orient === 'horizontal') {
  17564. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  17565. nextX = x + moveX;
  17566. // Wrap when width exceeds maxWidth or meet a `newline` group
  17567. // FIXME compare before adding gap?
  17568. if (nextX > maxWidth || child.newline) {
  17569. x = 0;
  17570. nextX = moveX;
  17571. y += currentLineMaxSize + gap;
  17572. currentLineMaxSize = rect.height;
  17573. }
  17574. else {
  17575. // FIXME: consider rect.y is not `0`?
  17576. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  17577. }
  17578. }
  17579. else {
  17580. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  17581. nextY = y + moveY;
  17582. // Wrap when width exceeds maxHeight or meet a `newline` group
  17583. if (nextY > maxHeight || child.newline) {
  17584. x += currentLineMaxSize + gap;
  17585. y = 0;
  17586. nextY = moveY;
  17587. currentLineMaxSize = rect.width;
  17588. }
  17589. else {
  17590. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  17591. }
  17592. }
  17593. if (child.newline) {
  17594. return;
  17595. }
  17596. position[0] = x;
  17597. position[1] = y;
  17598. orient === 'horizontal'
  17599. ? (x = nextX + gap)
  17600. : (y = nextY + gap);
  17601. });
  17602. }
  17603. /**
  17604. * VBox or HBox layouting
  17605. * @param {string} orient
  17606. * @param {module:zrender/container/Group} group
  17607. * @param {number} gap
  17608. * @param {number} [width=Infinity]
  17609. * @param {number} [height=Infinity]
  17610. */
  17611. var box = boxLayout;
  17612. /**
  17613. * VBox layouting
  17614. * @param {module:zrender/container/Group} group
  17615. * @param {number} gap
  17616. * @param {number} [width=Infinity]
  17617. * @param {number} [height=Infinity]
  17618. */
  17619. var vbox = curry(boxLayout, 'vertical');
  17620. /**
  17621. * HBox layouting
  17622. * @param {module:zrender/container/Group} group
  17623. * @param {number} gap
  17624. * @param {number} [width=Infinity]
  17625. * @param {number} [height=Infinity]
  17626. */
  17627. var hbox = curry(boxLayout, 'horizontal');
  17628. /**
  17629. * If x or x2 is not specified or 'center' 'left' 'right',
  17630. * the width would be as long as possible.
  17631. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  17632. * the height would be as long as possible.
  17633. *
  17634. * @param {Object} positionInfo
  17635. * @param {number|string} [positionInfo.x]
  17636. * @param {number|string} [positionInfo.y]
  17637. * @param {number|string} [positionInfo.x2]
  17638. * @param {number|string} [positionInfo.y2]
  17639. * @param {Object} containerRect {width, height}
  17640. * @param {string|number} margin
  17641. * @return {Object} {width, height}
  17642. */
  17643. /**
  17644. * Parse position info.
  17645. *
  17646. * @param {Object} positionInfo
  17647. * @param {number|string} [positionInfo.left]
  17648. * @param {number|string} [positionInfo.top]
  17649. * @param {number|string} [positionInfo.right]
  17650. * @param {number|string} [positionInfo.bottom]
  17651. * @param {number|string} [positionInfo.width]
  17652. * @param {number|string} [positionInfo.height]
  17653. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  17654. * @param {Object} containerRect
  17655. * @param {string|number} [margin]
  17656. *
  17657. * @return {module:zrender/core/BoundingRect}
  17658. */
  17659. function getLayoutRect(
  17660. positionInfo, containerRect, margin
  17661. ) {
  17662. margin = normalizeCssArray$1(margin || 0);
  17663. var containerWidth = containerRect.width;
  17664. var containerHeight = containerRect.height;
  17665. var left = parsePercent$1(positionInfo.left, containerWidth);
  17666. var top = parsePercent$1(positionInfo.top, containerHeight);
  17667. var right = parsePercent$1(positionInfo.right, containerWidth);
  17668. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17669. var width = parsePercent$1(positionInfo.width, containerWidth);
  17670. var height = parsePercent$1(positionInfo.height, containerHeight);
  17671. var verticalMargin = margin[2] + margin[0];
  17672. var horizontalMargin = margin[1] + margin[3];
  17673. var aspect = positionInfo.aspect;
  17674. // If width is not specified, calculate width from left and right
  17675. if (isNaN(width)) {
  17676. width = containerWidth - right - horizontalMargin - left;
  17677. }
  17678. if (isNaN(height)) {
  17679. height = containerHeight - bottom - verticalMargin - top;
  17680. }
  17681. if (aspect != null) {
  17682. // If width and height are not given
  17683. // 1. Graph should not exceeds the container
  17684. // 2. Aspect must be keeped
  17685. // 3. Graph should take the space as more as possible
  17686. // FIXME
  17687. // Margin is not considered, because there is no case that both
  17688. // using margin and aspect so far.
  17689. if (isNaN(width) && isNaN(height)) {
  17690. if (aspect > containerWidth / containerHeight) {
  17691. width = containerWidth * 0.8;
  17692. }
  17693. else {
  17694. height = containerHeight * 0.8;
  17695. }
  17696. }
  17697. // Calculate width or height with given aspect
  17698. if (isNaN(width)) {
  17699. width = aspect * height;
  17700. }
  17701. if (isNaN(height)) {
  17702. height = width / aspect;
  17703. }
  17704. }
  17705. // If left is not specified, calculate left from right and width
  17706. if (isNaN(left)) {
  17707. left = containerWidth - right - width - horizontalMargin;
  17708. }
  17709. if (isNaN(top)) {
  17710. top = containerHeight - bottom - height - verticalMargin;
  17711. }
  17712. // Align left and top
  17713. switch (positionInfo.left || positionInfo.right) {
  17714. case 'center':
  17715. left = containerWidth / 2 - width / 2 - margin[3];
  17716. break;
  17717. case 'right':
  17718. left = containerWidth - width - horizontalMargin;
  17719. break;
  17720. }
  17721. switch (positionInfo.top || positionInfo.bottom) {
  17722. case 'middle':
  17723. case 'center':
  17724. top = containerHeight / 2 - height / 2 - margin[0];
  17725. break;
  17726. case 'bottom':
  17727. top = containerHeight - height - verticalMargin;
  17728. break;
  17729. }
  17730. // If something is wrong and left, top, width, height are calculated as NaN
  17731. left = left || 0;
  17732. top = top || 0;
  17733. if (isNaN(width)) {
  17734. // Width may be NaN if only one value is given except width
  17735. width = containerWidth - horizontalMargin - left - (right || 0);
  17736. }
  17737. if (isNaN(height)) {
  17738. // Height may be NaN if only one value is given except height
  17739. height = containerHeight - verticalMargin - top - (bottom || 0);
  17740. }
  17741. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  17742. rect.margin = margin;
  17743. return rect;
  17744. }
  17745. /**
  17746. * Position a zr element in viewport
  17747. * Group position is specified by either
  17748. * {left, top}, {right, bottom}
  17749. * If all properties exists, right and bottom will be igonred.
  17750. *
  17751. * Logic:
  17752. * 1. Scale (against origin point in parent coord)
  17753. * 2. Rotate (against origin point in parent coord)
  17754. * 3. Traslate (with el.position by this method)
  17755. * So this method only fixes the last step 'Traslate', which does not affect
  17756. * scaling and rotating.
  17757. *
  17758. * If be called repeatly with the same input el, the same result will be gotten.
  17759. *
  17760. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  17761. * @param {Object} positionInfo
  17762. * @param {number|string} [positionInfo.left]
  17763. * @param {number|string} [positionInfo.top]
  17764. * @param {number|string} [positionInfo.right]
  17765. * @param {number|string} [positionInfo.bottom]
  17766. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  17767. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  17768. * @param {Object} containerRect
  17769. * @param {string|number} margin
  17770. * @param {Object} [opt]
  17771. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  17772. * @param {Array.<number>} [opt.boundingMode='all']
  17773. * Specify how to calculate boundingRect when locating.
  17774. * 'all': Position the boundingRect that is transformed and uioned
  17775. * both itself and its descendants.
  17776. * This mode simplies confine the elements in the bounding
  17777. * of their container (e.g., using 'right: 0').
  17778. * 'raw': Position the boundingRect that is not transformed and only itself.
  17779. * This mode is useful when you want a element can overflow its
  17780. * container. (Consider a rotated circle needs to be located in a corner.)
  17781. * In this mode positionInfo.width/height can only be number.
  17782. */
  17783. function positionElement(el, positionInfo, containerRect, margin, opt) {
  17784. var h = !opt || !opt.hv || opt.hv[0];
  17785. var v = !opt || !opt.hv || opt.hv[1];
  17786. var boundingMode = opt && opt.boundingMode || 'all';
  17787. if (!h && !v) {
  17788. return;
  17789. }
  17790. var rect;
  17791. if (boundingMode === 'raw') {
  17792. rect = el.type === 'group'
  17793. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  17794. : el.getBoundingRect();
  17795. }
  17796. else {
  17797. rect = el.getBoundingRect();
  17798. if (el.needLocalTransform()) {
  17799. var transform = el.getLocalTransform();
  17800. // Notice: raw rect may be inner object of el,
  17801. // which should not be modified.
  17802. rect = rect.clone();
  17803. rect.applyTransform(transform);
  17804. }
  17805. }
  17806. // The real width and height can not be specified but calculated by the given el.
  17807. positionInfo = getLayoutRect(
  17808. defaults(
  17809. {width: rect.width, height: rect.height},
  17810. positionInfo
  17811. ),
  17812. containerRect,
  17813. margin
  17814. );
  17815. // Because 'tranlate' is the last step in transform
  17816. // (see zrender/core/Transformable#getLocalTransform),
  17817. // we can just only modify el.position to get final result.
  17818. var elPos = el.position;
  17819. var dx = h ? positionInfo.x - rect.x : 0;
  17820. var dy = v ? positionInfo.y - rect.y : 0;
  17821. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  17822. }
  17823. /**
  17824. * @param {Object} option Contains some of the properties in HV_NAMES.
  17825. * @param {number} hvIdx 0: horizontal; 1: vertical.
  17826. */
  17827. /**
  17828. * Consider Case:
  17829. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  17830. * through setOption or media query, using normal zrUtil.merge will cause
  17831. * {right: 0} does not take effect.
  17832. *
  17833. * @example
  17834. * ComponentModel.extend({
  17835. * init: function () {
  17836. * ...
  17837. * var inputPositionParams = layout.getLayoutParams(option);
  17838. * this.mergeOption(inputPositionParams);
  17839. * },
  17840. * mergeOption: function (newOption) {
  17841. * newOption && zrUtil.merge(thisOption, newOption, true);
  17842. * layout.mergeLayoutParam(thisOption, newOption);
  17843. * }
  17844. * });
  17845. *
  17846. * @param {Object} targetOption
  17847. * @param {Object} newOption
  17848. * @param {Object|string} [opt]
  17849. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17850. * that width (or height) should not be calculated by left and right (or top and bottom).
  17851. */
  17852. function mergeLayoutParam(targetOption, newOption, opt) {
  17853. !isObject$1(opt) && (opt = {});
  17854. var ignoreSize = opt.ignoreSize;
  17855. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17856. var hResult = merge$$1(HV_NAMES[0], 0);
  17857. var vResult = merge$$1(HV_NAMES[1], 1);
  17858. copy(HV_NAMES[0], targetOption, hResult);
  17859. copy(HV_NAMES[1], targetOption, vResult);
  17860. function merge$$1(names, hvIdx) {
  17861. var newParams = {};
  17862. var newValueCount = 0;
  17863. var merged = {};
  17864. var mergedValueCount = 0;
  17865. var enoughParamNumber = 2;
  17866. each$3(names, function (name) {
  17867. merged[name] = targetOption[name];
  17868. });
  17869. each$3(names, function (name) {
  17870. // Consider case: newOption.width is null, which is
  17871. // set by user for removing width setting.
  17872. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17873. hasValue(newParams, name) && newValueCount++;
  17874. hasValue(merged, name) && mergedValueCount++;
  17875. });
  17876. if (ignoreSize[hvIdx]) {
  17877. // Only one of left/right is premitted to exist.
  17878. if (hasValue(newOption, names[1])) {
  17879. merged[names[2]] = null;
  17880. }
  17881. else if (hasValue(newOption, names[2])) {
  17882. merged[names[1]] = null;
  17883. }
  17884. return merged;
  17885. }
  17886. // Case: newOption: {width: ..., right: ...},
  17887. // or targetOption: {right: ...} and newOption: {width: ...},
  17888. // There is no conflict when merged only has params count
  17889. // little than enoughParamNumber.
  17890. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17891. return merged;
  17892. }
  17893. // Case: newOption: {width: ..., right: ...},
  17894. // Than we can make sure user only want those two, and ignore
  17895. // all origin params in targetOption.
  17896. else if (newValueCount >= enoughParamNumber) {
  17897. return newParams;
  17898. }
  17899. else {
  17900. // Chose another param from targetOption by priority.
  17901. for (var i = 0; i < names.length; i++) {
  17902. var name = names[i];
  17903. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17904. newParams[name] = targetOption[name];
  17905. break;
  17906. }
  17907. }
  17908. return newParams;
  17909. }
  17910. }
  17911. function hasProp(obj, name) {
  17912. return obj.hasOwnProperty(name);
  17913. }
  17914. function hasValue(obj, name) {
  17915. return obj[name] != null && obj[name] !== 'auto';
  17916. }
  17917. function copy(names, target, source) {
  17918. each$3(names, function (name) {
  17919. target[name] = source[name];
  17920. });
  17921. }
  17922. }
  17923. /**
  17924. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17925. * @param {Object} source
  17926. * @return {Object} Result contains those props.
  17927. */
  17928. function getLayoutParams(source) {
  17929. return copyLayoutParams({}, source);
  17930. }
  17931. /**
  17932. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17933. * @param {Object} source
  17934. * @return {Object} Result contains those props.
  17935. */
  17936. function copyLayoutParams(target, source) {
  17937. source && target && each$3(LOCATION_PARAMS, function (name) {
  17938. source.hasOwnProperty(name) && (target[name] = source[name]);
  17939. });
  17940. return target;
  17941. }
  17942. /*
  17943. * Licensed to the Apache Software Foundation (ASF) under one
  17944. * or more contributor license agreements. See the NOTICE file
  17945. * distributed with this work for additional information
  17946. * regarding copyright ownership. The ASF licenses this file
  17947. * to you under the Apache License, Version 2.0 (the
  17948. * "License"); you may not use this file except in compliance
  17949. * with the License. You may obtain a copy of the License at
  17950. *
  17951. * http://www.apache.org/licenses/LICENSE-2.0
  17952. *
  17953. * Unless required by applicable law or agreed to in writing,
  17954. * software distributed under the License is distributed on an
  17955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17956. * KIND, either express or implied. See the License for the
  17957. * specific language governing permissions and limitations
  17958. * under the License.
  17959. */
  17960. var boxLayoutMixin = {
  17961. getBoxLayoutParams: function () {
  17962. return {
  17963. left: this.get('left'),
  17964. top: this.get('top'),
  17965. right: this.get('right'),
  17966. bottom: this.get('bottom'),
  17967. width: this.get('width'),
  17968. height: this.get('height')
  17969. };
  17970. }
  17971. };
  17972. /*
  17973. * Licensed to the Apache Software Foundation (ASF) under one
  17974. * or more contributor license agreements. See the NOTICE file
  17975. * distributed with this work for additional information
  17976. * regarding copyright ownership. The ASF licenses this file
  17977. * to you under the Apache License, Version 2.0 (the
  17978. * "License"); you may not use this file except in compliance
  17979. * with the License. You may obtain a copy of the License at
  17980. *
  17981. * http://www.apache.org/licenses/LICENSE-2.0
  17982. *
  17983. * Unless required by applicable law or agreed to in writing,
  17984. * software distributed under the License is distributed on an
  17985. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17986. * KIND, either express or implied. See the License for the
  17987. * specific language governing permissions and limitations
  17988. * under the License.
  17989. */
  17990. /**
  17991. * Component model
  17992. *
  17993. * @module echarts/model/Component
  17994. */
  17995. var inner$1 = makeInner();
  17996. /**
  17997. * @alias module:echarts/model/Component
  17998. * @constructor
  17999. * @param {Object} option
  18000. * @param {module:echarts/model/Model} parentModel
  18001. * @param {module:echarts/model/Model} ecModel
  18002. */
  18003. var ComponentModel = Model.extend({
  18004. type: 'component',
  18005. /**
  18006. * @readOnly
  18007. * @type {string}
  18008. */
  18009. id: '',
  18010. /**
  18011. * Because simplified concept is probably better, series.name (or component.name)
  18012. * has been having too many resposibilities:
  18013. * (1) Generating id (which requires name in option should not be modified).
  18014. * (2) As an index to mapping series when merging option or calling API (a name
  18015. * can refer to more then one components, which is convinient is some case).
  18016. * (3) Display.
  18017. * @readOnly
  18018. */
  18019. name: '',
  18020. /**
  18021. * @readOnly
  18022. * @type {string}
  18023. */
  18024. mainType: '',
  18025. /**
  18026. * @readOnly
  18027. * @type {string}
  18028. */
  18029. subType: '',
  18030. /**
  18031. * @readOnly
  18032. * @type {number}
  18033. */
  18034. componentIndex: 0,
  18035. /**
  18036. * @type {Object}
  18037. * @protected
  18038. */
  18039. defaultOption: null,
  18040. /**
  18041. * @type {module:echarts/model/Global}
  18042. * @readOnly
  18043. */
  18044. ecModel: null,
  18045. /**
  18046. * key: componentType
  18047. * value: Component model list, can not be null.
  18048. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18049. * @readOnly
  18050. */
  18051. dependentModels: [],
  18052. /**
  18053. * @type {string}
  18054. * @readOnly
  18055. */
  18056. uid: null,
  18057. /**
  18058. * Support merge layout params.
  18059. * Only support 'box' now (left/right/top/bottom/width/height).
  18060. * @type {string|Object} Object can be {ignoreSize: true}
  18061. * @readOnly
  18062. */
  18063. layoutMode: null,
  18064. $constructor: function (option, parentModel, ecModel, extraOpt) {
  18065. Model.call(this, option, parentModel, ecModel, extraOpt);
  18066. this.uid = getUID('ec_cpt_model');
  18067. },
  18068. init: function (option, parentModel, ecModel, extraOpt) {
  18069. this.mergeDefaultAndTheme(option, ecModel);
  18070. },
  18071. mergeDefaultAndTheme: function (option, ecModel) {
  18072. var layoutMode = this.layoutMode;
  18073. var inputPositionParams = layoutMode
  18074. ? getLayoutParams(option) : {};
  18075. var themeModel = ecModel.getTheme();
  18076. merge(option, themeModel.get(this.mainType));
  18077. merge(option, this.getDefaultOption());
  18078. if (layoutMode) {
  18079. mergeLayoutParam(option, inputPositionParams, layoutMode);
  18080. }
  18081. },
  18082. mergeOption: function (option, extraOpt) {
  18083. merge(this.option, option, true);
  18084. var layoutMode = this.layoutMode;
  18085. if (layoutMode) {
  18086. mergeLayoutParam(this.option, option, layoutMode);
  18087. }
  18088. },
  18089. // Hooker after init or mergeOption
  18090. optionUpdated: function (newCptOption, isInit) {},
  18091. getDefaultOption: function () {
  18092. var fields = inner$1(this);
  18093. if (!fields.defaultOption) {
  18094. var optList = [];
  18095. var Class = this.constructor;
  18096. while (Class) {
  18097. var opt = Class.prototype.defaultOption;
  18098. opt && optList.push(opt);
  18099. Class = Class.superClass;
  18100. }
  18101. var defaultOption = {};
  18102. for (var i = optList.length - 1; i >= 0; i--) {
  18103. defaultOption = merge(defaultOption, optList[i], true);
  18104. }
  18105. fields.defaultOption = defaultOption;
  18106. }
  18107. return fields.defaultOption;
  18108. },
  18109. getReferringComponents: function (mainType) {
  18110. return this.ecModel.queryComponents({
  18111. mainType: mainType,
  18112. index: this.get(mainType + 'Index', true),
  18113. id: this.get(mainType + 'Id', true)
  18114. });
  18115. }
  18116. });
  18117. // Reset ComponentModel.extend, add preConstruct.
  18118. // clazzUtil.enableClassExtend(
  18119. // ComponentModel,
  18120. // function (option, parentModel, ecModel, extraOpt) {
  18121. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  18122. // zrUtil.extend(this, extraOpt);
  18123. // this.uid = componentUtil.getUID('componentModel');
  18124. // // this.setReadOnly([
  18125. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  18126. // // 'dependentModels', 'componentIndex'
  18127. // // ]);
  18128. // }
  18129. // );
  18130. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  18131. enableClassManagement(
  18132. ComponentModel, {registerWhenExtend: true}
  18133. );
  18134. enableSubTypeDefaulter(ComponentModel);
  18135. // Add capability of ComponentModel.topologicalTravel.
  18136. enableTopologicalTravel(ComponentModel, getDependencies);
  18137. function getDependencies(componentType) {
  18138. var deps = [];
  18139. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  18140. deps = deps.concat(Clazz.prototype.dependencies || []);
  18141. });
  18142. // Ensure main type.
  18143. deps = map(deps, function (type) {
  18144. return parseClassType$1(type).main;
  18145. });
  18146. // Hack dataset for convenience.
  18147. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  18148. deps.unshift('dataset');
  18149. }
  18150. return deps;
  18151. }
  18152. mixin(ComponentModel, boxLayoutMixin);
  18153. /*
  18154. * Licensed to the Apache Software Foundation (ASF) under one
  18155. * or more contributor license agreements. See the NOTICE file
  18156. * distributed with this work for additional information
  18157. * regarding copyright ownership. The ASF licenses this file
  18158. * to you under the Apache License, Version 2.0 (the
  18159. * "License"); you may not use this file except in compliance
  18160. * with the License. You may obtain a copy of the License at
  18161. *
  18162. * http://www.apache.org/licenses/LICENSE-2.0
  18163. *
  18164. * Unless required by applicable law or agreed to in writing,
  18165. * software distributed under the License is distributed on an
  18166. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18167. * KIND, either express or implied. See the License for the
  18168. * specific language governing permissions and limitations
  18169. * under the License.
  18170. */
  18171. var platform = '';
  18172. // Navigator not exists in node
  18173. if (typeof navigator !== 'undefined') {
  18174. platform = navigator.platform || '';
  18175. }
  18176. var globalDefault = {
  18177. // backgroundColor: 'rgba(0,0,0,0)',
  18178. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  18179. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  18180. // Light colors:
  18181. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  18182. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  18183. // Dark colors:
  18184. color: [
  18185. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  18186. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  18187. ],
  18188. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  18189. // If xAxis and yAxis declared, grid is created by default.
  18190. // grid: {},
  18191. textStyle: {
  18192. // color: '#000',
  18193. // decoration: 'none',
  18194. // PENDING
  18195. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  18196. // fontFamily: 'Arial, Verdana, sans-serif',
  18197. fontSize: 12,
  18198. fontStyle: 'normal',
  18199. fontWeight: 'normal'
  18200. },
  18201. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  18202. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  18203. // Default is source-over
  18204. blendMode: null,
  18205. animation: 'auto',
  18206. animationDuration: 1000,
  18207. animationDurationUpdate: 300,
  18208. animationEasing: 'exponentialOut',
  18209. animationEasingUpdate: 'cubicOut',
  18210. animationThreshold: 2000,
  18211. // Configuration for progressive/incremental rendering
  18212. progressiveThreshold: 3000,
  18213. progressive: 400,
  18214. // Threshold of if use single hover layer to optimize.
  18215. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  18216. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  18217. // which is unexpected.
  18218. // see example <echarts/test/heatmap-large.html>.
  18219. hoverLayerThreshold: 3000,
  18220. // See: module:echarts/scale/Time
  18221. useUTC: false
  18222. };
  18223. /*
  18224. * Licensed to the Apache Software Foundation (ASF) under one
  18225. * or more contributor license agreements. See the NOTICE file
  18226. * distributed with this work for additional information
  18227. * regarding copyright ownership. The ASF licenses this file
  18228. * to you under the Apache License, Version 2.0 (the
  18229. * "License"); you may not use this file except in compliance
  18230. * with the License. You may obtain a copy of the License at
  18231. *
  18232. * http://www.apache.org/licenses/LICENSE-2.0
  18233. *
  18234. * Unless required by applicable law or agreed to in writing,
  18235. * software distributed under the License is distributed on an
  18236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18237. * KIND, either express or implied. See the License for the
  18238. * specific language governing permissions and limitations
  18239. * under the License.
  18240. */
  18241. var inner$2 = makeInner();
  18242. function getNearestColorPalette(colors, requestColorNum) {
  18243. var paletteNum = colors.length;
  18244. // TODO colors must be in order
  18245. for (var i = 0; i < paletteNum; i++) {
  18246. if (colors[i].length > requestColorNum) {
  18247. return colors[i];
  18248. }
  18249. }
  18250. return colors[paletteNum - 1];
  18251. }
  18252. var colorPaletteMixin = {
  18253. clearColorPalette: function () {
  18254. inner$2(this).colorIdx = 0;
  18255. inner$2(this).colorNameMap = {};
  18256. },
  18257. /**
  18258. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  18259. * twise with the same parameters will get different result.
  18260. * @param {Object} [scope=this]
  18261. * @param {Object} [requestColorNum]
  18262. * @return {string} color string.
  18263. */
  18264. getColorFromPalette: function (name, scope, requestColorNum) {
  18265. scope = scope || this;
  18266. var scopeFields = inner$2(scope);
  18267. var colorIdx = scopeFields.colorIdx || 0;
  18268. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  18269. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  18270. if (colorNameMap.hasOwnProperty(name)) {
  18271. return colorNameMap[name];
  18272. }
  18273. var defaultColorPalette = normalizeToArray(this.get('color', true));
  18274. var layeredColorPalette = this.get('colorLayer', true);
  18275. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  18276. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  18277. // In case can't find in layered color palette.
  18278. colorPalette = colorPalette || defaultColorPalette;
  18279. if (!colorPalette || !colorPalette.length) {
  18280. return;
  18281. }
  18282. var color = colorPalette[colorIdx];
  18283. if (name) {
  18284. colorNameMap[name] = color;
  18285. }
  18286. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  18287. return color;
  18288. }
  18289. };
  18290. /*
  18291. * Licensed to the Apache Software Foundation (ASF) under one
  18292. * or more contributor license agreements. See the NOTICE file
  18293. * distributed with this work for additional information
  18294. * regarding copyright ownership. The ASF licenses this file
  18295. * to you under the Apache License, Version 2.0 (the
  18296. * "License"); you may not use this file except in compliance
  18297. * with the License. You may obtain a copy of the License at
  18298. *
  18299. * http://www.apache.org/licenses/LICENSE-2.0
  18300. *
  18301. * Unless required by applicable law or agreed to in writing,
  18302. * software distributed under the License is distributed on an
  18303. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18304. * KIND, either express or implied. See the License for the
  18305. * specific language governing permissions and limitations
  18306. * under the License.
  18307. */
  18308. // Avoid typo.
  18309. var SOURCE_FORMAT_ORIGINAL = 'original';
  18310. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  18311. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  18312. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  18313. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  18314. // ??? CHANGE A NAME
  18315. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  18316. var SERIES_LAYOUT_BY_COLUMN = 'column';
  18317. var SERIES_LAYOUT_BY_ROW = 'row';
  18318. /*
  18319. * Licensed to the Apache Software Foundation (ASF) under one
  18320. * or more contributor license agreements. See the NOTICE file
  18321. * distributed with this work for additional information
  18322. * regarding copyright ownership. The ASF licenses this file
  18323. * to you under the Apache License, Version 2.0 (the
  18324. * "License"); you may not use this file except in compliance
  18325. * with the License. You may obtain a copy of the License at
  18326. *
  18327. * http://www.apache.org/licenses/LICENSE-2.0
  18328. *
  18329. * Unless required by applicable law or agreed to in writing,
  18330. * software distributed under the License is distributed on an
  18331. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18332. * KIND, either express or implied. See the License for the
  18333. * specific language governing permissions and limitations
  18334. * under the License.
  18335. */
  18336. /**
  18337. * [sourceFormat]
  18338. *
  18339. * + "original":
  18340. * This format is only used in series.data, where
  18341. * itemStyle can be specified in data item.
  18342. *
  18343. * + "arrayRows":
  18344. * [
  18345. * ['product', 'score', 'amount'],
  18346. * ['Matcha Latte', 89.3, 95.8],
  18347. * ['Milk Tea', 92.1, 89.4],
  18348. * ['Cheese Cocoa', 94.4, 91.2],
  18349. * ['Walnut Brownie', 85.4, 76.9]
  18350. * ]
  18351. *
  18352. * + "objectRows":
  18353. * [
  18354. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  18355. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  18356. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  18357. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  18358. * ]
  18359. *
  18360. * + "keyedColumns":
  18361. * {
  18362. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  18363. * 'count': [823, 235, 1042, 988],
  18364. * 'score': [95.8, 81.4, 91.2, 76.9]
  18365. * }
  18366. *
  18367. * + "typedArray"
  18368. *
  18369. * + "unknown"
  18370. */
  18371. /**
  18372. * @constructor
  18373. * @param {Object} fields
  18374. * @param {string} fields.sourceFormat
  18375. * @param {Array|Object} fields.fromDataset
  18376. * @param {Array|Object} [fields.data]
  18377. * @param {string} [seriesLayoutBy='column']
  18378. * @param {Array.<Object|string>} [dimensionsDefine]
  18379. * @param {Objet|HashMap} [encodeDefine]
  18380. * @param {number} [startIndex=0]
  18381. * @param {number} [dimensionsDetectCount]
  18382. */
  18383. function Source(fields) {
  18384. /**
  18385. * @type {boolean}
  18386. */
  18387. this.fromDataset = fields.fromDataset;
  18388. /**
  18389. * Not null/undefined.
  18390. * @type {Array|Object}
  18391. */
  18392. this.data = fields.data || (
  18393. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  18394. );
  18395. /**
  18396. * See also "detectSourceFormat".
  18397. * Not null/undefined.
  18398. * @type {string}
  18399. */
  18400. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  18401. /**
  18402. * 'row' or 'column'
  18403. * Not null/undefined.
  18404. * @type {string} seriesLayoutBy
  18405. */
  18406. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18407. /**
  18408. * dimensions definition in option.
  18409. * can be null/undefined.
  18410. * @type {Array.<Object|string>}
  18411. */
  18412. this.dimensionsDefine = fields.dimensionsDefine;
  18413. /**
  18414. * encode definition in option.
  18415. * can be null/undefined.
  18416. * @type {Objet|HashMap}
  18417. */
  18418. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  18419. /**
  18420. * Not null/undefined, uint.
  18421. * @type {number}
  18422. */
  18423. this.startIndex = fields.startIndex || 0;
  18424. /**
  18425. * Can be null/undefined (when unknown), uint.
  18426. * @type {number}
  18427. */
  18428. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  18429. }
  18430. /**
  18431. * Wrap original series data for some compatibility cases.
  18432. */
  18433. Source.seriesDataToSource = function (data) {
  18434. return new Source({
  18435. data: data,
  18436. sourceFormat: isTypedArray(data)
  18437. ? SOURCE_FORMAT_TYPED_ARRAY
  18438. : SOURCE_FORMAT_ORIGINAL,
  18439. fromDataset: false
  18440. });
  18441. };
  18442. enableClassCheck(Source);
  18443. /*
  18444. * Licensed to the Apache Software Foundation (ASF) under one
  18445. * or more contributor license agreements. See the NOTICE file
  18446. * distributed with this work for additional information
  18447. * regarding copyright ownership. The ASF licenses this file
  18448. * to you under the Apache License, Version 2.0 (the
  18449. * "License"); you may not use this file except in compliance
  18450. * with the License. You may obtain a copy of the License at
  18451. *
  18452. * http://www.apache.org/licenses/LICENSE-2.0
  18453. *
  18454. * Unless required by applicable law or agreed to in writing,
  18455. * software distributed under the License is distributed on an
  18456. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18457. * KIND, either express or implied. See the License for the
  18458. * specific language governing permissions and limitations
  18459. * under the License.
  18460. */
  18461. // The result of `guessOrdinal`.
  18462. var BE_ORDINAL = {
  18463. Must: 1, // Encounter string but not '-' and not number-like.
  18464. Might: 2, // Encounter string but number-like.
  18465. Not: 3 // Other cases
  18466. };
  18467. var inner$3 = makeInner();
  18468. /**
  18469. * @see {module:echarts/data/Source}
  18470. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  18471. * @return {string} sourceFormat
  18472. */
  18473. function detectSourceFormat(datasetModel) {
  18474. var data = datasetModel.option.source;
  18475. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18476. if (isTypedArray(data)) {
  18477. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18478. }
  18479. else if (isArray(data)) {
  18480. // FIXME Whether tolerate null in top level array?
  18481. if (data.length === 0) {
  18482. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18483. }
  18484. for (var i = 0, len = data.length; i < len; i++) {
  18485. var item = data[i];
  18486. if (item == null) {
  18487. continue;
  18488. }
  18489. else if (isArray(item)) {
  18490. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18491. break;
  18492. }
  18493. else if (isObject$1(item)) {
  18494. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18495. break;
  18496. }
  18497. }
  18498. }
  18499. else if (isObject$1(data)) {
  18500. for (var key in data) {
  18501. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  18502. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18503. break;
  18504. }
  18505. }
  18506. }
  18507. else if (data != null) {
  18508. throw new Error('Invalid data');
  18509. }
  18510. inner$3(datasetModel).sourceFormat = sourceFormat;
  18511. }
  18512. /**
  18513. * [Scenarios]:
  18514. * (1) Provide source data directly:
  18515. * series: {
  18516. * encode: {...},
  18517. * dimensions: [...]
  18518. * seriesLayoutBy: 'row',
  18519. * data: [[...]]
  18520. * }
  18521. * (2) Refer to datasetModel.
  18522. * series: [{
  18523. * encode: {...}
  18524. * // Ignore datasetIndex means `datasetIndex: 0`
  18525. * // and the dimensions defination in dataset is used
  18526. * }, {
  18527. * encode: {...},
  18528. * seriesLayoutBy: 'column',
  18529. * datasetIndex: 1
  18530. * }]
  18531. *
  18532. * Get data from series itself or datset.
  18533. * @return {module:echarts/data/Source} source
  18534. */
  18535. function getSource(seriesModel) {
  18536. return inner$3(seriesModel).source;
  18537. }
  18538. /**
  18539. * MUST be called before mergeOption of all series.
  18540. * @param {module:echarts/model/Global} ecModel
  18541. */
  18542. function resetSourceDefaulter(ecModel) {
  18543. // `datasetMap` is used to make default encode.
  18544. inner$3(ecModel).datasetMap = createHashMap();
  18545. }
  18546. /**
  18547. * [Caution]:
  18548. * MUST be called after series option merged and
  18549. * before "series.getInitailData()" called.
  18550. *
  18551. * [The rule of making default encode]:
  18552. * Category axis (if exists) alway map to the first dimension.
  18553. * Each other axis occupies a subsequent dimension.
  18554. *
  18555. * [Why make default encode]:
  18556. * Simplify the typing of encode in option, avoiding the case like that:
  18557. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  18558. * where the "y" have to be manually typed as "1, 2, 3, ...".
  18559. *
  18560. * @param {module:echarts/model/Series} seriesModel
  18561. */
  18562. function prepareSource(seriesModel) {
  18563. var seriesOption = seriesModel.option;
  18564. var data = seriesOption.data;
  18565. var sourceFormat = isTypedArray(data)
  18566. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  18567. var fromDataset = false;
  18568. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  18569. var sourceHeader = seriesOption.sourceHeader;
  18570. var dimensionsDefine = seriesOption.dimensions;
  18571. var datasetModel = getDatasetModel(seriesModel);
  18572. if (datasetModel) {
  18573. var datasetOption = datasetModel.option;
  18574. data = datasetOption.source;
  18575. sourceFormat = inner$3(datasetModel).sourceFormat;
  18576. fromDataset = true;
  18577. // These settings from series has higher priority.
  18578. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  18579. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  18580. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  18581. }
  18582. var completeResult = completeBySourceData(
  18583. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  18584. );
  18585. inner$3(seriesModel).source = new Source({
  18586. data: data,
  18587. fromDataset: fromDataset,
  18588. seriesLayoutBy: seriesLayoutBy,
  18589. sourceFormat: sourceFormat,
  18590. dimensionsDefine: completeResult.dimensionsDefine,
  18591. startIndex: completeResult.startIndex,
  18592. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  18593. // Note: dataset option does not have `encode`.
  18594. encodeDefine: seriesOption.encode
  18595. });
  18596. }
  18597. // return {startIndex, dimensionsDefine, dimensionsCount}
  18598. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  18599. if (!data) {
  18600. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  18601. }
  18602. var dimensionsDetectCount;
  18603. var startIndex;
  18604. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18605. // Rule: Most of the first line are string: it is header.
  18606. // Caution: consider a line with 5 string and 1 number,
  18607. // it still can not be sure it is a head, because the
  18608. // 5 string may be 5 values of category columns.
  18609. if (sourceHeader === 'auto' || sourceHeader == null) {
  18610. arrayRowsTravelFirst(function (val) {
  18611. // '-' is regarded as null/undefined.
  18612. if (val != null && val !== '-') {
  18613. if (isString(val)) {
  18614. startIndex == null && (startIndex = 1);
  18615. }
  18616. else {
  18617. startIndex = 0;
  18618. }
  18619. }
  18620. // 10 is an experience number, avoid long loop.
  18621. }, seriesLayoutBy, data, 10);
  18622. }
  18623. else {
  18624. startIndex = sourceHeader ? 1 : 0;
  18625. }
  18626. if (!dimensionsDefine && startIndex === 1) {
  18627. dimensionsDefine = [];
  18628. arrayRowsTravelFirst(function (val, index) {
  18629. dimensionsDefine[index] = val != null ? val : '';
  18630. }, seriesLayoutBy, data);
  18631. }
  18632. dimensionsDetectCount = dimensionsDefine
  18633. ? dimensionsDefine.length
  18634. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  18635. ? data.length
  18636. : data[0]
  18637. ? data[0].length
  18638. : null;
  18639. }
  18640. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18641. if (!dimensionsDefine) {
  18642. dimensionsDefine = objectRowsCollectDimensions(data);
  18643. }
  18644. }
  18645. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18646. if (!dimensionsDefine) {
  18647. dimensionsDefine = [];
  18648. each$1(data, function (colArr, key) {
  18649. dimensionsDefine.push(key);
  18650. });
  18651. }
  18652. }
  18653. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18654. var value0 = getDataItemValue(data[0]);
  18655. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  18656. }
  18657. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18658. if (__DEV__) {
  18659. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18660. }
  18661. }
  18662. return {
  18663. startIndex: startIndex,
  18664. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  18665. dimensionsDetectCount: dimensionsDetectCount
  18666. };
  18667. }
  18668. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18669. // which is reasonable. But dimension name is duplicated.
  18670. // Returns undefined or an array contains only object without null/undefiend or string.
  18671. function normalizeDimensionsDefine(dimensionsDefine) {
  18672. if (!dimensionsDefine) {
  18673. // The meaning of null/undefined is different from empty array.
  18674. return;
  18675. }
  18676. var nameMap = createHashMap();
  18677. return map(dimensionsDefine, function (item, index) {
  18678. item = extend({}, isObject$1(item) ? item : {name: item});
  18679. // User can set null in dimensions.
  18680. // We dont auto specify name, othewise a given name may
  18681. // cause it be refered unexpectedly.
  18682. if (item.name == null) {
  18683. return item;
  18684. }
  18685. // Also consider number form like 2012.
  18686. item.name += '';
  18687. // User may also specify displayName.
  18688. // displayName will always exists except user not
  18689. // specified or dim name is not specified or detected.
  18690. // (A auto generated dim name will not be used as
  18691. // displayName).
  18692. if (item.displayName == null) {
  18693. item.displayName = item.name;
  18694. }
  18695. var exist = nameMap.get(item.name);
  18696. if (!exist) {
  18697. nameMap.set(item.name, {count: 1});
  18698. }
  18699. else {
  18700. item.name += '-' + exist.count++;
  18701. }
  18702. return item;
  18703. });
  18704. }
  18705. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18706. maxLoop == null && (maxLoop = Infinity);
  18707. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18708. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18709. cb(data[i] ? data[i][0] : null, i);
  18710. }
  18711. }
  18712. else {
  18713. var value0 = data[0] || [];
  18714. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18715. cb(value0[i], i);
  18716. }
  18717. }
  18718. }
  18719. function objectRowsCollectDimensions(data) {
  18720. var firstIndex = 0;
  18721. var obj;
  18722. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18723. if (obj) {
  18724. var dimensions = [];
  18725. each$1(obj, function (value, key) {
  18726. dimensions.push(key);
  18727. });
  18728. return dimensions;
  18729. }
  18730. }
  18731. /**
  18732. * [The strategy of the arrengment of data dimensions for dataset]:
  18733. * "value way": all axes are non-category axes. So series one by one take
  18734. * several (the number is coordSysDims.length) dimensions from dataset.
  18735. * The result of data arrengment of data dimensions like:
  18736. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18737. * "category way": at least one axis is category axis. So the the first data
  18738. * dimension is always mapped to the first category axis and shared by
  18739. * all of the series. The other data dimensions are taken by series like
  18740. * "value way" does.
  18741. * The result of data arrengment of data dimensions like:
  18742. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18743. *
  18744. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  18745. * @param {module:model/Series} seriesModel
  18746. * @param {module:data/Source} source
  18747. * @return {Object} encode Never be `null/undefined`.
  18748. */
  18749. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18750. var encode = {};
  18751. var datasetModel = getDatasetModel(seriesModel);
  18752. // Currently only make default when using dataset, util more reqirements occur.
  18753. if (!datasetModel || !coordDimensions) {
  18754. return encode;
  18755. }
  18756. var encodeItemName = [];
  18757. var encodeSeriesName = [];
  18758. var ecModel = seriesModel.ecModel;
  18759. var datasetMap = inner$3(ecModel).datasetMap;
  18760. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18761. var baseCategoryDimIndex;
  18762. var categoryWayValueDimStart;
  18763. coordDimensions = coordDimensions.slice();
  18764. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18765. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {name: coordDimInfo});
  18766. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18767. baseCategoryDimIndex = coordDimIdx;
  18768. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  18769. }
  18770. encode[coordDimInfo.name] = [];
  18771. });
  18772. var datasetRecord = datasetMap.get(key)
  18773. || datasetMap.set(key, {categoryWayDim: categoryWayValueDimStart, valueWayDim: 0});
  18774. // TODO
  18775. // Auto detect first time axis and do arrangement.
  18776. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18777. var coordDimName = coordDimInfo.name;
  18778. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18779. // In value way.
  18780. if (baseCategoryDimIndex == null) {
  18781. var start = datasetRecord.valueWayDim;
  18782. pushDim(encode[coordDimName], start, count);
  18783. pushDim(encodeSeriesName, start, count);
  18784. datasetRecord.valueWayDim += count;
  18785. // ??? TODO give a better default series name rule?
  18786. // especially when encode x y specified.
  18787. // consider: when mutiple series share one dimension
  18788. // category axis, series name should better use
  18789. // the other dimsion name. On the other hand, use
  18790. // both dimensions name.
  18791. }
  18792. // In category way, the first category axis.
  18793. else if (baseCategoryDimIndex === coordDimIdx) {
  18794. pushDim(encode[coordDimName], 0, count);
  18795. pushDim(encodeItemName, 0, count);
  18796. }
  18797. // In category way, the other axis.
  18798. else {
  18799. var start = datasetRecord.categoryWayDim;
  18800. pushDim(encode[coordDimName], start, count);
  18801. pushDim(encodeSeriesName, start, count);
  18802. datasetRecord.categoryWayDim += count;
  18803. }
  18804. });
  18805. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18806. for (var i = 0; i < idxCount; i++) {
  18807. dimIdxArr.push(idxFrom + i);
  18808. }
  18809. }
  18810. function getDataDimCountOnCoordDim(coordDimInfo) {
  18811. var dimsDef = coordDimInfo.dimsDef;
  18812. return dimsDef ? dimsDef.length : 1;
  18813. }
  18814. encodeItemName.length && (encode.itemName = encodeItemName);
  18815. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18816. return encode;
  18817. }
  18818. /**
  18819. * Work for data like [{name: ..., value: ...}, ...].
  18820. *
  18821. * @param {module:model/Series} seriesModel
  18822. * @param {module:data/Source} source
  18823. * @return {Object} encode Never be `null/undefined`.
  18824. */
  18825. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18826. var encode = {};
  18827. var datasetModel = getDatasetModel(seriesModel);
  18828. // Currently only make default when using dataset, util more reqirements occur.
  18829. if (!datasetModel) {
  18830. return encode;
  18831. }
  18832. var sourceFormat = source.sourceFormat;
  18833. var dimensionsDefine = source.dimensionsDefine;
  18834. var potentialNameDimIndex;
  18835. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18836. each$1(dimensionsDefine, function (dim, idx) {
  18837. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  18838. potentialNameDimIndex = idx;
  18839. }
  18840. });
  18841. }
  18842. // idxResult: {v, n}.
  18843. var idxResult = (function () {
  18844. var idxRes0 = {};
  18845. var idxRes1 = {};
  18846. var guessRecords = [];
  18847. // 5 is an experience value.
  18848. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18849. var guessResult = doGuessOrdinal(
  18850. source.data, sourceFormat, source.seriesLayoutBy,
  18851. dimensionsDefine, source.startIndex, i
  18852. );
  18853. guessRecords.push(guessResult);
  18854. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18855. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18856. // and then find a name dim with the priority:
  18857. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18858. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18859. idxRes0.v = i;
  18860. }
  18861. if (idxRes0.n == null
  18862. || (idxRes0.n === idxRes0.v)
  18863. || (!isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not)
  18864. ) {
  18865. idxRes0.n = i;
  18866. }
  18867. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18868. return idxRes0;
  18869. }
  18870. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18871. // find the first BE_ORDINAL.Might as the value dim,
  18872. // and then find a name dim with the priority:
  18873. // "other dim" > "the value dim itself".
  18874. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18875. // treated as number.
  18876. if (!isPureNumber) {
  18877. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18878. idxRes1.v = i;
  18879. }
  18880. if (idxRes1.n == null || (idxRes1.n === idxRes1.v)) {
  18881. idxRes1.n = i;
  18882. }
  18883. }
  18884. }
  18885. function fulfilled(idxResult) {
  18886. return idxResult.v != null && idxResult.n != null;
  18887. }
  18888. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18889. })();
  18890. if (idxResult) {
  18891. encode.value = idxResult.v;
  18892. // `potentialNameDimIndex` has highest priority.
  18893. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18894. // By default, label use itemName in charts.
  18895. // So we dont set encodeLabel here.
  18896. encode.itemName = [nameDimIndex];
  18897. encode.seriesName = [nameDimIndex];
  18898. }
  18899. return encode;
  18900. }
  18901. /**
  18902. * If return null/undefined, indicate that should not use datasetModel.
  18903. */
  18904. function getDatasetModel(seriesModel) {
  18905. var option = seriesModel.option;
  18906. // Caution: consider the scenario:
  18907. // A dataset is declared and a series is not expected to use the dataset,
  18908. // and at the beginning `setOption({series: { noData })` (just prepare other
  18909. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18910. // the user should set an empty array to avoid that dataset is used by default.
  18911. var thisData = option.data;
  18912. if (!thisData) {
  18913. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18914. }
  18915. }
  18916. /**
  18917. * The rule should not be complex, otherwise user might not
  18918. * be able to known where the data is wrong.
  18919. * The code is ugly, but how to make it neat?
  18920. *
  18921. * @param {module:echars/data/Source} source
  18922. * @param {number} dimIndex
  18923. * @return {BE_ORDINAL} guess result.
  18924. */
  18925. function guessOrdinal(source, dimIndex) {
  18926. return doGuessOrdinal(
  18927. source.data,
  18928. source.sourceFormat,
  18929. source.seriesLayoutBy,
  18930. source.dimensionsDefine,
  18931. source.startIndex,
  18932. dimIndex
  18933. );
  18934. }
  18935. // dimIndex may be overflow source data.
  18936. // return {BE_ORDINAL}
  18937. function doGuessOrdinal(
  18938. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18939. ) {
  18940. var result;
  18941. // Experience value.
  18942. var maxLoop = 5;
  18943. if (isTypedArray(data)) {
  18944. return BE_ORDINAL.Not;
  18945. }
  18946. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18947. // always exists in source.
  18948. var dimName;
  18949. var dimType;
  18950. if (dimensionsDefine) {
  18951. var dimDefItem = dimensionsDefine[dimIndex];
  18952. if (isObject$1(dimDefItem)) {
  18953. dimName = dimDefItem.name;
  18954. dimType = dimDefItem.type;
  18955. }
  18956. else if (isString(dimDefItem)) {
  18957. dimName = dimDefItem;
  18958. }
  18959. }
  18960. if (dimType != null) {
  18961. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  18962. }
  18963. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18964. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18965. var sample = data[dimIndex];
  18966. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18967. if ((result = detectValue(sample[startIndex + i])) != null) {
  18968. return result;
  18969. }
  18970. }
  18971. }
  18972. else {
  18973. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18974. var row = data[startIndex + i];
  18975. if (row && (result = detectValue(row[dimIndex])) != null) {
  18976. return result;
  18977. }
  18978. }
  18979. }
  18980. }
  18981. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18982. if (!dimName) {
  18983. return BE_ORDINAL.Not;
  18984. }
  18985. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18986. var item = data[i];
  18987. if (item && (result = detectValue(item[dimName])) != null) {
  18988. return result;
  18989. }
  18990. }
  18991. }
  18992. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18993. if (!dimName) {
  18994. return BE_ORDINAL.Not;
  18995. }
  18996. var sample = data[dimName];
  18997. if (!sample || isTypedArray(sample)) {
  18998. return BE_ORDINAL.Not;
  18999. }
  19000. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  19001. if ((result = detectValue(sample[i])) != null) {
  19002. return result;
  19003. }
  19004. }
  19005. }
  19006. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19007. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19008. var item = data[i];
  19009. var val = getDataItemValue(item);
  19010. if (!isArray(val)) {
  19011. return BE_ORDINAL.Not;
  19012. }
  19013. if ((result = detectValue(val[dimIndex])) != null) {
  19014. return result;
  19015. }
  19016. }
  19017. }
  19018. function detectValue(val) {
  19019. var beStr = isString(val);
  19020. // Consider usage convenience, '1', '2' will be treated as "number".
  19021. // `isFinit('')` get `true`.
  19022. if (val != null && isFinite(val) && val !== '') {
  19023. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  19024. }
  19025. else if (beStr && val !== '-') {
  19026. return BE_ORDINAL.Must;
  19027. }
  19028. }
  19029. return BE_ORDINAL.Not;
  19030. }
  19031. /*
  19032. * Licensed to the Apache Software Foundation (ASF) under one
  19033. * or more contributor license agreements. See the NOTICE file
  19034. * distributed with this work for additional information
  19035. * regarding copyright ownership. The ASF licenses this file
  19036. * to you under the Apache License, Version 2.0 (the
  19037. * "License"); you may not use this file except in compliance
  19038. * with the License. You may obtain a copy of the License at
  19039. *
  19040. * http://www.apache.org/licenses/LICENSE-2.0
  19041. *
  19042. * Unless required by applicable law or agreed to in writing,
  19043. * software distributed under the License is distributed on an
  19044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19045. * KIND, either express or implied. See the License for the
  19046. * specific language governing permissions and limitations
  19047. * under the License.
  19048. */
  19049. /**
  19050. * ECharts global model
  19051. *
  19052. * @module {echarts/model/Global}
  19053. */
  19054. /**
  19055. * Caution: If the mechanism should be changed some day, these cases
  19056. * should be considered:
  19057. *
  19058. * (1) In `merge option` mode, if using the same option to call `setOption`
  19059. * many times, the result should be the same (try our best to ensure that).
  19060. * (2) In `merge option` mode, if a component has no id/name specified, it
  19061. * will be merged by index, and the result sequence of the components is
  19062. * consistent to the original sequence.
  19063. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  19064. * `mergeOption` in module:echarts/model/OptionManager.
  19065. */
  19066. var OPTION_INNER_KEY = '\0_ec_inner';
  19067. /**
  19068. * @alias module:echarts/model/Global
  19069. *
  19070. * @param {Object} option
  19071. * @param {module:echarts/model/Model} parentModel
  19072. * @param {Object} theme
  19073. */
  19074. var GlobalModel = Model.extend({
  19075. init: function (option, parentModel, theme, optionManager) {
  19076. theme = theme || {};
  19077. this.option = null; // Mark as not initialized.
  19078. /**
  19079. * @type {module:echarts/model/Model}
  19080. * @private
  19081. */
  19082. this._theme = new Model(theme);
  19083. /**
  19084. * @type {module:echarts/model/OptionManager}
  19085. */
  19086. this._optionManager = optionManager;
  19087. },
  19088. setOption: function (option, optionPreprocessorFuncs) {
  19089. assert$1(
  19090. !(OPTION_INNER_KEY in option),
  19091. 'please use chart.getOption()'
  19092. );
  19093. this._optionManager.setOption(option, optionPreprocessorFuncs);
  19094. this.resetOption(null);
  19095. },
  19096. /**
  19097. * @param {string} type null/undefined: reset all.
  19098. * 'recreate': force recreate all.
  19099. * 'timeline': only reset timeline option
  19100. * 'media': only reset media query option
  19101. * @return {boolean} Whether option changed.
  19102. */
  19103. resetOption: function (type) {
  19104. var optionChanged = false;
  19105. var optionManager = this._optionManager;
  19106. if (!type || type === 'recreate') {
  19107. var baseOption = optionManager.mountOption(type === 'recreate');
  19108. if (!this.option || type === 'recreate') {
  19109. initBase.call(this, baseOption);
  19110. }
  19111. else {
  19112. this.restoreData();
  19113. this.mergeOption(baseOption);
  19114. }
  19115. optionChanged = true;
  19116. }
  19117. if (type === 'timeline' || type === 'media') {
  19118. this.restoreData();
  19119. }
  19120. if (!type || type === 'recreate' || type === 'timeline') {
  19121. var timelineOption = optionManager.getTimelineOption(this);
  19122. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  19123. }
  19124. if (!type || type === 'recreate' || type === 'media') {
  19125. var mediaOptions = optionManager.getMediaOption(this, this._api);
  19126. if (mediaOptions.length) {
  19127. each$1(mediaOptions, function (mediaOption) {
  19128. this.mergeOption(mediaOption, optionChanged = true);
  19129. }, this);
  19130. }
  19131. }
  19132. return optionChanged;
  19133. },
  19134. /**
  19135. * @protected
  19136. */
  19137. mergeOption: function (newOption) {
  19138. var option = this.option;
  19139. var componentsMap = this._componentsMap;
  19140. var newCptTypes = [];
  19141. resetSourceDefaulter(this);
  19142. // If no component class, merge directly.
  19143. // For example: color, animaiton options, etc.
  19144. each$1(newOption, function (componentOption, mainType) {
  19145. if (componentOption == null) {
  19146. return;
  19147. }
  19148. if (!ComponentModel.hasClass(mainType)) {
  19149. // globalSettingTask.dirty();
  19150. option[mainType] = option[mainType] == null
  19151. ? clone(componentOption)
  19152. : merge(option[mainType], componentOption, true);
  19153. }
  19154. else if (mainType) {
  19155. newCptTypes.push(mainType);
  19156. }
  19157. });
  19158. ComponentModel.topologicalTravel(
  19159. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  19160. );
  19161. function visitComponent(mainType, dependencies) {
  19162. var newCptOptionList = normalizeToArray(newOption[mainType]);
  19163. var mapResult = mappingToExists(
  19164. componentsMap.get(mainType), newCptOptionList
  19165. );
  19166. makeIdAndName(mapResult);
  19167. // Set mainType and complete subType.
  19168. each$1(mapResult, function (item, index) {
  19169. var opt = item.option;
  19170. if (isObject$1(opt)) {
  19171. item.keyInfo.mainType = mainType;
  19172. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  19173. }
  19174. });
  19175. var dependentModels = getComponentsByTypes(
  19176. componentsMap, dependencies
  19177. );
  19178. option[mainType] = [];
  19179. componentsMap.set(mainType, []);
  19180. each$1(mapResult, function (resultItem, index) {
  19181. var componentModel = resultItem.exist;
  19182. var newCptOption = resultItem.option;
  19183. assert$1(
  19184. isObject$1(newCptOption) || componentModel,
  19185. 'Empty component definition'
  19186. );
  19187. // Consider where is no new option and should be merged using {},
  19188. // see removeEdgeAndAdd in topologicalTravel and
  19189. // ComponentModel.getAllClassMainTypes.
  19190. if (!newCptOption) {
  19191. componentModel.mergeOption({}, this);
  19192. componentModel.optionUpdated({}, false);
  19193. }
  19194. else {
  19195. var ComponentModelClass = ComponentModel.getClass(
  19196. mainType, resultItem.keyInfo.subType, true
  19197. );
  19198. if (componentModel && componentModel.constructor === ComponentModelClass) {
  19199. componentModel.name = resultItem.keyInfo.name;
  19200. // componentModel.settingTask && componentModel.settingTask.dirty();
  19201. componentModel.mergeOption(newCptOption, this);
  19202. componentModel.optionUpdated(newCptOption, false);
  19203. }
  19204. else {
  19205. // PENDING Global as parent ?
  19206. var extraOpt = extend(
  19207. {
  19208. dependentModels: dependentModels,
  19209. componentIndex: index
  19210. },
  19211. resultItem.keyInfo
  19212. );
  19213. componentModel = new ComponentModelClass(
  19214. newCptOption, this, this, extraOpt
  19215. );
  19216. extend(componentModel, extraOpt);
  19217. componentModel.init(newCptOption, this, this, extraOpt);
  19218. // Call optionUpdated after init.
  19219. // newCptOption has been used as componentModel.option
  19220. // and may be merged with theme and default, so pass null
  19221. // to avoid confusion.
  19222. componentModel.optionUpdated(null, true);
  19223. }
  19224. }
  19225. componentsMap.get(mainType)[index] = componentModel;
  19226. option[mainType][index] = componentModel.option;
  19227. }, this);
  19228. // Backup series for filtering.
  19229. if (mainType === 'series') {
  19230. createSeriesIndices(this, componentsMap.get('series'));
  19231. }
  19232. }
  19233. this._seriesIndicesMap = createHashMap(
  19234. this._seriesIndices = this._seriesIndices || []
  19235. );
  19236. },
  19237. /**
  19238. * Get option for output (cloned option and inner info removed)
  19239. * @public
  19240. * @return {Object}
  19241. */
  19242. getOption: function () {
  19243. var option = clone(this.option);
  19244. each$1(option, function (opts, mainType) {
  19245. if (ComponentModel.hasClass(mainType)) {
  19246. var opts = normalizeToArray(opts);
  19247. for (var i = opts.length - 1; i >= 0; i--) {
  19248. // Remove options with inner id.
  19249. if (isIdInner(opts[i])) {
  19250. opts.splice(i, 1);
  19251. }
  19252. }
  19253. option[mainType] = opts;
  19254. }
  19255. });
  19256. delete option[OPTION_INNER_KEY];
  19257. return option;
  19258. },
  19259. /**
  19260. * @return {module:echarts/model/Model}
  19261. */
  19262. getTheme: function () {
  19263. return this._theme;
  19264. },
  19265. /**
  19266. * @param {string} mainType
  19267. * @param {number} [idx=0]
  19268. * @return {module:echarts/model/Component}
  19269. */
  19270. getComponent: function (mainType, idx) {
  19271. var list = this._componentsMap.get(mainType);
  19272. if (list) {
  19273. return list[idx || 0];
  19274. }
  19275. },
  19276. /**
  19277. * If none of index and id and name used, return all components with mainType.
  19278. * @param {Object} condition
  19279. * @param {string} condition.mainType
  19280. * @param {string} [condition.subType] If ignore, only query by mainType
  19281. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  19282. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  19283. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  19284. * @return {Array.<module:echarts/model/Component>}
  19285. */
  19286. queryComponents: function (condition) {
  19287. var mainType = condition.mainType;
  19288. if (!mainType) {
  19289. return [];
  19290. }
  19291. var index = condition.index;
  19292. var id = condition.id;
  19293. var name = condition.name;
  19294. var cpts = this._componentsMap.get(mainType);
  19295. if (!cpts || !cpts.length) {
  19296. return [];
  19297. }
  19298. var result;
  19299. if (index != null) {
  19300. if (!isArray(index)) {
  19301. index = [index];
  19302. }
  19303. result = filter(map(index, function (idx) {
  19304. return cpts[idx];
  19305. }), function (val) {
  19306. return !!val;
  19307. });
  19308. }
  19309. else if (id != null) {
  19310. var isIdArray = isArray(id);
  19311. result = filter(cpts, function (cpt) {
  19312. return (isIdArray && indexOf(id, cpt.id) >= 0)
  19313. || (!isIdArray && cpt.id === id);
  19314. });
  19315. }
  19316. else if (name != null) {
  19317. var isNameArray = isArray(name);
  19318. result = filter(cpts, function (cpt) {
  19319. return (isNameArray && indexOf(name, cpt.name) >= 0)
  19320. || (!isNameArray && cpt.name === name);
  19321. });
  19322. }
  19323. else {
  19324. // Return all components with mainType
  19325. result = cpts.slice();
  19326. }
  19327. return filterBySubType(result, condition);
  19328. },
  19329. /**
  19330. * The interface is different from queryComponents,
  19331. * which is convenient for inner usage.
  19332. *
  19333. * @usage
  19334. * var result = findComponents(
  19335. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  19336. * );
  19337. * var result = findComponents(
  19338. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  19339. * );
  19340. * var result = findComponents(
  19341. * {mainType: 'series',
  19342. * filter: function (model, index) {...}}
  19343. * );
  19344. * // result like [component0, componnet1, ...]
  19345. *
  19346. * @param {Object} condition
  19347. * @param {string} condition.mainType Mandatory.
  19348. * @param {string} [condition.subType] Optional.
  19349. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  19350. * where xxx is mainType.
  19351. * If query attribute is null/undefined or has no index/id/name,
  19352. * do not filtering by query conditions, which is convenient for
  19353. * no-payload situations or when target of action is global.
  19354. * @param {Function} [condition.filter] parameter: component, return boolean.
  19355. * @return {Array.<module:echarts/model/Component>}
  19356. */
  19357. findComponents: function (condition) {
  19358. var query = condition.query;
  19359. var mainType = condition.mainType;
  19360. var queryCond = getQueryCond(query);
  19361. var result = queryCond
  19362. ? this.queryComponents(queryCond)
  19363. : this._componentsMap.get(mainType);
  19364. return doFilter(filterBySubType(result, condition));
  19365. function getQueryCond(q) {
  19366. var indexAttr = mainType + 'Index';
  19367. var idAttr = mainType + 'Id';
  19368. var nameAttr = mainType + 'Name';
  19369. return q && (
  19370. q[indexAttr] != null
  19371. || q[idAttr] != null
  19372. || q[nameAttr] != null
  19373. )
  19374. ? {
  19375. mainType: mainType,
  19376. // subType will be filtered finally.
  19377. index: q[indexAttr],
  19378. id: q[idAttr],
  19379. name: q[nameAttr]
  19380. }
  19381. : null;
  19382. }
  19383. function doFilter(res) {
  19384. return condition.filter
  19385. ? filter(res, condition.filter)
  19386. : res;
  19387. }
  19388. },
  19389. /**
  19390. * @usage
  19391. * eachComponent('legend', function (legendModel, index) {
  19392. * ...
  19393. * });
  19394. * eachComponent(function (componentType, model, index) {
  19395. * // componentType does not include subType
  19396. * // (componentType is 'xxx' but not 'xxx.aa')
  19397. * });
  19398. * eachComponent(
  19399. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  19400. * function (model, index) {...}
  19401. * );
  19402. * eachComponent(
  19403. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  19404. * function (model, index) {...}
  19405. * );
  19406. *
  19407. * @param {string|Object=} mainType When mainType is object, the definition
  19408. * is the same as the method 'findComponents'.
  19409. * @param {Function} cb
  19410. * @param {*} context
  19411. */
  19412. eachComponent: function (mainType, cb, context) {
  19413. var componentsMap = this._componentsMap;
  19414. if (typeof mainType === 'function') {
  19415. context = cb;
  19416. cb = mainType;
  19417. componentsMap.each(function (components, componentType) {
  19418. each$1(components, function (component, index) {
  19419. cb.call(context, componentType, component, index);
  19420. });
  19421. });
  19422. }
  19423. else if (isString(mainType)) {
  19424. each$1(componentsMap.get(mainType), cb, context);
  19425. }
  19426. else if (isObject$1(mainType)) {
  19427. var queryResult = this.findComponents(mainType);
  19428. each$1(queryResult, cb, context);
  19429. }
  19430. },
  19431. /**
  19432. * @param {string} name
  19433. * @return {Array.<module:echarts/model/Series>}
  19434. */
  19435. getSeriesByName: function (name) {
  19436. var series = this._componentsMap.get('series');
  19437. return filter(series, function (oneSeries) {
  19438. return oneSeries.name === name;
  19439. });
  19440. },
  19441. /**
  19442. * @param {number} seriesIndex
  19443. * @return {module:echarts/model/Series}
  19444. */
  19445. getSeriesByIndex: function (seriesIndex) {
  19446. return this._componentsMap.get('series')[seriesIndex];
  19447. },
  19448. /**
  19449. * Get series list before filtered by type.
  19450. * FIXME: rename to getRawSeriesByType?
  19451. *
  19452. * @param {string} subType
  19453. * @return {Array.<module:echarts/model/Series>}
  19454. */
  19455. getSeriesByType: function (subType) {
  19456. var series = this._componentsMap.get('series');
  19457. return filter(series, function (oneSeries) {
  19458. return oneSeries.subType === subType;
  19459. });
  19460. },
  19461. /**
  19462. * @return {Array.<module:echarts/model/Series>}
  19463. */
  19464. getSeries: function () {
  19465. return this._componentsMap.get('series').slice();
  19466. },
  19467. /**
  19468. * @return {number}
  19469. */
  19470. getSeriesCount: function () {
  19471. return this._componentsMap.get('series').length;
  19472. },
  19473. /**
  19474. * After filtering, series may be different
  19475. * frome raw series.
  19476. *
  19477. * @param {Function} cb
  19478. * @param {*} context
  19479. */
  19480. eachSeries: function (cb, context) {
  19481. assertSeriesInitialized(this);
  19482. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19483. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19484. cb.call(context, series, rawSeriesIndex);
  19485. }, this);
  19486. },
  19487. /**
  19488. * Iterate raw series before filtered.
  19489. *
  19490. * @param {Function} cb
  19491. * @param {*} context
  19492. */
  19493. eachRawSeries: function (cb, context) {
  19494. each$1(this._componentsMap.get('series'), cb, context);
  19495. },
  19496. /**
  19497. * After filtering, series may be different.
  19498. * frome raw series.
  19499. *
  19500. * @param {string} subType.
  19501. * @param {Function} cb
  19502. * @param {*} context
  19503. */
  19504. eachSeriesByType: function (subType, cb, context) {
  19505. assertSeriesInitialized(this);
  19506. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19507. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19508. if (series.subType === subType) {
  19509. cb.call(context, series, rawSeriesIndex);
  19510. }
  19511. }, this);
  19512. },
  19513. /**
  19514. * Iterate raw series before filtered of given type.
  19515. *
  19516. * @parma {string} subType
  19517. * @param {Function} cb
  19518. * @param {*} context
  19519. */
  19520. eachRawSeriesByType: function (subType, cb, context) {
  19521. return each$1(this.getSeriesByType(subType), cb, context);
  19522. },
  19523. /**
  19524. * @param {module:echarts/model/Series} seriesModel
  19525. */
  19526. isSeriesFiltered: function (seriesModel) {
  19527. assertSeriesInitialized(this);
  19528. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  19529. },
  19530. /**
  19531. * @return {Array.<number>}
  19532. */
  19533. getCurrentSeriesIndices: function () {
  19534. return (this._seriesIndices || []).slice();
  19535. },
  19536. /**
  19537. * @param {Function} cb
  19538. * @param {*} context
  19539. */
  19540. filterSeries: function (cb, context) {
  19541. assertSeriesInitialized(this);
  19542. var filteredSeries = filter(
  19543. this._componentsMap.get('series'), cb, context
  19544. );
  19545. createSeriesIndices(this, filteredSeries);
  19546. },
  19547. restoreData: function (payload) {
  19548. var componentsMap = this._componentsMap;
  19549. createSeriesIndices(this, componentsMap.get('series'));
  19550. var componentTypes = [];
  19551. componentsMap.each(function (components, componentType) {
  19552. componentTypes.push(componentType);
  19553. });
  19554. ComponentModel.topologicalTravel(
  19555. componentTypes,
  19556. ComponentModel.getAllClassMainTypes(),
  19557. function (componentType, dependencies) {
  19558. each$1(componentsMap.get(componentType), function (component) {
  19559. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  19560. && component.restoreData();
  19561. });
  19562. }
  19563. );
  19564. }
  19565. });
  19566. function isNotTargetSeries(seriesModel, payload) {
  19567. if (payload) {
  19568. var index = payload.seiresIndex;
  19569. var id = payload.seriesId;
  19570. var name = payload.seriesName;
  19571. return (index != null && seriesModel.componentIndex !== index)
  19572. || (id != null && seriesModel.id !== id)
  19573. || (name != null && seriesModel.name !== name);
  19574. }
  19575. }
  19576. /**
  19577. * @inner
  19578. */
  19579. function mergeTheme(option, theme) {
  19580. // PENDING
  19581. // NOT use `colorLayer` in theme if option has `color`
  19582. var notMergeColorLayer = option.color && !option.colorLayer;
  19583. each$1(theme, function (themeItem, name) {
  19584. if (name === 'colorLayer' && notMergeColorLayer) {
  19585. return;
  19586. }
  19587. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  19588. if (!ComponentModel.hasClass(name)) {
  19589. if (typeof themeItem === 'object') {
  19590. option[name] = !option[name]
  19591. ? clone(themeItem)
  19592. : merge(option[name], themeItem, false);
  19593. }
  19594. else {
  19595. if (option[name] == null) {
  19596. option[name] = themeItem;
  19597. }
  19598. }
  19599. }
  19600. });
  19601. }
  19602. function initBase(baseOption) {
  19603. baseOption = baseOption;
  19604. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  19605. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  19606. this.option = {};
  19607. this.option[OPTION_INNER_KEY] = 1;
  19608. /**
  19609. * Init with series: [], in case of calling findSeries method
  19610. * before series initialized.
  19611. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  19612. * @private
  19613. */
  19614. this._componentsMap = createHashMap({series: []});
  19615. /**
  19616. * Mapping between filtered series list and raw series list.
  19617. * key: filtered series indices, value: raw series indices.
  19618. * @type {Array.<nubmer>}
  19619. * @private
  19620. */
  19621. this._seriesIndices;
  19622. this._seriesIndicesMap;
  19623. mergeTheme(baseOption, this._theme.option);
  19624. // TODO Needs clone when merging to the unexisted property
  19625. merge(baseOption, globalDefault, false);
  19626. this.mergeOption(baseOption);
  19627. }
  19628. /**
  19629. * @inner
  19630. * @param {Array.<string>|string} types model types
  19631. * @return {Object} key: {string} type, value: {Array.<Object>} models
  19632. */
  19633. function getComponentsByTypes(componentsMap, types) {
  19634. if (!isArray(types)) {
  19635. types = types ? [types] : [];
  19636. }
  19637. var ret = {};
  19638. each$1(types, function (type) {
  19639. ret[type] = (componentsMap.get(type) || []).slice();
  19640. });
  19641. return ret;
  19642. }
  19643. /**
  19644. * @inner
  19645. */
  19646. function determineSubType(mainType, newCptOption, existComponent) {
  19647. var subType = newCptOption.type
  19648. ? newCptOption.type
  19649. : existComponent
  19650. ? existComponent.subType
  19651. // Use determineSubType only when there is no existComponent.
  19652. : ComponentModel.determineSubType(mainType, newCptOption);
  19653. // tooltip, markline, markpoint may always has no subType
  19654. return subType;
  19655. }
  19656. /**
  19657. * @inner
  19658. */
  19659. function createSeriesIndices(ecModel, seriesModels) {
  19660. ecModel._seriesIndicesMap = createHashMap(
  19661. ecModel._seriesIndices = map(seriesModels, function (series) {
  19662. return series.componentIndex;
  19663. }) || []
  19664. );
  19665. }
  19666. /**
  19667. * @inner
  19668. */
  19669. function filterBySubType(components, condition) {
  19670. // Using hasOwnProperty for restrict. Consider
  19671. // subType is undefined in user payload.
  19672. return condition.hasOwnProperty('subType')
  19673. ? filter(components, function (cpt) {
  19674. return cpt.subType === condition.subType;
  19675. })
  19676. : components;
  19677. }
  19678. /**
  19679. * @inner
  19680. */
  19681. function assertSeriesInitialized(ecModel) {
  19682. // Components that use _seriesIndices should depends on series component,
  19683. // which make sure that their initialization is after series.
  19684. if (__DEV__) {
  19685. if (!ecModel._seriesIndices) {
  19686. throw new Error('Option should contains series.');
  19687. }
  19688. }
  19689. }
  19690. mixin(GlobalModel, colorPaletteMixin);
  19691. /*
  19692. * Licensed to the Apache Software Foundation (ASF) under one
  19693. * or more contributor license agreements. See the NOTICE file
  19694. * distributed with this work for additional information
  19695. * regarding copyright ownership. The ASF licenses this file
  19696. * to you under the Apache License, Version 2.0 (the
  19697. * "License"); you may not use this file except in compliance
  19698. * with the License. You may obtain a copy of the License at
  19699. *
  19700. * http://www.apache.org/licenses/LICENSE-2.0
  19701. *
  19702. * Unless required by applicable law or agreed to in writing,
  19703. * software distributed under the License is distributed on an
  19704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19705. * KIND, either express or implied. See the License for the
  19706. * specific language governing permissions and limitations
  19707. * under the License.
  19708. */
  19709. var echartsAPIList = [
  19710. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  19711. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  19712. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  19713. ];
  19714. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  19715. function ExtensionAPI(chartInstance) {
  19716. each$1(echartsAPIList, function (name) {
  19717. this[name] = bind(chartInstance[name], chartInstance);
  19718. }, this);
  19719. }
  19720. /*
  19721. * Licensed to the Apache Software Foundation (ASF) under one
  19722. * or more contributor license agreements. See the NOTICE file
  19723. * distributed with this work for additional information
  19724. * regarding copyright ownership. The ASF licenses this file
  19725. * to you under the Apache License, Version 2.0 (the
  19726. * "License"); you may not use this file except in compliance
  19727. * with the License. You may obtain a copy of the License at
  19728. *
  19729. * http://www.apache.org/licenses/LICENSE-2.0
  19730. *
  19731. * Unless required by applicable law or agreed to in writing,
  19732. * software distributed under the License is distributed on an
  19733. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19734. * KIND, either express or implied. See the License for the
  19735. * specific language governing permissions and limitations
  19736. * under the License.
  19737. */
  19738. var coordinateSystemCreators = {};
  19739. function CoordinateSystemManager() {
  19740. this._coordinateSystems = [];
  19741. }
  19742. CoordinateSystemManager.prototype = {
  19743. constructor: CoordinateSystemManager,
  19744. create: function (ecModel, api) {
  19745. var coordinateSystems = [];
  19746. each$1(coordinateSystemCreators, function (creater, type) {
  19747. var list = creater.create(ecModel, api);
  19748. coordinateSystems = coordinateSystems.concat(list || []);
  19749. });
  19750. this._coordinateSystems = coordinateSystems;
  19751. },
  19752. update: function (ecModel, api) {
  19753. each$1(this._coordinateSystems, function (coordSys) {
  19754. coordSys.update && coordSys.update(ecModel, api);
  19755. });
  19756. },
  19757. getCoordinateSystems: function () {
  19758. return this._coordinateSystems.slice();
  19759. }
  19760. };
  19761. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  19762. coordinateSystemCreators[type] = coordinateSystemCreator;
  19763. };
  19764. CoordinateSystemManager.get = function (type) {
  19765. return coordinateSystemCreators[type];
  19766. };
  19767. /*
  19768. * Licensed to the Apache Software Foundation (ASF) under one
  19769. * or more contributor license agreements. See the NOTICE file
  19770. * distributed with this work for additional information
  19771. * regarding copyright ownership. The ASF licenses this file
  19772. * to you under the Apache License, Version 2.0 (the
  19773. * "License"); you may not use this file except in compliance
  19774. * with the License. You may obtain a copy of the License at
  19775. *
  19776. * http://www.apache.org/licenses/LICENSE-2.0
  19777. *
  19778. * Unless required by applicable law or agreed to in writing,
  19779. * software distributed under the License is distributed on an
  19780. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19781. * KIND, either express or implied. See the License for the
  19782. * specific language governing permissions and limitations
  19783. * under the License.
  19784. */
  19785. /**
  19786. * ECharts option manager
  19787. *
  19788. * @module {echarts/model/OptionManager}
  19789. */
  19790. var each$4 = each$1;
  19791. var clone$3 = clone;
  19792. var map$1 = map;
  19793. var merge$1 = merge;
  19794. var QUERY_REG = /^(min|max)?(.+)$/;
  19795. /**
  19796. * TERM EXPLANATIONS:
  19797. *
  19798. * [option]:
  19799. *
  19800. * An object that contains definitions of components. For example:
  19801. * var option = {
  19802. * title: {...},
  19803. * legend: {...},
  19804. * visualMap: {...},
  19805. * series: [
  19806. * {data: [...]},
  19807. * {data: [...]},
  19808. * ...
  19809. * ]
  19810. * };
  19811. *
  19812. * [rawOption]:
  19813. *
  19814. * An object input to echarts.setOption. 'rawOption' may be an
  19815. * 'option', or may be an object contains multi-options. For example:
  19816. * var option = {
  19817. * baseOption: {
  19818. * title: {...},
  19819. * legend: {...},
  19820. * series: [
  19821. * {data: [...]},
  19822. * {data: [...]},
  19823. * ...
  19824. * ]
  19825. * },
  19826. * timeline: {...},
  19827. * options: [
  19828. * {title: {...}, series: {data: [...]}},
  19829. * {title: {...}, series: {data: [...]}},
  19830. * ...
  19831. * ],
  19832. * media: [
  19833. * {
  19834. * query: {maxWidth: 320},
  19835. * option: {series: {x: 20}, visualMap: {show: false}}
  19836. * },
  19837. * {
  19838. * query: {minWidth: 320, maxWidth: 720},
  19839. * option: {series: {x: 500}, visualMap: {show: true}}
  19840. * },
  19841. * {
  19842. * option: {series: {x: 1200}, visualMap: {show: true}}
  19843. * }
  19844. * ]
  19845. * };
  19846. *
  19847. * @alias module:echarts/model/OptionManager
  19848. * @param {module:echarts/ExtensionAPI} api
  19849. */
  19850. function OptionManager(api) {
  19851. /**
  19852. * @private
  19853. * @type {module:echarts/ExtensionAPI}
  19854. */
  19855. this._api = api;
  19856. /**
  19857. * @private
  19858. * @type {Array.<number>}
  19859. */
  19860. this._timelineOptions = [];
  19861. /**
  19862. * @private
  19863. * @type {Array.<Object>}
  19864. */
  19865. this._mediaList = [];
  19866. /**
  19867. * @private
  19868. * @type {Object}
  19869. */
  19870. this._mediaDefault;
  19871. /**
  19872. * -1, means default.
  19873. * empty means no media.
  19874. * @private
  19875. * @type {Array.<number>}
  19876. */
  19877. this._currentMediaIndices = [];
  19878. /**
  19879. * @private
  19880. * @type {Object}
  19881. */
  19882. this._optionBackup;
  19883. /**
  19884. * @private
  19885. * @type {Object}
  19886. */
  19887. this._newBaseOption;
  19888. }
  19889. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19890. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19891. // rawOption cloned and backuped when timeline changed, which does no
  19892. // good to performance. What's more, that both timeline and setOption
  19893. // method supply 'notMerge' brings complex and some problems.
  19894. // Consider this case:
  19895. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19896. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19897. OptionManager.prototype = {
  19898. constructor: OptionManager,
  19899. /**
  19900. * @public
  19901. * @param {Object} rawOption Raw option.
  19902. * @param {module:echarts/model/Global} ecModel
  19903. * @param {Array.<Function>} optionPreprocessorFuncs
  19904. * @return {Object} Init option
  19905. */
  19906. setOption: function (rawOption, optionPreprocessorFuncs) {
  19907. if (rawOption) {
  19908. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19909. each$1(normalizeToArray(rawOption.series), function (series) {
  19910. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19911. });
  19912. }
  19913. // Caution: some series modify option data, if do not clone,
  19914. // it should ensure that the repeat modify correctly
  19915. // (create a new object when modify itself).
  19916. rawOption = clone$3(rawOption);
  19917. // FIXME
  19918. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19919. var oldOptionBackup = this._optionBackup;
  19920. var newParsedOption = parseRawOption.call(
  19921. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19922. );
  19923. this._newBaseOption = newParsedOption.baseOption;
  19924. // For setOption at second time (using merge mode);
  19925. if (oldOptionBackup) {
  19926. // Only baseOption can be merged.
  19927. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19928. // For simplicity, timeline options and media options do not support merge,
  19929. // that is, if you `setOption` twice and both has timeline options, the latter
  19930. // timeline opitons will not be merged to the formers, but just substitude them.
  19931. if (newParsedOption.timelineOptions.length) {
  19932. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19933. }
  19934. if (newParsedOption.mediaList.length) {
  19935. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19936. }
  19937. if (newParsedOption.mediaDefault) {
  19938. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19939. }
  19940. }
  19941. else {
  19942. this._optionBackup = newParsedOption;
  19943. }
  19944. },
  19945. /**
  19946. * @param {boolean} isRecreate
  19947. * @return {Object}
  19948. */
  19949. mountOption: function (isRecreate) {
  19950. var optionBackup = this._optionBackup;
  19951. // TODO
  19952. // 如果没有reset功能则不clone。
  19953. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19954. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19955. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19956. this._currentMediaIndices = [];
  19957. return clone$3(isRecreate
  19958. // this._optionBackup.baseOption, which is created at the first `setOption`
  19959. // called, and is merged into every new option by inner method `mergeOption`
  19960. // each time `setOption` called, can be only used in `isRecreate`, because
  19961. // its reliability is under suspicion. In other cases option merge is
  19962. // performed by `model.mergeOption`.
  19963. ? optionBackup.baseOption : this._newBaseOption
  19964. );
  19965. },
  19966. /**
  19967. * @param {module:echarts/model/Global} ecModel
  19968. * @return {Object}
  19969. */
  19970. getTimelineOption: function (ecModel) {
  19971. var option;
  19972. var timelineOptions = this._timelineOptions;
  19973. if (timelineOptions.length) {
  19974. // getTimelineOption can only be called after ecModel inited,
  19975. // so we can get currentIndex from timelineModel.
  19976. var timelineModel = ecModel.getComponent('timeline');
  19977. if (timelineModel) {
  19978. option = clone$3(
  19979. timelineOptions[timelineModel.getCurrentIndex()],
  19980. true
  19981. );
  19982. }
  19983. }
  19984. return option;
  19985. },
  19986. /**
  19987. * @param {module:echarts/model/Global} ecModel
  19988. * @return {Array.<Object>}
  19989. */
  19990. getMediaOption: function (ecModel) {
  19991. var ecWidth = this._api.getWidth();
  19992. var ecHeight = this._api.getHeight();
  19993. var mediaList = this._mediaList;
  19994. var mediaDefault = this._mediaDefault;
  19995. var indices = [];
  19996. var result = [];
  19997. // No media defined.
  19998. if (!mediaList.length && !mediaDefault) {
  19999. return result;
  20000. }
  20001. // Multi media may be applied, the latter defined media has higher priority.
  20002. for (var i = 0, len = mediaList.length; i < len; i++) {
  20003. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  20004. indices.push(i);
  20005. }
  20006. }
  20007. // FIXME
  20008. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  20009. if (!indices.length && mediaDefault) {
  20010. indices = [-1];
  20011. }
  20012. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  20013. result = map$1(indices, function (index) {
  20014. return clone$3(
  20015. index === -1 ? mediaDefault.option : mediaList[index].option
  20016. );
  20017. });
  20018. }
  20019. // Otherwise return nothing.
  20020. this._currentMediaIndices = indices;
  20021. return result;
  20022. }
  20023. };
  20024. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  20025. var timelineOptions = [];
  20026. var mediaList = [];
  20027. var mediaDefault;
  20028. var baseOption;
  20029. // Compatible with ec2.
  20030. var timelineOpt = rawOption.timeline;
  20031. if (rawOption.baseOption) {
  20032. baseOption = rawOption.baseOption;
  20033. }
  20034. // For timeline
  20035. if (timelineOpt || rawOption.options) {
  20036. baseOption = baseOption || {};
  20037. timelineOptions = (rawOption.options || []).slice();
  20038. }
  20039. // For media query
  20040. if (rawOption.media) {
  20041. baseOption = baseOption || {};
  20042. var media = rawOption.media;
  20043. each$4(media, function (singleMedia) {
  20044. if (singleMedia && singleMedia.option) {
  20045. if (singleMedia.query) {
  20046. mediaList.push(singleMedia);
  20047. }
  20048. else if (!mediaDefault) {
  20049. // Use the first media default.
  20050. mediaDefault = singleMedia;
  20051. }
  20052. }
  20053. });
  20054. }
  20055. // For normal option
  20056. if (!baseOption) {
  20057. baseOption = rawOption;
  20058. }
  20059. // Set timelineOpt to baseOption in ec3,
  20060. // which is convenient for merge option.
  20061. if (!baseOption.timeline) {
  20062. baseOption.timeline = timelineOpt;
  20063. }
  20064. // Preprocess.
  20065. each$4([baseOption].concat(timelineOptions)
  20066. .concat(map(mediaList, function (media) {
  20067. return media.option;
  20068. })),
  20069. function (option) {
  20070. each$4(optionPreprocessorFuncs, function (preProcess) {
  20071. preProcess(option, isNew);
  20072. });
  20073. }
  20074. );
  20075. return {
  20076. baseOption: baseOption,
  20077. timelineOptions: timelineOptions,
  20078. mediaDefault: mediaDefault,
  20079. mediaList: mediaList
  20080. };
  20081. }
  20082. /**
  20083. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  20084. * Support: width, height, aspectRatio
  20085. * Can use max or min as prefix.
  20086. */
  20087. function applyMediaQuery(query, ecWidth, ecHeight) {
  20088. var realMap = {
  20089. width: ecWidth,
  20090. height: ecHeight,
  20091. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  20092. };
  20093. var applicatable = true;
  20094. each$1(query, function (value, attr) {
  20095. var matched = attr.match(QUERY_REG);
  20096. if (!matched || !matched[1] || !matched[2]) {
  20097. return;
  20098. }
  20099. var operator = matched[1];
  20100. var realAttr = matched[2].toLowerCase();
  20101. if (!compare(realMap[realAttr], value, operator)) {
  20102. applicatable = false;
  20103. }
  20104. });
  20105. return applicatable;
  20106. }
  20107. function compare(real, expect, operator) {
  20108. if (operator === 'min') {
  20109. return real >= expect;
  20110. }
  20111. else if (operator === 'max') {
  20112. return real <= expect;
  20113. }
  20114. else { // Equals
  20115. return real === expect;
  20116. }
  20117. }
  20118. function indicesEquals(indices1, indices2) {
  20119. // indices is always order by asc and has only finite number.
  20120. return indices1.join(',') === indices2.join(',');
  20121. }
  20122. /**
  20123. * Consider case:
  20124. * `chart.setOption(opt1);`
  20125. * Then user do some interaction like dataZoom, dataView changing.
  20126. * `chart.setOption(opt2);`
  20127. * Then user press 'reset button' in toolbox.
  20128. *
  20129. * After doing that all of the interaction effects should be reset, the
  20130. * chart should be the same as the result of invoke
  20131. * `chart.setOption(opt1); chart.setOption(opt2);`.
  20132. *
  20133. * Although it is not able ensure that
  20134. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  20135. * `chart.setOption(merge(opt1, opt2));` exactly,
  20136. * this might be the only simple way to implement that feature.
  20137. *
  20138. * MEMO: We've considered some other approaches:
  20139. * 1. Each model handle its self restoration but not uniform treatment.
  20140. * (Too complex in logic and error-prone)
  20141. * 2. Use a shadow ecModel. (Performace expensive)
  20142. */
  20143. function mergeOption(oldOption, newOption) {
  20144. newOption = newOption || {};
  20145. each$4(newOption, function (newCptOpt, mainType) {
  20146. if (newCptOpt == null) {
  20147. return;
  20148. }
  20149. var oldCptOpt = oldOption[mainType];
  20150. if (!ComponentModel.hasClass(mainType)) {
  20151. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  20152. }
  20153. else {
  20154. newCptOpt = normalizeToArray(newCptOpt);
  20155. oldCptOpt = normalizeToArray(oldCptOpt);
  20156. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  20157. oldOption[mainType] = map$1(mapResult, function (item) {
  20158. return (item.option && item.exist)
  20159. ? merge$1(item.exist, item.option, true)
  20160. : (item.exist || item.option);
  20161. });
  20162. }
  20163. });
  20164. }
  20165. /*
  20166. * Licensed to the Apache Software Foundation (ASF) under one
  20167. * or more contributor license agreements. See the NOTICE file
  20168. * distributed with this work for additional information
  20169. * regarding copyright ownership. The ASF licenses this file
  20170. * to you under the Apache License, Version 2.0 (the
  20171. * "License"); you may not use this file except in compliance
  20172. * with the License. You may obtain a copy of the License at
  20173. *
  20174. * http://www.apache.org/licenses/LICENSE-2.0
  20175. *
  20176. * Unless required by applicable law or agreed to in writing,
  20177. * software distributed under the License is distributed on an
  20178. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20179. * KIND, either express or implied. See the License for the
  20180. * specific language governing permissions and limitations
  20181. * under the License.
  20182. */
  20183. var each$5 = each$1;
  20184. var isObject$3 = isObject$1;
  20185. var POSSIBLE_STYLES = [
  20186. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  20187. 'chordStyle', 'label', 'labelLine'
  20188. ];
  20189. function compatEC2ItemStyle(opt) {
  20190. var itemStyleOpt = opt && opt.itemStyle;
  20191. if (!itemStyleOpt) {
  20192. return;
  20193. }
  20194. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  20195. var styleName = POSSIBLE_STYLES[i];
  20196. var normalItemStyleOpt = itemStyleOpt.normal;
  20197. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  20198. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  20199. opt[styleName] = opt[styleName] || {};
  20200. if (!opt[styleName].normal) {
  20201. opt[styleName].normal = normalItemStyleOpt[styleName];
  20202. }
  20203. else {
  20204. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  20205. }
  20206. normalItemStyleOpt[styleName] = null;
  20207. }
  20208. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  20209. opt[styleName] = opt[styleName] || {};
  20210. if (!opt[styleName].emphasis) {
  20211. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  20212. }
  20213. else {
  20214. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  20215. }
  20216. emphasisItemStyleOpt[styleName] = null;
  20217. }
  20218. }
  20219. }
  20220. function convertNormalEmphasis(opt, optType, useExtend) {
  20221. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  20222. var normalOpt = opt[optType].normal;
  20223. var emphasisOpt = opt[optType].emphasis;
  20224. if (normalOpt) {
  20225. // Timeline controlStyle has other properties besides normal and emphasis
  20226. if (useExtend) {
  20227. opt[optType].normal = opt[optType].emphasis = null;
  20228. defaults(opt[optType], normalOpt);
  20229. }
  20230. else {
  20231. opt[optType] = normalOpt;
  20232. }
  20233. }
  20234. if (emphasisOpt) {
  20235. opt.emphasis = opt.emphasis || {};
  20236. opt.emphasis[optType] = emphasisOpt;
  20237. }
  20238. }
  20239. }
  20240. function removeEC3NormalStatus(opt) {
  20241. convertNormalEmphasis(opt, 'itemStyle');
  20242. convertNormalEmphasis(opt, 'lineStyle');
  20243. convertNormalEmphasis(opt, 'areaStyle');
  20244. convertNormalEmphasis(opt, 'label');
  20245. convertNormalEmphasis(opt, 'labelLine');
  20246. // treemap
  20247. convertNormalEmphasis(opt, 'upperLabel');
  20248. // graph
  20249. convertNormalEmphasis(opt, 'edgeLabel');
  20250. }
  20251. function compatTextStyle(opt, propName) {
  20252. // Check whether is not object (string\null\undefined ...)
  20253. var labelOptSingle = isObject$3(opt) && opt[propName];
  20254. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  20255. if (textStyle) {
  20256. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  20257. var propName = TEXT_STYLE_OPTIONS[i];
  20258. if (textStyle.hasOwnProperty(propName)) {
  20259. labelOptSingle[propName] = textStyle[propName];
  20260. }
  20261. }
  20262. }
  20263. }
  20264. function compatEC3CommonStyles(opt) {
  20265. if (opt) {
  20266. removeEC3NormalStatus(opt);
  20267. compatTextStyle(opt, 'label');
  20268. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  20269. }
  20270. }
  20271. function processSeries(seriesOpt) {
  20272. if (!isObject$3(seriesOpt)) {
  20273. return;
  20274. }
  20275. compatEC2ItemStyle(seriesOpt);
  20276. removeEC3NormalStatus(seriesOpt);
  20277. compatTextStyle(seriesOpt, 'label');
  20278. // treemap
  20279. compatTextStyle(seriesOpt, 'upperLabel');
  20280. // graph
  20281. compatTextStyle(seriesOpt, 'edgeLabel');
  20282. if (seriesOpt.emphasis) {
  20283. compatTextStyle(seriesOpt.emphasis, 'label');
  20284. // treemap
  20285. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  20286. // graph
  20287. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  20288. }
  20289. var markPoint = seriesOpt.markPoint;
  20290. if (markPoint) {
  20291. compatEC2ItemStyle(markPoint);
  20292. compatEC3CommonStyles(markPoint);
  20293. }
  20294. var markLine = seriesOpt.markLine;
  20295. if (markLine) {
  20296. compatEC2ItemStyle(markLine);
  20297. compatEC3CommonStyles(markLine);
  20298. }
  20299. var markArea = seriesOpt.markArea;
  20300. if (markArea) {
  20301. compatEC3CommonStyles(markArea);
  20302. }
  20303. var data = seriesOpt.data;
  20304. // Break with ec3: if `setOption` again, there may be no `type` in option,
  20305. // then the backward compat based on option type will not be performed.
  20306. if (seriesOpt.type === 'graph') {
  20307. data = data || seriesOpt.nodes;
  20308. var edgeData = seriesOpt.links || seriesOpt.edges;
  20309. if (edgeData && !isTypedArray(edgeData)) {
  20310. for (var i = 0; i < edgeData.length; i++) {
  20311. compatEC3CommonStyles(edgeData[i]);
  20312. }
  20313. }
  20314. each$1(seriesOpt.categories, function (opt) {
  20315. removeEC3NormalStatus(opt);
  20316. });
  20317. }
  20318. if (data && !isTypedArray(data)) {
  20319. for (var i = 0; i < data.length; i++) {
  20320. compatEC3CommonStyles(data[i]);
  20321. }
  20322. }
  20323. // mark point data
  20324. var markPoint = seriesOpt.markPoint;
  20325. if (markPoint && markPoint.data) {
  20326. var mpData = markPoint.data;
  20327. for (var i = 0; i < mpData.length; i++) {
  20328. compatEC3CommonStyles(mpData[i]);
  20329. }
  20330. }
  20331. // mark line data
  20332. var markLine = seriesOpt.markLine;
  20333. if (markLine && markLine.data) {
  20334. var mlData = markLine.data;
  20335. for (var i = 0; i < mlData.length; i++) {
  20336. if (isArray(mlData[i])) {
  20337. compatEC3CommonStyles(mlData[i][0]);
  20338. compatEC3CommonStyles(mlData[i][1]);
  20339. }
  20340. else {
  20341. compatEC3CommonStyles(mlData[i]);
  20342. }
  20343. }
  20344. }
  20345. // Series
  20346. if (seriesOpt.type === 'gauge') {
  20347. compatTextStyle(seriesOpt, 'axisLabel');
  20348. compatTextStyle(seriesOpt, 'title');
  20349. compatTextStyle(seriesOpt, 'detail');
  20350. }
  20351. else if (seriesOpt.type === 'treemap') {
  20352. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  20353. each$1(seriesOpt.levels, function (opt) {
  20354. removeEC3NormalStatus(opt);
  20355. });
  20356. }
  20357. else if (seriesOpt.type === 'tree') {
  20358. removeEC3NormalStatus(seriesOpt.leaves);
  20359. }
  20360. // sunburst starts from ec4, so it does not need to compat levels.
  20361. }
  20362. function toArr(o) {
  20363. return isArray(o) ? o : o ? [o] : [];
  20364. }
  20365. function toObj(o) {
  20366. return (isArray(o) ? o[0] : o) || {};
  20367. }
  20368. var compatStyle = function (option, isTheme) {
  20369. each$5(toArr(option.series), function (seriesOpt) {
  20370. isObject$3(seriesOpt) && processSeries(seriesOpt);
  20371. });
  20372. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  20373. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  20374. each$5(
  20375. axes,
  20376. function (axisName) {
  20377. each$5(toArr(option[axisName]), function (axisOpt) {
  20378. if (axisOpt) {
  20379. compatTextStyle(axisOpt, 'axisLabel');
  20380. compatTextStyle(axisOpt.axisPointer, 'label');
  20381. }
  20382. });
  20383. }
  20384. );
  20385. each$5(toArr(option.parallel), function (parallelOpt) {
  20386. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  20387. compatTextStyle(parallelAxisDefault, 'axisLabel');
  20388. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  20389. });
  20390. each$5(toArr(option.calendar), function (calendarOpt) {
  20391. convertNormalEmphasis(calendarOpt, 'itemStyle');
  20392. compatTextStyle(calendarOpt, 'dayLabel');
  20393. compatTextStyle(calendarOpt, 'monthLabel');
  20394. compatTextStyle(calendarOpt, 'yearLabel');
  20395. });
  20396. // radar.name.textStyle
  20397. each$5(toArr(option.radar), function (radarOpt) {
  20398. compatTextStyle(radarOpt, 'name');
  20399. });
  20400. each$5(toArr(option.geo), function (geoOpt) {
  20401. if (isObject$3(geoOpt)) {
  20402. compatEC3CommonStyles(geoOpt);
  20403. each$5(toArr(geoOpt.regions), function (regionObj) {
  20404. compatEC3CommonStyles(regionObj);
  20405. });
  20406. }
  20407. });
  20408. each$5(toArr(option.timeline), function (timelineOpt) {
  20409. compatEC3CommonStyles(timelineOpt);
  20410. convertNormalEmphasis(timelineOpt, 'label');
  20411. convertNormalEmphasis(timelineOpt, 'itemStyle');
  20412. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  20413. var data = timelineOpt.data;
  20414. isArray(data) && each$1(data, function (item) {
  20415. if (isObject$1(item)) {
  20416. convertNormalEmphasis(item, 'label');
  20417. convertNormalEmphasis(item, 'itemStyle');
  20418. }
  20419. });
  20420. });
  20421. each$5(toArr(option.toolbox), function (toolboxOpt) {
  20422. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  20423. each$5(toolboxOpt.feature, function (featureOpt) {
  20424. convertNormalEmphasis(featureOpt, 'iconStyle');
  20425. });
  20426. });
  20427. compatTextStyle(toObj(option.axisPointer), 'label');
  20428. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  20429. };
  20430. /*
  20431. * Licensed to the Apache Software Foundation (ASF) under one
  20432. * or more contributor license agreements. See the NOTICE file
  20433. * distributed with this work for additional information
  20434. * regarding copyright ownership. The ASF licenses this file
  20435. * to you under the Apache License, Version 2.0 (the
  20436. * "License"); you may not use this file except in compliance
  20437. * with the License. You may obtain a copy of the License at
  20438. *
  20439. * http://www.apache.org/licenses/LICENSE-2.0
  20440. *
  20441. * Unless required by applicable law or agreed to in writing,
  20442. * software distributed under the License is distributed on an
  20443. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20444. * KIND, either express or implied. See the License for the
  20445. * specific language governing permissions and limitations
  20446. * under the License.
  20447. */
  20448. // Compatitable with 2.0
  20449. function get(opt, path) {
  20450. path = path.split(',');
  20451. var obj = opt;
  20452. for (var i = 0; i < path.length; i++) {
  20453. obj = obj && obj[path[i]];
  20454. if (obj == null) {
  20455. break;
  20456. }
  20457. }
  20458. return obj;
  20459. }
  20460. function set$1(opt, path, val, overwrite) {
  20461. path = path.split(',');
  20462. var obj = opt;
  20463. var key;
  20464. for (var i = 0; i < path.length - 1; i++) {
  20465. key = path[i];
  20466. if (obj[key] == null) {
  20467. obj[key] = {};
  20468. }
  20469. obj = obj[key];
  20470. }
  20471. if (overwrite || obj[path[i]] == null) {
  20472. obj[path[i]] = val;
  20473. }
  20474. }
  20475. function compatLayoutProperties(option) {
  20476. each$1(LAYOUT_PROPERTIES, function (prop) {
  20477. if (prop[0] in option && !(prop[1] in option)) {
  20478. option[prop[1]] = option[prop[0]];
  20479. }
  20480. });
  20481. }
  20482. var LAYOUT_PROPERTIES = [
  20483. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  20484. ];
  20485. var COMPATITABLE_COMPONENTS = [
  20486. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  20487. ];
  20488. var backwardCompat = function (option, isTheme) {
  20489. compatStyle(option, isTheme);
  20490. // Make sure series array for model initialization.
  20491. option.series = normalizeToArray(option.series);
  20492. each$1(option.series, function (seriesOpt) {
  20493. if (!isObject$1(seriesOpt)) {
  20494. return;
  20495. }
  20496. var seriesType = seriesOpt.type;
  20497. if (seriesType === 'line') {
  20498. if (seriesOpt.clipOverflow != null) {
  20499. seriesOpt.clip = seriesOpt.clipOverflow;
  20500. }
  20501. }
  20502. else if (seriesType === 'pie' || seriesType === 'gauge') {
  20503. if (seriesOpt.clockWise != null) {
  20504. seriesOpt.clockwise = seriesOpt.clockWise;
  20505. }
  20506. }
  20507. else if (seriesType === 'gauge') {
  20508. var pointerColor = get(seriesOpt, 'pointer.color');
  20509. pointerColor != null
  20510. && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  20511. }
  20512. compatLayoutProperties(seriesOpt);
  20513. });
  20514. // dataRange has changed to visualMap
  20515. if (option.dataRange) {
  20516. option.visualMap = option.dataRange;
  20517. }
  20518. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  20519. var options = option[componentName];
  20520. if (options) {
  20521. if (!isArray(options)) {
  20522. options = [options];
  20523. }
  20524. each$1(options, function (option) {
  20525. compatLayoutProperties(option);
  20526. });
  20527. }
  20528. });
  20529. };
  20530. /*
  20531. * Licensed to the Apache Software Foundation (ASF) under one
  20532. * or more contributor license agreements. See the NOTICE file
  20533. * distributed with this work for additional information
  20534. * regarding copyright ownership. The ASF licenses this file
  20535. * to you under the Apache License, Version 2.0 (the
  20536. * "License"); you may not use this file except in compliance
  20537. * with the License. You may obtain a copy of the License at
  20538. *
  20539. * http://www.apache.org/licenses/LICENSE-2.0
  20540. *
  20541. * Unless required by applicable law or agreed to in writing,
  20542. * software distributed under the License is distributed on an
  20543. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20544. * KIND, either express or implied. See the License for the
  20545. * specific language governing permissions and limitations
  20546. * under the License.
  20547. */
  20548. // (1) [Caution]: the logic is correct based on the premises:
  20549. // data processing stage is blocked in stream.
  20550. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  20551. // (2) Only register once when import repeatly.
  20552. // Should be executed after series filtered and before stack calculation.
  20553. var dataStack = function (ecModel) {
  20554. var stackInfoMap = createHashMap();
  20555. ecModel.eachSeries(function (seriesModel) {
  20556. var stack = seriesModel.get('stack');
  20557. // Compatibal: when `stack` is set as '', do not stack.
  20558. if (stack) {
  20559. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  20560. var data = seriesModel.getData();
  20561. var stackInfo = {
  20562. // Used for calculate axis extent automatically.
  20563. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  20564. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  20565. stackedDimension: data.getCalculationInfo('stackedDimension'),
  20566. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  20567. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  20568. data: data,
  20569. seriesModel: seriesModel
  20570. };
  20571. // If stacked on axis that do not support data stack.
  20572. if (!stackInfo.stackedDimension
  20573. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  20574. ) {
  20575. return;
  20576. }
  20577. stackInfoList.length && data.setCalculationInfo(
  20578. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  20579. );
  20580. stackInfoList.push(stackInfo);
  20581. }
  20582. });
  20583. stackInfoMap.each(calculateStack);
  20584. };
  20585. function calculateStack(stackInfoList) {
  20586. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  20587. var resultVal = [];
  20588. var resultNaN = [NaN, NaN];
  20589. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  20590. var targetData = targetStackInfo.data;
  20591. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  20592. // Should not write on raw data, because stack series model list changes
  20593. // depending on legend selection.
  20594. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  20595. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  20596. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  20597. // should also be NaN, to draw a appropriate belt area.
  20598. if (isNaN(sum)) {
  20599. return resultNaN;
  20600. }
  20601. var byValue;
  20602. var stackedDataRawIndex;
  20603. if (isStackedByIndex) {
  20604. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  20605. }
  20606. else {
  20607. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  20608. }
  20609. // If stackOver is NaN, chart view will render point on value start.
  20610. var stackedOver = NaN;
  20611. for (var j = idxInStack - 1; j >= 0; j--) {
  20612. var stackInfo = stackInfoList[j];
  20613. // Has been optimized by inverted indices on `stackedByDimension`.
  20614. if (!isStackedByIndex) {
  20615. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  20616. }
  20617. if (stackedDataRawIndex >= 0) {
  20618. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  20619. // Considering positive stack, negative stack and empty data
  20620. if ((sum >= 0 && val > 0) // Positive stack
  20621. || (sum <= 0 && val < 0) // Negative stack
  20622. ) {
  20623. sum += val;
  20624. stackedOver = val;
  20625. break;
  20626. }
  20627. }
  20628. }
  20629. resultVal[0] = sum;
  20630. resultVal[1] = stackedOver;
  20631. return resultVal;
  20632. });
  20633. targetData.hostModel.setData(newData);
  20634. // Update for consequent calculation
  20635. targetStackInfo.data = newData;
  20636. });
  20637. }
  20638. /*
  20639. * Licensed to the Apache Software Foundation (ASF) under one
  20640. * or more contributor license agreements. See the NOTICE file
  20641. * distributed with this work for additional information
  20642. * regarding copyright ownership. The ASF licenses this file
  20643. * to you under the Apache License, Version 2.0 (the
  20644. * "License"); you may not use this file except in compliance
  20645. * with the License. You may obtain a copy of the License at
  20646. *
  20647. * http://www.apache.org/licenses/LICENSE-2.0
  20648. *
  20649. * Unless required by applicable law or agreed to in writing,
  20650. * software distributed under the License is distributed on an
  20651. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20652. * KIND, either express or implied. See the License for the
  20653. * specific language governing permissions and limitations
  20654. * under the License.
  20655. */
  20656. // TODO
  20657. // ??? refactor? check the outer usage of data provider.
  20658. // merge with defaultDimValueGetter?
  20659. /**
  20660. * If normal array used, mutable chunk size is supported.
  20661. * If typed array used, chunk size must be fixed.
  20662. */
  20663. function DefaultDataProvider(source, dimSize) {
  20664. if (!Source.isInstance(source)) {
  20665. source = Source.seriesDataToSource(source);
  20666. }
  20667. this._source = source;
  20668. var data = this._data = source.data;
  20669. var sourceFormat = source.sourceFormat;
  20670. // Typed array. TODO IE10+?
  20671. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20672. if (__DEV__) {
  20673. if (dimSize == null) {
  20674. throw new Error('Typed array data must specify dimension size');
  20675. }
  20676. }
  20677. this._offset = 0;
  20678. this._dimSize = dimSize;
  20679. this._data = data;
  20680. }
  20681. var methods = providerMethods[
  20682. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  20683. ? sourceFormat + '_' + source.seriesLayoutBy
  20684. : sourceFormat
  20685. ];
  20686. if (__DEV__) {
  20687. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20688. }
  20689. extend(this, methods);
  20690. }
  20691. var providerProto = DefaultDataProvider.prototype;
  20692. // If data is pure without style configuration
  20693. providerProto.pure = false;
  20694. // If data is persistent and will not be released after use.
  20695. providerProto.persistent = true;
  20696. // ???! FIXME legacy data provider do not has method getSource
  20697. providerProto.getSource = function () {
  20698. return this._source;
  20699. };
  20700. var providerMethods = {
  20701. 'arrayRows_column': {
  20702. pure: true,
  20703. count: function () {
  20704. return Math.max(0, this._data.length - this._source.startIndex);
  20705. },
  20706. getItem: function (idx) {
  20707. return this._data[idx + this._source.startIndex];
  20708. },
  20709. appendData: appendDataSimply
  20710. },
  20711. 'arrayRows_row': {
  20712. pure: true,
  20713. count: function () {
  20714. var row = this._data[0];
  20715. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  20716. },
  20717. getItem: function (idx) {
  20718. idx += this._source.startIndex;
  20719. var item = [];
  20720. var data = this._data;
  20721. for (var i = 0; i < data.length; i++) {
  20722. var row = data[i];
  20723. item.push(row ? row[idx] : null);
  20724. }
  20725. return item;
  20726. },
  20727. appendData: function () {
  20728. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20729. }
  20730. },
  20731. 'objectRows': {
  20732. pure: true,
  20733. count: countSimply,
  20734. getItem: getItemSimply,
  20735. appendData: appendDataSimply
  20736. },
  20737. 'keyedColumns': {
  20738. pure: true,
  20739. count: function () {
  20740. var dimName = this._source.dimensionsDefine[0].name;
  20741. var col = this._data[dimName];
  20742. return col ? col.length : 0;
  20743. },
  20744. getItem: function (idx) {
  20745. var item = [];
  20746. var dims = this._source.dimensionsDefine;
  20747. for (var i = 0; i < dims.length; i++) {
  20748. var col = this._data[dims[i].name];
  20749. item.push(col ? col[idx] : null);
  20750. }
  20751. return item;
  20752. },
  20753. appendData: function (newData) {
  20754. var data = this._data;
  20755. each$1(newData, function (newCol, key) {
  20756. var oldCol = data[key] || (data[key] = []);
  20757. for (var i = 0; i < (newCol || []).length; i++) {
  20758. oldCol.push(newCol[i]);
  20759. }
  20760. });
  20761. }
  20762. },
  20763. 'original': {
  20764. count: countSimply,
  20765. getItem: getItemSimply,
  20766. appendData: appendDataSimply
  20767. },
  20768. 'typedArray': {
  20769. persistent: false,
  20770. pure: true,
  20771. count: function () {
  20772. return this._data ? (this._data.length / this._dimSize) : 0;
  20773. },
  20774. getItem: function (idx, out) {
  20775. idx = idx - this._offset;
  20776. out = out || [];
  20777. var offset = this._dimSize * idx;
  20778. for (var i = 0; i < this._dimSize; i++) {
  20779. out[i] = this._data[offset + i];
  20780. }
  20781. return out;
  20782. },
  20783. appendData: function (newData) {
  20784. if (__DEV__) {
  20785. assert$1(
  20786. isTypedArray(newData),
  20787. 'Added data must be TypedArray if data in initialization is TypedArray'
  20788. );
  20789. }
  20790. this._data = newData;
  20791. },
  20792. // Clean self if data is already used.
  20793. clean: function () {
  20794. // PENDING
  20795. this._offset += this.count();
  20796. this._data = null;
  20797. }
  20798. }
  20799. };
  20800. function countSimply() {
  20801. return this._data.length;
  20802. }
  20803. function getItemSimply(idx) {
  20804. return this._data[idx];
  20805. }
  20806. function appendDataSimply(newData) {
  20807. for (var i = 0; i < newData.length; i++) {
  20808. this._data.push(newData[i]);
  20809. }
  20810. }
  20811. var rawValueGetters = {
  20812. arrayRows: getRawValueSimply,
  20813. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20814. return dimIndex != null ? dataItem[dimName] : dataItem;
  20815. },
  20816. keyedColumns: getRawValueSimply,
  20817. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20818. // FIXME
  20819. // In some case (markpoint in geo (geo-map.html)), dataItem
  20820. // is {coord: [...]}
  20821. var value = getDataItemValue(dataItem);
  20822. return (dimIndex == null || !(value instanceof Array))
  20823. ? value
  20824. : value[dimIndex];
  20825. },
  20826. typedArray: getRawValueSimply
  20827. };
  20828. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20829. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20830. }
  20831. var defaultDimValueGetters = {
  20832. arrayRows: getDimValueSimply,
  20833. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20834. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20835. },
  20836. keyedColumns: getDimValueSimply,
  20837. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20838. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20839. // If dataItem is an plain object with no value field, the var `value`
  20840. // will be assigned with the object, but it will be tread correctly
  20841. // in the `convertDataValue`.
  20842. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20843. // If any dataItem is like { value: 10 }
  20844. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20845. this.hasItemOption = true;
  20846. }
  20847. return converDataValue(
  20848. (value instanceof Array)
  20849. ? value[dimIndex]
  20850. // If value is a single number or something else not array.
  20851. : value,
  20852. this._dimensionInfos[dimName]
  20853. );
  20854. },
  20855. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20856. return dataItem[dimIndex];
  20857. }
  20858. };
  20859. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20860. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20861. }
  20862. /**
  20863. * This helper method convert value in data.
  20864. * @param {string|number|Date} value
  20865. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20866. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20867. */
  20868. function converDataValue(value, dimInfo) {
  20869. // Performance sensitive.
  20870. var dimType = dimInfo && dimInfo.type;
  20871. if (dimType === 'ordinal') {
  20872. // If given value is a category string
  20873. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20874. return ordinalMeta
  20875. ? ordinalMeta.parseAndCollect(value)
  20876. : value;
  20877. }
  20878. if (dimType === 'time'
  20879. // spead up when using timestamp
  20880. && typeof value !== 'number'
  20881. && value != null
  20882. && value !== '-'
  20883. ) {
  20884. value = +parseDate(value);
  20885. }
  20886. // dimType defaults 'number'.
  20887. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20888. // parse to NaN.
  20889. return (value == null || value === '')
  20890. ? NaN
  20891. // If string (like '-'), using '+' parse to NaN
  20892. // If object, also parse to NaN
  20893. : +value;
  20894. }
  20895. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20896. // Consider persistent.
  20897. // Caution: why use raw value to display on label or tooltip?
  20898. // A reason is to avoid format. For example time value we do not know
  20899. // how to format is expected. More over, if stack is used, calculated
  20900. // value may be 0.91000000001, which have brings trouble to display.
  20901. // TODO: consider how to treat null/undefined/NaN when display?
  20902. /**
  20903. * @param {module:echarts/data/List} data
  20904. * @param {number} dataIndex
  20905. * @param {string|number} [dim] dimName or dimIndex
  20906. * @return {Array.<number>|string|number} can be null/undefined.
  20907. */
  20908. function retrieveRawValue(data, dataIndex, dim) {
  20909. if (!data) {
  20910. return;
  20911. }
  20912. // Consider data may be not persistent.
  20913. var dataItem = data.getRawDataItem(dataIndex);
  20914. if (dataItem == null) {
  20915. return;
  20916. }
  20917. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20918. var dimName;
  20919. var dimIndex;
  20920. var dimInfo = data.getDimensionInfo(dim);
  20921. if (dimInfo) {
  20922. dimName = dimInfo.name;
  20923. dimIndex = dimInfo.index;
  20924. }
  20925. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20926. }
  20927. /**
  20928. * Compatible with some cases (in pie, map) like:
  20929. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20930. * where only sourceFormat is 'original' and 'objectRows' supported.
  20931. *
  20932. * ??? TODO
  20933. * Supported detail options in data item when using 'arrayRows'.
  20934. *
  20935. * @param {module:echarts/data/List} data
  20936. * @param {number} dataIndex
  20937. * @param {string} attr like 'selected'
  20938. */
  20939. function retrieveRawAttr(data, dataIndex, attr) {
  20940. if (!data) {
  20941. return;
  20942. }
  20943. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20944. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20945. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20946. ) {
  20947. return;
  20948. }
  20949. var dataItem = data.getRawDataItem(dataIndex);
  20950. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20951. dataItem = null;
  20952. }
  20953. if (dataItem) {
  20954. return dataItem[attr];
  20955. }
  20956. }
  20957. /*
  20958. * Licensed to the Apache Software Foundation (ASF) under one
  20959. * or more contributor license agreements. See the NOTICE file
  20960. * distributed with this work for additional information
  20961. * regarding copyright ownership. The ASF licenses this file
  20962. * to you under the Apache License, Version 2.0 (the
  20963. * "License"); you may not use this file except in compliance
  20964. * with the License. You may obtain a copy of the License at
  20965. *
  20966. * http://www.apache.org/licenses/LICENSE-2.0
  20967. *
  20968. * Unless required by applicable law or agreed to in writing,
  20969. * software distributed under the License is distributed on an
  20970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20971. * KIND, either express or implied. See the License for the
  20972. * specific language governing permissions and limitations
  20973. * under the License.
  20974. */
  20975. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20976. // PENDING A little ugly
  20977. var dataFormatMixin = {
  20978. /**
  20979. * Get params for formatter
  20980. * @param {number} dataIndex
  20981. * @param {string} [dataType]
  20982. * @return {Object}
  20983. */
  20984. getDataParams: function (dataIndex, dataType) {
  20985. var data = this.getData(dataType);
  20986. var rawValue = this.getRawValue(dataIndex, dataType);
  20987. var rawDataIndex = data.getRawIndex(dataIndex);
  20988. var name = data.getName(dataIndex);
  20989. var itemOpt = data.getRawDataItem(dataIndex);
  20990. var color = data.getItemVisual(dataIndex, 'color');
  20991. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  20992. var tooltipModel = this.ecModel.getComponent('tooltip');
  20993. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20994. var renderMode = getTooltipRenderMode(renderModeOption);
  20995. var mainType = this.mainType;
  20996. var isSeries = mainType === 'series';
  20997. var userOutput = data.userOutput;
  20998. return {
  20999. componentType: mainType,
  21000. componentSubType: this.subType,
  21001. componentIndex: this.componentIndex,
  21002. seriesType: isSeries ? this.subType : null,
  21003. seriesIndex: this.seriesIndex,
  21004. seriesId: isSeries ? this.id : null,
  21005. seriesName: isSeries ? this.name : null,
  21006. name: name,
  21007. dataIndex: rawDataIndex,
  21008. data: itemOpt,
  21009. dataType: dataType,
  21010. value: rawValue,
  21011. color: color,
  21012. borderColor: borderColor,
  21013. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  21014. encode: userOutput ? userOutput.encode : null,
  21015. marker: getTooltipMarker({
  21016. color: color,
  21017. renderMode: renderMode
  21018. }),
  21019. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  21020. $vars: ['seriesName', 'name', 'value']
  21021. };
  21022. },
  21023. /**
  21024. * Format label
  21025. * @param {number} dataIndex
  21026. * @param {string} [status='normal'] 'normal' or 'emphasis'
  21027. * @param {string} [dataType]
  21028. * @param {number} [dimIndex] Only used in some chart that
  21029. * use formatter in different dimensions, like radar.
  21030. * @param {string} [labelProp='label']
  21031. * @return {string} If not formatter, return null/undefined
  21032. */
  21033. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  21034. status = status || 'normal';
  21035. var data = this.getData(dataType);
  21036. var itemModel = data.getItemModel(dataIndex);
  21037. var params = this.getDataParams(dataIndex, dataType);
  21038. if (dimIndex != null && (params.value instanceof Array)) {
  21039. params.value = params.value[dimIndex];
  21040. }
  21041. var formatter = itemModel.get(
  21042. status === 'normal'
  21043. ? [labelProp || 'label', 'formatter']
  21044. : [status, labelProp || 'label', 'formatter']
  21045. );
  21046. if (typeof formatter === 'function') {
  21047. params.status = status;
  21048. params.dimensionIndex = dimIndex;
  21049. return formatter(params);
  21050. }
  21051. else if (typeof formatter === 'string') {
  21052. var str = formatTpl(formatter, params);
  21053. // Support 'aaa{@[3]}bbb{@product}ccc'.
  21054. // Do not support '}' in dim name util have to.
  21055. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  21056. var len = dim.length;
  21057. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  21058. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  21059. }
  21060. return retrieveRawValue(data, dataIndex, dim);
  21061. });
  21062. }
  21063. },
  21064. /**
  21065. * Get raw value in option
  21066. * @param {number} idx
  21067. * @param {string} [dataType]
  21068. * @return {Array|number|string}
  21069. */
  21070. getRawValue: function (idx, dataType) {
  21071. return retrieveRawValue(this.getData(dataType), idx);
  21072. },
  21073. /**
  21074. * Should be implemented.
  21075. * @param {number} dataIndex
  21076. * @param {boolean} [multipleSeries=false]
  21077. * @param {number} [dataType]
  21078. * @return {string} tooltip string
  21079. */
  21080. formatTooltip: function () {
  21081. // Empty function
  21082. }
  21083. };
  21084. /*
  21085. * Licensed to the Apache Software Foundation (ASF) under one
  21086. * or more contributor license agreements. See the NOTICE file
  21087. * distributed with this work for additional information
  21088. * regarding copyright ownership. The ASF licenses this file
  21089. * to you under the Apache License, Version 2.0 (the
  21090. * "License"); you may not use this file except in compliance
  21091. * with the License. You may obtain a copy of the License at
  21092. *
  21093. * http://www.apache.org/licenses/LICENSE-2.0
  21094. *
  21095. * Unless required by applicable law or agreed to in writing,
  21096. * software distributed under the License is distributed on an
  21097. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21098. * KIND, either express or implied. See the License for the
  21099. * specific language governing permissions and limitations
  21100. * under the License.
  21101. */
  21102. /**
  21103. * @param {Object} define
  21104. * @return See the return of `createTask`.
  21105. */
  21106. function createTask(define) {
  21107. return new Task(define);
  21108. }
  21109. /**
  21110. * @constructor
  21111. * @param {Object} define
  21112. * @param {Function} define.reset Custom reset
  21113. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  21114. * @param {Function} [define.count] count is used to determin data task.
  21115. * @param {Function} [define.onDirty] count is used to determin data task.
  21116. */
  21117. function Task(define) {
  21118. define = define || {};
  21119. this._reset = define.reset;
  21120. this._plan = define.plan;
  21121. this._count = define.count;
  21122. this._onDirty = define.onDirty;
  21123. this._dirty = true;
  21124. // Context must be specified implicitly, to
  21125. // avoid miss update context when model changed.
  21126. this.context;
  21127. }
  21128. var taskProto = Task.prototype;
  21129. /**
  21130. * @param {Object} performArgs
  21131. * @param {number} [performArgs.step] Specified step.
  21132. * @param {number} [performArgs.skip] Skip customer perform call.
  21133. * @param {number} [performArgs.modBy] Sampling window size.
  21134. * @param {number} [performArgs.modDataCount] Sampling count.
  21135. */
  21136. taskProto.perform = function (performArgs) {
  21137. var upTask = this._upstream;
  21138. var skip = performArgs && performArgs.skip;
  21139. // TODO some refactor.
  21140. // Pull data. Must pull data each time, because context.data
  21141. // may be updated by Series.setData.
  21142. if (this._dirty && upTask) {
  21143. var context = this.context;
  21144. context.data = context.outputData = upTask.context.outputData;
  21145. }
  21146. if (this.__pipeline) {
  21147. this.__pipeline.currentTask = this;
  21148. }
  21149. var planResult;
  21150. if (this._plan && !skip) {
  21151. planResult = this._plan(this.context);
  21152. }
  21153. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  21154. // elements uniformed distributed when progress, especially when moving or zooming.
  21155. var lastModBy = normalizeModBy(this._modBy);
  21156. var lastModDataCount = this._modDataCount || 0;
  21157. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  21158. var modDataCount = performArgs && performArgs.modDataCount || 0;
  21159. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  21160. planResult = 'reset';
  21161. }
  21162. function normalizeModBy(val) {
  21163. !(val >= 1) && (val = 1); // jshint ignore:line
  21164. return val;
  21165. }
  21166. var forceFirstProgress;
  21167. if (this._dirty || planResult === 'reset') {
  21168. this._dirty = false;
  21169. forceFirstProgress = reset(this, skip);
  21170. }
  21171. this._modBy = modBy;
  21172. this._modDataCount = modDataCount;
  21173. var step = performArgs && performArgs.step;
  21174. if (upTask) {
  21175. if (__DEV__) {
  21176. assert$1(upTask._outputDueEnd != null);
  21177. }
  21178. this._dueEnd = upTask._outputDueEnd;
  21179. }
  21180. // DataTask or overallTask
  21181. else {
  21182. if (__DEV__) {
  21183. assert$1(!this._progress || this._count);
  21184. }
  21185. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  21186. }
  21187. // Note: Stubs, that its host overall task let it has progress, has progress.
  21188. // If no progress, pass index from upstream to downstream each time plan called.
  21189. if (this._progress) {
  21190. var start = this._dueIndex;
  21191. var end = Math.min(
  21192. step != null ? this._dueIndex + step : Infinity,
  21193. this._dueEnd
  21194. );
  21195. if (!skip && (forceFirstProgress || start < end)) {
  21196. var progress = this._progress;
  21197. if (isArray(progress)) {
  21198. for (var i = 0; i < progress.length; i++) {
  21199. doProgress(this, progress[i], start, end, modBy, modDataCount);
  21200. }
  21201. }
  21202. else {
  21203. doProgress(this, progress, start, end, modBy, modDataCount);
  21204. }
  21205. }
  21206. this._dueIndex = end;
  21207. // If no `outputDueEnd`, assume that output data and
  21208. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  21209. var outputDueEnd = this._settedOutputEnd != null
  21210. ? this._settedOutputEnd : end;
  21211. if (__DEV__) {
  21212. // ??? Can not rollback.
  21213. assert$1(outputDueEnd >= this._outputDueEnd);
  21214. }
  21215. this._outputDueEnd = outputDueEnd;
  21216. }
  21217. else {
  21218. // (1) Some overall task has no progress.
  21219. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  21220. // This should always be performed so it can be passed to downstream.
  21221. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  21222. ? this._settedOutputEnd : this._dueEnd;
  21223. }
  21224. return this.unfinished();
  21225. };
  21226. var iterator = (function () {
  21227. var end;
  21228. var current;
  21229. var modBy;
  21230. var modDataCount;
  21231. var winCount;
  21232. var it = {
  21233. reset: function (s, e, sStep, sCount) {
  21234. current = s;
  21235. end = e;
  21236. modBy = sStep;
  21237. modDataCount = sCount;
  21238. winCount = Math.ceil(modDataCount / modBy);
  21239. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  21240. }
  21241. };
  21242. return it;
  21243. function sequentialNext() {
  21244. return current < end ? current++ : null;
  21245. }
  21246. function modNext() {
  21247. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  21248. var result = current >= end
  21249. ? null
  21250. : dataIndex < modDataCount
  21251. ? dataIndex
  21252. // If modDataCount is smaller than data.count() (consider `appendData` case),
  21253. // Use normal linear rendering mode.
  21254. : current;
  21255. current++;
  21256. return result;
  21257. }
  21258. })();
  21259. taskProto.dirty = function () {
  21260. this._dirty = true;
  21261. this._onDirty && this._onDirty(this.context);
  21262. };
  21263. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  21264. iterator.reset(start, end, modBy, modDataCount);
  21265. taskIns._callingProgress = progress;
  21266. taskIns._callingProgress({
  21267. start: start, end: end, count: end - start, next: iterator.next
  21268. }, taskIns.context);
  21269. }
  21270. function reset(taskIns, skip) {
  21271. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  21272. taskIns._settedOutputEnd = null;
  21273. var progress;
  21274. var forceFirstProgress;
  21275. if (!skip && taskIns._reset) {
  21276. progress = taskIns._reset(taskIns.context);
  21277. if (progress && progress.progress) {
  21278. forceFirstProgress = progress.forceFirstProgress;
  21279. progress = progress.progress;
  21280. }
  21281. // To simplify no progress checking, array must has item.
  21282. if (isArray(progress) && !progress.length) {
  21283. progress = null;
  21284. }
  21285. }
  21286. taskIns._progress = progress;
  21287. taskIns._modBy = taskIns._modDataCount = null;
  21288. var downstream = taskIns._downstream;
  21289. downstream && downstream.dirty();
  21290. return forceFirstProgress;
  21291. }
  21292. /**
  21293. * @return {boolean}
  21294. */
  21295. taskProto.unfinished = function () {
  21296. return this._progress && this._dueIndex < this._dueEnd;
  21297. };
  21298. /**
  21299. * @param {Object} downTask The downstream task.
  21300. * @return {Object} The downstream task.
  21301. */
  21302. taskProto.pipe = function (downTask) {
  21303. if (__DEV__) {
  21304. assert$1(downTask && !downTask._disposed && downTask !== this);
  21305. }
  21306. // If already downstream, do not dirty downTask.
  21307. if (this._downstream !== downTask || this._dirty) {
  21308. this._downstream = downTask;
  21309. downTask._upstream = this;
  21310. downTask.dirty();
  21311. }
  21312. };
  21313. taskProto.dispose = function () {
  21314. if (this._disposed) {
  21315. return;
  21316. }
  21317. this._upstream && (this._upstream._downstream = null);
  21318. this._downstream && (this._downstream._upstream = null);
  21319. this._dirty = false;
  21320. this._disposed = true;
  21321. };
  21322. taskProto.getUpstream = function () {
  21323. return this._upstream;
  21324. };
  21325. taskProto.getDownstream = function () {
  21326. return this._downstream;
  21327. };
  21328. taskProto.setOutputEnd = function (end) {
  21329. // This only happend in dataTask, dataZoom, map, currently.
  21330. // where dataZoom do not set end each time, but only set
  21331. // when reset. So we should record the setted end, in case
  21332. // that the stub of dataZoom perform again and earse the
  21333. // setted end by upstream.
  21334. this._outputDueEnd = this._settedOutputEnd = end;
  21335. };
  21336. ///////////////////////////////////////////////////////////
  21337. // For stream debug (Should be commented out after used!)
  21338. // Usage: printTask(this, 'begin');
  21339. // Usage: printTask(this, null, {someExtraProp});
  21340. // function printTask(task, prefix, extra) {
  21341. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  21342. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  21343. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  21344. // var props = [];
  21345. // if (task.__pipeline) {
  21346. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  21347. // props.push({text: 'idx', value: val});
  21348. // } else {
  21349. // var stubCount = 0;
  21350. // task.agentStubMap.each(() => stubCount++);
  21351. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  21352. // }
  21353. // props.push({text: 'uid', value: task.uidDebug});
  21354. // if (task.__pipeline) {
  21355. // props.push({text: 'pid', value: task.__pipeline.id});
  21356. // task.agent && props.push(
  21357. // {text: 'stubFor', value: task.agent.uidDebug}
  21358. // );
  21359. // }
  21360. // props.push(
  21361. // {text: 'dirty', value: task._dirty},
  21362. // {text: 'dueIndex', value: task._dueIndex},
  21363. // {text: 'dueEnd', value: task._dueEnd},
  21364. // {text: 'outputDueEnd', value: task._outputDueEnd}
  21365. // );
  21366. // if (extra) {
  21367. // Object.keys(extra).forEach(key => {
  21368. // props.push({text: key, value: extra[key]});
  21369. // });
  21370. // }
  21371. // var args = ['color: blue'];
  21372. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  21373. // args.push('color: black', 'color: red'),
  21374. // `${item.text}: %c${item.value}`
  21375. // )).join('%c, ');
  21376. // console.log.apply(console, [msg].concat(args));
  21377. // // console.log(this);
  21378. // }
  21379. /*
  21380. * Licensed to the Apache Software Foundation (ASF) under one
  21381. * or more contributor license agreements. See the NOTICE file
  21382. * distributed with this work for additional information
  21383. * regarding copyright ownership. The ASF licenses this file
  21384. * to you under the Apache License, Version 2.0 (the
  21385. * "License"); you may not use this file except in compliance
  21386. * with the License. You may obtain a copy of the License at
  21387. *
  21388. * http://www.apache.org/licenses/LICENSE-2.0
  21389. *
  21390. * Unless required by applicable law or agreed to in writing,
  21391. * software distributed under the License is distributed on an
  21392. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21393. * KIND, either express or implied. See the License for the
  21394. * specific language governing permissions and limitations
  21395. * under the License.
  21396. */
  21397. var inner$4 = makeInner();
  21398. var SeriesModel = ComponentModel.extend({
  21399. type: 'series.__base__',
  21400. /**
  21401. * @readOnly
  21402. */
  21403. seriesIndex: 0,
  21404. // coodinateSystem will be injected in the echarts/CoordinateSystem
  21405. coordinateSystem: null,
  21406. /**
  21407. * @type {Object}
  21408. * @protected
  21409. */
  21410. defaultOption: null,
  21411. /**
  21412. * legend visual provider to the legend component
  21413. * @type {Object}
  21414. */
  21415. // PENDING
  21416. legendVisualProvider: null,
  21417. /**
  21418. * Access path of color for visual
  21419. */
  21420. visualColorAccessPath: 'itemStyle.color',
  21421. /**
  21422. * Access path of borderColor for visual
  21423. */
  21424. visualBorderColorAccessPath: 'itemStyle.borderColor',
  21425. /**
  21426. * Support merge layout params.
  21427. * Only support 'box' now (left/right/top/bottom/width/height).
  21428. * @type {string|Object} Object can be {ignoreSize: true}
  21429. * @readOnly
  21430. */
  21431. layoutMode: null,
  21432. init: function (option, parentModel, ecModel, extraOpt) {
  21433. /**
  21434. * @type {number}
  21435. * @readOnly
  21436. */
  21437. this.seriesIndex = this.componentIndex;
  21438. this.dataTask = createTask({
  21439. count: dataTaskCount,
  21440. reset: dataTaskReset
  21441. });
  21442. this.dataTask.context = {model: this};
  21443. this.mergeDefaultAndTheme(option, ecModel);
  21444. prepareSource(this);
  21445. var data = this.getInitialData(option, ecModel);
  21446. wrapData(data, this);
  21447. this.dataTask.context.data = data;
  21448. if (__DEV__) {
  21449. assert$1(data, 'getInitialData returned invalid data.');
  21450. }
  21451. /**
  21452. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  21453. * @private
  21454. */
  21455. inner$4(this).dataBeforeProcessed = data;
  21456. // If we reverse the order (make data firstly, and then make
  21457. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21458. // cause data.graph.data !== data when using
  21459. // module:echarts/data/Graph or module:echarts/data/Tree.
  21460. // See module:echarts/data/helper/linkList
  21461. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21462. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21463. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21464. // Call `seriesModel.getRawData()` instead.
  21465. // this.restoreData();
  21466. autoSeriesName(this);
  21467. },
  21468. /**
  21469. * Util for merge default and theme to option
  21470. * @param {Object} option
  21471. * @param {module:echarts/model/Global} ecModel
  21472. */
  21473. mergeDefaultAndTheme: function (option, ecModel) {
  21474. var layoutMode = this.layoutMode;
  21475. var inputPositionParams = layoutMode
  21476. ? getLayoutParams(option) : {};
  21477. // Backward compat: using subType on theme.
  21478. // But if name duplicate between series subType
  21479. // (for example: parallel) add component mainType,
  21480. // add suffix 'Series'.
  21481. var themeSubType = this.subType;
  21482. if (ComponentModel.hasClass(themeSubType)) {
  21483. themeSubType += 'Series';
  21484. }
  21485. merge(
  21486. option,
  21487. ecModel.getTheme().get(this.subType)
  21488. );
  21489. merge(option, this.getDefaultOption());
  21490. // Default label emphasis `show`
  21491. defaultEmphasis(option, 'label', ['show']);
  21492. this.fillDataTextStyle(option.data);
  21493. if (layoutMode) {
  21494. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21495. }
  21496. },
  21497. mergeOption: function (newSeriesOption, ecModel) {
  21498. // this.settingTask.dirty();
  21499. newSeriesOption = merge(this.option, newSeriesOption, true);
  21500. this.fillDataTextStyle(newSeriesOption.data);
  21501. var layoutMode = this.layoutMode;
  21502. if (layoutMode) {
  21503. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21504. }
  21505. prepareSource(this);
  21506. var data = this.getInitialData(newSeriesOption, ecModel);
  21507. wrapData(data, this);
  21508. this.dataTask.dirty();
  21509. this.dataTask.context.data = data;
  21510. inner$4(this).dataBeforeProcessed = data;
  21511. autoSeriesName(this);
  21512. },
  21513. fillDataTextStyle: function (data) {
  21514. // Default data label emphasis `show`
  21515. // FIXME Tree structure data ?
  21516. // FIXME Performance ?
  21517. if (data && !isTypedArray(data)) {
  21518. var props = ['show'];
  21519. for (var i = 0; i < data.length; i++) {
  21520. if (data[i] && data[i].label) {
  21521. defaultEmphasis(data[i], 'label', props);
  21522. }
  21523. }
  21524. }
  21525. },
  21526. /**
  21527. * Init a data structure from data related option in series
  21528. * Must be overwritten
  21529. */
  21530. getInitialData: function () {},
  21531. /**
  21532. * Append data to list
  21533. * @param {Object} params
  21534. * @param {Array|TypedArray} params.data
  21535. */
  21536. appendData: function (params) {
  21537. // FIXME ???
  21538. // (1) If data from dataset, forbidden append.
  21539. // (2) support append data of dataset.
  21540. var data = this.getRawData();
  21541. data.appendData(params.data);
  21542. },
  21543. /**
  21544. * Consider some method like `filter`, `map` need make new data,
  21545. * We should make sure that `seriesModel.getData()` get correct
  21546. * data in the stream procedure. So we fetch data from upstream
  21547. * each time `task.perform` called.
  21548. * @param {string} [dataType]
  21549. * @return {module:echarts/data/List}
  21550. */
  21551. getData: function (dataType) {
  21552. var task = getCurrentTask(this);
  21553. if (task) {
  21554. var data = task.context.data;
  21555. return dataType == null ? data : data.getLinkedData(dataType);
  21556. }
  21557. else {
  21558. // When series is not alive (that may happen when click toolbox
  21559. // restore or setOption with not merge mode), series data may
  21560. // be still need to judge animation or something when graphic
  21561. // elements want to know whether fade out.
  21562. return inner$4(this).data;
  21563. }
  21564. },
  21565. /**
  21566. * @param {module:echarts/data/List} data
  21567. */
  21568. setData: function (data) {
  21569. var task = getCurrentTask(this);
  21570. if (task) {
  21571. var context = task.context;
  21572. // Consider case: filter, data sample.
  21573. if (context.data !== data && task.modifyOutputEnd) {
  21574. task.setOutputEnd(data.count());
  21575. }
  21576. context.outputData = data;
  21577. // Caution: setData should update context.data,
  21578. // Because getData may be called multiply in a
  21579. // single stage and expect to get the data just
  21580. // set. (For example, AxisProxy, x y both call
  21581. // getData and setDate sequentially).
  21582. // So the context.data should be fetched from
  21583. // upstream each time when a stage starts to be
  21584. // performed.
  21585. if (task !== this.dataTask) {
  21586. context.data = data;
  21587. }
  21588. }
  21589. inner$4(this).data = data;
  21590. },
  21591. /**
  21592. * @see {module:echarts/data/helper/sourceHelper#getSource}
  21593. * @return {module:echarts/data/Source} source
  21594. */
  21595. getSource: function () {
  21596. return getSource(this);
  21597. },
  21598. /**
  21599. * Get data before processed
  21600. * @return {module:echarts/data/List}
  21601. */
  21602. getRawData: function () {
  21603. return inner$4(this).dataBeforeProcessed;
  21604. },
  21605. /**
  21606. * Get base axis if has coordinate system and has axis.
  21607. * By default use coordSys.getBaseAxis();
  21608. * Can be overrided for some chart.
  21609. * @return {type} description
  21610. */
  21611. getBaseAxis: function () {
  21612. var coordSys = this.coordinateSystem;
  21613. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21614. },
  21615. // FIXME
  21616. /**
  21617. * Default tooltip formatter
  21618. *
  21619. * @param {number} dataIndex
  21620. * @param {boolean} [multipleSeries=false]
  21621. * @param {number} [dataType]
  21622. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  21623. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21624. * string is used as DOM HTML content.
  21625. * 'richText' is used for rendering tooltip in rich text form, for those where
  21626. * DOM operation is not supported.
  21627. * @return {Object} formatted tooltip with `html` and `markers`
  21628. */
  21629. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  21630. var series = this;
  21631. renderMode = renderMode || 'html';
  21632. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  21633. var isRichText = renderMode === 'richText';
  21634. var markers = {};
  21635. var markerId = 0;
  21636. function formatArrayValue(value) {
  21637. // ??? TODO refactor these logic.
  21638. // check: category-no-encode-has-axis-data in dataset.html
  21639. var vertially = reduce(value, function (vertially, val, idx) {
  21640. var dimItem = data.getDimensionInfo(idx);
  21641. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21642. }, 0);
  21643. var result = [];
  21644. tooltipDims.length
  21645. ? each$1(tooltipDims, function (dim) {
  21646. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21647. })
  21648. // By default, all dims is used on tooltip.
  21649. : each$1(value, setEachItem);
  21650. function setEachItem(val, dim) {
  21651. var dimInfo = data.getDimensionInfo(dim);
  21652. // If `dimInfo.tooltip` is not set, show tooltip.
  21653. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21654. return;
  21655. }
  21656. var dimType = dimInfo.type;
  21657. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  21658. var dimHead = getTooltipMarker({
  21659. color: color,
  21660. type: 'subItem',
  21661. renderMode: renderMode,
  21662. markerId: markName
  21663. });
  21664. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  21665. var valStr = (vertially
  21666. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  21667. : ''
  21668. )
  21669. // FIXME should not format time for raw data?
  21670. + encodeHTML(dimType === 'ordinal'
  21671. ? val + ''
  21672. : dimType === 'time'
  21673. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  21674. : addCommas(val)
  21675. );
  21676. valStr && result.push(valStr);
  21677. if (isRichText) {
  21678. markers[markName] = color;
  21679. ++markerId;
  21680. }
  21681. }
  21682. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  21683. var content = newLine + result.join(newLine || ', ');
  21684. return {
  21685. renderMode: renderMode,
  21686. content: content,
  21687. style: markers
  21688. };
  21689. }
  21690. function formatSingleValue(val) {
  21691. // return encodeHTML(addCommas(val));
  21692. return {
  21693. renderMode: renderMode,
  21694. content: encodeHTML(addCommas(val)),
  21695. style: markers
  21696. };
  21697. }
  21698. var data = this.getData();
  21699. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  21700. var tooltipDimLen = tooltipDims.length;
  21701. var value = this.getRawValue(dataIndex);
  21702. var isValueArr = isArray(value);
  21703. var color = data.getItemVisual(dataIndex, 'color');
  21704. if (isObject$1(color) && color.colorStops) {
  21705. color = (color.colorStops[0] || {}).color;
  21706. }
  21707. color = color || 'transparent';
  21708. // Complicated rule for pretty tooltip.
  21709. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  21710. ? formatArrayValue(value)
  21711. : tooltipDimLen
  21712. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  21713. : formatSingleValue(isValueArr ? value[0] : value);
  21714. var content = formattedValue.content;
  21715. var markName = series.seriesIndex + 'at' + markerId;
  21716. var colorEl = getTooltipMarker({
  21717. color: color,
  21718. type: 'item',
  21719. renderMode: renderMode,
  21720. markerId: markName
  21721. });
  21722. markers[markName] = color;
  21723. ++markerId;
  21724. var name = data.getName(dataIndex);
  21725. var seriesName = this.name;
  21726. if (!isNameSpecified(this)) {
  21727. seriesName = '';
  21728. }
  21729. seriesName = seriesName
  21730. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  21731. : '';
  21732. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  21733. var html = !multipleSeries
  21734. ? seriesName + colorStr
  21735. + (name
  21736. ? encodeHTML(name) + ': ' + content
  21737. : content
  21738. )
  21739. : colorStr + seriesName + content;
  21740. return {
  21741. html: html,
  21742. markers: markers
  21743. };
  21744. },
  21745. /**
  21746. * @return {boolean}
  21747. */
  21748. isAnimationEnabled: function () {
  21749. if (env$1.node) {
  21750. return false;
  21751. }
  21752. var animationEnabled = this.getShallow('animation');
  21753. if (animationEnabled) {
  21754. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21755. animationEnabled = false;
  21756. }
  21757. }
  21758. return animationEnabled;
  21759. },
  21760. restoreData: function () {
  21761. this.dataTask.dirty();
  21762. },
  21763. getColorFromPalette: function (name, scope, requestColorNum) {
  21764. var ecModel = this.ecModel;
  21765. // PENDING
  21766. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  21767. if (!color) {
  21768. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21769. }
  21770. return color;
  21771. },
  21772. /**
  21773. * Use `data.mapDimension(coordDim, true)` instead.
  21774. * @deprecated
  21775. */
  21776. coordDimToDataDim: function (coordDim) {
  21777. return this.getRawData().mapDimension(coordDim, true);
  21778. },
  21779. /**
  21780. * Get progressive rendering count each step
  21781. * @return {number}
  21782. */
  21783. getProgressive: function () {
  21784. return this.get('progressive');
  21785. },
  21786. /**
  21787. * Get progressive rendering count each step
  21788. * @return {number}
  21789. */
  21790. getProgressiveThreshold: function () {
  21791. return this.get('progressiveThreshold');
  21792. },
  21793. /**
  21794. * Get data indices for show tooltip content. See tooltip.
  21795. * @abstract
  21796. * @param {Array.<string>|string} dim
  21797. * @param {Array.<number>} value
  21798. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21799. * @return {Object} {dataIndices, nestestValue}.
  21800. */
  21801. getAxisTooltipData: null,
  21802. /**
  21803. * See tooltip.
  21804. * @abstract
  21805. * @param {number} dataIndex
  21806. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21807. */
  21808. getTooltipPosition: null,
  21809. /**
  21810. * @see {module:echarts/stream/Scheduler}
  21811. */
  21812. pipeTask: null,
  21813. /**
  21814. * Convinient for override in extended class.
  21815. * @protected
  21816. * @type {Function}
  21817. */
  21818. preventIncremental: null,
  21819. /**
  21820. * @public
  21821. * @readOnly
  21822. * @type {Object}
  21823. */
  21824. pipelineContext: null
  21825. });
  21826. mixin(SeriesModel, dataFormatMixin);
  21827. mixin(SeriesModel, colorPaletteMixin);
  21828. /**
  21829. * MUST be called after `prepareSource` called
  21830. * Here we need to make auto series, especially for auto legend. But we
  21831. * do not modify series.name in option to avoid side effects.
  21832. */
  21833. function autoSeriesName(seriesModel) {
  21834. // User specified name has higher priority, otherwise it may cause
  21835. // series can not be queried unexpectedly.
  21836. var name = seriesModel.name;
  21837. if (!isNameSpecified(seriesModel)) {
  21838. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21839. }
  21840. }
  21841. function getSeriesAutoName(seriesModel) {
  21842. var data = seriesModel.getRawData();
  21843. var dataDims = data.mapDimension('seriesName', true);
  21844. var nameArr = [];
  21845. each$1(dataDims, function (dataDim) {
  21846. var dimInfo = data.getDimensionInfo(dataDim);
  21847. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21848. });
  21849. return nameArr.join(' ');
  21850. }
  21851. function dataTaskCount(context) {
  21852. return context.model.getRawData().count();
  21853. }
  21854. function dataTaskReset(context) {
  21855. var seriesModel = context.model;
  21856. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21857. return dataTaskProgress;
  21858. }
  21859. function dataTaskProgress(param, context) {
  21860. // Avoid repead cloneShallow when data just created in reset.
  21861. if (context.outputData && param.end > context.outputData.count()) {
  21862. context.model.getRawData().cloneShallow(context.outputData);
  21863. }
  21864. }
  21865. // TODO refactor
  21866. function wrapData(data, seriesModel) {
  21867. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21868. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21869. });
  21870. }
  21871. function onDataSelfChange(seriesModel) {
  21872. var task = getCurrentTask(seriesModel);
  21873. if (task) {
  21874. // Consider case: filter, selectRange
  21875. task.setOutputEnd(this.count());
  21876. }
  21877. }
  21878. function getCurrentTask(seriesModel) {
  21879. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21880. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21881. if (pipeline) {
  21882. // When pipline finished, the currrentTask keep the last
  21883. // task (renderTask).
  21884. var task = pipeline.currentTask;
  21885. if (task) {
  21886. var agentStubMap = task.agentStubMap;
  21887. if (agentStubMap) {
  21888. task = agentStubMap.get(seriesModel.uid);
  21889. }
  21890. }
  21891. return task;
  21892. }
  21893. }
  21894. /*
  21895. * Licensed to the Apache Software Foundation (ASF) under one
  21896. * or more contributor license agreements. See the NOTICE file
  21897. * distributed with this work for additional information
  21898. * regarding copyright ownership. The ASF licenses this file
  21899. * to you under the Apache License, Version 2.0 (the
  21900. * "License"); you may not use this file except in compliance
  21901. * with the License. You may obtain a copy of the License at
  21902. *
  21903. * http://www.apache.org/licenses/LICENSE-2.0
  21904. *
  21905. * Unless required by applicable law or agreed to in writing,
  21906. * software distributed under the License is distributed on an
  21907. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21908. * KIND, either express or implied. See the License for the
  21909. * specific language governing permissions and limitations
  21910. * under the License.
  21911. */
  21912. var Component$1 = function () {
  21913. /**
  21914. * @type {module:zrender/container/Group}
  21915. * @readOnly
  21916. */
  21917. this.group = new Group();
  21918. /**
  21919. * @type {string}
  21920. * @readOnly
  21921. */
  21922. this.uid = getUID('viewComponent');
  21923. };
  21924. Component$1.prototype = {
  21925. constructor: Component$1,
  21926. init: function (ecModel, api) {},
  21927. render: function (componentModel, ecModel, api, payload) {},
  21928. dispose: function () {},
  21929. /**
  21930. * @param {string} eventType
  21931. * @param {Object} query
  21932. * @param {module:zrender/Element} targetEl
  21933. * @param {Object} packedEvent
  21934. * @return {boolen} Pass only when return `true`.
  21935. */
  21936. filterForExposedEvent: null
  21937. };
  21938. var componentProto = Component$1.prototype;
  21939. componentProto.updateView =
  21940. componentProto.updateLayout =
  21941. componentProto.updateVisual =
  21942. function (seriesModel, ecModel, api, payload) {
  21943. // Do nothing;
  21944. };
  21945. // Enable Component.extend.
  21946. enableClassExtend(Component$1);
  21947. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21948. enableClassManagement(Component$1, {registerWhenExtend: true});
  21949. /*
  21950. * Licensed to the Apache Software Foundation (ASF) under one
  21951. * or more contributor license agreements. See the NOTICE file
  21952. * distributed with this work for additional information
  21953. * regarding copyright ownership. The ASF licenses this file
  21954. * to you under the Apache License, Version 2.0 (the
  21955. * "License"); you may not use this file except in compliance
  21956. * with the License. You may obtain a copy of the License at
  21957. *
  21958. * http://www.apache.org/licenses/LICENSE-2.0
  21959. *
  21960. * Unless required by applicable law or agreed to in writing,
  21961. * software distributed under the License is distributed on an
  21962. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21963. * KIND, either express or implied. See the License for the
  21964. * specific language governing permissions and limitations
  21965. * under the License.
  21966. */
  21967. /**
  21968. * @return {string} If large mode changed, return string 'reset';
  21969. */
  21970. var createRenderPlanner = function () {
  21971. var inner = makeInner();
  21972. return function (seriesModel) {
  21973. var fields = inner(seriesModel);
  21974. var pipelineContext = seriesModel.pipelineContext;
  21975. var originalLarge = fields.large;
  21976. var originalProgressive = fields.progressiveRender;
  21977. // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  21978. // exists. See #11611 . Probably we need to modify this structure, see the comment
  21979. // on `performRawSeries` in `Schedular.js`.
  21980. var large = fields.large = pipelineContext && pipelineContext.large;
  21981. var progressive = fields.progressiveRender = pipelineContext && pipelineContext.progressiveRender;
  21982. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21983. };
  21984. };
  21985. /*
  21986. * Licensed to the Apache Software Foundation (ASF) under one
  21987. * or more contributor license agreements. See the NOTICE file
  21988. * distributed with this work for additional information
  21989. * regarding copyright ownership. The ASF licenses this file
  21990. * to you under the Apache License, Version 2.0 (the
  21991. * "License"); you may not use this file except in compliance
  21992. * with the License. You may obtain a copy of the License at
  21993. *
  21994. * http://www.apache.org/licenses/LICENSE-2.0
  21995. *
  21996. * Unless required by applicable law or agreed to in writing,
  21997. * software distributed under the License is distributed on an
  21998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21999. * KIND, either express or implied. See the License for the
  22000. * specific language governing permissions and limitations
  22001. * under the License.
  22002. */
  22003. var inner$5 = makeInner();
  22004. var renderPlanner = createRenderPlanner();
  22005. function Chart() {
  22006. /**
  22007. * @type {module:zrender/container/Group}
  22008. * @readOnly
  22009. */
  22010. this.group = new Group();
  22011. /**
  22012. * @type {string}
  22013. * @readOnly
  22014. */
  22015. this.uid = getUID('viewChart');
  22016. this.renderTask = createTask({
  22017. plan: renderTaskPlan,
  22018. reset: renderTaskReset
  22019. });
  22020. this.renderTask.context = {view: this};
  22021. }
  22022. Chart.prototype = {
  22023. type: 'chart',
  22024. /**
  22025. * Init the chart.
  22026. * @param {module:echarts/model/Global} ecModel
  22027. * @param {module:echarts/ExtensionAPI} api
  22028. */
  22029. init: function (ecModel, api) {},
  22030. /**
  22031. * Render the chart.
  22032. * @param {module:echarts/model/Series} seriesModel
  22033. * @param {module:echarts/model/Global} ecModel
  22034. * @param {module:echarts/ExtensionAPI} api
  22035. * @param {Object} payload
  22036. */
  22037. render: function (seriesModel, ecModel, api, payload) {},
  22038. /**
  22039. * Highlight series or specified data item.
  22040. * @param {module:echarts/model/Series} seriesModel
  22041. * @param {module:echarts/model/Global} ecModel
  22042. * @param {module:echarts/ExtensionAPI} api
  22043. * @param {Object} payload
  22044. */
  22045. highlight: function (seriesModel, ecModel, api, payload) {
  22046. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  22047. },
  22048. /**
  22049. * Downplay series or specified data item.
  22050. * @param {module:echarts/model/Series} seriesModel
  22051. * @param {module:echarts/model/Global} ecModel
  22052. * @param {module:echarts/ExtensionAPI} api
  22053. * @param {Object} payload
  22054. */
  22055. downplay: function (seriesModel, ecModel, api, payload) {
  22056. toggleHighlight(seriesModel.getData(), payload, 'normal');
  22057. },
  22058. /**
  22059. * Remove self.
  22060. * @param {module:echarts/model/Global} ecModel
  22061. * @param {module:echarts/ExtensionAPI} api
  22062. */
  22063. remove: function (ecModel, api) {
  22064. this.group.removeAll();
  22065. },
  22066. /**
  22067. * Dispose self.
  22068. * @param {module:echarts/model/Global} ecModel
  22069. * @param {module:echarts/ExtensionAPI} api
  22070. */
  22071. dispose: function () {},
  22072. /**
  22073. * Rendering preparation in progressive mode.
  22074. * @param {module:echarts/model/Series} seriesModel
  22075. * @param {module:echarts/model/Global} ecModel
  22076. * @param {module:echarts/ExtensionAPI} api
  22077. * @param {Object} payload
  22078. */
  22079. incrementalPrepareRender: null,
  22080. /**
  22081. * Render in progressive mode.
  22082. * @param {Object} params See taskParams in `stream/task.js`
  22083. * @param {module:echarts/model/Series} seriesModel
  22084. * @param {module:echarts/model/Global} ecModel
  22085. * @param {module:echarts/ExtensionAPI} api
  22086. * @param {Object} payload
  22087. */
  22088. incrementalRender: null,
  22089. /**
  22090. * Update transform directly.
  22091. * @param {module:echarts/model/Series} seriesModel
  22092. * @param {module:echarts/model/Global} ecModel
  22093. * @param {module:echarts/ExtensionAPI} api
  22094. * @param {Object} payload
  22095. * @return {Object} {update: true}
  22096. */
  22097. updateTransform: null,
  22098. /**
  22099. * The view contains the given point.
  22100. * @interface
  22101. * @param {Array.<number>} point
  22102. * @return {boolean}
  22103. */
  22104. // containPoint: function () {}
  22105. /**
  22106. * @param {string} eventType
  22107. * @param {Object} query
  22108. * @param {module:zrender/Element} targetEl
  22109. * @param {Object} packedEvent
  22110. * @return {boolen} Pass only when return `true`.
  22111. */
  22112. filterForExposedEvent: null
  22113. };
  22114. var chartProto = Chart.prototype;
  22115. chartProto.updateView =
  22116. chartProto.updateLayout =
  22117. chartProto.updateVisual =
  22118. function (seriesModel, ecModel, api, payload) {
  22119. this.render(seriesModel, ecModel, api, payload);
  22120. };
  22121. /**
  22122. * Set state of single element
  22123. * @param {module:zrender/Element} el
  22124. * @param {string} state 'normal'|'emphasis'
  22125. * @param {number} highlightDigit
  22126. */
  22127. function elSetState(el, state, highlightDigit) {
  22128. if (el) {
  22129. el.trigger(state, highlightDigit);
  22130. if (el.isGroup
  22131. // Simple optimize.
  22132. && !isHighDownDispatcher(el)
  22133. ) {
  22134. for (var i = 0, len = el.childCount(); i < len; i++) {
  22135. elSetState(el.childAt(i), state, highlightDigit);
  22136. }
  22137. }
  22138. }
  22139. }
  22140. /**
  22141. * @param {module:echarts/data/List} data
  22142. * @param {Object} payload
  22143. * @param {string} state 'normal'|'emphasis'
  22144. */
  22145. function toggleHighlight(data, payload, state) {
  22146. var dataIndex = queryDataIndex(data, payload);
  22147. var highlightDigit = (payload && payload.highlightKey != null)
  22148. ? getHighlightDigit(payload.highlightKey)
  22149. : null;
  22150. if (dataIndex != null) {
  22151. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  22152. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22153. });
  22154. }
  22155. else {
  22156. data.eachItemGraphicEl(function (el) {
  22157. elSetState(el, state, highlightDigit);
  22158. });
  22159. }
  22160. }
  22161. // Enable Chart.extend.
  22162. enableClassExtend(Chart, ['dispose']);
  22163. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  22164. enableClassManagement(Chart, {registerWhenExtend: true});
  22165. Chart.markUpdateMethod = function (payload, methodName) {
  22166. inner$5(payload).updateMethod = methodName;
  22167. };
  22168. function renderTaskPlan(context) {
  22169. return renderPlanner(context.model);
  22170. }
  22171. function renderTaskReset(context) {
  22172. var seriesModel = context.model;
  22173. var ecModel = context.ecModel;
  22174. var api = context.api;
  22175. var payload = context.payload;
  22176. // ???! remove updateView updateVisual
  22177. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22178. var view = context.view;
  22179. var updateMethod = payload && inner$5(payload).updateMethod;
  22180. var methodName = progressiveRender
  22181. ? 'incrementalPrepareRender'
  22182. : (updateMethod && view[updateMethod])
  22183. ? updateMethod
  22184. // `appendData` is also supported when data amount
  22185. // is less than progressive threshold.
  22186. : 'render';
  22187. if (methodName !== 'render') {
  22188. view[methodName](seriesModel, ecModel, api, payload);
  22189. }
  22190. return progressMethodMap[methodName];
  22191. }
  22192. var progressMethodMap = {
  22193. incrementalPrepareRender: {
  22194. progress: function (params, context) {
  22195. context.view.incrementalRender(
  22196. params, context.model, context.ecModel, context.api, context.payload
  22197. );
  22198. }
  22199. },
  22200. render: {
  22201. // Put view.render in `progress` to support appendData. But in this case
  22202. // view.render should not be called in reset, otherwise it will be called
  22203. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22204. // in any cases.
  22205. forceFirstProgress: true,
  22206. progress: function (params, context) {
  22207. context.view.render(
  22208. context.model, context.ecModel, context.api, context.payload
  22209. );
  22210. }
  22211. }
  22212. };
  22213. /*
  22214. * Licensed to the Apache Software Foundation (ASF) under one
  22215. * or more contributor license agreements. See the NOTICE file
  22216. * distributed with this work for additional information
  22217. * regarding copyright ownership. The ASF licenses this file
  22218. * to you under the Apache License, Version 2.0 (the
  22219. * "License"); you may not use this file except in compliance
  22220. * with the License. You may obtain a copy of the License at
  22221. *
  22222. * http://www.apache.org/licenses/LICENSE-2.0
  22223. *
  22224. * Unless required by applicable law or agreed to in writing,
  22225. * software distributed under the License is distributed on an
  22226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22227. * KIND, either express or implied. See the License for the
  22228. * specific language governing permissions and limitations
  22229. * under the License.
  22230. */
  22231. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22232. var RATE = '\0__throttleRate';
  22233. var THROTTLE_TYPE = '\0__throttleType';
  22234. /**
  22235. * @public
  22236. * @param {(Function)} fn
  22237. * @param {number} [delay=0] Unit: ms.
  22238. * @param {boolean} [debounce=false]
  22239. * true: If call interval less than `delay`, only the last call works.
  22240. * false: If call interval less than `delay, call works on fixed rate.
  22241. * @return {(Function)} throttled fn.
  22242. */
  22243. function throttle(fn, delay, debounce) {
  22244. var currCall;
  22245. var lastCall = 0;
  22246. var lastExec = 0;
  22247. var timer = null;
  22248. var diff;
  22249. var scope;
  22250. var args;
  22251. var debounceNextCall;
  22252. delay = delay || 0;
  22253. function exec() {
  22254. lastExec = (new Date()).getTime();
  22255. timer = null;
  22256. fn.apply(scope, args || []);
  22257. }
  22258. var cb = function () {
  22259. currCall = (new Date()).getTime();
  22260. scope = this;
  22261. args = arguments;
  22262. var thisDelay = debounceNextCall || delay;
  22263. var thisDebounce = debounceNextCall || debounce;
  22264. debounceNextCall = null;
  22265. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22266. clearTimeout(timer);
  22267. // Here we should make sure that: the `exec` SHOULD NOT be called later
  22268. // than a new call of `cb`, that is, preserving the command order. Consider
  22269. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22270. // happens, either the `exec` is called dierectly, or the call is delayed.
  22271. // But the delayed call should never be later than next call of `cb`. Under
  22272. // this assurance, we can simply update view state each time `dispatchAction`
  22273. // triggered by user roaming, but not need to add extra code to avoid the
  22274. // state being "rolled-back".
  22275. if (thisDebounce) {
  22276. timer = setTimeout(exec, thisDelay);
  22277. }
  22278. else {
  22279. if (diff >= 0) {
  22280. exec();
  22281. }
  22282. else {
  22283. timer = setTimeout(exec, -diff);
  22284. }
  22285. }
  22286. lastCall = currCall;
  22287. };
  22288. /**
  22289. * Clear throttle.
  22290. * @public
  22291. */
  22292. cb.clear = function () {
  22293. if (timer) {
  22294. clearTimeout(timer);
  22295. timer = null;
  22296. }
  22297. };
  22298. /**
  22299. * Enable debounce once.
  22300. */
  22301. cb.debounceNextCall = function (debounceDelay) {
  22302. debounceNextCall = debounceDelay;
  22303. };
  22304. return cb;
  22305. }
  22306. /**
  22307. * Create throttle method or update throttle rate.
  22308. *
  22309. * @example
  22310. * ComponentView.prototype.render = function () {
  22311. * ...
  22312. * throttle.createOrUpdate(
  22313. * this,
  22314. * '_dispatchAction',
  22315. * this.model.get('throttle'),
  22316. * 'fixRate'
  22317. * );
  22318. * };
  22319. * ComponentView.prototype.remove = function () {
  22320. * throttle.clear(this, '_dispatchAction');
  22321. * };
  22322. * ComponentView.prototype.dispose = function () {
  22323. * throttle.clear(this, '_dispatchAction');
  22324. * };
  22325. *
  22326. * @public
  22327. * @param {Object} obj
  22328. * @param {string} fnAttr
  22329. * @param {number} [rate]
  22330. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  22331. * @return {Function} throttled function.
  22332. */
  22333. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22334. var fn = obj[fnAttr];
  22335. if (!fn) {
  22336. return;
  22337. }
  22338. var originFn = fn[ORIGIN_METHOD] || fn;
  22339. var lastThrottleType = fn[THROTTLE_TYPE];
  22340. var lastRate = fn[RATE];
  22341. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22342. if (rate == null || !throttleType) {
  22343. return (obj[fnAttr] = originFn);
  22344. }
  22345. fn = obj[fnAttr] = throttle(
  22346. originFn, rate, throttleType === 'debounce'
  22347. );
  22348. fn[ORIGIN_METHOD] = originFn;
  22349. fn[THROTTLE_TYPE] = throttleType;
  22350. fn[RATE] = rate;
  22351. }
  22352. return fn;
  22353. }
  22354. /**
  22355. * Clear throttle. Example see throttle.createOrUpdate.
  22356. *
  22357. * @public
  22358. * @param {Object} obj
  22359. * @param {string} fnAttr
  22360. */
  22361. function clear(obj, fnAttr) {
  22362. var fn = obj[fnAttr];
  22363. if (fn && fn[ORIGIN_METHOD]) {
  22364. obj[fnAttr] = fn[ORIGIN_METHOD];
  22365. }
  22366. }
  22367. /*
  22368. * Licensed to the Apache Software Foundation (ASF) under one
  22369. * or more contributor license agreements. See the NOTICE file
  22370. * distributed with this work for additional information
  22371. * regarding copyright ownership. The ASF licenses this file
  22372. * to you under the Apache License, Version 2.0 (the
  22373. * "License"); you may not use this file except in compliance
  22374. * with the License. You may obtain a copy of the License at
  22375. *
  22376. * http://www.apache.org/licenses/LICENSE-2.0
  22377. *
  22378. * Unless required by applicable law or agreed to in writing,
  22379. * software distributed under the License is distributed on an
  22380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22381. * KIND, either express or implied. See the License for the
  22382. * specific language governing permissions and limitations
  22383. * under the License.
  22384. */
  22385. var seriesColor = {
  22386. createOnAllSeries: true,
  22387. performRawSeries: true,
  22388. reset: function (seriesModel, ecModel) {
  22389. var data = seriesModel.getData();
  22390. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  22391. // Set in itemStyle
  22392. var color = seriesModel.get(colorAccessPath);
  22393. var colorCallback = (isFunction$1(color) && !(color instanceof Gradient))
  22394. ? color : null;
  22395. // Default color
  22396. if (!color || colorCallback) {
  22397. color = seriesModel.getColorFromPalette(
  22398. // TODO series count changed.
  22399. seriesModel.name, null, ecModel.getSeriesCount()
  22400. );
  22401. }
  22402. data.setVisual('color', color);
  22403. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  22404. var borderColor = seriesModel.get(borderColorAccessPath);
  22405. data.setVisual('borderColor', borderColor);
  22406. // Only visible series has each data be visual encoded
  22407. if (!ecModel.isSeriesFiltered(seriesModel)) {
  22408. if (colorCallback) {
  22409. data.each(function (idx) {
  22410. data.setItemVisual(
  22411. idx, 'color', colorCallback(seriesModel.getDataParams(idx))
  22412. );
  22413. });
  22414. }
  22415. // itemStyle in each data item
  22416. var dataEach = function (data, idx) {
  22417. var itemModel = data.getItemModel(idx);
  22418. var color = itemModel.get(colorAccessPath, true);
  22419. var borderColor = itemModel.get(borderColorAccessPath, true);
  22420. if (color != null) {
  22421. data.setItemVisual(idx, 'color', color);
  22422. }
  22423. if (borderColor != null) {
  22424. data.setItemVisual(idx, 'borderColor', borderColor);
  22425. }
  22426. };
  22427. return { dataEach: data.hasItemOption ? dataEach : null };
  22428. }
  22429. }
  22430. };
  22431. /*
  22432. * Licensed to the Apache Software Foundation (ASF) under one
  22433. * or more contributor license agreements. See the NOTICE file
  22434. * distributed with this work for additional information
  22435. * regarding copyright ownership. The ASF licenses this file
  22436. * to you under the Apache License, Version 2.0 (the
  22437. * "License"); you may not use this file except in compliance
  22438. * with the License. You may obtain a copy of the License at
  22439. *
  22440. * http://www.apache.org/licenses/LICENSE-2.0
  22441. *
  22442. * Unless required by applicable law or agreed to in writing,
  22443. * software distributed under the License is distributed on an
  22444. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22445. * KIND, either express or implied. See the License for the
  22446. * specific language governing permissions and limitations
  22447. * under the License.
  22448. */
  22449. /**
  22450. * Language: English.
  22451. */
  22452. var lang = {
  22453. legend: {
  22454. selector: {
  22455. all: 'All',
  22456. inverse: 'Inv'
  22457. }
  22458. },
  22459. toolbox: {
  22460. brush: {
  22461. title: {
  22462. rect: 'Box Select',
  22463. polygon: 'Lasso Select',
  22464. lineX: 'Horizontally Select',
  22465. lineY: 'Vertically Select',
  22466. keep: 'Keep Selections',
  22467. clear: 'Clear Selections'
  22468. }
  22469. },
  22470. dataView: {
  22471. title: 'Data View',
  22472. lang: ['Data View', 'Close', 'Refresh']
  22473. },
  22474. dataZoom: {
  22475. title: {
  22476. zoom: 'Zoom',
  22477. back: 'Zoom Reset'
  22478. }
  22479. },
  22480. magicType: {
  22481. title: {
  22482. line: 'Switch to Line Chart',
  22483. bar: 'Switch to Bar Chart',
  22484. stack: 'Stack',
  22485. tiled: 'Tile'
  22486. }
  22487. },
  22488. restore: {
  22489. title: 'Restore'
  22490. },
  22491. saveAsImage: {
  22492. title: 'Save as Image',
  22493. lang: ['Right Click to Save Image']
  22494. }
  22495. },
  22496. series: {
  22497. typeNames: {
  22498. pie: 'Pie chart',
  22499. bar: 'Bar chart',
  22500. line: 'Line chart',
  22501. scatter: 'Scatter plot',
  22502. effectScatter: 'Ripple scatter plot',
  22503. radar: 'Radar chart',
  22504. tree: 'Tree',
  22505. treemap: 'Treemap',
  22506. boxplot: 'Boxplot',
  22507. candlestick: 'Candlestick',
  22508. k: 'K line chart',
  22509. heatmap: 'Heat map',
  22510. map: 'Map',
  22511. parallel: 'Parallel coordinate map',
  22512. lines: 'Line graph',
  22513. graph: 'Relationship graph',
  22514. sankey: 'Sankey diagram',
  22515. funnel: 'Funnel chart',
  22516. gauge: 'Guage',
  22517. pictorialBar: 'Pictorial bar',
  22518. themeRiver: 'Theme River Map',
  22519. sunburst: 'Sunburst'
  22520. }
  22521. },
  22522. aria: {
  22523. general: {
  22524. withTitle: 'This is a chart about "{title}"',
  22525. withoutTitle: 'This is a chart'
  22526. },
  22527. series: {
  22528. single: {
  22529. prefix: '',
  22530. withName: ' with type {seriesType} named {seriesName}.',
  22531. withoutName: ' with type {seriesType}.'
  22532. },
  22533. multiple: {
  22534. prefix: '. It consists of {seriesCount} series count.',
  22535. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  22536. withoutName: ' The {seriesId} series is a {seriesType}.',
  22537. separator: {
  22538. middle: '',
  22539. end: ''
  22540. }
  22541. }
  22542. },
  22543. data: {
  22544. allData: 'The data is as follows: ',
  22545. partialData: 'The first {displayCnt} items are: ',
  22546. withName: 'the data for {name} is {value}',
  22547. withoutName: '{value}',
  22548. separator: {
  22549. middle: ',',
  22550. end: '.'
  22551. }
  22552. }
  22553. }
  22554. };
  22555. /*
  22556. * Licensed to the Apache Software Foundation (ASF) under one
  22557. * or more contributor license agreements. See the NOTICE file
  22558. * distributed with this work for additional information
  22559. * regarding copyright ownership. The ASF licenses this file
  22560. * to you under the Apache License, Version 2.0 (the
  22561. * "License"); you may not use this file except in compliance
  22562. * with the License. You may obtain a copy of the License at
  22563. *
  22564. * http://www.apache.org/licenses/LICENSE-2.0
  22565. *
  22566. * Unless required by applicable law or agreed to in writing,
  22567. * software distributed under the License is distributed on an
  22568. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22569. * KIND, either express or implied. See the License for the
  22570. * specific language governing permissions and limitations
  22571. * under the License.
  22572. */
  22573. var aria = function (dom, ecModel) {
  22574. var ariaModel = ecModel.getModel('aria');
  22575. if (!ariaModel.get('show')) {
  22576. return;
  22577. }
  22578. else if (ariaModel.get('description')) {
  22579. dom.setAttribute('aria-label', ariaModel.get('description'));
  22580. return;
  22581. }
  22582. var seriesCnt = 0;
  22583. ecModel.eachSeries(function (seriesModel, idx) {
  22584. ++seriesCnt;
  22585. }, this);
  22586. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  22587. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  22588. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  22589. var ariaLabel;
  22590. if (seriesCnt < 1) {
  22591. // No series, no aria label
  22592. return;
  22593. }
  22594. else {
  22595. var title = getTitle();
  22596. if (title) {
  22597. ariaLabel = replace(getConfig('general.withTitle'), {
  22598. title: title
  22599. });
  22600. }
  22601. else {
  22602. ariaLabel = getConfig('general.withoutTitle');
  22603. }
  22604. var seriesLabels = [];
  22605. var prefix = seriesCnt > 1
  22606. ? 'series.multiple.prefix'
  22607. : 'series.single.prefix';
  22608. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  22609. ecModel.eachSeries(function (seriesModel, idx) {
  22610. if (idx < displaySeriesCnt) {
  22611. var seriesLabel;
  22612. var seriesName = seriesModel.get('name');
  22613. var seriesTpl = 'series.'
  22614. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  22615. seriesLabel = getConfig(seriesName
  22616. ? seriesTpl + 'withName'
  22617. : seriesTpl + 'withoutName');
  22618. seriesLabel = replace(seriesLabel, {
  22619. seriesId: seriesModel.seriesIndex,
  22620. seriesName: seriesModel.get('name'),
  22621. seriesType: getSeriesTypeName(seriesModel.subType)
  22622. });
  22623. var data = seriesModel.getData();
  22624. window.data = data;
  22625. if (data.count() > maxDataCnt) {
  22626. // Show part of data
  22627. seriesLabel += replace(getConfig('data.partialData'), {
  22628. displayCnt: maxDataCnt
  22629. });
  22630. }
  22631. else {
  22632. seriesLabel += getConfig('data.allData');
  22633. }
  22634. var dataLabels = [];
  22635. for (var i = 0; i < data.count(); i++) {
  22636. if (i < maxDataCnt) {
  22637. var name = data.getName(i);
  22638. var value = retrieveRawValue(data, i);
  22639. dataLabels.push(
  22640. replace(
  22641. name
  22642. ? getConfig('data.withName')
  22643. : getConfig('data.withoutName'),
  22644. {
  22645. name: name,
  22646. value: value
  22647. }
  22648. )
  22649. );
  22650. }
  22651. }
  22652. seriesLabel += dataLabels
  22653. .join(getConfig('data.separator.middle'))
  22654. + getConfig('data.separator.end');
  22655. seriesLabels.push(seriesLabel);
  22656. }
  22657. });
  22658. ariaLabel += seriesLabels
  22659. .join(getConfig('series.multiple.separator.middle'))
  22660. + getConfig('series.multiple.separator.end');
  22661. dom.setAttribute('aria-label', ariaLabel);
  22662. }
  22663. function replace(str, keyValues) {
  22664. if (typeof str !== 'string') {
  22665. return str;
  22666. }
  22667. var result = str;
  22668. each$1(keyValues, function (value, key) {
  22669. result = result.replace(
  22670. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  22671. value
  22672. );
  22673. });
  22674. return result;
  22675. }
  22676. function getConfig(path) {
  22677. var userConfig = ariaModel.get(path);
  22678. if (userConfig == null) {
  22679. var pathArr = path.split('.');
  22680. var result = lang.aria;
  22681. for (var i = 0; i < pathArr.length; ++i) {
  22682. result = result[pathArr[i]];
  22683. }
  22684. return result;
  22685. }
  22686. else {
  22687. return userConfig;
  22688. }
  22689. }
  22690. function getTitle() {
  22691. var title = ecModel.getModel('title').option;
  22692. if (title && title.length) {
  22693. title = title[0];
  22694. }
  22695. return title && title.text;
  22696. }
  22697. function getSeriesTypeName(type) {
  22698. return lang.series.typeNames[type] || '自定义图';
  22699. }
  22700. };
  22701. /*
  22702. * Licensed to the Apache Software Foundation (ASF) under one
  22703. * or more contributor license agreements. See the NOTICE file
  22704. * distributed with this work for additional information
  22705. * regarding copyright ownership. The ASF licenses this file
  22706. * to you under the Apache License, Version 2.0 (the
  22707. * "License"); you may not use this file except in compliance
  22708. * with the License. You may obtain a copy of the License at
  22709. *
  22710. * http://www.apache.org/licenses/LICENSE-2.0
  22711. *
  22712. * Unless required by applicable law or agreed to in writing,
  22713. * software distributed under the License is distributed on an
  22714. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22715. * KIND, either express or implied. See the License for the
  22716. * specific language governing permissions and limitations
  22717. * under the License.
  22718. */
  22719. var PI$1 = Math.PI;
  22720. /**
  22721. * @param {module:echarts/ExtensionAPI} api
  22722. * @param {Object} [opts]
  22723. * @param {string} [opts.text]
  22724. * @param {string} [opts.color]
  22725. * @param {string} [opts.textColor]
  22726. * @return {module:zrender/Element}
  22727. */
  22728. var loadingDefault = function (api, opts) {
  22729. opts = opts || {};
  22730. defaults(opts, {
  22731. text: 'loading',
  22732. textColor: '#000',
  22733. fontSize: '12px',
  22734. maskColor: 'rgba(255, 255, 255, 0.8)',
  22735. showSpinner: true,
  22736. color: '#c23531',
  22737. spinnerRadius: 10,
  22738. lineWidth: 5,
  22739. zlevel: 0
  22740. });
  22741. var group = new Group();
  22742. var mask = new Rect({
  22743. style: {
  22744. fill: opts.maskColor
  22745. },
  22746. zlevel: opts.zlevel,
  22747. z: 10000
  22748. });
  22749. group.add(mask);
  22750. var font = opts.fontSize + ' sans-serif';
  22751. var labelRect = new Rect({
  22752. style: {
  22753. fill: 'none',
  22754. text: opts.text,
  22755. font: font,
  22756. textPosition: 'right',
  22757. textDistance: 10,
  22758. textFill: opts.textColor
  22759. },
  22760. zlevel: opts.zlevel,
  22761. z: 10001
  22762. });
  22763. group.add(labelRect);
  22764. if (opts.showSpinner) {
  22765. var arc = new Arc({
  22766. shape: {
  22767. startAngle: -PI$1 / 2,
  22768. endAngle: -PI$1 / 2 + 0.1,
  22769. r: opts.spinnerRadius
  22770. },
  22771. style: {
  22772. stroke: opts.color,
  22773. lineCap: 'round',
  22774. lineWidth: opts.lineWidth
  22775. },
  22776. zlevel: opts.zlevel,
  22777. z: 10001
  22778. });
  22779. arc.animateShape(true)
  22780. .when(1000, {
  22781. endAngle: PI$1 * 3 / 2
  22782. })
  22783. .start('circularInOut');
  22784. arc.animateShape(true)
  22785. .when(1000, {
  22786. startAngle: PI$1 * 3 / 2
  22787. })
  22788. .delay(300)
  22789. .start('circularInOut');
  22790. group.add(arc);
  22791. }
  22792. // Inject resize
  22793. group.resize = function () {
  22794. var textWidth = getWidth(opts.text, font);
  22795. var r = opts.showSpinner ? opts.spinnerRadius : 0;
  22796. // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  22797. // textDistance needs to be calculated when both animation and text exist
  22798. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2
  22799. // only show the text
  22800. - (opts.showSpinner ? 0 : textWidth / 2);
  22801. var cy = api.getHeight() / 2;
  22802. opts.showSpinner && arc.setShape({
  22803. cx: cx,
  22804. cy: cy
  22805. });
  22806. labelRect.setShape({
  22807. x: cx - r,
  22808. y: cy - r,
  22809. width: r * 2,
  22810. height: r * 2
  22811. });
  22812. mask.setShape({
  22813. x: 0,
  22814. y: 0,
  22815. width: api.getWidth(),
  22816. height: api.getHeight()
  22817. });
  22818. };
  22819. group.resize();
  22820. return group;
  22821. };
  22822. /*
  22823. * Licensed to the Apache Software Foundation (ASF) under one
  22824. * or more contributor license agreements. See the NOTICE file
  22825. * distributed with this work for additional information
  22826. * regarding copyright ownership. The ASF licenses this file
  22827. * to you under the Apache License, Version 2.0 (the
  22828. * "License"); you may not use this file except in compliance
  22829. * with the License. You may obtain a copy of the License at
  22830. *
  22831. * http://www.apache.org/licenses/LICENSE-2.0
  22832. *
  22833. * Unless required by applicable law or agreed to in writing,
  22834. * software distributed under the License is distributed on an
  22835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22836. * KIND, either express or implied. See the License for the
  22837. * specific language governing permissions and limitations
  22838. * under the License.
  22839. */
  22840. /**
  22841. * @module echarts/stream/Scheduler
  22842. */
  22843. /**
  22844. * @constructor
  22845. */
  22846. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22847. this.ecInstance = ecInstance;
  22848. this.api = api;
  22849. this.unfinished;
  22850. // Fix current processors in case that in some rear cases that
  22851. // processors might be registered after echarts instance created.
  22852. // Register processors incrementally for a echarts instance is
  22853. // not supported by this stream architecture.
  22854. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22855. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22856. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22857. /**
  22858. * @private
  22859. * @type {
  22860. * [handlerUID: string]: {
  22861. * seriesTaskMap?: {
  22862. * [seriesUID: string]: Task
  22863. * },
  22864. * overallTask?: Task
  22865. * }
  22866. * }
  22867. */
  22868. this._stageTaskMap = createHashMap();
  22869. }
  22870. var proto = Scheduler.prototype;
  22871. /**
  22872. * @param {module:echarts/model/Global} ecModel
  22873. * @param {Object} payload
  22874. */
  22875. proto.restoreData = function (ecModel, payload) {
  22876. // TODO: Only restore needed series and components, but not all components.
  22877. // Currently `restoreData` of all of the series and component will be called.
  22878. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22879. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22880. // and some components like coordinate system, axes, dataZoom, visualMap only
  22881. // need their target series refresh.
  22882. // (1) If we are implementing this feature some day, we should consider these cases:
  22883. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22884. // on the settings of `dataZoom`), it should be re-performed if the component
  22885. // is modified by `setOption`.
  22886. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22887. // it should be re-performed when the result array of `getTargetSeries` changed.
  22888. // We use `dependencies` to cover these issues.
  22889. // (3) How to update target series when coordinate system related components modified.
  22890. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22891. // and this case all of the tasks will be set as dirty.
  22892. ecModel.restoreData(payload);
  22893. // Theoretically an overall task not only depends on each of its target series, but also
  22894. // depends on all of the series.
  22895. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22896. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22897. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22898. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22899. // probably cause state chaos (consider `dataZoomProcessor`).
  22900. this._stageTaskMap.each(function (taskRecord) {
  22901. var overallTask = taskRecord.overallTask;
  22902. overallTask && overallTask.dirty();
  22903. });
  22904. };
  22905. // If seriesModel provided, incremental threshold is check by series data.
  22906. proto.getPerformArgs = function (task, isBlock) {
  22907. // For overall task
  22908. if (!task.__pipeline) {
  22909. return;
  22910. }
  22911. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22912. var pCtx = pipeline.context;
  22913. var incremental = !isBlock
  22914. && pipeline.progressiveEnabled
  22915. && (!pCtx || pCtx.progressiveRender)
  22916. && task.__idxInPipeline > pipeline.blockIndex;
  22917. var step = incremental ? pipeline.step : null;
  22918. var modDataCount = pCtx && pCtx.modDataCount;
  22919. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22920. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22921. };
  22922. proto.getPipeline = function (pipelineId) {
  22923. return this._pipelineMap.get(pipelineId);
  22924. };
  22925. /**
  22926. * Current, progressive rendering starts from visual and layout.
  22927. * Always detect render mode in the same stage, avoiding that incorrect
  22928. * detection caused by data filtering.
  22929. * Caution:
  22930. * `updateStreamModes` use `seriesModel.getData()`.
  22931. */
  22932. proto.updateStreamModes = function (seriesModel, view) {
  22933. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22934. var data = seriesModel.getData();
  22935. var dataLen = data.count();
  22936. // `progressiveRender` means that can render progressively in each
  22937. // animation frame. Note that some types of series do not provide
  22938. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22939. // use the term `incremental` but not `progressive` to describe the
  22940. // case that `chart.appendData`.
  22941. var progressiveRender = pipeline.progressiveEnabled
  22942. && view.incrementalPrepareRender
  22943. && dataLen >= pipeline.threshold;
  22944. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22945. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22946. // see `test/candlestick-large3.html`
  22947. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22948. seriesModel.pipelineContext = pipeline.context = {
  22949. progressiveRender: progressiveRender,
  22950. modDataCount: modDataCount,
  22951. large: large
  22952. };
  22953. };
  22954. proto.restorePipelines = function (ecModel) {
  22955. var scheduler = this;
  22956. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22957. ecModel.eachSeries(function (seriesModel) {
  22958. var progressive = seriesModel.getProgressive();
  22959. var pipelineId = seriesModel.uid;
  22960. pipelineMap.set(pipelineId, {
  22961. id: pipelineId,
  22962. head: null,
  22963. tail: null,
  22964. threshold: seriesModel.getProgressiveThreshold(),
  22965. progressiveEnabled: progressive
  22966. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22967. blockIndex: -1,
  22968. step: Math.round(progressive || 700),
  22969. count: 0
  22970. });
  22971. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22972. });
  22973. };
  22974. proto.prepareStageTasks = function () {
  22975. var stageTaskMap = this._stageTaskMap;
  22976. var ecModel = this.ecInstance.getModel();
  22977. var api = this.api;
  22978. each$1(this._allHandlers, function (handler) {
  22979. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22980. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22981. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22982. }, this);
  22983. };
  22984. proto.prepareView = function (view, model, ecModel, api) {
  22985. var renderTask = view.renderTask;
  22986. var context = renderTask.context;
  22987. context.model = model;
  22988. context.ecModel = ecModel;
  22989. context.api = api;
  22990. renderTask.__block = !view.incrementalPrepareRender;
  22991. pipe(this, model, renderTask);
  22992. };
  22993. proto.performDataProcessorTasks = function (ecModel, payload) {
  22994. // If we do not use `block` here, it should be considered when to update modes.
  22995. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22996. };
  22997. // opt
  22998. // opt.visualType: 'visual' or 'layout'
  22999. // opt.setDirty
  23000. proto.performVisualTasks = function (ecModel, payload, opt) {
  23001. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  23002. };
  23003. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  23004. opt = opt || {};
  23005. var unfinished;
  23006. each$1(stageHandlers, function (stageHandler, idx) {
  23007. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  23008. return;
  23009. }
  23010. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  23011. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23012. var overallTask = stageHandlerRecord.overallTask;
  23013. if (overallTask) {
  23014. var overallNeedDirty;
  23015. var agentStubMap = overallTask.agentStubMap;
  23016. agentStubMap.each(function (stub) {
  23017. if (needSetDirty(opt, stub)) {
  23018. stub.dirty();
  23019. overallNeedDirty = true;
  23020. }
  23021. });
  23022. overallNeedDirty && overallTask.dirty();
  23023. updatePayload(overallTask, payload);
  23024. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  23025. // Execute stubs firstly, which may set the overall task dirty,
  23026. // then execute the overall task. And stub will call seriesModel.setData,
  23027. // which ensures that in the overallTask seriesModel.getData() will not
  23028. // return incorrect data.
  23029. agentStubMap.each(function (stub) {
  23030. stub.perform(performArgs);
  23031. });
  23032. unfinished |= overallTask.perform(performArgs);
  23033. }
  23034. else if (seriesTaskMap) {
  23035. seriesTaskMap.each(function (task, pipelineId) {
  23036. if (needSetDirty(opt, task)) {
  23037. task.dirty();
  23038. }
  23039. var performArgs = scheduler.getPerformArgs(task, opt.block);
  23040. // FIXME
  23041. // if intending to decalare `performRawSeries` in handlers, only
  23042. // stream-independent (specifically, data item independent) operations can be
  23043. // performed. Because is a series is filtered, most of the tasks will not
  23044. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23045. // Perhaps we should not provide a separate callback for this case instead
  23046. // of providing the config `performRawSeries`. The stream-dependent operaions
  23047. // and stream-independent operations should better not be mixed.
  23048. performArgs.skip = !stageHandler.performRawSeries
  23049. && ecModel.isSeriesFiltered(task.context.model);
  23050. updatePayload(task, payload);
  23051. unfinished |= task.perform(performArgs);
  23052. });
  23053. }
  23054. });
  23055. function needSetDirty(opt, task) {
  23056. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23057. }
  23058. scheduler.unfinished |= unfinished;
  23059. }
  23060. proto.performSeriesTasks = function (ecModel) {
  23061. var unfinished;
  23062. ecModel.eachSeries(function (seriesModel) {
  23063. // Progress to the end for dataInit and dataRestore.
  23064. unfinished |= seriesModel.dataTask.perform();
  23065. });
  23066. this.unfinished |= unfinished;
  23067. };
  23068. proto.plan = function () {
  23069. // Travel pipelines, check block.
  23070. this._pipelineMap.each(function (pipeline) {
  23071. var task = pipeline.tail;
  23072. do {
  23073. if (task.__block) {
  23074. pipeline.blockIndex = task.__idxInPipeline;
  23075. break;
  23076. }
  23077. task = task.getUpstream();
  23078. }
  23079. while (task);
  23080. });
  23081. };
  23082. var updatePayload = proto.updatePayload = function (task, payload) {
  23083. payload !== 'remain' && (task.context.payload = payload);
  23084. };
  23085. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  23086. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  23087. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  23088. var seriesType = stageHandler.seriesType;
  23089. var getTargetSeries = stageHandler.getTargetSeries;
  23090. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23091. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23092. // it works but it may cause other irrelevant charts blocked.
  23093. if (stageHandler.createOnAllSeries) {
  23094. ecModel.eachRawSeries(create);
  23095. }
  23096. else if (seriesType) {
  23097. ecModel.eachRawSeriesByType(seriesType, create);
  23098. }
  23099. else if (getTargetSeries) {
  23100. getTargetSeries(ecModel, api).each(create);
  23101. }
  23102. function create(seriesModel) {
  23103. var pipelineId = seriesModel.uid;
  23104. // Init tasks for each seriesModel only once.
  23105. // Reuse original task instance.
  23106. var task = seriesTaskMap.get(pipelineId)
  23107. || seriesTaskMap.set(pipelineId, createTask({
  23108. plan: seriesTaskPlan,
  23109. reset: seriesTaskReset,
  23110. count: seriesTaskCount
  23111. }));
  23112. task.context = {
  23113. model: seriesModel,
  23114. ecModel: ecModel,
  23115. api: api,
  23116. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23117. plan: stageHandler.plan,
  23118. reset: stageHandler.reset,
  23119. scheduler: scheduler
  23120. };
  23121. pipe(scheduler, seriesModel, task);
  23122. }
  23123. // Clear unused series tasks.
  23124. var pipelineMap = scheduler._pipelineMap;
  23125. seriesTaskMap.each(function (task, pipelineId) {
  23126. if (!pipelineMap.get(pipelineId)) {
  23127. task.dispose();
  23128. seriesTaskMap.removeKey(pipelineId);
  23129. }
  23130. });
  23131. }
  23132. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  23133. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  23134. // For overall task, the function only be called on reset stage.
  23135. || createTask({reset: overallTaskReset});
  23136. overallTask.context = {
  23137. ecModel: ecModel,
  23138. api: api,
  23139. overallReset: stageHandler.overallReset,
  23140. scheduler: scheduler
  23141. };
  23142. // Reuse orignal stubs.
  23143. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  23144. var seriesType = stageHandler.seriesType;
  23145. var getTargetSeries = stageHandler.getTargetSeries;
  23146. var overallProgress = true;
  23147. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  23148. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23149. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23150. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23151. // we set the pipeline block.
  23152. if (seriesType) {
  23153. ecModel.eachRawSeriesByType(seriesType, createStub);
  23154. }
  23155. else if (getTargetSeries) {
  23156. getTargetSeries(ecModel, api).each(createStub);
  23157. }
  23158. // Otherwise, (usually it is legancy case), the overall task will only be
  23159. // executed when upstream dirty. Otherwise the progressive rendering of all
  23160. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23161. // dirty info from upsteam.
  23162. else {
  23163. overallProgress = false;
  23164. each$1(ecModel.getSeries(), createStub);
  23165. }
  23166. function createStub(seriesModel) {
  23167. var pipelineId = seriesModel.uid;
  23168. var stub = agentStubMap.get(pipelineId);
  23169. if (!stub) {
  23170. stub = agentStubMap.set(pipelineId, createTask(
  23171. {reset: stubReset, onDirty: stubOnDirty}
  23172. ));
  23173. // When the result of `getTargetSeries` changed, the overallTask
  23174. // should be set as dirty and re-performed.
  23175. overallTask.dirty();
  23176. }
  23177. stub.context = {
  23178. model: seriesModel,
  23179. overallProgress: overallProgress,
  23180. modifyOutputEnd: modifyOutputEnd
  23181. };
  23182. stub.agent = overallTask;
  23183. stub.__block = overallProgress;
  23184. pipe(scheduler, seriesModel, stub);
  23185. }
  23186. // Clear unused stubs.
  23187. var pipelineMap = scheduler._pipelineMap;
  23188. agentStubMap.each(function (stub, pipelineId) {
  23189. if (!pipelineMap.get(pipelineId)) {
  23190. stub.dispose();
  23191. // When the result of `getTargetSeries` changed, the overallTask
  23192. // should be set as dirty and re-performed.
  23193. overallTask.dirty();
  23194. agentStubMap.removeKey(pipelineId);
  23195. }
  23196. });
  23197. }
  23198. function overallTaskReset(context) {
  23199. context.overallReset(
  23200. context.ecModel, context.api, context.payload
  23201. );
  23202. }
  23203. function stubReset(context, upstreamContext) {
  23204. return context.overallProgress && stubProgress;
  23205. }
  23206. function stubProgress() {
  23207. this.agent.dirty();
  23208. this.getDownstream().dirty();
  23209. }
  23210. function stubOnDirty() {
  23211. this.agent && this.agent.dirty();
  23212. }
  23213. function seriesTaskPlan(context) {
  23214. return context.plan && context.plan(
  23215. context.model, context.ecModel, context.api, context.payload
  23216. );
  23217. }
  23218. function seriesTaskReset(context) {
  23219. if (context.useClearVisual) {
  23220. context.data.clearAllVisual();
  23221. }
  23222. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  23223. context.model, context.ecModel, context.api, context.payload
  23224. ));
  23225. return resetDefines.length > 1
  23226. ? map(resetDefines, function (v, idx) {
  23227. return makeSeriesTaskProgress(idx);
  23228. })
  23229. : singleSeriesTaskProgress;
  23230. }
  23231. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23232. function makeSeriesTaskProgress(resetDefineIdx) {
  23233. return function (params, context) {
  23234. var data = context.data;
  23235. var resetDefine = context.resetDefines[resetDefineIdx];
  23236. if (resetDefine && resetDefine.dataEach) {
  23237. for (var i = params.start; i < params.end; i++) {
  23238. resetDefine.dataEach(data, i);
  23239. }
  23240. }
  23241. else if (resetDefine && resetDefine.progress) {
  23242. resetDefine.progress(params, data);
  23243. }
  23244. };
  23245. }
  23246. function seriesTaskCount(context) {
  23247. return context.data.count();
  23248. }
  23249. function pipe(scheduler, seriesModel, task) {
  23250. var pipelineId = seriesModel.uid;
  23251. var pipeline = scheduler._pipelineMap.get(pipelineId);
  23252. !pipeline.head && (pipeline.head = task);
  23253. pipeline.tail && pipeline.tail.pipe(task);
  23254. pipeline.tail = task;
  23255. task.__idxInPipeline = pipeline.count++;
  23256. task.__pipeline = pipeline;
  23257. }
  23258. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23259. if (isFunction$1(stageHandler)) {
  23260. stageHandler = {
  23261. overallReset: stageHandler,
  23262. seriesType: detectSeriseType(stageHandler)
  23263. };
  23264. }
  23265. stageHandler.uid = getUID('stageHandler');
  23266. visualType && (stageHandler.visualType = visualType);
  23267. return stageHandler;
  23268. };
  23269. /**
  23270. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23271. * To ensure that they can work normally, they should work in block mode, that is,
  23272. * they should not be started util the previous tasks finished. So they cause the
  23273. * progressive rendering disabled. We try to detect the series type, to narrow down
  23274. * the block range to only the series type they concern, but not all series.
  23275. */
  23276. function detectSeriseType(legacyFunc) {
  23277. seriesType = null;
  23278. try {
  23279. // Assume there is no async when calling `eachSeriesByType`.
  23280. legacyFunc(ecModelMock, apiMock);
  23281. }
  23282. catch (e) {
  23283. }
  23284. return seriesType;
  23285. }
  23286. var ecModelMock = {};
  23287. var apiMock = {};
  23288. var seriesType;
  23289. mockMethods(ecModelMock, GlobalModel);
  23290. mockMethods(apiMock, ExtensionAPI);
  23291. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23292. seriesType = type;
  23293. };
  23294. ecModelMock.eachComponent = function (cond) {
  23295. if (cond.mainType === 'series' && cond.subType) {
  23296. seriesType = cond.subType;
  23297. }
  23298. };
  23299. function mockMethods(target, Clz) {
  23300. /* eslint-disable */
  23301. for (var name in Clz.prototype) {
  23302. // Do not use hasOwnProperty
  23303. target[name] = noop;
  23304. }
  23305. /* eslint-enable */
  23306. }
  23307. /*
  23308. * Licensed to the Apache Software Foundation (ASF) under one
  23309. * or more contributor license agreements. See the NOTICE file
  23310. * distributed with this work for additional information
  23311. * regarding copyright ownership. The ASF licenses this file
  23312. * to you under the Apache License, Version 2.0 (the
  23313. * "License"); you may not use this file except in compliance
  23314. * with the License. You may obtain a copy of the License at
  23315. *
  23316. * http://www.apache.org/licenses/LICENSE-2.0
  23317. *
  23318. * Unless required by applicable law or agreed to in writing,
  23319. * software distributed under the License is distributed on an
  23320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23321. * KIND, either express or implied. See the License for the
  23322. * specific language governing permissions and limitations
  23323. * under the License.
  23324. */
  23325. var colorAll = [
  23326. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  23327. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  23328. ];
  23329. var lightTheme = {
  23330. color: colorAll,
  23331. colorLayer: [
  23332. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  23333. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  23334. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  23335. colorAll
  23336. ]
  23337. };
  23338. /*
  23339. * Licensed to the Apache Software Foundation (ASF) under one
  23340. * or more contributor license agreements. See the NOTICE file
  23341. * distributed with this work for additional information
  23342. * regarding copyright ownership. The ASF licenses this file
  23343. * to you under the Apache License, Version 2.0 (the
  23344. * "License"); you may not use this file except in compliance
  23345. * with the License. You may obtain a copy of the License at
  23346. *
  23347. * http://www.apache.org/licenses/LICENSE-2.0
  23348. *
  23349. * Unless required by applicable law or agreed to in writing,
  23350. * software distributed under the License is distributed on an
  23351. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23352. * KIND, either express or implied. See the License for the
  23353. * specific language governing permissions and limitations
  23354. * under the License.
  23355. */
  23356. var contrastColor = '#eee';
  23357. var axisCommon = function () {
  23358. return {
  23359. axisLine: {
  23360. lineStyle: {
  23361. color: contrastColor
  23362. }
  23363. },
  23364. axisTick: {
  23365. lineStyle: {
  23366. color: contrastColor
  23367. }
  23368. },
  23369. axisLabel: {
  23370. textStyle: {
  23371. color: contrastColor
  23372. }
  23373. },
  23374. splitLine: {
  23375. lineStyle: {
  23376. type: 'dashed',
  23377. color: '#aaa'
  23378. }
  23379. },
  23380. splitArea: {
  23381. areaStyle: {
  23382. color: contrastColor
  23383. }
  23384. }
  23385. };
  23386. };
  23387. var colorPalette = [
  23388. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  23389. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  23390. ];
  23391. var theme = {
  23392. color: colorPalette,
  23393. backgroundColor: '#333',
  23394. tooltip: {
  23395. axisPointer: {
  23396. lineStyle: {
  23397. color: contrastColor
  23398. },
  23399. crossStyle: {
  23400. color: contrastColor
  23401. },
  23402. label: {
  23403. color: '#000'
  23404. }
  23405. }
  23406. },
  23407. legend: {
  23408. textStyle: {
  23409. color: contrastColor
  23410. }
  23411. },
  23412. textStyle: {
  23413. color: contrastColor
  23414. },
  23415. title: {
  23416. textStyle: {
  23417. color: contrastColor
  23418. }
  23419. },
  23420. toolbox: {
  23421. iconStyle: {
  23422. normal: {
  23423. borderColor: contrastColor
  23424. }
  23425. }
  23426. },
  23427. dataZoom: {
  23428. textStyle: {
  23429. color: contrastColor
  23430. }
  23431. },
  23432. visualMap: {
  23433. textStyle: {
  23434. color: contrastColor
  23435. }
  23436. },
  23437. timeline: {
  23438. lineStyle: {
  23439. color: contrastColor
  23440. },
  23441. itemStyle: {
  23442. normal: {
  23443. color: colorPalette[1]
  23444. }
  23445. },
  23446. label: {
  23447. normal: {
  23448. textStyle: {
  23449. color: contrastColor
  23450. }
  23451. }
  23452. },
  23453. controlStyle: {
  23454. normal: {
  23455. color: contrastColor,
  23456. borderColor: contrastColor
  23457. }
  23458. }
  23459. },
  23460. timeAxis: axisCommon(),
  23461. logAxis: axisCommon(),
  23462. valueAxis: axisCommon(),
  23463. categoryAxis: axisCommon(),
  23464. line: {
  23465. symbol: 'circle'
  23466. },
  23467. graph: {
  23468. color: colorPalette
  23469. },
  23470. gauge: {
  23471. title: {
  23472. textStyle: {
  23473. color: contrastColor
  23474. }
  23475. }
  23476. },
  23477. candlestick: {
  23478. itemStyle: {
  23479. normal: {
  23480. color: '#FD1050',
  23481. color0: '#0CF49B',
  23482. borderColor: '#FD1050',
  23483. borderColor0: '#0CF49B'
  23484. }
  23485. }
  23486. }
  23487. };
  23488. theme.categoryAxis.splitLine.show = false;
  23489. /*
  23490. * Licensed to the Apache Software Foundation (ASF) under one
  23491. * or more contributor license agreements. See the NOTICE file
  23492. * distributed with this work for additional information
  23493. * regarding copyright ownership. The ASF licenses this file
  23494. * to you under the Apache License, Version 2.0 (the
  23495. * "License"); you may not use this file except in compliance
  23496. * with the License. You may obtain a copy of the License at
  23497. *
  23498. * http://www.apache.org/licenses/LICENSE-2.0
  23499. *
  23500. * Unless required by applicable law or agreed to in writing,
  23501. * software distributed under the License is distributed on an
  23502. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23503. * KIND, either express or implied. See the License for the
  23504. * specific language governing permissions and limitations
  23505. * under the License.
  23506. */
  23507. /**
  23508. * This module is imported by echarts directly.
  23509. *
  23510. * Notice:
  23511. * Always keep this file exists for backward compatibility.
  23512. * Because before 4.1.0, dataset is an optional component,
  23513. * some users may import this module manually.
  23514. */
  23515. ComponentModel.extend({
  23516. type: 'dataset',
  23517. /**
  23518. * @protected
  23519. */
  23520. defaultOption: {
  23521. // 'row', 'column'
  23522. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  23523. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  23524. sourceHeader: null,
  23525. dimensions: null,
  23526. source: null
  23527. },
  23528. optionUpdated: function () {
  23529. detectSourceFormat(this);
  23530. }
  23531. });
  23532. Component$1.extend({
  23533. type: 'dataset'
  23534. });
  23535. /**
  23536. * 椭圆形状
  23537. * @module zrender/graphic/shape/Ellipse
  23538. */
  23539. var Ellipse = Path.extend({
  23540. type: 'ellipse',
  23541. shape: {
  23542. cx: 0, cy: 0,
  23543. rx: 0, ry: 0
  23544. },
  23545. buildPath: function (ctx, shape) {
  23546. var k = 0.5522848;
  23547. var x = shape.cx;
  23548. var y = shape.cy;
  23549. var a = shape.rx;
  23550. var b = shape.ry;
  23551. var ox = a * k; // 水平控制点偏移量
  23552. var oy = b * k; // 垂直控制点偏移量
  23553. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  23554. ctx.moveTo(x - a, y);
  23555. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  23556. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  23557. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  23558. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  23559. ctx.closePath();
  23560. }
  23561. });
  23562. // import RadialGradient from '../graphic/RadialGradient';
  23563. // import Pattern from '../graphic/Pattern';
  23564. // import * as vector from '../core/vector';
  23565. // Most of the values can be separated by comma and/or white space.
  23566. var DILIMITER_REG = /[\s,]+/;
  23567. /**
  23568. * For big svg string, this method might be time consuming.
  23569. *
  23570. * @param {string} svg xml string
  23571. * @return {Object} xml root.
  23572. */
  23573. function parseXML(svg) {
  23574. if (isString(svg)) {
  23575. var parser = new DOMParser();
  23576. svg = parser.parseFromString(svg, 'text/xml');
  23577. }
  23578. // Document node. If using $.get, doc node may be input.
  23579. if (svg.nodeType === 9) {
  23580. svg = svg.firstChild;
  23581. }
  23582. // nodeName of <!DOCTYPE svg> is also 'svg'.
  23583. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  23584. svg = svg.nextSibling;
  23585. }
  23586. return svg;
  23587. }
  23588. function SVGParser() {
  23589. this._defs = {};
  23590. this._root = null;
  23591. this._isDefine = false;
  23592. this._isText = false;
  23593. }
  23594. SVGParser.prototype.parse = function (xml, opt) {
  23595. opt = opt || {};
  23596. var svg = parseXML(xml);
  23597. if (!svg) {
  23598. throw new Error('Illegal svg');
  23599. }
  23600. var root = new Group();
  23601. this._root = root;
  23602. // parse view port
  23603. var viewBox = svg.getAttribute('viewBox') || '';
  23604. // If width/height not specified, means "100%" of `opt.width/height`.
  23605. // TODO: Other percent value not supported yet.
  23606. var width = parseFloat(svg.getAttribute('width') || opt.width);
  23607. var height = parseFloat(svg.getAttribute('height') || opt.height);
  23608. // If width/height not specified, set as null for output.
  23609. isNaN(width) && (width = null);
  23610. isNaN(height) && (height = null);
  23611. // Apply inline style on svg element.
  23612. parseAttributes(svg, root, null, true);
  23613. var child = svg.firstChild;
  23614. while (child) {
  23615. this._parseNode(child, root);
  23616. child = child.nextSibling;
  23617. }
  23618. var viewBoxRect;
  23619. var viewBoxTransform;
  23620. if (viewBox) {
  23621. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  23622. // Some invalid case like viewBox: 'none'.
  23623. if (viewBoxArr.length >= 4) {
  23624. viewBoxRect = {
  23625. x: parseFloat(viewBoxArr[0] || 0),
  23626. y: parseFloat(viewBoxArr[1] || 0),
  23627. width: parseFloat(viewBoxArr[2]),
  23628. height: parseFloat(viewBoxArr[3])
  23629. };
  23630. }
  23631. }
  23632. if (viewBoxRect && width != null && height != null) {
  23633. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  23634. if (!opt.ignoreViewBox) {
  23635. // If set transform on the output group, it probably bring trouble when
  23636. // some users only intend to show the clipped content inside the viewBox,
  23637. // but not intend to transform the output group. So we keep the output
  23638. // group no transform. If the user intend to use the viewBox as a
  23639. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  23640. // manually according to the viewBox info in the output of this method.
  23641. var elRoot = root;
  23642. root = new Group();
  23643. root.add(elRoot);
  23644. elRoot.scale = viewBoxTransform.scale.slice();
  23645. elRoot.position = viewBoxTransform.position.slice();
  23646. }
  23647. }
  23648. // Some shapes might be overflow the viewport, which should be
  23649. // clipped despite whether the viewBox is used, as the SVG does.
  23650. if (!opt.ignoreRootClip && width != null && height != null) {
  23651. root.setClipPath(new Rect({
  23652. shape: {x: 0, y: 0, width: width, height: height}
  23653. }));
  23654. }
  23655. // Set width/height on group just for output the viewport size.
  23656. return {
  23657. root: root,
  23658. width: width,
  23659. height: height,
  23660. viewBoxRect: viewBoxRect,
  23661. viewBoxTransform: viewBoxTransform
  23662. };
  23663. };
  23664. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  23665. var nodeName = xmlNode.nodeName.toLowerCase();
  23666. // TODO
  23667. // support <style>...</style> in svg, where nodeName is 'style',
  23668. // CSS classes is defined globally wherever the style tags are declared.
  23669. if (nodeName === 'defs') {
  23670. // define flag
  23671. this._isDefine = true;
  23672. }
  23673. else if (nodeName === 'text') {
  23674. this._isText = true;
  23675. }
  23676. var el;
  23677. if (this._isDefine) {
  23678. var parser = defineParsers[nodeName];
  23679. if (parser) {
  23680. var def = parser.call(this, xmlNode);
  23681. var id = xmlNode.getAttribute('id');
  23682. if (id) {
  23683. this._defs[id] = def;
  23684. }
  23685. }
  23686. }
  23687. else {
  23688. var parser = nodeParsers[nodeName];
  23689. if (parser) {
  23690. el = parser.call(this, xmlNode, parentGroup);
  23691. parentGroup.add(el);
  23692. }
  23693. }
  23694. var child = xmlNode.firstChild;
  23695. while (child) {
  23696. if (child.nodeType === 1) {
  23697. this._parseNode(child, el);
  23698. }
  23699. // Is text
  23700. if (child.nodeType === 3 && this._isText) {
  23701. this._parseText(child, el);
  23702. }
  23703. child = child.nextSibling;
  23704. }
  23705. // Quit define
  23706. if (nodeName === 'defs') {
  23707. this._isDefine = false;
  23708. }
  23709. else if (nodeName === 'text') {
  23710. this._isText = false;
  23711. }
  23712. };
  23713. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  23714. if (xmlNode.nodeType === 1) {
  23715. var dx = xmlNode.getAttribute('dx') || 0;
  23716. var dy = xmlNode.getAttribute('dy') || 0;
  23717. this._textX += parseFloat(dx);
  23718. this._textY += parseFloat(dy);
  23719. }
  23720. var text = new Text({
  23721. style: {
  23722. text: xmlNode.textContent,
  23723. transformText: true
  23724. },
  23725. position: [this._textX || 0, this._textY || 0]
  23726. });
  23727. inheritStyle(parentGroup, text);
  23728. parseAttributes(xmlNode, text, this._defs);
  23729. var fontSize = text.style.fontSize;
  23730. if (fontSize && fontSize < 9) {
  23731. // PENDING
  23732. text.style.fontSize = 9;
  23733. text.scale = text.scale || [1, 1];
  23734. text.scale[0] *= fontSize / 9;
  23735. text.scale[1] *= fontSize / 9;
  23736. }
  23737. var rect = text.getBoundingRect();
  23738. this._textX += rect.width;
  23739. parentGroup.add(text);
  23740. return text;
  23741. };
  23742. var nodeParsers = {
  23743. 'g': function (xmlNode, parentGroup) {
  23744. var g = new Group();
  23745. inheritStyle(parentGroup, g);
  23746. parseAttributes(xmlNode, g, this._defs);
  23747. return g;
  23748. },
  23749. 'rect': function (xmlNode, parentGroup) {
  23750. var rect = new Rect();
  23751. inheritStyle(parentGroup, rect);
  23752. parseAttributes(xmlNode, rect, this._defs);
  23753. rect.setShape({
  23754. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23755. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23756. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23757. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23758. });
  23759. // console.log(xmlNode.getAttribute('transform'));
  23760. // console.log(rect.transform);
  23761. return rect;
  23762. },
  23763. 'circle': function (xmlNode, parentGroup) {
  23764. var circle = new Circle();
  23765. inheritStyle(parentGroup, circle);
  23766. parseAttributes(xmlNode, circle, this._defs);
  23767. circle.setShape({
  23768. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23769. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23770. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23771. });
  23772. return circle;
  23773. },
  23774. 'line': function (xmlNode, parentGroup) {
  23775. var line = new Line();
  23776. inheritStyle(parentGroup, line);
  23777. parseAttributes(xmlNode, line, this._defs);
  23778. line.setShape({
  23779. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23780. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23781. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23782. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23783. });
  23784. return line;
  23785. },
  23786. 'ellipse': function (xmlNode, parentGroup) {
  23787. var ellipse = new Ellipse();
  23788. inheritStyle(parentGroup, ellipse);
  23789. parseAttributes(xmlNode, ellipse, this._defs);
  23790. ellipse.setShape({
  23791. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23792. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23793. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23794. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23795. });
  23796. return ellipse;
  23797. },
  23798. 'polygon': function (xmlNode, parentGroup) {
  23799. var points = xmlNode.getAttribute('points');
  23800. if (points) {
  23801. points = parsePoints(points);
  23802. }
  23803. var polygon = new Polygon({
  23804. shape: {
  23805. points: points || []
  23806. }
  23807. });
  23808. inheritStyle(parentGroup, polygon);
  23809. parseAttributes(xmlNode, polygon, this._defs);
  23810. return polygon;
  23811. },
  23812. 'polyline': function (xmlNode, parentGroup) {
  23813. var path = new Path();
  23814. inheritStyle(parentGroup, path);
  23815. parseAttributes(xmlNode, path, this._defs);
  23816. var points = xmlNode.getAttribute('points');
  23817. if (points) {
  23818. points = parsePoints(points);
  23819. }
  23820. var polyline = new Polyline({
  23821. shape: {
  23822. points: points || []
  23823. }
  23824. });
  23825. return polyline;
  23826. },
  23827. 'image': function (xmlNode, parentGroup) {
  23828. var img = new ZImage();
  23829. inheritStyle(parentGroup, img);
  23830. parseAttributes(xmlNode, img, this._defs);
  23831. img.setStyle({
  23832. image: xmlNode.getAttribute('xlink:href'),
  23833. x: xmlNode.getAttribute('x'),
  23834. y: xmlNode.getAttribute('y'),
  23835. width: xmlNode.getAttribute('width'),
  23836. height: xmlNode.getAttribute('height')
  23837. });
  23838. return img;
  23839. },
  23840. 'text': function (xmlNode, parentGroup) {
  23841. var x = xmlNode.getAttribute('x') || 0;
  23842. var y = xmlNode.getAttribute('y') || 0;
  23843. var dx = xmlNode.getAttribute('dx') || 0;
  23844. var dy = xmlNode.getAttribute('dy') || 0;
  23845. this._textX = parseFloat(x) + parseFloat(dx);
  23846. this._textY = parseFloat(y) + parseFloat(dy);
  23847. var g = new Group();
  23848. inheritStyle(parentGroup, g);
  23849. parseAttributes(xmlNode, g, this._defs);
  23850. return g;
  23851. },
  23852. 'tspan': function (xmlNode, parentGroup) {
  23853. var x = xmlNode.getAttribute('x');
  23854. var y = xmlNode.getAttribute('y');
  23855. if (x != null) {
  23856. // new offset x
  23857. this._textX = parseFloat(x);
  23858. }
  23859. if (y != null) {
  23860. // new offset y
  23861. this._textY = parseFloat(y);
  23862. }
  23863. var dx = xmlNode.getAttribute('dx') || 0;
  23864. var dy = xmlNode.getAttribute('dy') || 0;
  23865. var g = new Group();
  23866. inheritStyle(parentGroup, g);
  23867. parseAttributes(xmlNode, g, this._defs);
  23868. this._textX += dx;
  23869. this._textY += dy;
  23870. return g;
  23871. },
  23872. 'path': function (xmlNode, parentGroup) {
  23873. // TODO svg fill rule
  23874. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23875. // path.style.globalCompositeOperation = 'xor';
  23876. var d = xmlNode.getAttribute('d') || '';
  23877. // Performance sensitive.
  23878. var path = createFromString(d);
  23879. inheritStyle(parentGroup, path);
  23880. parseAttributes(xmlNode, path, this._defs);
  23881. return path;
  23882. }
  23883. };
  23884. var defineParsers = {
  23885. 'lineargradient': function (xmlNode) {
  23886. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23887. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23888. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23889. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23890. var gradient = new LinearGradient(x1, y1, x2, y2);
  23891. _parseGradientColorStops(xmlNode, gradient);
  23892. return gradient;
  23893. },
  23894. 'radialgradient': function (xmlNode) {
  23895. }
  23896. };
  23897. function _parseGradientColorStops(xmlNode, gradient) {
  23898. var stop = xmlNode.firstChild;
  23899. while (stop) {
  23900. if (stop.nodeType === 1) {
  23901. var offset = stop.getAttribute('offset');
  23902. if (offset.indexOf('%') > 0) { // percentage
  23903. offset = parseInt(offset, 10) / 100;
  23904. }
  23905. else if (offset) { // number from 0 to 1
  23906. offset = parseFloat(offset);
  23907. }
  23908. else {
  23909. offset = 0;
  23910. }
  23911. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23912. gradient.addColorStop(offset, stopColor);
  23913. }
  23914. stop = stop.nextSibling;
  23915. }
  23916. }
  23917. function inheritStyle(parent, child) {
  23918. if (parent && parent.__inheritedStyle) {
  23919. if (!child.__inheritedStyle) {
  23920. child.__inheritedStyle = {};
  23921. }
  23922. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23923. }
  23924. }
  23925. function parsePoints(pointsString) {
  23926. var list = trim(pointsString).split(DILIMITER_REG);
  23927. var points = [];
  23928. for (var i = 0; i < list.length; i += 2) {
  23929. var x = parseFloat(list[i]);
  23930. var y = parseFloat(list[i + 1]);
  23931. points.push([x, y]);
  23932. }
  23933. return points;
  23934. }
  23935. var attributesMap = {
  23936. 'fill': 'fill',
  23937. 'stroke': 'stroke',
  23938. 'stroke-width': 'lineWidth',
  23939. 'opacity': 'opacity',
  23940. 'fill-opacity': 'fillOpacity',
  23941. 'stroke-opacity': 'strokeOpacity',
  23942. 'stroke-dasharray': 'lineDash',
  23943. 'stroke-dashoffset': 'lineDashOffset',
  23944. 'stroke-linecap': 'lineCap',
  23945. 'stroke-linejoin': 'lineJoin',
  23946. 'stroke-miterlimit': 'miterLimit',
  23947. 'font-family': 'fontFamily',
  23948. 'font-size': 'fontSize',
  23949. 'font-style': 'fontStyle',
  23950. 'font-weight': 'fontWeight',
  23951. 'text-align': 'textAlign',
  23952. 'alignment-baseline': 'textBaseline'
  23953. };
  23954. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23955. var zrStyle = el.__inheritedStyle || {};
  23956. var isTextEl = el.type === 'text';
  23957. // TODO Shadow
  23958. if (xmlNode.nodeType === 1) {
  23959. parseTransformAttribute(xmlNode, el);
  23960. extend(zrStyle, parseStyleAttribute(xmlNode));
  23961. if (!onlyInlineStyle) {
  23962. for (var svgAttrName in attributesMap) {
  23963. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23964. var attrValue = xmlNode.getAttribute(svgAttrName);
  23965. if (attrValue != null) {
  23966. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23967. }
  23968. }
  23969. }
  23970. }
  23971. }
  23972. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23973. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23974. el.style = el.style || new Style();
  23975. var elStyle = el.style;
  23976. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23977. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23978. each$1([
  23979. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23980. ], function (propName) {
  23981. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23982. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23983. });
  23984. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23985. zrStyle.textBaseline = 'alphabetic';
  23986. }
  23987. if (zrStyle.textBaseline === 'alphabetic') {
  23988. zrStyle.textBaseline = 'bottom';
  23989. }
  23990. if (zrStyle.textAlign === 'start') {
  23991. zrStyle.textAlign = 'left';
  23992. }
  23993. if (zrStyle.textAlign === 'end') {
  23994. zrStyle.textAlign = 'right';
  23995. }
  23996. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23997. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23998. ], function (propName) {
  23999. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  24000. });
  24001. if (zrStyle.lineDash) {
  24002. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  24003. }
  24004. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  24005. // enable stroke
  24006. el[elStrokeProp] = true;
  24007. }
  24008. el.__inheritedStyle = zrStyle;
  24009. }
  24010. var urlRegex = /url\(\s*#(.*?)\)/;
  24011. function getPaint(str, defs) {
  24012. // if (str === 'none') {
  24013. // return;
  24014. // }
  24015. var urlMatch = defs && str && str.match(urlRegex);
  24016. if (urlMatch) {
  24017. var url = trim(urlMatch[1]);
  24018. var def = defs[url];
  24019. return def;
  24020. }
  24021. return str;
  24022. }
  24023. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  24024. function parseTransformAttribute(xmlNode, node) {
  24025. var transform = xmlNode.getAttribute('transform');
  24026. if (transform) {
  24027. transform = transform.replace(/,/g, ' ');
  24028. var m = null;
  24029. var transformOps = [];
  24030. transform.replace(transformRegex, function (str, type, value) {
  24031. transformOps.push(type, value);
  24032. });
  24033. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  24034. var value = transformOps[i];
  24035. var type = transformOps[i - 1];
  24036. m = m || create$1();
  24037. switch (type) {
  24038. case 'translate':
  24039. value = trim(value).split(DILIMITER_REG);
  24040. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  24041. break;
  24042. case 'scale':
  24043. value = trim(value).split(DILIMITER_REG);
  24044. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  24045. break;
  24046. case 'rotate':
  24047. value = trim(value).split(DILIMITER_REG);
  24048. rotate(m, m, parseFloat(value[0]));
  24049. break;
  24050. case 'skew':
  24051. value = trim(value).split(DILIMITER_REG);
  24052. console.warn('Skew transform is not supported yet');
  24053. break;
  24054. case 'matrix':
  24055. var value = trim(value).split(DILIMITER_REG);
  24056. m[0] = parseFloat(value[0]);
  24057. m[1] = parseFloat(value[1]);
  24058. m[2] = parseFloat(value[2]);
  24059. m[3] = parseFloat(value[3]);
  24060. m[4] = parseFloat(value[4]);
  24061. m[5] = parseFloat(value[5]);
  24062. break;
  24063. }
  24064. }
  24065. node.setLocalTransform(m);
  24066. }
  24067. }
  24068. // Value may contain space.
  24069. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  24070. function parseStyleAttribute(xmlNode) {
  24071. var style = xmlNode.getAttribute('style');
  24072. var result = {};
  24073. if (!style) {
  24074. return result;
  24075. }
  24076. var styleList = {};
  24077. styleRegex.lastIndex = 0;
  24078. var styleRegResult;
  24079. while ((styleRegResult = styleRegex.exec(style)) != null) {
  24080. styleList[styleRegResult[1]] = styleRegResult[2];
  24081. }
  24082. for (var svgAttrName in attributesMap) {
  24083. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  24084. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  24085. }
  24086. }
  24087. return result;
  24088. }
  24089. /**
  24090. * @param {Array.<number>} viewBoxRect
  24091. * @param {number} width
  24092. * @param {number} height
  24093. * @return {Object} {scale, position}
  24094. */
  24095. function makeViewBoxTransform(viewBoxRect, width, height) {
  24096. var scaleX = width / viewBoxRect.width;
  24097. var scaleY = height / viewBoxRect.height;
  24098. var scale = Math.min(scaleX, scaleY);
  24099. // preserveAspectRatio 'xMidYMid'
  24100. var viewBoxScale = [scale, scale];
  24101. var viewBoxPosition = [
  24102. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  24103. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  24104. ];
  24105. return {
  24106. scale: viewBoxScale,
  24107. position: viewBoxPosition
  24108. };
  24109. }
  24110. /**
  24111. * @param {string|XMLElement} xml
  24112. * @param {Object} [opt]
  24113. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  24114. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  24115. * @param {boolean} [opt.ignoreViewBox]
  24116. * @param {boolean} [opt.ignoreRootClip]
  24117. * @return {Object} result:
  24118. * {
  24119. * root: Group, The root of the the result tree of zrender shapes,
  24120. * width: number, the viewport width of the SVG,
  24121. * height: number, the viewport height of the SVG,
  24122. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  24123. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  24124. * }
  24125. */
  24126. /*
  24127. * Licensed to the Apache Software Foundation (ASF) under one
  24128. * or more contributor license agreements. See the NOTICE file
  24129. * distributed with this work for additional information
  24130. * regarding copyright ownership. The ASF licenses this file
  24131. * to you under the Apache License, Version 2.0 (the
  24132. * "License"); you may not use this file except in compliance
  24133. * with the License. You may obtain a copy of the License at
  24134. *
  24135. * http://www.apache.org/licenses/LICENSE-2.0
  24136. *
  24137. * Unless required by applicable law or agreed to in writing,
  24138. * software distributed under the License is distributed on an
  24139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24140. * KIND, either express or implied. See the License for the
  24141. * specific language governing permissions and limitations
  24142. * under the License.
  24143. */
  24144. var storage = createHashMap();
  24145. // For minimize the code size of common echarts package,
  24146. // do not put too much logic in this module.
  24147. var mapDataStorage = {
  24148. // The format of record: see `echarts.registerMap`.
  24149. // Compatible with previous `echarts.registerMap`.
  24150. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  24151. var records;
  24152. if (isArray(rawGeoJson)) {
  24153. records = rawGeoJson;
  24154. }
  24155. else if (rawGeoJson.svg) {
  24156. records = [{
  24157. type: 'svg',
  24158. source: rawGeoJson.svg,
  24159. specialAreas: rawGeoJson.specialAreas
  24160. }];
  24161. }
  24162. else {
  24163. // Backward compatibility.
  24164. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  24165. rawSpecialAreas = rawGeoJson.specialAreas;
  24166. rawGeoJson = rawGeoJson.geoJson;
  24167. }
  24168. records = [{
  24169. type: 'geoJSON',
  24170. source: rawGeoJson,
  24171. specialAreas: rawSpecialAreas
  24172. }];
  24173. }
  24174. each$1(records, function (record) {
  24175. var type = record.type;
  24176. type === 'geoJson' && (type = record.type = 'geoJSON');
  24177. var parse = parsers[type];
  24178. if (__DEV__) {
  24179. assert$1(parse, 'Illegal map type: ' + type);
  24180. }
  24181. parse(record);
  24182. });
  24183. return storage.set(mapName, records);
  24184. },
  24185. retrieveMap: function (mapName) {
  24186. return storage.get(mapName);
  24187. }
  24188. };
  24189. var parsers = {
  24190. geoJSON: function (record) {
  24191. var source = record.source;
  24192. record.geoJSON = !isString(source)
  24193. ? source
  24194. : (typeof JSON !== 'undefined' && JSON.parse)
  24195. ? JSON.parse(source)
  24196. : (new Function('return (' + source + ');'))();
  24197. },
  24198. // Only perform parse to XML object here, which might be time
  24199. // consiming for large SVG.
  24200. // Although convert XML to zrender element is also time consiming,
  24201. // if we do it here, the clone of zrender elements has to be
  24202. // required. So we do it once for each geo instance, util real
  24203. // performance issues call for optimizing it.
  24204. svg: function (record) {
  24205. record.svgXML = parseXML(record.source);
  24206. }
  24207. };
  24208. /*
  24209. * Licensed to the Apache Software Foundation (ASF) under one
  24210. * or more contributor license agreements. See the NOTICE file
  24211. * distributed with this work for additional information
  24212. * regarding copyright ownership. The ASF licenses this file
  24213. * to you under the Apache License, Version 2.0 (the
  24214. * "License"); you may not use this file except in compliance
  24215. * with the License. You may obtain a copy of the License at
  24216. *
  24217. * http://www.apache.org/licenses/LICENSE-2.0
  24218. *
  24219. * Unless required by applicable law or agreed to in writing,
  24220. * software distributed under the License is distributed on an
  24221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24222. * KIND, either express or implied. See the License for the
  24223. * specific language governing permissions and limitations
  24224. * under the License.
  24225. */
  24226. var assert = assert$1;
  24227. var each = each$1;
  24228. var isFunction = isFunction$1;
  24229. var isObject = isObject$1;
  24230. var parseClassType = ComponentModel.parseClassType;
  24231. var version = '4.9.0';
  24232. var dependencies = {
  24233. zrender: '4.3.2'
  24234. };
  24235. var TEST_FRAME_REMAIN_TIME = 1;
  24236. var PRIORITY_PROCESSOR_FILTER = 1000;
  24237. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  24238. var PRIORITY_PROCESSOR_DATASTACK = 900;
  24239. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24240. var PRIORITY_VISUAL_LAYOUT = 1000;
  24241. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24242. var PRIORITY_VISUAL_GLOBAL = 2000;
  24243. var PRIORITY_VISUAL_CHART = 3000;
  24244. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  24245. var PRIORITY_VISUAL_COMPONENT = 4000;
  24246. // FIXME
  24247. // necessary?
  24248. var PRIORITY_VISUAL_BRUSH = 5000;
  24249. var PRIORITY = {
  24250. PROCESSOR: {
  24251. FILTER: PRIORITY_PROCESSOR_FILTER,
  24252. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24253. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24254. },
  24255. VISUAL: {
  24256. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24257. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24258. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24259. CHART: PRIORITY_VISUAL_CHART,
  24260. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24261. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24262. BRUSH: PRIORITY_VISUAL_BRUSH
  24263. }
  24264. };
  24265. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24266. // where they must not be invoked nestedly, except the only case: invoke
  24267. // dispatchAction with updateMethod "none" in main process.
  24268. // This flag is used to carry out this rule.
  24269. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24270. var IN_MAIN_PROCESS = '__flagInMainProcess';
  24271. var OPTION_UPDATED = '__optionUpdated';
  24272. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24273. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  24274. return function (eventName, handler, context) {
  24275. if (!ignoreDisposed && this._disposed) {
  24276. disposedWarning(this.id);
  24277. return;
  24278. }
  24279. // Event name is all lowercase
  24280. eventName = eventName && eventName.toLowerCase();
  24281. Eventful.prototype[method].call(this, eventName, handler, context);
  24282. };
  24283. }
  24284. /**
  24285. * @module echarts~MessageCenter
  24286. */
  24287. function MessageCenter() {
  24288. Eventful.call(this);
  24289. }
  24290. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  24291. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  24292. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  24293. mixin(MessageCenter, Eventful);
  24294. /**
  24295. * @module echarts~ECharts
  24296. */
  24297. function ECharts(dom, theme$$1, opts) {
  24298. opts = opts || {};
  24299. // Get theme by name
  24300. if (typeof theme$$1 === 'string') {
  24301. theme$$1 = themeStorage[theme$$1];
  24302. }
  24303. /**
  24304. * @type {string}
  24305. */
  24306. this.id;
  24307. /**
  24308. * Group id
  24309. * @type {string}
  24310. */
  24311. this.group;
  24312. /**
  24313. * @type {HTMLElement}
  24314. * @private
  24315. */
  24316. this._dom = dom;
  24317. var defaultRenderer = 'canvas';
  24318. if (__DEV__) {
  24319. defaultRenderer = (
  24320. typeof window === 'undefined' ? global : window
  24321. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24322. }
  24323. /**
  24324. * @type {module:zrender/ZRender}
  24325. * @private
  24326. */
  24327. var zr = this._zr = init$1(dom, {
  24328. renderer: opts.renderer || defaultRenderer,
  24329. devicePixelRatio: opts.devicePixelRatio,
  24330. width: opts.width,
  24331. height: opts.height
  24332. });
  24333. /**
  24334. * Expect 60 fps.
  24335. * @type {Function}
  24336. * @private
  24337. */
  24338. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24339. var theme$$1 = clone(theme$$1);
  24340. theme$$1 && backwardCompat(theme$$1, true);
  24341. /**
  24342. * @type {Object}
  24343. * @private
  24344. */
  24345. this._theme = theme$$1;
  24346. /**
  24347. * @type {Array.<module:echarts/view/Chart>}
  24348. * @private
  24349. */
  24350. this._chartsViews = [];
  24351. /**
  24352. * @type {Object.<string, module:echarts/view/Chart>}
  24353. * @private
  24354. */
  24355. this._chartsMap = {};
  24356. /**
  24357. * @type {Array.<module:echarts/view/Component>}
  24358. * @private
  24359. */
  24360. this._componentsViews = [];
  24361. /**
  24362. * @type {Object.<string, module:echarts/view/Component>}
  24363. * @private
  24364. */
  24365. this._componentsMap = {};
  24366. /**
  24367. * @type {module:echarts/CoordinateSystem}
  24368. * @private
  24369. */
  24370. this._coordSysMgr = new CoordinateSystemManager();
  24371. /**
  24372. * @type {module:echarts/ExtensionAPI}
  24373. * @private
  24374. */
  24375. var api = this._api = createExtensionAPI(this);
  24376. // Sort on demand
  24377. function prioritySortFunc(a, b) {
  24378. return a.__prio - b.__prio;
  24379. }
  24380. sort(visualFuncs, prioritySortFunc);
  24381. sort(dataProcessorFuncs, prioritySortFunc);
  24382. /**
  24383. * @type {module:echarts/stream/Scheduler}
  24384. */
  24385. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  24386. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  24387. /**
  24388. * @type {module:echarts~MessageCenter}
  24389. * @private
  24390. */
  24391. this._messageCenter = new MessageCenter();
  24392. // Init mouse events
  24393. this._initEvents();
  24394. // In case some people write `window.onresize = chart.resize`
  24395. this.resize = bind(this.resize, this);
  24396. // Can't dispatch action during rendering procedure
  24397. this._pendingActions = [];
  24398. zr.animation.on('frame', this._onframe, this);
  24399. bindRenderedEvent(zr, this);
  24400. // ECharts instance can be used as value.
  24401. setAsPrimitive(this);
  24402. }
  24403. var echartsProto = ECharts.prototype;
  24404. echartsProto._onframe = function () {
  24405. if (this._disposed) {
  24406. return;
  24407. }
  24408. var scheduler = this._scheduler;
  24409. // Lazy update
  24410. if (this[OPTION_UPDATED]) {
  24411. var silent = this[OPTION_UPDATED].silent;
  24412. this[IN_MAIN_PROCESS] = true;
  24413. prepare(this);
  24414. updateMethods.update.call(this);
  24415. this[IN_MAIN_PROCESS] = false;
  24416. this[OPTION_UPDATED] = false;
  24417. flushPendingActions.call(this, silent);
  24418. triggerUpdatedEvent.call(this, silent);
  24419. }
  24420. // Avoid do both lazy update and progress in one frame.
  24421. else if (scheduler.unfinished) {
  24422. // Stream progress.
  24423. var remainTime = TEST_FRAME_REMAIN_TIME;
  24424. var ecModel = this._model;
  24425. var api = this._api;
  24426. scheduler.unfinished = false;
  24427. do {
  24428. var startTime = +new Date();
  24429. scheduler.performSeriesTasks(ecModel);
  24430. // Currently dataProcessorFuncs do not check threshold.
  24431. scheduler.performDataProcessorTasks(ecModel);
  24432. updateStreamModes(this, ecModel);
  24433. // Do not update coordinate system here. Because that coord system update in
  24434. // each frame is not a good user experience. So we follow the rule that
  24435. // the extent of the coordinate system is determin in the first frame (the
  24436. // frame is executed immedietely after task reset.
  24437. // this._coordSysMgr.update(ecModel, api);
  24438. // console.log('--- ec frame visual ---', remainTime);
  24439. scheduler.performVisualTasks(ecModel);
  24440. renderSeries(this, this._model, api, 'remain');
  24441. remainTime -= (+new Date() - startTime);
  24442. }
  24443. while (remainTime > 0 && scheduler.unfinished);
  24444. // Call flush explicitly for trigger finished event.
  24445. if (!scheduler.unfinished) {
  24446. this._zr.flush();
  24447. }
  24448. // Else, zr flushing be ensue within the same frame,
  24449. // because zr flushing is after onframe event.
  24450. }
  24451. };
  24452. /**
  24453. * @return {HTMLElement}
  24454. */
  24455. echartsProto.getDom = function () {
  24456. return this._dom;
  24457. };
  24458. /**
  24459. * @return {module:zrender~ZRender}
  24460. */
  24461. echartsProto.getZr = function () {
  24462. return this._zr;
  24463. };
  24464. /**
  24465. * Usage:
  24466. * chart.setOption(option, notMerge, lazyUpdate);
  24467. * chart.setOption(option, {
  24468. * notMerge: ...,
  24469. * lazyUpdate: ...,
  24470. * silent: ...
  24471. * });
  24472. *
  24473. * @param {Object} option
  24474. * @param {Object|boolean} [opts] opts or notMerge.
  24475. * @param {boolean} [opts.notMerge=false]
  24476. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  24477. */
  24478. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  24479. if (__DEV__) {
  24480. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  24481. }
  24482. if (this._disposed) {
  24483. disposedWarning(this.id);
  24484. return;
  24485. }
  24486. var silent;
  24487. if (isObject(notMerge)) {
  24488. lazyUpdate = notMerge.lazyUpdate;
  24489. silent = notMerge.silent;
  24490. notMerge = notMerge.notMerge;
  24491. }
  24492. this[IN_MAIN_PROCESS] = true;
  24493. if (!this._model || notMerge) {
  24494. var optionManager = new OptionManager(this._api);
  24495. var theme$$1 = this._theme;
  24496. var ecModel = this._model = new GlobalModel();
  24497. ecModel.scheduler = this._scheduler;
  24498. ecModel.init(null, null, theme$$1, optionManager);
  24499. }
  24500. this._model.setOption(option, optionPreprocessorFuncs);
  24501. if (lazyUpdate) {
  24502. this[OPTION_UPDATED] = {silent: silent};
  24503. this[IN_MAIN_PROCESS] = false;
  24504. }
  24505. else {
  24506. prepare(this);
  24507. updateMethods.update.call(this);
  24508. // Ensure zr refresh sychronously, and then pixel in canvas can be
  24509. // fetched after `setOption`.
  24510. this._zr.flush();
  24511. this[OPTION_UPDATED] = false;
  24512. this[IN_MAIN_PROCESS] = false;
  24513. flushPendingActions.call(this, silent);
  24514. triggerUpdatedEvent.call(this, silent);
  24515. }
  24516. };
  24517. /**
  24518. * @DEPRECATED
  24519. */
  24520. echartsProto.setTheme = function () {
  24521. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  24522. };
  24523. /**
  24524. * @return {module:echarts/model/Global}
  24525. */
  24526. echartsProto.getModel = function () {
  24527. return this._model;
  24528. };
  24529. /**
  24530. * @return {Object}
  24531. */
  24532. echartsProto.getOption = function () {
  24533. return this._model && this._model.getOption();
  24534. };
  24535. /**
  24536. * @return {number}
  24537. */
  24538. echartsProto.getWidth = function () {
  24539. return this._zr.getWidth();
  24540. };
  24541. /**
  24542. * @return {number}
  24543. */
  24544. echartsProto.getHeight = function () {
  24545. return this._zr.getHeight();
  24546. };
  24547. /**
  24548. * @return {number}
  24549. */
  24550. echartsProto.getDevicePixelRatio = function () {
  24551. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  24552. };
  24553. /**
  24554. * Get canvas which has all thing rendered
  24555. * @param {Object} opts
  24556. * @param {string} [opts.backgroundColor]
  24557. * @return {string}
  24558. */
  24559. echartsProto.getRenderedCanvas = function (opts) {
  24560. if (!env$1.canvasSupported) {
  24561. return;
  24562. }
  24563. opts = opts || {};
  24564. opts.pixelRatio = opts.pixelRatio || 1;
  24565. opts.backgroundColor = opts.backgroundColor
  24566. || this._model.get('backgroundColor');
  24567. var zr = this._zr;
  24568. // var list = zr.storage.getDisplayList();
  24569. // Stop animations
  24570. // Never works before in init animation, so remove it.
  24571. // zrUtil.each(list, function (el) {
  24572. // el.stopAnimation(true);
  24573. // });
  24574. return zr.painter.getRenderedCanvas(opts);
  24575. };
  24576. /**
  24577. * Get svg data url
  24578. * @return {string}
  24579. */
  24580. echartsProto.getSvgDataURL = function () {
  24581. if (!env$1.svgSupported) {
  24582. return;
  24583. }
  24584. var zr = this._zr;
  24585. var list = zr.storage.getDisplayList();
  24586. // Stop animations
  24587. each$1(list, function (el) {
  24588. el.stopAnimation(true);
  24589. });
  24590. return zr.painter.toDataURL();
  24591. };
  24592. /**
  24593. * @return {string}
  24594. * @param {Object} opts
  24595. * @param {string} [opts.type='png']
  24596. * @param {string} [opts.pixelRatio=1]
  24597. * @param {string} [opts.backgroundColor]
  24598. * @param {string} [opts.excludeComponents]
  24599. */
  24600. echartsProto.getDataURL = function (opts) {
  24601. if (this._disposed) {
  24602. disposedWarning(this.id);
  24603. return;
  24604. }
  24605. opts = opts || {};
  24606. var excludeComponents = opts.excludeComponents;
  24607. var ecModel = this._model;
  24608. var excludesComponentViews = [];
  24609. var self = this;
  24610. each(excludeComponents, function (componentType) {
  24611. ecModel.eachComponent({
  24612. mainType: componentType
  24613. }, function (component) {
  24614. var view = self._componentsMap[component.__viewId];
  24615. if (!view.group.ignore) {
  24616. excludesComponentViews.push(view);
  24617. view.group.ignore = true;
  24618. }
  24619. });
  24620. });
  24621. var url = this._zr.painter.getType() === 'svg'
  24622. ? this.getSvgDataURL()
  24623. : this.getRenderedCanvas(opts).toDataURL(
  24624. 'image/' + (opts && opts.type || 'png')
  24625. );
  24626. each(excludesComponentViews, function (view) {
  24627. view.group.ignore = false;
  24628. });
  24629. return url;
  24630. };
  24631. /**
  24632. * @return {string}
  24633. * @param {Object} opts
  24634. * @param {string} [opts.type='png']
  24635. * @param {string} [opts.pixelRatio=1]
  24636. * @param {string} [opts.backgroundColor]
  24637. */
  24638. echartsProto.getConnectedDataURL = function (opts) {
  24639. if (this._disposed) {
  24640. disposedWarning(this.id);
  24641. return;
  24642. }
  24643. if (!env$1.canvasSupported) {
  24644. return;
  24645. }
  24646. var isSvg = opts.type === 'svg';
  24647. var groupId = this.group;
  24648. var mathMin = Math.min;
  24649. var mathMax = Math.max;
  24650. var MAX_NUMBER = Infinity;
  24651. if (connectedGroups[groupId]) {
  24652. var left = MAX_NUMBER;
  24653. var top = MAX_NUMBER;
  24654. var right = -MAX_NUMBER;
  24655. var bottom = -MAX_NUMBER;
  24656. var canvasList = [];
  24657. var dpr = (opts && opts.pixelRatio) || 1;
  24658. each$1(instances, function (chart, id) {
  24659. if (chart.group === groupId) {
  24660. var canvas = isSvg
  24661. ? chart.getZr().painter.getSvgDom().innerHTML
  24662. : chart.getRenderedCanvas(clone(opts));
  24663. var boundingRect = chart.getDom().getBoundingClientRect();
  24664. left = mathMin(boundingRect.left, left);
  24665. top = mathMin(boundingRect.top, top);
  24666. right = mathMax(boundingRect.right, right);
  24667. bottom = mathMax(boundingRect.bottom, bottom);
  24668. canvasList.push({
  24669. dom: canvas,
  24670. left: boundingRect.left,
  24671. top: boundingRect.top
  24672. });
  24673. }
  24674. });
  24675. left *= dpr;
  24676. top *= dpr;
  24677. right *= dpr;
  24678. bottom *= dpr;
  24679. var width = right - left;
  24680. var height = bottom - top;
  24681. var targetCanvas = createCanvas();
  24682. var zr = init$1(targetCanvas, {
  24683. renderer: isSvg ? 'svg' : 'canvas'
  24684. });
  24685. zr.resize({
  24686. width: width,
  24687. height: height
  24688. });
  24689. if (isSvg) {
  24690. var content = '';
  24691. each(canvasList, function (item) {
  24692. var x = item.left - left;
  24693. var y = item.top - top;
  24694. content += '<g transform="translate(' + x + ','
  24695. + y + ')">' + item.dom + '</g>';
  24696. });
  24697. zr.painter.getSvgRoot().innerHTML = content;
  24698. if (opts.connectedBackgroundColor) {
  24699. zr.painter.setBackgroundColor(opts.connectedBackgroundColor);
  24700. }
  24701. zr.refreshImmediately();
  24702. return zr.painter.toDataURL();
  24703. }
  24704. else {
  24705. // Background between the charts
  24706. if (opts.connectedBackgroundColor) {
  24707. zr.add(new Rect({
  24708. shape: {
  24709. x: 0,
  24710. y: 0,
  24711. width: width,
  24712. height: height
  24713. },
  24714. style: {
  24715. fill: opts.connectedBackgroundColor
  24716. }
  24717. }));
  24718. }
  24719. each(canvasList, function (item) {
  24720. var img = new ZImage({
  24721. style: {
  24722. x: item.left * dpr - left,
  24723. y: item.top * dpr - top,
  24724. image: item.dom
  24725. }
  24726. });
  24727. zr.add(img);
  24728. });
  24729. zr.refreshImmediately();
  24730. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24731. }
  24732. }
  24733. else {
  24734. return this.getDataURL(opts);
  24735. }
  24736. };
  24737. /**
  24738. * Convert from logical coordinate system to pixel coordinate system.
  24739. * See CoordinateSystem#convertToPixel.
  24740. * @param {string|Object} finder
  24741. * If string, e.g., 'geo', means {geoIndex: 0}.
  24742. * If Object, could contain some of these properties below:
  24743. * {
  24744. * seriesIndex / seriesId / seriesName,
  24745. * geoIndex / geoId, geoName,
  24746. * bmapIndex / bmapId / bmapName,
  24747. * xAxisIndex / xAxisId / xAxisName,
  24748. * yAxisIndex / yAxisId / yAxisName,
  24749. * gridIndex / gridId / gridName,
  24750. * ... (can be extended)
  24751. * }
  24752. * @param {Array|number} value
  24753. * @return {Array|number} result
  24754. */
  24755. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  24756. /**
  24757. * Convert from pixel coordinate system to logical coordinate system.
  24758. * See CoordinateSystem#convertFromPixel.
  24759. * @param {string|Object} finder
  24760. * If string, e.g., 'geo', means {geoIndex: 0}.
  24761. * If Object, could contain some of these properties below:
  24762. * {
  24763. * seriesIndex / seriesId / seriesName,
  24764. * geoIndex / geoId / geoName,
  24765. * bmapIndex / bmapId / bmapName,
  24766. * xAxisIndex / xAxisId / xAxisName,
  24767. * yAxisIndex / yAxisId / yAxisName
  24768. * gridIndex / gridId / gridName,
  24769. * ... (can be extended)
  24770. * }
  24771. * @param {Array|number} value
  24772. * @return {Array|number} result
  24773. */
  24774. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24775. function doConvertPixel(methodName, finder, value) {
  24776. if (this._disposed) {
  24777. disposedWarning(this.id);
  24778. return;
  24779. }
  24780. var ecModel = this._model;
  24781. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24782. var result;
  24783. finder = parseFinder(ecModel, finder);
  24784. for (var i = 0; i < coordSysList.length; i++) {
  24785. var coordSys = coordSysList[i];
  24786. if (coordSys[methodName]
  24787. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24788. ) {
  24789. return result;
  24790. }
  24791. }
  24792. if (__DEV__) {
  24793. console.warn(
  24794. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24795. );
  24796. }
  24797. }
  24798. /**
  24799. * Is the specified coordinate systems or components contain the given pixel point.
  24800. * @param {string|Object} finder
  24801. * If string, e.g., 'geo', means {geoIndex: 0}.
  24802. * If Object, could contain some of these properties below:
  24803. * {
  24804. * seriesIndex / seriesId / seriesName,
  24805. * geoIndex / geoId / geoName,
  24806. * bmapIndex / bmapId / bmapName,
  24807. * xAxisIndex / xAxisId / xAxisName,
  24808. * yAxisIndex / yAxisId / yAxisName,
  24809. * gridIndex / gridId / gridName,
  24810. * ... (can be extended)
  24811. * }
  24812. * @param {Array|number} value
  24813. * @return {boolean} result
  24814. */
  24815. echartsProto.containPixel = function (finder, value) {
  24816. if (this._disposed) {
  24817. disposedWarning(this.id);
  24818. return;
  24819. }
  24820. var ecModel = this._model;
  24821. var result;
  24822. finder = parseFinder(ecModel, finder);
  24823. each$1(finder, function (models, key) {
  24824. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24825. var coordSys = model.coordinateSystem;
  24826. if (coordSys && coordSys.containPoint) {
  24827. result |= !!coordSys.containPoint(value);
  24828. }
  24829. else if (key === 'seriesModels') {
  24830. var view = this._chartsMap[model.__viewId];
  24831. if (view && view.containPoint) {
  24832. result |= view.containPoint(value, model);
  24833. }
  24834. else {
  24835. if (__DEV__) {
  24836. console.warn(key + ': ' + (view
  24837. ? 'The found component do not support containPoint.'
  24838. : 'No view mapping to the found component.'
  24839. ));
  24840. }
  24841. }
  24842. }
  24843. else {
  24844. if (__DEV__) {
  24845. console.warn(key + ': containPoint is not supported');
  24846. }
  24847. }
  24848. }, this);
  24849. }, this);
  24850. return !!result;
  24851. };
  24852. /**
  24853. * Get visual from series or data.
  24854. * @param {string|Object} finder
  24855. * If string, e.g., 'series', means {seriesIndex: 0}.
  24856. * If Object, could contain some of these properties below:
  24857. * {
  24858. * seriesIndex / seriesId / seriesName,
  24859. * dataIndex / dataIndexInside
  24860. * }
  24861. * If dataIndex is not specified, series visual will be fetched,
  24862. * but not data item visual.
  24863. * If all of seriesIndex, seriesId, seriesName are not specified,
  24864. * visual will be fetched from first series.
  24865. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24866. */
  24867. echartsProto.getVisual = function (finder, visualType) {
  24868. var ecModel = this._model;
  24869. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24870. var seriesModel = finder.seriesModel;
  24871. if (__DEV__) {
  24872. if (!seriesModel) {
  24873. console.warn('There is no specified seires model');
  24874. }
  24875. }
  24876. var data = seriesModel.getData();
  24877. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24878. ? finder.dataIndexInside
  24879. : finder.hasOwnProperty('dataIndex')
  24880. ? data.indexOfRawIndex(finder.dataIndex)
  24881. : null;
  24882. return dataIndexInside != null
  24883. ? data.getItemVisual(dataIndexInside, visualType)
  24884. : data.getVisual(visualType);
  24885. };
  24886. /**
  24887. * Get view of corresponding component model
  24888. * @param {module:echarts/model/Component} componentModel
  24889. * @return {module:echarts/view/Component}
  24890. */
  24891. echartsProto.getViewOfComponentModel = function (componentModel) {
  24892. return this._componentsMap[componentModel.__viewId];
  24893. };
  24894. /**
  24895. * Get view of corresponding series model
  24896. * @param {module:echarts/model/Series} seriesModel
  24897. * @return {module:echarts/view/Chart}
  24898. */
  24899. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24900. return this._chartsMap[seriesModel.__viewId];
  24901. };
  24902. var updateMethods = {
  24903. prepareAndUpdate: function (payload) {
  24904. prepare(this);
  24905. updateMethods.update.call(this, payload);
  24906. },
  24907. /**
  24908. * @param {Object} payload
  24909. * @private
  24910. */
  24911. update: function (payload) {
  24912. // console.profile && console.profile('update');
  24913. var ecModel = this._model;
  24914. var api = this._api;
  24915. var zr = this._zr;
  24916. var coordSysMgr = this._coordSysMgr;
  24917. var scheduler = this._scheduler;
  24918. // update before setOption
  24919. if (!ecModel) {
  24920. return;
  24921. }
  24922. scheduler.restoreData(ecModel, payload);
  24923. scheduler.performSeriesTasks(ecModel);
  24924. // TODO
  24925. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24926. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24927. // Create new coordinate system each update
  24928. // In LineView may save the old coordinate system and use it to get the orignal point
  24929. coordSysMgr.create(ecModel, api);
  24930. scheduler.performDataProcessorTasks(ecModel, payload);
  24931. // Current stream render is not supported in data process. So we can update
  24932. // stream modes after data processing, where the filtered data is used to
  24933. // deteming whether use progressive rendering.
  24934. updateStreamModes(this, ecModel);
  24935. // We update stream modes before coordinate system updated, then the modes info
  24936. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24937. // the drawback is the full coord info can not be fetched. Fortunately this full
  24938. // coord is not requied in stream mode updater currently.
  24939. coordSysMgr.update(ecModel, api);
  24940. clearColorPalette(ecModel);
  24941. scheduler.performVisualTasks(ecModel, payload);
  24942. render(this, ecModel, api, payload);
  24943. // Set background
  24944. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24945. // In IE8
  24946. if (!env$1.canvasSupported) {
  24947. var colorArr = parse(backgroundColor);
  24948. backgroundColor = stringify(colorArr, 'rgb');
  24949. if (colorArr[3] === 0) {
  24950. backgroundColor = 'transparent';
  24951. }
  24952. }
  24953. else {
  24954. zr.setBackgroundColor(backgroundColor);
  24955. }
  24956. performPostUpdateFuncs(ecModel, api);
  24957. // console.profile && console.profileEnd('update');
  24958. },
  24959. /**
  24960. * @param {Object} payload
  24961. * @private
  24962. */
  24963. updateTransform: function (payload) {
  24964. var ecModel = this._model;
  24965. var ecIns = this;
  24966. var api = this._api;
  24967. // update before setOption
  24968. if (!ecModel) {
  24969. return;
  24970. }
  24971. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24972. var componentDirtyList = [];
  24973. ecModel.eachComponent(function (componentType, componentModel) {
  24974. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24975. if (componentView && componentView.__alive) {
  24976. if (componentView.updateTransform) {
  24977. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24978. result && result.update && componentDirtyList.push(componentView);
  24979. }
  24980. else {
  24981. componentDirtyList.push(componentView);
  24982. }
  24983. }
  24984. });
  24985. var seriesDirtyMap = createHashMap();
  24986. ecModel.eachSeries(function (seriesModel) {
  24987. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24988. if (chartView.updateTransform) {
  24989. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24990. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24991. }
  24992. else {
  24993. seriesDirtyMap.set(seriesModel.uid, 1);
  24994. }
  24995. });
  24996. clearColorPalette(ecModel);
  24997. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24998. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24999. this._scheduler.performVisualTasks(
  25000. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  25001. );
  25002. // Currently, not call render of components. Geo render cost a lot.
  25003. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  25004. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  25005. performPostUpdateFuncs(ecModel, this._api);
  25006. },
  25007. /**
  25008. * @param {Object} payload
  25009. * @private
  25010. */
  25011. updateView: function (payload) {
  25012. var ecModel = this._model;
  25013. // update before setOption
  25014. if (!ecModel) {
  25015. return;
  25016. }
  25017. Chart.markUpdateMethod(payload, 'updateView');
  25018. clearColorPalette(ecModel);
  25019. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25020. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  25021. render(this, this._model, this._api, payload);
  25022. performPostUpdateFuncs(ecModel, this._api);
  25023. },
  25024. /**
  25025. * @param {Object} payload
  25026. * @private
  25027. */
  25028. updateVisual: function (payload) {
  25029. updateMethods.update.call(this, payload);
  25030. // var ecModel = this._model;
  25031. // // update before setOption
  25032. // if (!ecModel) {
  25033. // return;
  25034. // }
  25035. // ChartView.markUpdateMethod(payload, 'updateVisual');
  25036. // clearColorPalette(ecModel);
  25037. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25038. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  25039. // render(this, this._model, this._api, payload);
  25040. // performPostUpdateFuncs(ecModel, this._api);
  25041. },
  25042. /**
  25043. * @param {Object} payload
  25044. * @private
  25045. */
  25046. updateLayout: function (payload) {
  25047. updateMethods.update.call(this, payload);
  25048. // var ecModel = this._model;
  25049. // // update before setOption
  25050. // if (!ecModel) {
  25051. // return;
  25052. // }
  25053. // ChartView.markUpdateMethod(payload, 'updateLayout');
  25054. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25055. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  25056. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  25057. // render(this, this._model, this._api, payload);
  25058. // performPostUpdateFuncs(ecModel, this._api);
  25059. }
  25060. };
  25061. function prepare(ecIns) {
  25062. var ecModel = ecIns._model;
  25063. var scheduler = ecIns._scheduler;
  25064. scheduler.restorePipelines(ecModel);
  25065. scheduler.prepareStageTasks();
  25066. prepareView(ecIns, 'component', ecModel, scheduler);
  25067. prepareView(ecIns, 'chart', ecModel, scheduler);
  25068. scheduler.plan();
  25069. }
  25070. /**
  25071. * @private
  25072. */
  25073. function updateDirectly(ecIns, method, payload, mainType, subType) {
  25074. var ecModel = ecIns._model;
  25075. // broadcast
  25076. if (!mainType) {
  25077. // FIXME
  25078. // Chart will not be update directly here, except set dirty.
  25079. // But there is no such scenario now.
  25080. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  25081. return;
  25082. }
  25083. var query = {};
  25084. query[mainType + 'Id'] = payload[mainType + 'Id'];
  25085. query[mainType + 'Index'] = payload[mainType + 'Index'];
  25086. query[mainType + 'Name'] = payload[mainType + 'Name'];
  25087. var condition = {mainType: mainType, query: query};
  25088. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  25089. var excludeSeriesId = payload.excludeSeriesId;
  25090. if (excludeSeriesId != null) {
  25091. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  25092. }
  25093. // If dispatchAction before setOption, do nothing.
  25094. ecModel && ecModel.eachComponent(condition, function (model) {
  25095. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  25096. callView(ecIns[
  25097. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25098. ][model.__viewId]);
  25099. }
  25100. }, ecIns);
  25101. function callView(view) {
  25102. view && view.__alive && view[method] && view[method](
  25103. view.__model, ecModel, ecIns._api, payload
  25104. );
  25105. }
  25106. }
  25107. /**
  25108. * Resize the chart
  25109. * @param {Object} opts
  25110. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  25111. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  25112. * @param {boolean} [opts.silent=false]
  25113. */
  25114. echartsProto.resize = function (opts) {
  25115. if (__DEV__) {
  25116. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  25117. }
  25118. if (this._disposed) {
  25119. disposedWarning(this.id);
  25120. return;
  25121. }
  25122. this._zr.resize(opts);
  25123. var ecModel = this._model;
  25124. // Resize loading effect
  25125. this._loadingFX && this._loadingFX.resize();
  25126. if (!ecModel) {
  25127. return;
  25128. }
  25129. var optionChanged = ecModel.resetOption('media');
  25130. var silent = opts && opts.silent;
  25131. this[IN_MAIN_PROCESS] = true;
  25132. optionChanged && prepare(this);
  25133. updateMethods.update.call(this);
  25134. this[IN_MAIN_PROCESS] = false;
  25135. flushPendingActions.call(this, silent);
  25136. triggerUpdatedEvent.call(this, silent);
  25137. };
  25138. function updateStreamModes(ecIns, ecModel) {
  25139. var chartsMap = ecIns._chartsMap;
  25140. var scheduler = ecIns._scheduler;
  25141. ecModel.eachSeries(function (seriesModel) {
  25142. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  25143. });
  25144. }
  25145. /**
  25146. * Show loading effect
  25147. * @param {string} [name='default']
  25148. * @param {Object} [cfg]
  25149. */
  25150. echartsProto.showLoading = function (name, cfg) {
  25151. if (this._disposed) {
  25152. disposedWarning(this.id);
  25153. return;
  25154. }
  25155. if (isObject(name)) {
  25156. cfg = name;
  25157. name = '';
  25158. }
  25159. name = name || 'default';
  25160. this.hideLoading();
  25161. if (!loadingEffects[name]) {
  25162. if (__DEV__) {
  25163. console.warn('Loading effects ' + name + ' not exists.');
  25164. }
  25165. return;
  25166. }
  25167. var el = loadingEffects[name](this._api, cfg);
  25168. var zr = this._zr;
  25169. this._loadingFX = el;
  25170. zr.add(el);
  25171. };
  25172. /**
  25173. * Hide loading effect
  25174. */
  25175. echartsProto.hideLoading = function () {
  25176. if (this._disposed) {
  25177. disposedWarning(this.id);
  25178. return;
  25179. }
  25180. this._loadingFX && this._zr.remove(this._loadingFX);
  25181. this._loadingFX = null;
  25182. };
  25183. /**
  25184. * @param {Object} eventObj
  25185. * @return {Object}
  25186. */
  25187. echartsProto.makeActionFromEvent = function (eventObj) {
  25188. var payload = extend({}, eventObj);
  25189. payload.type = eventActionMap[eventObj.type];
  25190. return payload;
  25191. };
  25192. /**
  25193. * @pubilc
  25194. * @param {Object} payload
  25195. * @param {string} [payload.type] Action type
  25196. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  25197. * @param {boolean} [opt.silent=false] Whether trigger events.
  25198. * @param {boolean} [opt.flush=undefined]
  25199. * true: Flush immediately, and then pixel in canvas can be fetched
  25200. * immediately. Caution: it might affect performance.
  25201. * false: Not flush.
  25202. * undefined: Auto decide whether perform flush.
  25203. */
  25204. echartsProto.dispatchAction = function (payload, opt) {
  25205. if (this._disposed) {
  25206. disposedWarning(this.id);
  25207. return;
  25208. }
  25209. if (!isObject(opt)) {
  25210. opt = {silent: !!opt};
  25211. }
  25212. if (!actions[payload.type]) {
  25213. return;
  25214. }
  25215. // Avoid dispatch action before setOption. Especially in `connect`.
  25216. if (!this._model) {
  25217. return;
  25218. }
  25219. // May dispatchAction in rendering procedure
  25220. if (this[IN_MAIN_PROCESS]) {
  25221. this._pendingActions.push(payload);
  25222. return;
  25223. }
  25224. doDispatchAction.call(this, payload, opt.silent);
  25225. if (opt.flush) {
  25226. this._zr.flush(true);
  25227. }
  25228. else if (opt.flush !== false && env$1.browser.weChat) {
  25229. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25230. // hang when sliding page (on touch event), which cause that zr does not
  25231. // refresh util user interaction finished, which is not expected.
  25232. // But `dispatchAction` may be called too frequently when pan on touch
  25233. // screen, which impacts performance if do not throttle them.
  25234. this._throttledZrFlush();
  25235. }
  25236. flushPendingActions.call(this, opt.silent);
  25237. triggerUpdatedEvent.call(this, opt.silent);
  25238. };
  25239. function doDispatchAction(payload, silent) {
  25240. var payloadType = payload.type;
  25241. var escapeConnect = payload.escapeConnect;
  25242. var actionWrap = actions[payloadType];
  25243. var actionInfo = actionWrap.actionInfo;
  25244. var cptType = (actionInfo.update || 'update').split(':');
  25245. var updateMethod = cptType.pop();
  25246. cptType = cptType[0] != null && parseClassType(cptType[0]);
  25247. this[IN_MAIN_PROCESS] = true;
  25248. var payloads = [payload];
  25249. var batched = false;
  25250. // Batch action
  25251. if (payload.batch) {
  25252. batched = true;
  25253. payloads = map(payload.batch, function (item) {
  25254. item = defaults(extend({}, item), payload);
  25255. item.batch = null;
  25256. return item;
  25257. });
  25258. }
  25259. var eventObjBatch = [];
  25260. var eventObj;
  25261. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  25262. each(payloads, function (batchItem) {
  25263. // Action can specify the event by return it.
  25264. eventObj = actionWrap.action(batchItem, this._model, this._api);
  25265. // Emit event outside
  25266. eventObj = eventObj || extend({}, batchItem);
  25267. // Convert type to eventType
  25268. eventObj.type = actionInfo.event || eventObj.type;
  25269. eventObjBatch.push(eventObj);
  25270. // light update does not perform data process, layout and visual.
  25271. if (isHighDown) {
  25272. // method, payload, mainType, subType
  25273. updateDirectly(this, updateMethod, batchItem, 'series');
  25274. }
  25275. else if (cptType) {
  25276. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  25277. }
  25278. }, this);
  25279. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  25280. // Still dirty
  25281. if (this[OPTION_UPDATED]) {
  25282. // FIXME Pass payload ?
  25283. prepare(this);
  25284. updateMethods.update.call(this, payload);
  25285. this[OPTION_UPDATED] = false;
  25286. }
  25287. else {
  25288. updateMethods[updateMethod].call(this, payload);
  25289. }
  25290. }
  25291. // Follow the rule of action batch
  25292. if (batched) {
  25293. eventObj = {
  25294. type: actionInfo.event || payloadType,
  25295. escapeConnect: escapeConnect,
  25296. batch: eventObjBatch
  25297. };
  25298. }
  25299. else {
  25300. eventObj = eventObjBatch[0];
  25301. }
  25302. this[IN_MAIN_PROCESS] = false;
  25303. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  25304. }
  25305. function flushPendingActions(silent) {
  25306. var pendingActions = this._pendingActions;
  25307. while (pendingActions.length) {
  25308. var payload = pendingActions.shift();
  25309. doDispatchAction.call(this, payload, silent);
  25310. }
  25311. }
  25312. function triggerUpdatedEvent(silent) {
  25313. !silent && this.trigger('updated');
  25314. }
  25315. /**
  25316. * Event `rendered` is triggered when zr
  25317. * rendered. It is useful for realtime
  25318. * snapshot (reflect animation).
  25319. *
  25320. * Event `finished` is triggered when:
  25321. * (1) zrender rendering finished.
  25322. * (2) initial animation finished.
  25323. * (3) progressive rendering finished.
  25324. * (4) no pending action.
  25325. * (5) no delayed setOption needs to be processed.
  25326. */
  25327. function bindRenderedEvent(zr, ecIns) {
  25328. zr.on('rendered', function () {
  25329. ecIns.trigger('rendered');
  25330. // The `finished` event should not be triggered repeatly,
  25331. // so it should only be triggered when rendering indeed happend
  25332. // in zrender. (Consider the case that dipatchAction is keep
  25333. // triggering when mouse move).
  25334. if (
  25335. // Although zr is dirty if initial animation is not finished
  25336. // and this checking is called on frame, we also check
  25337. // animation finished for robustness.
  25338. zr.animation.isFinished()
  25339. && !ecIns[OPTION_UPDATED]
  25340. && !ecIns._scheduler.unfinished
  25341. && !ecIns._pendingActions.length
  25342. ) {
  25343. ecIns.trigger('finished');
  25344. }
  25345. });
  25346. }
  25347. /**
  25348. * @param {Object} params
  25349. * @param {number} params.seriesIndex
  25350. * @param {Array|TypedArray} params.data
  25351. */
  25352. echartsProto.appendData = function (params) {
  25353. if (this._disposed) {
  25354. disposedWarning(this.id);
  25355. return;
  25356. }
  25357. var seriesIndex = params.seriesIndex;
  25358. var ecModel = this.getModel();
  25359. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25360. if (__DEV__) {
  25361. assert(params.data && seriesModel);
  25362. }
  25363. seriesModel.appendData(params);
  25364. // Note: `appendData` does not support that update extent of coordinate
  25365. // system, util some scenario require that. In the expected usage of
  25366. // `appendData`, the initial extent of coordinate system should better
  25367. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25368. // the extent changed while `appendData`, the location of the painted
  25369. // graphic elements have to be changed, which make the usage of
  25370. // `appendData` meaningless.
  25371. this._scheduler.unfinished = true;
  25372. };
  25373. /**
  25374. * Register event
  25375. * @method
  25376. */
  25377. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  25378. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  25379. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  25380. /**
  25381. * Prepare view instances of charts and components
  25382. * @param {module:echarts/model/Global} ecModel
  25383. * @private
  25384. */
  25385. function prepareView(ecIns, type, ecModel, scheduler) {
  25386. var isComponent = type === 'component';
  25387. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25388. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25389. var zr = ecIns._zr;
  25390. var api = ecIns._api;
  25391. for (var i = 0; i < viewList.length; i++) {
  25392. viewList[i].__alive = false;
  25393. }
  25394. isComponent
  25395. ? ecModel.eachComponent(function (componentType, model) {
  25396. componentType !== 'series' && doPrepare(model);
  25397. })
  25398. : ecModel.eachSeries(doPrepare);
  25399. function doPrepare(model) {
  25400. // Consider: id same and type changed.
  25401. var viewId = '_ec_' + model.id + '_' + model.type;
  25402. var view = viewMap[viewId];
  25403. if (!view) {
  25404. var classType = parseClassType(model.type);
  25405. var Clazz = isComponent
  25406. ? Component$1.getClass(classType.main, classType.sub)
  25407. : Chart.getClass(classType.sub);
  25408. if (__DEV__) {
  25409. assert(Clazz, classType.sub + ' does not exist.');
  25410. }
  25411. view = new Clazz();
  25412. view.init(ecModel, api);
  25413. viewMap[viewId] = view;
  25414. viewList.push(view);
  25415. zr.add(view.group);
  25416. }
  25417. model.__viewId = view.__id = viewId;
  25418. view.__alive = true;
  25419. view.__model = model;
  25420. view.group.__ecComponentInfo = {
  25421. mainType: model.mainType,
  25422. index: model.componentIndex
  25423. };
  25424. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25425. }
  25426. for (var i = 0; i < viewList.length;) {
  25427. var view = viewList[i];
  25428. if (!view.__alive) {
  25429. !isComponent && view.renderTask.dispose();
  25430. zr.remove(view.group);
  25431. view.dispose(ecModel, api);
  25432. viewList.splice(i, 1);
  25433. delete viewMap[view.__id];
  25434. view.__id = view.group.__ecComponentInfo = null;
  25435. }
  25436. else {
  25437. i++;
  25438. }
  25439. }
  25440. }
  25441. // /**
  25442. // * Encode visual infomation from data after data processing
  25443. // *
  25444. // * @param {module:echarts/model/Global} ecModel
  25445. // * @param {object} layout
  25446. // * @param {boolean} [layoutFilter] `true`: only layout,
  25447. // * `false`: only not layout,
  25448. // * `null`/`undefined`: all.
  25449. // * @param {string} taskBaseTag
  25450. // * @private
  25451. // */
  25452. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  25453. // each(visualFuncs, function (visual, index) {
  25454. // var isLayout = visual.isLayout;
  25455. // if (layoutFilter == null
  25456. // || (layoutFilter === false && !isLayout)
  25457. // || (layoutFilter === true && isLayout)
  25458. // ) {
  25459. // visual.func(ecModel, api, payload);
  25460. // }
  25461. // });
  25462. // }
  25463. function clearColorPalette(ecModel) {
  25464. ecModel.clearColorPalette();
  25465. ecModel.eachSeries(function (seriesModel) {
  25466. seriesModel.clearColorPalette();
  25467. });
  25468. }
  25469. function render(ecIns, ecModel, api, payload) {
  25470. renderComponents(ecIns, ecModel, api, payload);
  25471. each(ecIns._chartsViews, function (chart) {
  25472. chart.__alive = false;
  25473. });
  25474. renderSeries(ecIns, ecModel, api, payload);
  25475. // Remove groups of unrendered charts
  25476. each(ecIns._chartsViews, function (chart) {
  25477. if (!chart.__alive) {
  25478. chart.remove(ecModel, api);
  25479. }
  25480. });
  25481. }
  25482. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  25483. each(dirtyList || ecIns._componentsViews, function (componentView) {
  25484. var componentModel = componentView.__model;
  25485. componentView.render(componentModel, ecModel, api, payload);
  25486. updateZ(componentModel, componentView);
  25487. });
  25488. }
  25489. /**
  25490. * Render each chart and component
  25491. * @private
  25492. */
  25493. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  25494. // Render all charts
  25495. var scheduler = ecIns._scheduler;
  25496. var unfinished;
  25497. ecModel.eachSeries(function (seriesModel) {
  25498. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25499. chartView.__alive = true;
  25500. var renderTask = chartView.renderTask;
  25501. scheduler.updatePayload(renderTask, payload);
  25502. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  25503. renderTask.dirty();
  25504. }
  25505. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  25506. chartView.group.silent = !!seriesModel.get('silent');
  25507. updateZ(seriesModel, chartView);
  25508. updateBlend(seriesModel, chartView);
  25509. });
  25510. scheduler.unfinished |= unfinished;
  25511. // If use hover layer
  25512. updateHoverLayerStatus(ecIns, ecModel);
  25513. // Add aria
  25514. aria(ecIns._zr.dom, ecModel);
  25515. }
  25516. function performPostUpdateFuncs(ecModel, api) {
  25517. each(postUpdateFuncs, function (func) {
  25518. func(ecModel, api);
  25519. });
  25520. }
  25521. var MOUSE_EVENT_NAMES = [
  25522. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  25523. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  25524. ];
  25525. /**
  25526. * @private
  25527. */
  25528. echartsProto._initEvents = function () {
  25529. each(MOUSE_EVENT_NAMES, function (eveName) {
  25530. var handler = function (e) {
  25531. var ecModel = this.getModel();
  25532. var el = e.target;
  25533. var params;
  25534. var isGlobalOut = eveName === 'globalout';
  25535. // no e.target when 'globalout'.
  25536. if (isGlobalOut) {
  25537. params = {};
  25538. }
  25539. else if (el && el.dataIndex != null) {
  25540. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  25541. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  25542. }
  25543. // If element has custom eventData of components
  25544. else if (el && el.eventData) {
  25545. params = extend({}, el.eventData);
  25546. }
  25547. // Contract: if params prepared in mouse event,
  25548. // these properties must be specified:
  25549. // {
  25550. // componentType: string (component main type)
  25551. // componentIndex: number
  25552. // }
  25553. // Otherwise event query can not work.
  25554. if (params) {
  25555. var componentType = params.componentType;
  25556. var componentIndex = params.componentIndex;
  25557. // Special handling for historic reason: when trigger by
  25558. // markLine/markPoint/markArea, the componentType is
  25559. // 'markLine'/'markPoint'/'markArea', but we should better
  25560. // enable them to be queried by seriesIndex, since their
  25561. // option is set in each series.
  25562. if (componentType === 'markLine'
  25563. || componentType === 'markPoint'
  25564. || componentType === 'markArea'
  25565. ) {
  25566. componentType = 'series';
  25567. componentIndex = params.seriesIndex;
  25568. }
  25569. var model = componentType && componentIndex != null
  25570. && ecModel.getComponent(componentType, componentIndex);
  25571. var view = model && this[
  25572. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25573. ][model.__viewId];
  25574. if (__DEV__) {
  25575. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25576. // be missed, otherwise there is no way to distinguish source component.
  25577. // See `dataFormat.getDataParams`.
  25578. if (!isGlobalOut && !(model && view)) {
  25579. console.warn('model or view can not be found by params');
  25580. }
  25581. }
  25582. params.event = e;
  25583. params.type = eveName;
  25584. this._ecEventProcessor.eventInfo = {
  25585. targetEl: el,
  25586. packedEvent: params,
  25587. model: model,
  25588. view: view
  25589. };
  25590. this.trigger(eveName, params);
  25591. }
  25592. };
  25593. // Consider that some component (like tooltip, brush, ...)
  25594. // register zr event handler, but user event handler might
  25595. // do anything, such as call `setOption` or `dispatchAction`,
  25596. // which probably update any of the content and probably
  25597. // cause problem if it is called previous other inner handlers.
  25598. handler.zrEventfulCallAtLast = true;
  25599. this._zr.on(eveName, handler, this);
  25600. }, this);
  25601. each(eventActionMap, function (actionType, eventType) {
  25602. this._messageCenter.on(eventType, function (event) {
  25603. this.trigger(eventType, event);
  25604. }, this);
  25605. }, this);
  25606. };
  25607. /**
  25608. * @return {boolean}
  25609. */
  25610. echartsProto.isDisposed = function () {
  25611. return this._disposed;
  25612. };
  25613. /**
  25614. * Clear
  25615. */
  25616. echartsProto.clear = function () {
  25617. if (this._disposed) {
  25618. disposedWarning(this.id);
  25619. return;
  25620. }
  25621. this.setOption({ series: [] }, true);
  25622. };
  25623. /**
  25624. * Dispose instance
  25625. */
  25626. echartsProto.dispose = function () {
  25627. if (this._disposed) {
  25628. disposedWarning(this.id);
  25629. return;
  25630. }
  25631. this._disposed = true;
  25632. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25633. var api = this._api;
  25634. var ecModel = this._model;
  25635. each(this._componentsViews, function (component) {
  25636. component.dispose(ecModel, api);
  25637. });
  25638. each(this._chartsViews, function (chart) {
  25639. chart.dispose(ecModel, api);
  25640. });
  25641. // Dispose after all views disposed
  25642. this._zr.dispose();
  25643. delete instances[this.id];
  25644. };
  25645. mixin(ECharts, Eventful);
  25646. function disposedWarning(id) {
  25647. if (__DEV__) {
  25648. console.warn('Instance ' + id + ' has been disposed');
  25649. }
  25650. }
  25651. function updateHoverLayerStatus(ecIns, ecModel) {
  25652. var zr = ecIns._zr;
  25653. var storage = zr.storage;
  25654. var elCount = 0;
  25655. storage.traverse(function (el) {
  25656. elCount++;
  25657. });
  25658. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  25659. ecModel.eachSeries(function (seriesModel) {
  25660. if (seriesModel.preventUsingHoverLayer) {
  25661. return;
  25662. }
  25663. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25664. if (chartView.__alive) {
  25665. chartView.group.traverse(function (el) {
  25666. // Don't switch back.
  25667. el.useHoverLayer = true;
  25668. });
  25669. }
  25670. });
  25671. }
  25672. }
  25673. /**
  25674. * Update chart progressive and blend.
  25675. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25676. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25677. */
  25678. function updateBlend(seriesModel, chartView) {
  25679. var blendMode = seriesModel.get('blendMode') || null;
  25680. if (__DEV__) {
  25681. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  25682. console.warn('Only canvas support blendMode');
  25683. }
  25684. }
  25685. chartView.group.traverse(function (el) {
  25686. // FIXME marker and other components
  25687. if (!el.isGroup) {
  25688. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  25689. if (el.style.blend !== blendMode) {
  25690. el.setStyle('blend', blendMode);
  25691. }
  25692. }
  25693. if (el.eachPendingDisplayable) {
  25694. el.eachPendingDisplayable(function (displayable) {
  25695. displayable.setStyle('blend', blendMode);
  25696. });
  25697. }
  25698. });
  25699. }
  25700. /**
  25701. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25702. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25703. */
  25704. function updateZ(model, view) {
  25705. var z = model.get('z');
  25706. var zlevel = model.get('zlevel');
  25707. // Set z and zlevel
  25708. view.group.traverse(function (el) {
  25709. if (el.type !== 'group') {
  25710. z != null && (el.z = z);
  25711. zlevel != null && (el.zlevel = zlevel);
  25712. }
  25713. });
  25714. }
  25715. function createExtensionAPI(ecInstance) {
  25716. var coordSysMgr = ecInstance._coordSysMgr;
  25717. return extend(new ExtensionAPI(ecInstance), {
  25718. // Inject methods
  25719. getCoordinateSystems: bind(
  25720. coordSysMgr.getCoordinateSystems, coordSysMgr
  25721. ),
  25722. getComponentByElement: function (el) {
  25723. while (el) {
  25724. var modelInfo = el.__ecComponentInfo;
  25725. if (modelInfo != null) {
  25726. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  25727. }
  25728. el = el.parent;
  25729. }
  25730. }
  25731. });
  25732. }
  25733. /**
  25734. * @class
  25735. * Usage of query:
  25736. * `chart.on('click', query, handler);`
  25737. * The `query` can be:
  25738. * + The component type query string, only `mainType` or `mainType.subType`,
  25739. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25740. * + The component query object, like:
  25741. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25742. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25743. * + The data query object, like:
  25744. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25745. * + The other query object (cmponent customized query), like:
  25746. * `{element: 'some'}` (only available in custom series).
  25747. *
  25748. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25749. * same as there is no such prop in the `query` object.
  25750. */
  25751. function EventProcessor() {
  25752. // These info required: targetEl, packedEvent, model, view
  25753. this.eventInfo;
  25754. }
  25755. EventProcessor.prototype = {
  25756. constructor: EventProcessor,
  25757. normalizeQuery: function (query) {
  25758. var cptQuery = {};
  25759. var dataQuery = {};
  25760. var otherQuery = {};
  25761. // `query` is `mainType` or `mainType.subType` of component.
  25762. if (isString(query)) {
  25763. var condCptType = parseClassType(query);
  25764. // `.main` and `.sub` may be ''.
  25765. cptQuery.mainType = condCptType.main || null;
  25766. cptQuery.subType = condCptType.sub || null;
  25767. }
  25768. // `query` is an object, convert to {mainType, index, name, id}.
  25769. else {
  25770. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25771. // can not be used in `compomentModel.filterForExposedEvent`.
  25772. var suffixes = ['Index', 'Name', 'Id'];
  25773. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25774. each$1(query, function (val, key) {
  25775. var reserved = false;
  25776. for (var i = 0; i < suffixes.length; i++) {
  25777. var propSuffix = suffixes[i];
  25778. var suffixPos = key.lastIndexOf(propSuffix);
  25779. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25780. var mainType = key.slice(0, suffixPos);
  25781. // Consider `dataIndex`.
  25782. if (mainType !== 'data') {
  25783. cptQuery.mainType = mainType;
  25784. cptQuery[propSuffix.toLowerCase()] = val;
  25785. reserved = true;
  25786. }
  25787. }
  25788. }
  25789. if (dataKeys.hasOwnProperty(key)) {
  25790. dataQuery[key] = val;
  25791. reserved = true;
  25792. }
  25793. if (!reserved) {
  25794. otherQuery[key] = val;
  25795. }
  25796. });
  25797. }
  25798. return {
  25799. cptQuery: cptQuery,
  25800. dataQuery: dataQuery,
  25801. otherQuery: otherQuery
  25802. };
  25803. },
  25804. filter: function (eventType, query, args) {
  25805. // They should be assigned before each trigger call.
  25806. var eventInfo = this.eventInfo;
  25807. if (!eventInfo) {
  25808. return true;
  25809. }
  25810. var targetEl = eventInfo.targetEl;
  25811. var packedEvent = eventInfo.packedEvent;
  25812. var model = eventInfo.model;
  25813. var view = eventInfo.view;
  25814. // For event like 'globalout'.
  25815. if (!model || !view) {
  25816. return true;
  25817. }
  25818. var cptQuery = query.cptQuery;
  25819. var dataQuery = query.dataQuery;
  25820. return check(cptQuery, model, 'mainType')
  25821. && check(cptQuery, model, 'subType')
  25822. && check(cptQuery, model, 'index', 'componentIndex')
  25823. && check(cptQuery, model, 'name')
  25824. && check(cptQuery, model, 'id')
  25825. && check(dataQuery, packedEvent, 'name')
  25826. && check(dataQuery, packedEvent, 'dataIndex')
  25827. && check(dataQuery, packedEvent, 'dataType')
  25828. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25829. eventType, query.otherQuery, targetEl, packedEvent
  25830. ));
  25831. function check(query, host, prop, propOnHost) {
  25832. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25833. }
  25834. },
  25835. afterTrigger: function () {
  25836. // Make sure the eventInfo wont be used in next trigger.
  25837. this.eventInfo = null;
  25838. }
  25839. };
  25840. /**
  25841. * @type {Object} key: actionType.
  25842. * @inner
  25843. */
  25844. var actions = {};
  25845. /**
  25846. * Map eventType to actionType
  25847. * @type {Object}
  25848. */
  25849. var eventActionMap = {};
  25850. /**
  25851. * Data processor functions of each stage
  25852. * @type {Array.<Object.<string, Function>>}
  25853. * @inner
  25854. */
  25855. var dataProcessorFuncs = [];
  25856. /**
  25857. * @type {Array.<Function>}
  25858. * @inner
  25859. */
  25860. var optionPreprocessorFuncs = [];
  25861. /**
  25862. * @type {Array.<Function>}
  25863. * @inner
  25864. */
  25865. var postUpdateFuncs = [];
  25866. /**
  25867. * Visual encoding functions of each stage
  25868. * @type {Array.<Object.<string, Function>>}
  25869. */
  25870. var visualFuncs = [];
  25871. /**
  25872. * Theme storage
  25873. * @type {Object.<key, Object>}
  25874. */
  25875. var themeStorage = {};
  25876. /**
  25877. * Loading effects
  25878. */
  25879. var loadingEffects = {};
  25880. var instances = {};
  25881. var connectedGroups = {};
  25882. var idBase = new Date() - 0;
  25883. var groupIdBase = new Date() - 0;
  25884. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25885. function enableConnect(chart) {
  25886. var STATUS_PENDING = 0;
  25887. var STATUS_UPDATING = 1;
  25888. var STATUS_UPDATED = 2;
  25889. var STATUS_KEY = '__connectUpdateStatus';
  25890. function updateConnectedChartsStatus(charts, status) {
  25891. for (var i = 0; i < charts.length; i++) {
  25892. var otherChart = charts[i];
  25893. otherChart[STATUS_KEY] = status;
  25894. }
  25895. }
  25896. each(eventActionMap, function (actionType, eventType) {
  25897. chart._messageCenter.on(eventType, function (event) {
  25898. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25899. if (event && event.escapeConnect) {
  25900. return;
  25901. }
  25902. var action = chart.makeActionFromEvent(event);
  25903. var otherCharts = [];
  25904. each(instances, function (otherChart) {
  25905. if (otherChart !== chart && otherChart.group === chart.group) {
  25906. otherCharts.push(otherChart);
  25907. }
  25908. });
  25909. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25910. each(otherCharts, function (otherChart) {
  25911. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25912. otherChart.dispatchAction(action);
  25913. }
  25914. });
  25915. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25916. }
  25917. });
  25918. });
  25919. }
  25920. /**
  25921. * @param {HTMLElement} dom
  25922. * @param {Object} [theme]
  25923. * @param {Object} opts
  25924. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25925. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  25926. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  25927. * Can be 'auto' (the same as null/undefined)
  25928. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  25929. * Can be 'auto' (the same as null/undefined)
  25930. */
  25931. function init(dom, theme$$1, opts) {
  25932. if (__DEV__) {
  25933. // Check version
  25934. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  25935. throw new Error(
  25936. 'zrender/src ' + version$1
  25937. + ' is too old for ECharts ' + version
  25938. + '. Current version need ZRender '
  25939. + dependencies.zrender + '+'
  25940. );
  25941. }
  25942. if (!dom) {
  25943. throw new Error('Initialize failed: invalid dom.');
  25944. }
  25945. }
  25946. var existInstance = getInstanceByDom(dom);
  25947. if (existInstance) {
  25948. if (__DEV__) {
  25949. console.warn('There is a chart instance already initialized on the dom.');
  25950. }
  25951. return existInstance;
  25952. }
  25953. if (__DEV__) {
  25954. if (isDom(dom)
  25955. && dom.nodeName.toUpperCase() !== 'CANVAS'
  25956. && (
  25957. (!dom.clientWidth && (!opts || opts.width == null))
  25958. || (!dom.clientHeight && (!opts || opts.height == null))
  25959. )
  25960. ) {
  25961. console.warn('Can\'t get DOM width or height. Please check '
  25962. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  25963. + 'For example, you may need to call this in the callback '
  25964. + 'of window.onload.');
  25965. }
  25966. }
  25967. var chart = new ECharts(dom, theme$$1, opts);
  25968. chart.id = 'ec_' + idBase++;
  25969. instances[chart.id] = chart;
  25970. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25971. enableConnect(chart);
  25972. return chart;
  25973. }
  25974. /**
  25975. * @return {string|Array.<module:echarts~ECharts>} groupId
  25976. */
  25977. function connect(groupId) {
  25978. // Is array of charts
  25979. if (isArray(groupId)) {
  25980. var charts = groupId;
  25981. groupId = null;
  25982. // If any chart has group
  25983. each(charts, function (chart) {
  25984. if (chart.group != null) {
  25985. groupId = chart.group;
  25986. }
  25987. });
  25988. groupId = groupId || ('g_' + groupIdBase++);
  25989. each(charts, function (chart) {
  25990. chart.group = groupId;
  25991. });
  25992. }
  25993. connectedGroups[groupId] = true;
  25994. return groupId;
  25995. }
  25996. /**
  25997. * @DEPRECATED
  25998. * @return {string} groupId
  25999. */
  26000. function disConnect(groupId) {
  26001. connectedGroups[groupId] = false;
  26002. }
  26003. /**
  26004. * @return {string} groupId
  26005. */
  26006. var disconnect = disConnect;
  26007. /**
  26008. * Dispose a chart instance
  26009. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  26010. */
  26011. function dispose(chart) {
  26012. if (typeof chart === 'string') {
  26013. chart = instances[chart];
  26014. }
  26015. else if (!(chart instanceof ECharts)) {
  26016. // Try to treat as dom
  26017. chart = getInstanceByDom(chart);
  26018. }
  26019. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  26020. chart.dispose();
  26021. }
  26022. }
  26023. /**
  26024. * @param {HTMLElement} dom
  26025. * @return {echarts~ECharts}
  26026. */
  26027. function getInstanceByDom(dom) {
  26028. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  26029. }
  26030. /**
  26031. * @param {string} key
  26032. * @return {echarts~ECharts}
  26033. */
  26034. function getInstanceById(key) {
  26035. return instances[key];
  26036. }
  26037. /**
  26038. * Register theme
  26039. */
  26040. function registerTheme(name, theme$$1) {
  26041. themeStorage[name] = theme$$1;
  26042. }
  26043. /**
  26044. * Register option preprocessor
  26045. * @param {Function} preprocessorFunc
  26046. */
  26047. function registerPreprocessor(preprocessorFunc) {
  26048. optionPreprocessorFuncs.push(preprocessorFunc);
  26049. }
  26050. /**
  26051. * @param {number} [priority=1000]
  26052. * @param {Object|Function} processor
  26053. */
  26054. function registerProcessor(priority, processor) {
  26055. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  26056. }
  26057. /**
  26058. * Register postUpdater
  26059. * @param {Function} postUpdateFunc
  26060. */
  26061. function registerPostUpdate(postUpdateFunc) {
  26062. postUpdateFuncs.push(postUpdateFunc);
  26063. }
  26064. /**
  26065. * Usage:
  26066. * registerAction('someAction', 'someEvent', function () { ... });
  26067. * registerAction('someAction', function () { ... });
  26068. * registerAction(
  26069. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  26070. * function () { ... }
  26071. * );
  26072. *
  26073. * @param {(string|Object)} actionInfo
  26074. * @param {string} actionInfo.type
  26075. * @param {string} [actionInfo.event]
  26076. * @param {string} [actionInfo.update]
  26077. * @param {string} [eventName]
  26078. * @param {Function} action
  26079. */
  26080. function registerAction(actionInfo, eventName, action) {
  26081. if (typeof eventName === 'function') {
  26082. action = eventName;
  26083. eventName = '';
  26084. }
  26085. var actionType = isObject(actionInfo)
  26086. ? actionInfo.type
  26087. : ([actionInfo, actionInfo = {
  26088. event: eventName
  26089. }][0]);
  26090. // Event name is all lowercase
  26091. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  26092. eventName = actionInfo.event;
  26093. // Validate action type and event name.
  26094. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  26095. if (!actions[actionType]) {
  26096. actions[actionType] = {action: action, actionInfo: actionInfo};
  26097. }
  26098. eventActionMap[eventName] = actionType;
  26099. }
  26100. /**
  26101. * @param {string} type
  26102. * @param {*} CoordinateSystem
  26103. */
  26104. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  26105. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  26106. }
  26107. /**
  26108. * Get dimensions of specified coordinate system.
  26109. * @param {string} type
  26110. * @return {Array.<string|Object>}
  26111. */
  26112. function getCoordinateSystemDimensions(type) {
  26113. var coordSysCreator = CoordinateSystemManager.get(type);
  26114. if (coordSysCreator) {
  26115. return coordSysCreator.getDimensionsInfo
  26116. ? coordSysCreator.getDimensionsInfo()
  26117. : coordSysCreator.dimensions.slice();
  26118. }
  26119. }
  26120. /**
  26121. * Layout is a special stage of visual encoding
  26122. * Most visual encoding like color are common for different chart
  26123. * But each chart has it's own layout algorithm
  26124. *
  26125. * @param {number} [priority=1000]
  26126. * @param {Function} layoutTask
  26127. */
  26128. function registerLayout(priority, layoutTask) {
  26129. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  26130. }
  26131. /**
  26132. * @param {number} [priority=3000]
  26133. * @param {module:echarts/stream/Task} visualTask
  26134. */
  26135. function registerVisual(priority, visualTask) {
  26136. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  26137. }
  26138. /**
  26139. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  26140. */
  26141. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  26142. if (isFunction(priority) || isObject(priority)) {
  26143. fn = priority;
  26144. priority = defaultPriority;
  26145. }
  26146. if (__DEV__) {
  26147. if (isNaN(priority) || priority == null) {
  26148. throw new Error('Illegal priority');
  26149. }
  26150. // Check duplicate
  26151. each(targetList, function (wrap) {
  26152. assert(wrap.__raw !== fn);
  26153. });
  26154. }
  26155. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  26156. stageHandler.__prio = priority;
  26157. stageHandler.__raw = fn;
  26158. targetList.push(stageHandler);
  26159. return stageHandler;
  26160. }
  26161. /**
  26162. * @param {string} name
  26163. */
  26164. function registerLoading(name, loadingFx) {
  26165. loadingEffects[name] = loadingFx;
  26166. }
  26167. /**
  26168. * @param {Object} opts
  26169. * @param {string} [superClass]
  26170. */
  26171. function extendComponentModel(opts/*, superClass*/) {
  26172. // var Clazz = ComponentModel;
  26173. // if (superClass) {
  26174. // var classType = parseClassType(superClass);
  26175. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26176. // }
  26177. return ComponentModel.extend(opts);
  26178. }
  26179. /**
  26180. * @param {Object} opts
  26181. * @param {string} [superClass]
  26182. */
  26183. function extendComponentView(opts/*, superClass*/) {
  26184. // var Clazz = ComponentView;
  26185. // if (superClass) {
  26186. // var classType = parseClassType(superClass);
  26187. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  26188. // }
  26189. return Component$1.extend(opts);
  26190. }
  26191. /**
  26192. * @param {Object} opts
  26193. * @param {string} [superClass]
  26194. */
  26195. function extendSeriesModel(opts/*, superClass*/) {
  26196. // var Clazz = SeriesModel;
  26197. // if (superClass) {
  26198. // superClass = 'series.' + superClass.replace('series.', '');
  26199. // var classType = parseClassType(superClass);
  26200. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26201. // }
  26202. return SeriesModel.extend(opts);
  26203. }
  26204. /**
  26205. * @param {Object} opts
  26206. * @param {string} [superClass]
  26207. */
  26208. function extendChartView(opts/*, superClass*/) {
  26209. // var Clazz = ChartView;
  26210. // if (superClass) {
  26211. // superClass = superClass.replace('series.', '');
  26212. // var classType = parseClassType(superClass);
  26213. // Clazz = ChartView.getClass(classType.main, true);
  26214. // }
  26215. return Chart.extend(opts);
  26216. }
  26217. /**
  26218. * ZRender need a canvas context to do measureText.
  26219. * But in node environment canvas may be created by node-canvas.
  26220. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26221. *
  26222. * Be careful of using it in the browser.
  26223. *
  26224. * @param {Function} creator
  26225. * @example
  26226. * var Canvas = require('canvas');
  26227. * var echarts = require('echarts');
  26228. * echarts.setCanvasCreator(function () {
  26229. * // Small size is enough.
  26230. * return new Canvas(32, 32);
  26231. * });
  26232. */
  26233. function setCanvasCreator(creator) {
  26234. $override('createCanvas', creator);
  26235. }
  26236. /**
  26237. * @param {string} mapName
  26238. * @param {Array.<Object>|Object|string} geoJson
  26239. * @param {Object} [specialAreas]
  26240. *
  26241. * @example GeoJSON
  26242. * $.get('USA.json', function (geoJson) {
  26243. * echarts.registerMap('USA', geoJson);
  26244. * // Or
  26245. * echarts.registerMap('USA', {
  26246. * geoJson: geoJson,
  26247. * specialAreas: {}
  26248. * })
  26249. * });
  26250. *
  26251. * $.get('airport.svg', function (svg) {
  26252. * echarts.registerMap('airport', {
  26253. * svg: svg
  26254. * }
  26255. * });
  26256. *
  26257. * echarts.registerMap('eu', [
  26258. * {svg: eu-topographic.svg},
  26259. * {geoJSON: eu.json}
  26260. * ])
  26261. */
  26262. function registerMap(mapName, geoJson, specialAreas) {
  26263. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  26264. }
  26265. /**
  26266. * @param {string} mapName
  26267. * @return {Object}
  26268. */
  26269. function getMap(mapName) {
  26270. // For backward compatibility, only return the first one.
  26271. var records = mapDataStorage.retrieveMap(mapName);
  26272. return records && records[0] && {
  26273. geoJson: records[0].geoJSON,
  26274. specialAreas: records[0].specialAreas
  26275. };
  26276. }
  26277. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  26278. registerPreprocessor(backwardCompat);
  26279. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26280. registerLoading('default', loadingDefault);
  26281. // Default actions
  26282. registerAction({
  26283. type: 'highlight',
  26284. event: 'highlight',
  26285. update: 'highlight'
  26286. }, noop);
  26287. registerAction({
  26288. type: 'downplay',
  26289. event: 'downplay',
  26290. update: 'downplay'
  26291. }, noop);
  26292. // Default theme
  26293. registerTheme('light', lightTheme);
  26294. registerTheme('dark', theme);
  26295. // For backward compatibility, where the namespace `dataTool` will
  26296. // be mounted on `echarts` is the extension `dataTool` is imported.
  26297. var dataTool = {};
  26298. /*
  26299. * Licensed to the Apache Software Foundation (ASF) under one
  26300. * or more contributor license agreements. See the NOTICE file
  26301. * distributed with this work for additional information
  26302. * regarding copyright ownership. The ASF licenses this file
  26303. * to you under the Apache License, Version 2.0 (the
  26304. * "License"); you may not use this file except in compliance
  26305. * with the License. You may obtain a copy of the License at
  26306. *
  26307. * http://www.apache.org/licenses/LICENSE-2.0
  26308. *
  26309. * Unless required by applicable law or agreed to in writing,
  26310. * software distributed under the License is distributed on an
  26311. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26312. * KIND, either express or implied. See the License for the
  26313. * specific language governing permissions and limitations
  26314. * under the License.
  26315. */
  26316. function defaultKeyGetter(item) {
  26317. return item;
  26318. }
  26319. /**
  26320. * @param {Array} oldArr
  26321. * @param {Array} newArr
  26322. * @param {Function} oldKeyGetter
  26323. * @param {Function} newKeyGetter
  26324. * @param {Object} [context] Can be visited by this.context in callback.
  26325. */
  26326. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  26327. this._old = oldArr;
  26328. this._new = newArr;
  26329. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26330. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  26331. this.context = context;
  26332. }
  26333. DataDiffer.prototype = {
  26334. constructor: DataDiffer,
  26335. /**
  26336. * Callback function when add a data
  26337. */
  26338. add: function (func) {
  26339. this._add = func;
  26340. return this;
  26341. },
  26342. /**
  26343. * Callback function when update a data
  26344. */
  26345. update: function (func) {
  26346. this._update = func;
  26347. return this;
  26348. },
  26349. /**
  26350. * Callback function when remove a data
  26351. */
  26352. remove: function (func) {
  26353. this._remove = func;
  26354. return this;
  26355. },
  26356. execute: function () {
  26357. var oldArr = this._old;
  26358. var newArr = this._new;
  26359. var oldDataIndexMap = {};
  26360. var newDataIndexMap = {};
  26361. var oldDataKeyArr = [];
  26362. var newDataKeyArr = [];
  26363. var i;
  26364. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  26365. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  26366. for (i = 0; i < oldArr.length; i++) {
  26367. var key = oldDataKeyArr[i];
  26368. var idx = newDataIndexMap[key];
  26369. // idx can never be empty array here. see 'set null' logic below.
  26370. if (idx != null) {
  26371. // Consider there is duplicate key (for example, use dataItem.name as key).
  26372. // We should make sure every item in newArr and oldArr can be visited.
  26373. var len = idx.length;
  26374. if (len) {
  26375. len === 1 && (newDataIndexMap[key] = null);
  26376. idx = idx.shift();
  26377. }
  26378. else {
  26379. newDataIndexMap[key] = null;
  26380. }
  26381. this._update && this._update(idx, i);
  26382. }
  26383. else {
  26384. this._remove && this._remove(i);
  26385. }
  26386. }
  26387. for (var i = 0; i < newDataKeyArr.length; i++) {
  26388. var key = newDataKeyArr[i];
  26389. if (newDataIndexMap.hasOwnProperty(key)) {
  26390. var idx = newDataIndexMap[key];
  26391. if (idx == null) {
  26392. continue;
  26393. }
  26394. // idx can never be empty array here. see 'set null' logic above.
  26395. if (!idx.length) {
  26396. this._add && this._add(idx);
  26397. }
  26398. else {
  26399. for (var j = 0, len = idx.length; j < len; j++) {
  26400. this._add && this._add(idx[j]);
  26401. }
  26402. }
  26403. }
  26404. }
  26405. }
  26406. };
  26407. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  26408. for (var i = 0; i < arr.length; i++) {
  26409. // Add prefix to avoid conflict with Object.prototype.
  26410. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  26411. var existence = map[key];
  26412. if (existence == null) {
  26413. keyArr.push(key);
  26414. map[key] = i;
  26415. }
  26416. else {
  26417. if (!existence.length) {
  26418. map[key] = existence = [existence];
  26419. }
  26420. existence.push(i);
  26421. }
  26422. }
  26423. }
  26424. /*
  26425. * Licensed to the Apache Software Foundation (ASF) under one
  26426. * or more contributor license agreements. See the NOTICE file
  26427. * distributed with this work for additional information
  26428. * regarding copyright ownership. The ASF licenses this file
  26429. * to you under the Apache License, Version 2.0 (the
  26430. * "License"); you may not use this file except in compliance
  26431. * with the License. You may obtain a copy of the License at
  26432. *
  26433. * http://www.apache.org/licenses/LICENSE-2.0
  26434. *
  26435. * Unless required by applicable law or agreed to in writing,
  26436. * software distributed under the License is distributed on an
  26437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26438. * KIND, either express or implied. See the License for the
  26439. * specific language governing permissions and limitations
  26440. * under the License.
  26441. */
  26442. var OTHER_DIMENSIONS = createHashMap([
  26443. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  26444. ]);
  26445. function summarizeDimensions(data) {
  26446. var summary = {};
  26447. var encode = summary.encode = {};
  26448. var notExtraCoordDimMap = createHashMap();
  26449. var defaultedLabel = [];
  26450. var defaultedTooltip = [];
  26451. // See the comment of `List.js#userOutput`.
  26452. var userOutput = summary.userOutput = {
  26453. dimensionNames: data.dimensions.slice(),
  26454. encode: {}
  26455. };
  26456. each$1(data.dimensions, function (dimName) {
  26457. var dimItem = data.getDimensionInfo(dimName);
  26458. var coordDim = dimItem.coordDim;
  26459. if (coordDim) {
  26460. if (__DEV__) {
  26461. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  26462. }
  26463. var coordDimIndex = dimItem.coordDimIndex;
  26464. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  26465. if (!dimItem.isExtraCoord) {
  26466. notExtraCoordDimMap.set(coordDim, 1);
  26467. // Use the last coord dim (and label friendly) as default label,
  26468. // because when dataset is used, it is hard to guess which dimension
  26469. // can be value dimension. If both show x, y on label is not look good,
  26470. // and conventionally y axis is focused more.
  26471. if (mayLabelDimType(dimItem.type)) {
  26472. defaultedLabel[0] = dimName;
  26473. }
  26474. // User output encode do not contain generated coords.
  26475. // And it only has index. User can use index to retrieve value from the raw item array.
  26476. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  26477. }
  26478. if (dimItem.defaultTooltip) {
  26479. defaultedTooltip.push(dimName);
  26480. }
  26481. }
  26482. OTHER_DIMENSIONS.each(function (v, otherDim) {
  26483. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  26484. var dimIndex = dimItem.otherDims[otherDim];
  26485. if (dimIndex != null && dimIndex !== false) {
  26486. encodeArr[dimIndex] = dimItem.name;
  26487. }
  26488. });
  26489. });
  26490. var dataDimsOnCoord = [];
  26491. var encodeFirstDimNotExtra = {};
  26492. notExtraCoordDimMap.each(function (v, coordDim) {
  26493. var dimArr = encode[coordDim];
  26494. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  26495. // But should fix the case that radar axes: simplify the logic
  26496. // of `completeDimension`, remove `extraPrefix`.
  26497. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  26498. // Not necessary to remove duplicate, because a data
  26499. // dim canot on more than one coordDim.
  26500. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  26501. });
  26502. summary.dataDimsOnCoord = dataDimsOnCoord;
  26503. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  26504. var encodeLabel = encode.label;
  26505. // FIXME `encode.label` is not recommanded, because formatter can not be set
  26506. // in this way. Use label.formatter instead. May be remove this approach someday.
  26507. if (encodeLabel && encodeLabel.length) {
  26508. defaultedLabel = encodeLabel.slice();
  26509. }
  26510. var encodeTooltip = encode.tooltip;
  26511. if (encodeTooltip && encodeTooltip.length) {
  26512. defaultedTooltip = encodeTooltip.slice();
  26513. }
  26514. else if (!defaultedTooltip.length) {
  26515. defaultedTooltip = defaultedLabel.slice();
  26516. }
  26517. encode.defaultedLabel = defaultedLabel;
  26518. encode.defaultedTooltip = defaultedTooltip;
  26519. return summary;
  26520. }
  26521. function getOrCreateEncodeArr(encode, dim) {
  26522. if (!encode.hasOwnProperty(dim)) {
  26523. encode[dim] = [];
  26524. }
  26525. return encode[dim];
  26526. }
  26527. function getDimensionTypeByAxis(axisType) {
  26528. return axisType === 'category'
  26529. ? 'ordinal'
  26530. : axisType === 'time'
  26531. ? 'time'
  26532. : 'float';
  26533. }
  26534. function mayLabelDimType(dimType) {
  26535. // In most cases, ordinal and time do not suitable for label.
  26536. // Ordinal info can be displayed on axis. Time is too long.
  26537. return !(dimType === 'ordinal' || dimType === 'time');
  26538. }
  26539. // function findTheLastDimMayLabel(data) {
  26540. // // Get last value dim
  26541. // var dimensions = data.dimensions.slice();
  26542. // var valueType;
  26543. // var valueDim;
  26544. // while (dimensions.length && (
  26545. // valueDim = dimensions.pop(),
  26546. // valueType = data.getDimensionInfo(valueDim).type,
  26547. // valueType === 'ordinal' || valueType === 'time'
  26548. // )) {} // jshint ignore:line
  26549. // return valueDim;
  26550. // }
  26551. /*
  26552. * Licensed to the Apache Software Foundation (ASF) under one
  26553. * or more contributor license agreements. See the NOTICE file
  26554. * distributed with this work for additional information
  26555. * regarding copyright ownership. The ASF licenses this file
  26556. * to you under the Apache License, Version 2.0 (the
  26557. * "License"); you may not use this file except in compliance
  26558. * with the License. You may obtain a copy of the License at
  26559. *
  26560. * http://www.apache.org/licenses/LICENSE-2.0
  26561. *
  26562. * Unless required by applicable law or agreed to in writing,
  26563. * software distributed under the License is distributed on an
  26564. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26565. * KIND, either express or implied. See the License for the
  26566. * specific language governing permissions and limitations
  26567. * under the License.
  26568. */
  26569. /**
  26570. * @class
  26571. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  26572. */
  26573. function DataDimensionInfo(opt) {
  26574. if (opt != null) {
  26575. extend(this, opt);
  26576. }
  26577. /**
  26578. * Dimension name.
  26579. * Mandatory.
  26580. * @type {string}
  26581. */
  26582. // this.name;
  26583. /**
  26584. * The origin name in dimsDef, see source helper.
  26585. * If displayName given, the tooltip will displayed vertically.
  26586. * Optional.
  26587. * @type {string}
  26588. */
  26589. // this.displayName;
  26590. /**
  26591. * Which coordSys dimension this dimension mapped to.
  26592. * A `coordDim` can be a "coordSysDim" that the coordSys required
  26593. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  26594. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  26595. * (That is determined by whether `isExtraCoord` is `true`).
  26596. * Mandatory.
  26597. * @type {string}
  26598. */
  26599. // this.coordDim;
  26600. /**
  26601. * The index of this dimension in `series.encode[coordDim]`.
  26602. * Mandatory.
  26603. * @type {number}
  26604. */
  26605. // this.coordDimIndex;
  26606. /**
  26607. * Dimension type. The enumerable values are the key of
  26608. * `dataCtors` of `data/List`.
  26609. * Optional.
  26610. * @type {string}
  26611. */
  26612. // this.type;
  26613. /**
  26614. * This index of this dimension info in `data/List#_dimensionInfos`.
  26615. * Mandatory after added to `data/List`.
  26616. * @type {number}
  26617. */
  26618. // this.index;
  26619. /**
  26620. * The format of `otherDims` is:
  26621. * ```js
  26622. * {
  26623. * tooltip: number optional,
  26624. * label: number optional,
  26625. * itemName: number optional,
  26626. * seriesName: number optional,
  26627. * }
  26628. * ```
  26629. *
  26630. * A `series.encode` can specified these fields:
  26631. * ```js
  26632. * encode: {
  26633. * // "3, 1, 5" is the index of data dimension.
  26634. * tooltip: [3, 1, 5],
  26635. * label: [0, 3],
  26636. * ...
  26637. * }
  26638. * ```
  26639. * `otherDims` is the parse result of the `series.encode` above, like:
  26640. * ```js
  26641. * // Suppose the index of this data dimension is `3`.
  26642. * this.otherDims = {
  26643. * // `3` is at the index `0` of the `encode.tooltip`
  26644. * tooltip: 0,
  26645. * // `3` is at the index `1` of the `encode.tooltip`
  26646. * label: 1
  26647. * };
  26648. * ```
  26649. *
  26650. * This prop should never be `null`/`undefined` after initialized.
  26651. * @type {Object}
  26652. */
  26653. this.otherDims = {};
  26654. /**
  26655. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  26656. * "coordSys" required.
  26657. * Mandatory.
  26658. * @type {boolean}
  26659. */
  26660. // this.isExtraCoord;
  26661. /**
  26662. * @type {module:data/OrdinalMeta}
  26663. */
  26664. // this.ordinalMeta;
  26665. /**
  26666. * Whether to create inverted indices.
  26667. * @type {boolean}
  26668. */
  26669. // this.createInvertedIndices;
  26670. }
  26671. /*
  26672. * Licensed to the Apache Software Foundation (ASF) under one
  26673. * or more contributor license agreements. See the NOTICE file
  26674. * distributed with this work for additional information
  26675. * regarding copyright ownership. The ASF licenses this file
  26676. * to you under the Apache License, Version 2.0 (the
  26677. * "License"); you may not use this file except in compliance
  26678. * with the License. You may obtain a copy of the License at
  26679. *
  26680. * http://www.apache.org/licenses/LICENSE-2.0
  26681. *
  26682. * Unless required by applicable law or agreed to in writing,
  26683. * software distributed under the License is distributed on an
  26684. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26685. * KIND, either express or implied. See the License for the
  26686. * specific language governing permissions and limitations
  26687. * under the License.
  26688. */
  26689. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  26690. /**
  26691. * List for data storage
  26692. * @module echarts/data/List
  26693. */
  26694. var isObject$4 = isObject$1;
  26695. var UNDEFINED = 'undefined';
  26696. var INDEX_NOT_FOUND = -1;
  26697. // Use prefix to avoid index to be the same as otherIdList[idx],
  26698. // which will cause weird udpate animation.
  26699. var ID_PREFIX = 'e\0\0';
  26700. var dataCtors = {
  26701. 'float': typeof Float64Array === UNDEFINED
  26702. ? Array : Float64Array,
  26703. 'int': typeof Int32Array === UNDEFINED
  26704. ? Array : Int32Array,
  26705. // Ordinal data type can be string or int
  26706. 'ordinal': Array,
  26707. 'number': Array,
  26708. 'time': Array
  26709. };
  26710. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  26711. // different from the Ctor of typed array.
  26712. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  26713. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  26714. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  26715. function getIndicesCtor(list) {
  26716. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  26717. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  26718. }
  26719. function cloneChunk(originalChunk) {
  26720. var Ctor = originalChunk.constructor;
  26721. // Only shallow clone is enough when Array.
  26722. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  26723. }
  26724. var TRANSFERABLE_PROPERTIES = [
  26725. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  26726. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  26727. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  26728. ];
  26729. var CLONE_PROPERTIES = [
  26730. '_extent', '_approximateExtent', '_rawExtent'
  26731. ];
  26732. function transferProperties(target, source) {
  26733. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  26734. if (source.hasOwnProperty(propName)) {
  26735. target[propName] = source[propName];
  26736. }
  26737. });
  26738. target.__wrappedMethods = source.__wrappedMethods;
  26739. each$1(CLONE_PROPERTIES, function (propName) {
  26740. target[propName] = clone(source[propName]);
  26741. });
  26742. target._calculationInfo = extend(source._calculationInfo);
  26743. }
  26744. /**
  26745. * @constructor
  26746. * @alias module:echarts/data/List
  26747. *
  26748. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  26749. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26750. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26751. * @param {module:echarts/model/Model} hostModel
  26752. */
  26753. var List = function (dimensions, hostModel) {
  26754. dimensions = dimensions || ['x', 'y'];
  26755. var dimensionInfos = {};
  26756. var dimensionNames = [];
  26757. var invertedIndicesMap = {};
  26758. for (var i = 0; i < dimensions.length; i++) {
  26759. // Use the original dimensions[i], where other flag props may exists.
  26760. var dimensionInfo = dimensions[i];
  26761. if (isString(dimensionInfo)) {
  26762. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26763. }
  26764. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26765. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26766. }
  26767. var dimensionName = dimensionInfo.name;
  26768. dimensionInfo.type = dimensionInfo.type || 'float';
  26769. if (!dimensionInfo.coordDim) {
  26770. dimensionInfo.coordDim = dimensionName;
  26771. dimensionInfo.coordDimIndex = 0;
  26772. }
  26773. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26774. dimensionNames.push(dimensionName);
  26775. dimensionInfos[dimensionName] = dimensionInfo;
  26776. dimensionInfo.index = i;
  26777. if (dimensionInfo.createInvertedIndices) {
  26778. invertedIndicesMap[dimensionName] = [];
  26779. }
  26780. }
  26781. /**
  26782. * @readOnly
  26783. * @type {Array.<string>}
  26784. */
  26785. this.dimensions = dimensionNames;
  26786. /**
  26787. * Infomation of each data dimension, like data type.
  26788. * @type {Object}
  26789. */
  26790. this._dimensionInfos = dimensionInfos;
  26791. /**
  26792. * @type {module:echarts/model/Model}
  26793. */
  26794. this.hostModel = hostModel;
  26795. /**
  26796. * @type {module:echarts/model/Model}
  26797. */
  26798. this.dataType;
  26799. /**
  26800. * Indices stores the indices of data subset after filtered.
  26801. * This data subset will be used in chart.
  26802. * @type {Array.<number>}
  26803. * @readOnly
  26804. */
  26805. this._indices = null;
  26806. this._count = 0;
  26807. this._rawCount = 0;
  26808. /**
  26809. * Data storage
  26810. * @type {Object.<key, Array.<TypedArray|Array>>}
  26811. * @private
  26812. */
  26813. this._storage = {};
  26814. /**
  26815. * @type {Array.<string>}
  26816. */
  26817. this._nameList = [];
  26818. /**
  26819. * @type {Array.<string>}
  26820. */
  26821. this._idList = [];
  26822. /**
  26823. * Models of data option is stored sparse for optimizing memory cost
  26824. * @type {Array.<module:echarts/model/Model>}
  26825. * @private
  26826. */
  26827. this._optionModels = [];
  26828. /**
  26829. * Global visual properties after visual coding
  26830. * @type {Object}
  26831. * @private
  26832. */
  26833. this._visual = {};
  26834. /**
  26835. * Globel layout properties.
  26836. * @type {Object}
  26837. * @private
  26838. */
  26839. this._layout = {};
  26840. /**
  26841. * Item visual properties after visual coding
  26842. * @type {Array.<Object>}
  26843. * @private
  26844. */
  26845. this._itemVisuals = [];
  26846. /**
  26847. * Key: visual type, Value: boolean
  26848. * @type {Object}
  26849. * @readOnly
  26850. */
  26851. this.hasItemVisual = {};
  26852. /**
  26853. * Item layout properties after layout
  26854. * @type {Array.<Object>}
  26855. * @private
  26856. */
  26857. this._itemLayouts = [];
  26858. /**
  26859. * Graphic elemnents
  26860. * @type {Array.<module:zrender/Element>}
  26861. * @private
  26862. */
  26863. this._graphicEls = [];
  26864. /**
  26865. * Max size of each chunk.
  26866. * @type {number}
  26867. * @private
  26868. */
  26869. this._chunkSize = 1e5;
  26870. /**
  26871. * @type {number}
  26872. * @private
  26873. */
  26874. this._chunkCount = 0;
  26875. /**
  26876. * @type {Array.<Array|Object>}
  26877. * @private
  26878. */
  26879. this._rawData;
  26880. /**
  26881. * Raw extent will not be cloned, but only transfered.
  26882. * It will not be calculated util needed.
  26883. * key: dim,
  26884. * value: {end: number, extent: Array.<number>}
  26885. * @type {Object}
  26886. * @private
  26887. */
  26888. this._rawExtent = {};
  26889. /**
  26890. * @type {Object}
  26891. * @private
  26892. */
  26893. this._extent = {};
  26894. /**
  26895. * key: dim
  26896. * value: extent
  26897. * @type {Object}
  26898. * @private
  26899. */
  26900. this._approximateExtent = {};
  26901. /**
  26902. * Cache summary info for fast visit. See "dimensionHelper".
  26903. * @type {Object}
  26904. * @private
  26905. */
  26906. this._dimensionsSummary = summarizeDimensions(this);
  26907. /**
  26908. * @type {Object.<Array|TypedArray>}
  26909. * @private
  26910. */
  26911. this._invertedIndicesMap = invertedIndicesMap;
  26912. /**
  26913. * @type {Object}
  26914. * @private
  26915. */
  26916. this._calculationInfo = {};
  26917. /**
  26918. * User output info of this data.
  26919. * DO NOT use it in other places!
  26920. *
  26921. * When preparing user params for user callbacks, we have
  26922. * to clone these inner data structures to prevent users
  26923. * from modifying them to effect built-in logic. And for
  26924. * performance consideration we make this `userOutput` to
  26925. * avoid clone them too many times.
  26926. *
  26927. * @type {Object}
  26928. * @readOnly
  26929. */
  26930. this.userOutput = this._dimensionsSummary.userOutput;
  26931. };
  26932. var listProto = List.prototype;
  26933. listProto.type = 'list';
  26934. /**
  26935. * If each data item has it's own option
  26936. * @type {boolean}
  26937. */
  26938. listProto.hasItemOption = true;
  26939. /**
  26940. * The meanings of the input parameter `dim`:
  26941. *
  26942. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26943. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26944. * + If dim is a number-like string (e.g., `"1"`):
  26945. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26946. * + If not, it will be converted to a number, which means the index of the dimension.
  26947. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26948. * dimension setting, although now it seems that it is not a good idea.)
  26949. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26950. * if no dimension name is defined as `"1"`.
  26951. * + If dim is a not-number-like string, it means the concrete dim name.
  26952. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26953. * or customized in `dimensions` property of option like `"age"`.
  26954. *
  26955. * Get dimension name
  26956. * @param {string|number} dim See above.
  26957. * @return {string} Concrete dim name.
  26958. */
  26959. listProto.getDimension = function (dim) {
  26960. if (typeof dim === 'number'
  26961. // If being a number-like string but not being defined a dimension name.
  26962. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  26963. ) {
  26964. dim = this.dimensions[dim];
  26965. }
  26966. return dim;
  26967. };
  26968. /**
  26969. * Get type and calculation info of particular dimension
  26970. * @param {string|number} dim
  26971. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26972. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26973. */
  26974. listProto.getDimensionInfo = function (dim) {
  26975. // Do not clone, because there may be categories in dimInfo.
  26976. return this._dimensionInfos[this.getDimension(dim)];
  26977. };
  26978. /**
  26979. * @return {Array.<string>} concrete dimension name list on coord.
  26980. */
  26981. listProto.getDimensionsOnCoord = function () {
  26982. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26983. };
  26984. /**
  26985. * @param {string} coordDim
  26986. * @param {number} [idx] A coordDim may map to more than one data dim.
  26987. * If idx is `true`, return a array of all mapped dims.
  26988. * If idx is not specified, return the first dim not extra.
  26989. * @return {string|Array.<string>} concrete data dim.
  26990. * If idx is number, and not found, return null/undefined.
  26991. * If idx is `true`, and not found, return empty array (always return array).
  26992. */
  26993. listProto.mapDimension = function (coordDim, idx) {
  26994. var dimensionsSummary = this._dimensionsSummary;
  26995. if (idx == null) {
  26996. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26997. }
  26998. var dims = dimensionsSummary.encode[coordDim];
  26999. return idx === true
  27000. // always return array if idx is `true`
  27001. ? (dims || []).slice()
  27002. : (dims && dims[idx]);
  27003. };
  27004. /**
  27005. * Initialize from data
  27006. * @param {Array.<Object|number|Array>} data source or data or data provider.
  27007. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  27008. * default label/tooltip.
  27009. * A name can be specified in encode.itemName,
  27010. * or dataItem.name (only for series option data),
  27011. * or provided in nameList from outside.
  27012. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  27013. */
  27014. listProto.initData = function (data, nameList, dimValueGetter) {
  27015. var notProvider = Source.isInstance(data) || isArrayLike(data);
  27016. if (notProvider) {
  27017. data = new DefaultDataProvider(data, this.dimensions.length);
  27018. }
  27019. if (__DEV__) {
  27020. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  27021. throw new Error('Inavlid data provider.');
  27022. }
  27023. }
  27024. this._rawData = data;
  27025. // Clear
  27026. this._storage = {};
  27027. this._indices = null;
  27028. this._nameList = nameList || [];
  27029. this._idList = [];
  27030. this._nameRepeatCount = {};
  27031. if (!dimValueGetter) {
  27032. this.hasItemOption = false;
  27033. }
  27034. /**
  27035. * @readOnly
  27036. */
  27037. this.defaultDimValueGetter = defaultDimValueGetters[
  27038. this._rawData.getSource().sourceFormat
  27039. ];
  27040. // Default dim value getter
  27041. this._dimValueGetter = dimValueGetter = dimValueGetter
  27042. || this.defaultDimValueGetter;
  27043. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  27044. // Reset raw extent.
  27045. this._rawExtent = {};
  27046. this._initDataFromProvider(0, data.count());
  27047. // If data has no item option.
  27048. if (data.pure) {
  27049. this.hasItemOption = false;
  27050. }
  27051. };
  27052. listProto.getProvider = function () {
  27053. return this._rawData;
  27054. };
  27055. /**
  27056. * Caution: Can be only called on raw data (before `this._indices` created).
  27057. */
  27058. listProto.appendData = function (data) {
  27059. if (__DEV__) {
  27060. assert$1(!this._indices, 'appendData can only be called on raw data.');
  27061. }
  27062. var rawData = this._rawData;
  27063. var start = this.count();
  27064. rawData.appendData(data);
  27065. var end = rawData.count();
  27066. if (!rawData.persistent) {
  27067. end += start;
  27068. }
  27069. this._initDataFromProvider(start, end);
  27070. };
  27071. /**
  27072. * Caution: Can be only called on raw data (before `this._indices` created).
  27073. * This method does not modify `rawData` (`dataProvider`), but only
  27074. * add values to storage.
  27075. *
  27076. * The final count will be increased by `Math.max(values.length, names.length)`.
  27077. *
  27078. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  27079. * [
  27080. * [12, 33, 44],
  27081. * [NaN, 43, 1],
  27082. * ['-', 'asdf', 0]
  27083. * ]
  27084. * Each item is exaclty cooresponding to a dimension.
  27085. * @param {Array.<string>} [names]
  27086. */
  27087. listProto.appendValues = function (values, names) {
  27088. var chunkSize = this._chunkSize;
  27089. var storage = this._storage;
  27090. var dimensions = this.dimensions;
  27091. var dimLen = dimensions.length;
  27092. var rawExtent = this._rawExtent;
  27093. var start = this.count();
  27094. var end = start + Math.max(values.length, names ? names.length : 0);
  27095. var originalChunkCount = this._chunkCount;
  27096. for (var i = 0; i < dimLen; i++) {
  27097. var dim = dimensions[i];
  27098. if (!rawExtent[dim]) {
  27099. rawExtent[dim] = getInitialExtent();
  27100. }
  27101. if (!storage[dim]) {
  27102. storage[dim] = [];
  27103. }
  27104. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  27105. this._chunkCount = storage[dim].length;
  27106. }
  27107. var emptyDataItem = new Array(dimLen);
  27108. for (var idx = start; idx < end; idx++) {
  27109. var sourceIdx = idx - start;
  27110. var chunkIndex = Math.floor(idx / chunkSize);
  27111. var chunkOffset = idx % chunkSize;
  27112. // Store the data by dimensions
  27113. for (var k = 0; k < dimLen; k++) {
  27114. var dim = dimensions[k];
  27115. var val = this._dimValueGetterArrayRows(
  27116. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  27117. );
  27118. storage[dim][chunkIndex][chunkOffset] = val;
  27119. var dimRawExtent = rawExtent[dim];
  27120. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27121. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27122. }
  27123. if (names) {
  27124. this._nameList[idx] = names[sourceIdx];
  27125. }
  27126. }
  27127. this._rawCount = this._count = end;
  27128. // Reset data extent
  27129. this._extent = {};
  27130. prepareInvertedIndex(this);
  27131. };
  27132. listProto._initDataFromProvider = function (start, end) {
  27133. // Optimize.
  27134. if (start >= end) {
  27135. return;
  27136. }
  27137. var chunkSize = this._chunkSize;
  27138. var rawData = this._rawData;
  27139. var storage = this._storage;
  27140. var dimensions = this.dimensions;
  27141. var dimLen = dimensions.length;
  27142. var dimensionInfoMap = this._dimensionInfos;
  27143. var nameList = this._nameList;
  27144. var idList = this._idList;
  27145. var rawExtent = this._rawExtent;
  27146. var nameRepeatCount = this._nameRepeatCount = {};
  27147. var nameDimIdx;
  27148. var originalChunkCount = this._chunkCount;
  27149. for (var i = 0; i < dimLen; i++) {
  27150. var dim = dimensions[i];
  27151. if (!rawExtent[dim]) {
  27152. rawExtent[dim] = getInitialExtent();
  27153. }
  27154. var dimInfo = dimensionInfoMap[dim];
  27155. if (dimInfo.otherDims.itemName === 0) {
  27156. nameDimIdx = this._nameDimIdx = i;
  27157. }
  27158. if (dimInfo.otherDims.itemId === 0) {
  27159. this._idDimIdx = i;
  27160. }
  27161. if (!storage[dim]) {
  27162. storage[dim] = [];
  27163. }
  27164. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  27165. this._chunkCount = storage[dim].length;
  27166. }
  27167. var dataItem = new Array(dimLen);
  27168. for (var idx = start; idx < end; idx++) {
  27169. // NOTICE: Try not to write things into dataItem
  27170. dataItem = rawData.getItem(idx, dataItem);
  27171. // Each data item is value
  27172. // [1, 2]
  27173. // 2
  27174. // Bar chart, line chart which uses category axis
  27175. // only gives the 'y' value. 'x' value is the indices of category
  27176. // Use a tempValue to normalize the value to be a (x, y) value
  27177. var chunkIndex = Math.floor(idx / chunkSize);
  27178. var chunkOffset = idx % chunkSize;
  27179. // Store the data by dimensions
  27180. for (var k = 0; k < dimLen; k++) {
  27181. var dim = dimensions[k];
  27182. var dimStorage = storage[dim][chunkIndex];
  27183. // PENDING NULL is empty or zero
  27184. var val = this._dimValueGetter(dataItem, dim, idx, k);
  27185. dimStorage[chunkOffset] = val;
  27186. var dimRawExtent = rawExtent[dim];
  27187. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27188. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27189. }
  27190. // ??? FIXME not check by pure but sourceFormat?
  27191. // TODO refactor these logic.
  27192. if (!rawData.pure) {
  27193. var name = nameList[idx];
  27194. if (dataItem && name == null) {
  27195. // If dataItem is {name: ...}, it has highest priority.
  27196. // That is appropriate for many common cases.
  27197. if (dataItem.name != null) {
  27198. // There is no other place to persistent dataItem.name,
  27199. // so save it to nameList.
  27200. nameList[idx] = name = dataItem.name;
  27201. }
  27202. else if (nameDimIdx != null) {
  27203. var nameDim = dimensions[nameDimIdx];
  27204. var nameDimChunk = storage[nameDim][chunkIndex];
  27205. if (nameDimChunk) {
  27206. name = nameDimChunk[chunkOffset];
  27207. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  27208. if (ordinalMeta && ordinalMeta.categories.length) {
  27209. name = ordinalMeta.categories[name];
  27210. }
  27211. }
  27212. }
  27213. }
  27214. // Try using the id in option
  27215. // id or name is used on dynamical data, mapping old and new items.
  27216. var id = dataItem == null ? null : dataItem.id;
  27217. if (id == null && name != null) {
  27218. // Use name as id and add counter to avoid same name
  27219. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  27220. id = name;
  27221. if (nameRepeatCount[name] > 0) {
  27222. id += '__ec__' + nameRepeatCount[name];
  27223. }
  27224. nameRepeatCount[name]++;
  27225. }
  27226. id != null && (idList[idx] = id);
  27227. }
  27228. }
  27229. if (!rawData.persistent && rawData.clean) {
  27230. // Clean unused data if data source is typed array.
  27231. rawData.clean();
  27232. }
  27233. this._rawCount = this._count = end;
  27234. // Reset data extent
  27235. this._extent = {};
  27236. prepareInvertedIndex(this);
  27237. };
  27238. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  27239. var DataCtor = dataCtors[dimInfo.type];
  27240. var lastChunkIndex = chunkCount - 1;
  27241. var dim = dimInfo.name;
  27242. var resizeChunkArray = storage[dim][lastChunkIndex];
  27243. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  27244. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  27245. // The cost of the copy is probably inconsiderable
  27246. // within the initial chunkSize.
  27247. for (var j = 0; j < resizeChunkArray.length; j++) {
  27248. newStore[j] = resizeChunkArray[j];
  27249. }
  27250. storage[dim][lastChunkIndex] = newStore;
  27251. }
  27252. // Create new chunks.
  27253. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  27254. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  27255. }
  27256. }
  27257. function prepareInvertedIndex(list) {
  27258. var invertedIndicesMap = list._invertedIndicesMap;
  27259. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  27260. var dimInfo = list._dimensionInfos[dim];
  27261. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  27262. var ordinalMeta = dimInfo.ordinalMeta;
  27263. if (ordinalMeta) {
  27264. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  27265. ordinalMeta.categories.length
  27266. );
  27267. // The default value of TypedArray is 0. To avoid miss
  27268. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  27269. for (var i = 0; i < invertedIndices.length; i++) {
  27270. invertedIndices[i] = INDEX_NOT_FOUND;
  27271. }
  27272. for (var i = 0; i < list._count; i++) {
  27273. // Only support the case that all values are distinct.
  27274. invertedIndices[list.get(dim, i)] = i;
  27275. }
  27276. }
  27277. });
  27278. }
  27279. function getRawValueFromStore(list, dimIndex, rawIndex) {
  27280. var val;
  27281. if (dimIndex != null) {
  27282. var chunkSize = list._chunkSize;
  27283. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27284. var chunkOffset = rawIndex % chunkSize;
  27285. var dim = list.dimensions[dimIndex];
  27286. var chunk = list._storage[dim][chunkIndex];
  27287. if (chunk) {
  27288. val = chunk[chunkOffset];
  27289. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  27290. if (ordinalMeta && ordinalMeta.categories.length) {
  27291. val = ordinalMeta.categories[val];
  27292. }
  27293. }
  27294. }
  27295. return val;
  27296. }
  27297. /**
  27298. * @return {number}
  27299. */
  27300. listProto.count = function () {
  27301. return this._count;
  27302. };
  27303. listProto.getIndices = function () {
  27304. var newIndices;
  27305. var indices = this._indices;
  27306. if (indices) {
  27307. var Ctor = indices.constructor;
  27308. var thisCount = this._count;
  27309. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  27310. if (Ctor === Array) {
  27311. newIndices = new Ctor(thisCount);
  27312. for (var i = 0; i < thisCount; i++) {
  27313. newIndices[i] = indices[i];
  27314. }
  27315. }
  27316. else {
  27317. newIndices = new Ctor(indices.buffer, 0, thisCount);
  27318. }
  27319. }
  27320. else {
  27321. var Ctor = getIndicesCtor(this);
  27322. var newIndices = new Ctor(this.count());
  27323. for (var i = 0; i < newIndices.length; i++) {
  27324. newIndices[i] = i;
  27325. }
  27326. }
  27327. return newIndices;
  27328. };
  27329. /**
  27330. * Get value. Return NaN if idx is out of range.
  27331. * @param {string} dim Dim must be concrete name.
  27332. * @param {number} idx
  27333. * @param {boolean} stack
  27334. * @return {number}
  27335. */
  27336. listProto.get = function (dim, idx /*, stack */) {
  27337. if (!(idx >= 0 && idx < this._count)) {
  27338. return NaN;
  27339. }
  27340. var storage = this._storage;
  27341. if (!storage[dim]) {
  27342. // TODO Warn ?
  27343. return NaN;
  27344. }
  27345. idx = this.getRawIndex(idx);
  27346. var chunkIndex = Math.floor(idx / this._chunkSize);
  27347. var chunkOffset = idx % this._chunkSize;
  27348. var chunkStore = storage[dim][chunkIndex];
  27349. var value = chunkStore[chunkOffset];
  27350. // FIXME ordinal data type is not stackable
  27351. // if (stack) {
  27352. // var dimensionInfo = this._dimensionInfos[dim];
  27353. // if (dimensionInfo && dimensionInfo.stackable) {
  27354. // var stackedOn = this.stackedOn;
  27355. // while (stackedOn) {
  27356. // // Get no stacked data of stacked on
  27357. // var stackedValue = stackedOn.get(dim, idx);
  27358. // // Considering positive stack, negative stack and empty data
  27359. // if ((value >= 0 && stackedValue > 0) // Positive stack
  27360. // || (value <= 0 && stackedValue < 0) // Negative stack
  27361. // ) {
  27362. // value += stackedValue;
  27363. // }
  27364. // stackedOn = stackedOn.stackedOn;
  27365. // }
  27366. // }
  27367. // }
  27368. return value;
  27369. };
  27370. /**
  27371. * @param {string} dim concrete dim
  27372. * @param {number} rawIndex
  27373. * @return {number|string}
  27374. */
  27375. listProto.getByRawIndex = function (dim, rawIdx) {
  27376. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  27377. return NaN;
  27378. }
  27379. var dimStore = this._storage[dim];
  27380. if (!dimStore) {
  27381. // TODO Warn ?
  27382. return NaN;
  27383. }
  27384. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27385. var chunkOffset = rawIdx % this._chunkSize;
  27386. var chunkStore = dimStore[chunkIndex];
  27387. return chunkStore[chunkOffset];
  27388. };
  27389. /**
  27390. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  27391. * Hack a much simpler _getFast
  27392. * @private
  27393. */
  27394. listProto._getFast = function (dim, rawIdx) {
  27395. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27396. var chunkOffset = rawIdx % this._chunkSize;
  27397. var chunkStore = this._storage[dim][chunkIndex];
  27398. return chunkStore[chunkOffset];
  27399. };
  27400. /**
  27401. * Get value for multi dimensions.
  27402. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  27403. * @param {number} idx
  27404. * @return {number}
  27405. */
  27406. listProto.getValues = function (dimensions, idx /*, stack */) {
  27407. var values = [];
  27408. if (!isArray(dimensions)) {
  27409. // stack = idx;
  27410. idx = dimensions;
  27411. dimensions = this.dimensions;
  27412. }
  27413. for (var i = 0, len = dimensions.length; i < len; i++) {
  27414. values.push(this.get(dimensions[i], idx /*, stack */));
  27415. }
  27416. return values;
  27417. };
  27418. /**
  27419. * If value is NaN. Inlcuding '-'
  27420. * Only check the coord dimensions.
  27421. * @param {string} dim
  27422. * @param {number} idx
  27423. * @return {number}
  27424. */
  27425. listProto.hasValue = function (idx) {
  27426. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  27427. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  27428. // Ordinal type originally can be string or number.
  27429. // But when an ordinal type is used on coord, it can
  27430. // not be string but only number. So we can also use isNaN.
  27431. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  27432. return false;
  27433. }
  27434. }
  27435. return true;
  27436. };
  27437. /**
  27438. * Get extent of data in one dimension
  27439. * @param {string} dim
  27440. * @param {boolean} stack
  27441. */
  27442. listProto.getDataExtent = function (dim /*, stack */) {
  27443. // Make sure use concrete dim as cache name.
  27444. dim = this.getDimension(dim);
  27445. var dimData = this._storage[dim];
  27446. var initialExtent = getInitialExtent();
  27447. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  27448. if (!dimData) {
  27449. return initialExtent;
  27450. }
  27451. // Make more strict checkings to ensure hitting cache.
  27452. var currEnd = this.count();
  27453. // var cacheName = [dim, !!stack].join('_');
  27454. // var cacheName = dim;
  27455. // Consider the most cases when using data zoom, `getDataExtent`
  27456. // happened before filtering. We cache raw extent, which is not
  27457. // necessary to be cleared and recalculated when restore data.
  27458. var useRaw = !this._indices; // && !stack;
  27459. var dimExtent;
  27460. if (useRaw) {
  27461. return this._rawExtent[dim].slice();
  27462. }
  27463. dimExtent = this._extent[dim];
  27464. if (dimExtent) {
  27465. return dimExtent.slice();
  27466. }
  27467. dimExtent = initialExtent;
  27468. var min = dimExtent[0];
  27469. var max = dimExtent[1];
  27470. for (var i = 0; i < currEnd; i++) {
  27471. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  27472. var value = this._getFast(dim, this.getRawIndex(i));
  27473. value < min && (min = value);
  27474. value > max && (max = value);
  27475. }
  27476. dimExtent = [min, max];
  27477. this._extent[dim] = dimExtent;
  27478. return dimExtent;
  27479. };
  27480. /**
  27481. * Optimize for the scenario that data is filtered by a given extent.
  27482. * Consider that if data amount is more than hundreds of thousand,
  27483. * extent calculation will cost more than 10ms and the cache will
  27484. * be erased because of the filtering.
  27485. */
  27486. listProto.getApproximateExtent = function (dim /*, stack */) {
  27487. dim = this.getDimension(dim);
  27488. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  27489. };
  27490. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  27491. dim = this.getDimension(dim);
  27492. this._approximateExtent[dim] = extent.slice();
  27493. };
  27494. /**
  27495. * @param {string} key
  27496. * @return {*}
  27497. */
  27498. listProto.getCalculationInfo = function (key) {
  27499. return this._calculationInfo[key];
  27500. };
  27501. /**
  27502. * @param {string|Object} key or k-v object
  27503. * @param {*} [value]
  27504. */
  27505. listProto.setCalculationInfo = function (key, value) {
  27506. isObject$4(key)
  27507. ? extend(this._calculationInfo, key)
  27508. : (this._calculationInfo[key] = value);
  27509. };
  27510. /**
  27511. * Get sum of data in one dimension
  27512. * @param {string} dim
  27513. */
  27514. listProto.getSum = function (dim /*, stack */) {
  27515. var dimData = this._storage[dim];
  27516. var sum = 0;
  27517. if (dimData) {
  27518. for (var i = 0, len = this.count(); i < len; i++) {
  27519. var value = this.get(dim, i /*, stack */);
  27520. if (!isNaN(value)) {
  27521. sum += value;
  27522. }
  27523. }
  27524. }
  27525. return sum;
  27526. };
  27527. /**
  27528. * Get median of data in one dimension
  27529. * @param {string} dim
  27530. */
  27531. listProto.getMedian = function (dim /*, stack */) {
  27532. var dimDataArray = [];
  27533. // map all data of one dimension
  27534. this.each(dim, function (val, idx) {
  27535. if (!isNaN(val)) {
  27536. dimDataArray.push(val);
  27537. }
  27538. });
  27539. // TODO
  27540. // Use quick select?
  27541. // immutability & sort
  27542. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  27543. return a - b;
  27544. });
  27545. var len = this.count();
  27546. // calculate median
  27547. return len === 0
  27548. ? 0
  27549. : len % 2 === 1
  27550. ? sortedDimDataArray[(len - 1) / 2]
  27551. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  27552. };
  27553. // /**
  27554. // * Retreive the index with given value
  27555. // * @param {string} dim Concrete dimension.
  27556. // * @param {number} value
  27557. // * @return {number}
  27558. // */
  27559. // Currently incorrect: should return dataIndex but not rawIndex.
  27560. // Do not fix it until this method is to be used somewhere.
  27561. // FIXME Precision of float value
  27562. // listProto.indexOf = function (dim, value) {
  27563. // var storage = this._storage;
  27564. // var dimData = storage[dim];
  27565. // var chunkSize = this._chunkSize;
  27566. // if (dimData) {
  27567. // for (var i = 0, len = this.count(); i < len; i++) {
  27568. // var chunkIndex = Math.floor(i / chunkSize);
  27569. // var chunkOffset = i % chunkSize;
  27570. // if (dimData[chunkIndex][chunkOffset] === value) {
  27571. // return i;
  27572. // }
  27573. // }
  27574. // }
  27575. // return -1;
  27576. // };
  27577. /**
  27578. * Only support the dimension which inverted index created.
  27579. * Do not support other cases until required.
  27580. * @param {string} concrete dim
  27581. * @param {number|string} value
  27582. * @return {number} rawIndex
  27583. */
  27584. listProto.rawIndexOf = function (dim, value) {
  27585. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27586. if (__DEV__) {
  27587. if (!invertedIndices) {
  27588. throw new Error('Do not supported yet');
  27589. }
  27590. }
  27591. var rawIndex = invertedIndices[value];
  27592. if (rawIndex == null || isNaN(rawIndex)) {
  27593. return INDEX_NOT_FOUND;
  27594. }
  27595. return rawIndex;
  27596. };
  27597. /**
  27598. * Retreive the index with given name
  27599. * @param {number} idx
  27600. * @param {number} name
  27601. * @return {number}
  27602. */
  27603. listProto.indexOfName = function (name) {
  27604. for (var i = 0, len = this.count(); i < len; i++) {
  27605. if (this.getName(i) === name) {
  27606. return i;
  27607. }
  27608. }
  27609. return -1;
  27610. };
  27611. /**
  27612. * Retreive the index with given raw data index
  27613. * @param {number} idx
  27614. * @param {number} name
  27615. * @return {number}
  27616. */
  27617. listProto.indexOfRawIndex = function (rawIndex) {
  27618. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27619. return -1;
  27620. }
  27621. if (!this._indices) {
  27622. return rawIndex;
  27623. }
  27624. // Indices are ascending
  27625. var indices = this._indices;
  27626. // If rawIndex === dataIndex
  27627. var rawDataIndex = indices[rawIndex];
  27628. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  27629. return rawIndex;
  27630. }
  27631. var left = 0;
  27632. var right = this._count - 1;
  27633. while (left <= right) {
  27634. var mid = (left + right) / 2 | 0;
  27635. if (indices[mid] < rawIndex) {
  27636. left = mid + 1;
  27637. }
  27638. else if (indices[mid] > rawIndex) {
  27639. right = mid - 1;
  27640. }
  27641. else {
  27642. return mid;
  27643. }
  27644. }
  27645. return -1;
  27646. };
  27647. /**
  27648. * Retreive the index of nearest value
  27649. * @param {string} dim
  27650. * @param {number} value
  27651. * @param {number} [maxDistance=Infinity]
  27652. * @return {Array.<number>} If and only if multiple indices has
  27653. * the same value, they are put to the result.
  27654. */
  27655. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  27656. var storage = this._storage;
  27657. var dimData = storage[dim];
  27658. var nearestIndices = [];
  27659. if (!dimData) {
  27660. return nearestIndices;
  27661. }
  27662. if (maxDistance == null) {
  27663. maxDistance = Infinity;
  27664. }
  27665. var minDist = Infinity;
  27666. var minDiff = -1;
  27667. var nearestIndicesLen = 0;
  27668. // Check the test case of `test/ut/spec/data/List.js`.
  27669. for (var i = 0, len = this.count(); i < len; i++) {
  27670. var diff = value - this.get(dim, i);
  27671. var dist = Math.abs(diff);
  27672. if (dist <= maxDistance) {
  27673. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27674. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27675. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27676. // So we chose the one that `diff >= 0` in this csae.
  27677. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27678. // should be push to `nearestIndices`.
  27679. if (dist < minDist
  27680. || (dist === minDist && diff >= 0 && minDiff < 0)
  27681. ) {
  27682. minDist = dist;
  27683. minDiff = diff;
  27684. nearestIndicesLen = 0;
  27685. }
  27686. if (diff === minDiff) {
  27687. nearestIndices[nearestIndicesLen++] = i;
  27688. }
  27689. }
  27690. }
  27691. nearestIndices.length = nearestIndicesLen;
  27692. return nearestIndices;
  27693. };
  27694. /**
  27695. * Get raw data index
  27696. * @param {number} idx
  27697. * @return {number}
  27698. */
  27699. listProto.getRawIndex = getRawIndexWithoutIndices;
  27700. function getRawIndexWithoutIndices(idx) {
  27701. return idx;
  27702. }
  27703. function getRawIndexWithIndices(idx) {
  27704. if (idx < this._count && idx >= 0) {
  27705. return this._indices[idx];
  27706. }
  27707. return -1;
  27708. }
  27709. /**
  27710. * Get raw data item
  27711. * @param {number} idx
  27712. * @return {number}
  27713. */
  27714. listProto.getRawDataItem = function (idx) {
  27715. if (!this._rawData.persistent) {
  27716. var val = [];
  27717. for (var i = 0; i < this.dimensions.length; i++) {
  27718. var dim = this.dimensions[i];
  27719. val.push(this.get(dim, idx));
  27720. }
  27721. return val;
  27722. }
  27723. else {
  27724. return this._rawData.getItem(this.getRawIndex(idx));
  27725. }
  27726. };
  27727. /**
  27728. * @param {number} idx
  27729. * @param {boolean} [notDefaultIdx=false]
  27730. * @return {string}
  27731. */
  27732. listProto.getName = function (idx) {
  27733. var rawIndex = this.getRawIndex(idx);
  27734. return this._nameList[rawIndex]
  27735. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  27736. || '';
  27737. };
  27738. /**
  27739. * @param {number} idx
  27740. * @param {boolean} [notDefaultIdx=false]
  27741. * @return {string}
  27742. */
  27743. listProto.getId = function (idx) {
  27744. return getId(this, this.getRawIndex(idx));
  27745. };
  27746. function getId(list, rawIndex) {
  27747. var id = list._idList[rawIndex];
  27748. if (id == null) {
  27749. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  27750. }
  27751. if (id == null) {
  27752. // FIXME Check the usage in graph, should not use prefix.
  27753. id = ID_PREFIX + rawIndex;
  27754. }
  27755. return id;
  27756. }
  27757. function normalizeDimensions(dimensions) {
  27758. if (!isArray(dimensions)) {
  27759. dimensions = [dimensions];
  27760. }
  27761. return dimensions;
  27762. }
  27763. function validateDimensions(list, dims) {
  27764. for (var i = 0; i < dims.length; i++) {
  27765. // stroage may be empty when no data, so use
  27766. // dimensionInfos to check.
  27767. if (!list._dimensionInfos[dims[i]]) {
  27768. console.error('Unkown dimension ' + dims[i]);
  27769. }
  27770. }
  27771. }
  27772. /**
  27773. * Data iteration
  27774. * @param {string|Array.<string>}
  27775. * @param {Function} cb
  27776. * @param {*} [context=this]
  27777. *
  27778. * @example
  27779. * list.each('x', function (x, idx) {});
  27780. * list.each(['x', 'y'], function (x, y, idx) {});
  27781. * list.each(function (idx) {})
  27782. */
  27783. listProto.each = function (dims, cb, context, contextCompat) {
  27784. 'use strict';
  27785. if (!this._count) {
  27786. return;
  27787. }
  27788. if (typeof dims === 'function') {
  27789. contextCompat = context;
  27790. context = cb;
  27791. cb = dims;
  27792. dims = [];
  27793. }
  27794. // contextCompat just for compat echarts3
  27795. context = context || contextCompat || this;
  27796. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27797. if (__DEV__) {
  27798. validateDimensions(this, dims);
  27799. }
  27800. var dimSize = dims.length;
  27801. for (var i = 0; i < this.count(); i++) {
  27802. // Simple optimization
  27803. switch (dimSize) {
  27804. case 0:
  27805. cb.call(context, i);
  27806. break;
  27807. case 1:
  27808. cb.call(context, this.get(dims[0], i), i);
  27809. break;
  27810. case 2:
  27811. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27812. break;
  27813. default:
  27814. var k = 0;
  27815. var value = [];
  27816. for (; k < dimSize; k++) {
  27817. value[k] = this.get(dims[k], i);
  27818. }
  27819. // Index
  27820. value[k] = i;
  27821. cb.apply(context, value);
  27822. }
  27823. }
  27824. };
  27825. /**
  27826. * Data filter
  27827. * @param {string|Array.<string>}
  27828. * @param {Function} cb
  27829. * @param {*} [context=this]
  27830. */
  27831. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27832. 'use strict';
  27833. if (!this._count) {
  27834. return;
  27835. }
  27836. if (typeof dimensions === 'function') {
  27837. contextCompat = context;
  27838. context = cb;
  27839. cb = dimensions;
  27840. dimensions = [];
  27841. }
  27842. // contextCompat just for compat echarts3
  27843. context = context || contextCompat || this;
  27844. dimensions = map(
  27845. normalizeDimensions(dimensions), this.getDimension, this
  27846. );
  27847. if (__DEV__) {
  27848. validateDimensions(this, dimensions);
  27849. }
  27850. var count = this.count();
  27851. var Ctor = getIndicesCtor(this);
  27852. var newIndices = new Ctor(count);
  27853. var value = [];
  27854. var dimSize = dimensions.length;
  27855. var offset = 0;
  27856. var dim0 = dimensions[0];
  27857. for (var i = 0; i < count; i++) {
  27858. var keep;
  27859. var rawIdx = this.getRawIndex(i);
  27860. // Simple optimization
  27861. if (dimSize === 0) {
  27862. keep = cb.call(context, i);
  27863. }
  27864. else if (dimSize === 1) {
  27865. var val = this._getFast(dim0, rawIdx);
  27866. keep = cb.call(context, val, i);
  27867. }
  27868. else {
  27869. for (var k = 0; k < dimSize; k++) {
  27870. value[k] = this._getFast(dim0, rawIdx);
  27871. }
  27872. value[k] = i;
  27873. keep = cb.apply(context, value);
  27874. }
  27875. if (keep) {
  27876. newIndices[offset++] = rawIdx;
  27877. }
  27878. }
  27879. // Set indices after filtered.
  27880. if (offset < count) {
  27881. this._indices = newIndices;
  27882. }
  27883. this._count = offset;
  27884. // Reset data extent
  27885. this._extent = {};
  27886. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27887. return this;
  27888. };
  27889. /**
  27890. * Select data in range. (For optimization of filter)
  27891. * (Manually inline code, support 5 million data filtering in data zoom.)
  27892. */
  27893. listProto.selectRange = function (range) {
  27894. 'use strict';
  27895. if (!this._count) {
  27896. return;
  27897. }
  27898. var dimensions = [];
  27899. for (var dim in range) {
  27900. if (range.hasOwnProperty(dim)) {
  27901. dimensions.push(dim);
  27902. }
  27903. }
  27904. if (__DEV__) {
  27905. validateDimensions(this, dimensions);
  27906. }
  27907. var dimSize = dimensions.length;
  27908. if (!dimSize) {
  27909. return;
  27910. }
  27911. var originalCount = this.count();
  27912. var Ctor = getIndicesCtor(this);
  27913. var newIndices = new Ctor(originalCount);
  27914. var offset = 0;
  27915. var dim0 = dimensions[0];
  27916. var min = range[dim0][0];
  27917. var max = range[dim0][1];
  27918. var quickFinished = false;
  27919. if (!this._indices) {
  27920. // Extreme optimization for common case. About 2x faster in chrome.
  27921. var idx = 0;
  27922. if (dimSize === 1) {
  27923. var dimStorage = this._storage[dimensions[0]];
  27924. for (var k = 0; k < this._chunkCount; k++) {
  27925. var chunkStorage = dimStorage[k];
  27926. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27927. for (var i = 0; i < len; i++) {
  27928. var val = chunkStorage[i];
  27929. // NaN will not be filtered. Consider the case, in line chart, empty
  27930. // value indicates the line should be broken. But for the case like
  27931. // scatter plot, a data item with empty value will not be rendered,
  27932. // but the axis extent may be effected if some other dim of the data
  27933. // item has value. Fortunately it is not a significant negative effect.
  27934. if (
  27935. (val >= min && val <= max) || isNaN(val)
  27936. ) {
  27937. newIndices[offset++] = idx;
  27938. }
  27939. idx++;
  27940. }
  27941. }
  27942. quickFinished = true;
  27943. }
  27944. else if (dimSize === 2) {
  27945. var dimStorage = this._storage[dim0];
  27946. var dimStorage2 = this._storage[dimensions[1]];
  27947. var min2 = range[dimensions[1]][0];
  27948. var max2 = range[dimensions[1]][1];
  27949. for (var k = 0; k < this._chunkCount; k++) {
  27950. var chunkStorage = dimStorage[k];
  27951. var chunkStorage2 = dimStorage2[k];
  27952. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27953. for (var i = 0; i < len; i++) {
  27954. var val = chunkStorage[i];
  27955. var val2 = chunkStorage2[i];
  27956. // Do not filter NaN, see comment above.
  27957. if ((
  27958. (val >= min && val <= max) || isNaN(val)
  27959. )
  27960. && (
  27961. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  27962. )
  27963. ) {
  27964. newIndices[offset++] = idx;
  27965. }
  27966. idx++;
  27967. }
  27968. }
  27969. quickFinished = true;
  27970. }
  27971. }
  27972. if (!quickFinished) {
  27973. if (dimSize === 1) {
  27974. for (var i = 0; i < originalCount; i++) {
  27975. var rawIndex = this.getRawIndex(i);
  27976. var val = this._getFast(dim0, rawIndex);
  27977. // Do not filter NaN, see comment above.
  27978. if (
  27979. (val >= min && val <= max) || isNaN(val)
  27980. ) {
  27981. newIndices[offset++] = rawIndex;
  27982. }
  27983. }
  27984. }
  27985. else {
  27986. for (var i = 0; i < originalCount; i++) {
  27987. var keep = true;
  27988. var rawIndex = this.getRawIndex(i);
  27989. for (var k = 0; k < dimSize; k++) {
  27990. var dimk = dimensions[k];
  27991. var val = this._getFast(dim, rawIndex);
  27992. // Do not filter NaN, see comment above.
  27993. if (val < range[dimk][0] || val > range[dimk][1]) {
  27994. keep = false;
  27995. }
  27996. }
  27997. if (keep) {
  27998. newIndices[offset++] = this.getRawIndex(i);
  27999. }
  28000. }
  28001. }
  28002. }
  28003. // Set indices after filtered.
  28004. if (offset < originalCount) {
  28005. this._indices = newIndices;
  28006. }
  28007. this._count = offset;
  28008. // Reset data extent
  28009. this._extent = {};
  28010. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28011. return this;
  28012. };
  28013. /**
  28014. * Data mapping to a plain array
  28015. * @param {string|Array.<string>} [dimensions]
  28016. * @param {Function} cb
  28017. * @param {*} [context=this]
  28018. * @return {Array}
  28019. */
  28020. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  28021. 'use strict';
  28022. if (typeof dimensions === 'function') {
  28023. contextCompat = context;
  28024. context = cb;
  28025. cb = dimensions;
  28026. dimensions = [];
  28027. }
  28028. // contextCompat just for compat echarts3
  28029. context = context || contextCompat || this;
  28030. var result = [];
  28031. this.each(dimensions, function () {
  28032. result.push(cb && cb.apply(this, arguments));
  28033. }, context);
  28034. return result;
  28035. };
  28036. // Data in excludeDimensions is copied, otherwise transfered.
  28037. function cloneListForMapAndSample(original, excludeDimensions) {
  28038. var allDimensions = original.dimensions;
  28039. var list = new List(
  28040. map(allDimensions, original.getDimensionInfo, original),
  28041. original.hostModel
  28042. );
  28043. // FIXME If needs stackedOn, value may already been stacked
  28044. transferProperties(list, original);
  28045. var storage = list._storage = {};
  28046. var originalStorage = original._storage;
  28047. // Init storage
  28048. for (var i = 0; i < allDimensions.length; i++) {
  28049. var dim = allDimensions[i];
  28050. if (originalStorage[dim]) {
  28051. // Notice that we do not reset invertedIndicesMap here, becuase
  28052. // there is no scenario of mapping or sampling ordinal dimension.
  28053. if (indexOf(excludeDimensions, dim) >= 0) {
  28054. storage[dim] = cloneDimStore(originalStorage[dim]);
  28055. list._rawExtent[dim] = getInitialExtent();
  28056. list._extent[dim] = null;
  28057. }
  28058. else {
  28059. // Direct reference for other dimensions
  28060. storage[dim] = originalStorage[dim];
  28061. }
  28062. }
  28063. }
  28064. return list;
  28065. }
  28066. function cloneDimStore(originalDimStore) {
  28067. var newDimStore = new Array(originalDimStore.length);
  28068. for (var j = 0; j < originalDimStore.length; j++) {
  28069. newDimStore[j] = cloneChunk(originalDimStore[j]);
  28070. }
  28071. return newDimStore;
  28072. }
  28073. function getInitialExtent() {
  28074. return [Infinity, -Infinity];
  28075. }
  28076. /**
  28077. * Data mapping to a new List with given dimensions
  28078. * @param {string|Array.<string>} dimensions
  28079. * @param {Function} cb
  28080. * @param {*} [context=this]
  28081. * @return {Array}
  28082. */
  28083. listProto.map = function (dimensions, cb, context, contextCompat) {
  28084. 'use strict';
  28085. // contextCompat just for compat echarts3
  28086. context = context || contextCompat || this;
  28087. dimensions = map(
  28088. normalizeDimensions(dimensions), this.getDimension, this
  28089. );
  28090. if (__DEV__) {
  28091. validateDimensions(this, dimensions);
  28092. }
  28093. var list = cloneListForMapAndSample(this, dimensions);
  28094. // Following properties are all immutable.
  28095. // So we can reference to the same value
  28096. list._indices = this._indices;
  28097. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28098. var storage = list._storage;
  28099. var tmpRetValue = [];
  28100. var chunkSize = this._chunkSize;
  28101. var dimSize = dimensions.length;
  28102. var dataCount = this.count();
  28103. var values = [];
  28104. var rawExtent = list._rawExtent;
  28105. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  28106. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  28107. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  28108. }
  28109. values[dimSize] = dataIndex;
  28110. var retValue = cb && cb.apply(context, values);
  28111. if (retValue != null) {
  28112. // a number or string (in oridinal dimension)?
  28113. if (typeof retValue !== 'object') {
  28114. tmpRetValue[0] = retValue;
  28115. retValue = tmpRetValue;
  28116. }
  28117. var rawIndex = this.getRawIndex(dataIndex);
  28118. var chunkIndex = Math.floor(rawIndex / chunkSize);
  28119. var chunkOffset = rawIndex % chunkSize;
  28120. for (var i = 0; i < retValue.length; i++) {
  28121. var dim = dimensions[i];
  28122. var val = retValue[i];
  28123. var rawExtentOnDim = rawExtent[dim];
  28124. var dimStore = storage[dim];
  28125. if (dimStore) {
  28126. dimStore[chunkIndex][chunkOffset] = val;
  28127. }
  28128. if (val < rawExtentOnDim[0]) {
  28129. rawExtentOnDim[0] = val;
  28130. }
  28131. if (val > rawExtentOnDim[1]) {
  28132. rawExtentOnDim[1] = val;
  28133. }
  28134. }
  28135. }
  28136. }
  28137. return list;
  28138. };
  28139. /**
  28140. * Large data down sampling on given dimension
  28141. * @param {string} dimension
  28142. * @param {number} rate
  28143. * @param {Function} sampleValue
  28144. * @param {Function} sampleIndex Sample index for name and id
  28145. */
  28146. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28147. var list = cloneListForMapAndSample(this, [dimension]);
  28148. var targetStorage = list._storage;
  28149. var frameValues = [];
  28150. var frameSize = Math.floor(1 / rate);
  28151. var dimStore = targetStorage[dimension];
  28152. var len = this.count();
  28153. var chunkSize = this._chunkSize;
  28154. var rawExtentOnDim = list._rawExtent[dimension];
  28155. var newIndices = new (getIndicesCtor(this))(len);
  28156. var offset = 0;
  28157. for (var i = 0; i < len; i += frameSize) {
  28158. // Last frame
  28159. if (frameSize > len - i) {
  28160. frameSize = len - i;
  28161. frameValues.length = frameSize;
  28162. }
  28163. for (var k = 0; k < frameSize; k++) {
  28164. var dataIdx = this.getRawIndex(i + k);
  28165. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  28166. var originalChunkOffset = dataIdx % chunkSize;
  28167. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  28168. }
  28169. var value = sampleValue(frameValues);
  28170. var sampleFrameIdx = this.getRawIndex(
  28171. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  28172. );
  28173. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  28174. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  28175. // Only write value on the filtered data
  28176. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  28177. if (value < rawExtentOnDim[0]) {
  28178. rawExtentOnDim[0] = value;
  28179. }
  28180. if (value > rawExtentOnDim[1]) {
  28181. rawExtentOnDim[1] = value;
  28182. }
  28183. newIndices[offset++] = sampleFrameIdx;
  28184. }
  28185. list._count = offset;
  28186. list._indices = newIndices;
  28187. list.getRawIndex = getRawIndexWithIndices;
  28188. return list;
  28189. };
  28190. /**
  28191. * Get model of one data item.
  28192. *
  28193. * @param {number} idx
  28194. */
  28195. // FIXME Model proxy ?
  28196. listProto.getItemModel = function (idx) {
  28197. var hostModel = this.hostModel;
  28198. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  28199. };
  28200. /**
  28201. * Create a data differ
  28202. * @param {module:echarts/data/List} otherList
  28203. * @return {module:echarts/data/DataDiffer}
  28204. */
  28205. listProto.diff = function (otherList) {
  28206. var thisList = this;
  28207. return new DataDiffer(
  28208. otherList ? otherList.getIndices() : [],
  28209. this.getIndices(),
  28210. function (idx) {
  28211. return getId(otherList, idx);
  28212. },
  28213. function (idx) {
  28214. return getId(thisList, idx);
  28215. }
  28216. );
  28217. };
  28218. /**
  28219. * Get visual property.
  28220. * @param {string} key
  28221. */
  28222. listProto.getVisual = function (key) {
  28223. var visual = this._visual;
  28224. return visual && visual[key];
  28225. };
  28226. /**
  28227. * Set visual property
  28228. * @param {string|Object} key
  28229. * @param {*} [value]
  28230. *
  28231. * @example
  28232. * setVisual('color', color);
  28233. * setVisual({
  28234. * 'color': color
  28235. * });
  28236. */
  28237. listProto.setVisual = function (key, val) {
  28238. if (isObject$4(key)) {
  28239. for (var name in key) {
  28240. if (key.hasOwnProperty(name)) {
  28241. this.setVisual(name, key[name]);
  28242. }
  28243. }
  28244. return;
  28245. }
  28246. this._visual = this._visual || {};
  28247. this._visual[key] = val;
  28248. };
  28249. /**
  28250. * Set layout property.
  28251. * @param {string|Object} key
  28252. * @param {*} [val]
  28253. */
  28254. listProto.setLayout = function (key, val) {
  28255. if (isObject$4(key)) {
  28256. for (var name in key) {
  28257. if (key.hasOwnProperty(name)) {
  28258. this.setLayout(name, key[name]);
  28259. }
  28260. }
  28261. return;
  28262. }
  28263. this._layout[key] = val;
  28264. };
  28265. /**
  28266. * Get layout property.
  28267. * @param {string} key.
  28268. * @return {*}
  28269. */
  28270. listProto.getLayout = function (key) {
  28271. return this._layout[key];
  28272. };
  28273. /**
  28274. * Get layout of single data item
  28275. * @param {number} idx
  28276. */
  28277. listProto.getItemLayout = function (idx) {
  28278. return this._itemLayouts[idx];
  28279. };
  28280. /**
  28281. * Set layout of single data item
  28282. * @param {number} idx
  28283. * @param {Object} layout
  28284. * @param {boolean=} [merge=false]
  28285. */
  28286. listProto.setItemLayout = function (idx, layout, merge$$1) {
  28287. this._itemLayouts[idx] = merge$$1
  28288. ? extend(this._itemLayouts[idx] || {}, layout)
  28289. : layout;
  28290. };
  28291. /**
  28292. * Clear all layout of single data item
  28293. */
  28294. listProto.clearItemLayouts = function () {
  28295. this._itemLayouts.length = 0;
  28296. };
  28297. /**
  28298. * Get visual property of single data item
  28299. * @param {number} idx
  28300. * @param {string} key
  28301. * @param {boolean} [ignoreParent=false]
  28302. */
  28303. listProto.getItemVisual = function (idx, key, ignoreParent) {
  28304. var itemVisual = this._itemVisuals[idx];
  28305. var val = itemVisual && itemVisual[key];
  28306. if (val == null && !ignoreParent) {
  28307. // Use global visual property
  28308. return this.getVisual(key);
  28309. }
  28310. return val;
  28311. };
  28312. /**
  28313. * Set visual property of single data item
  28314. *
  28315. * @param {number} idx
  28316. * @param {string|Object} key
  28317. * @param {*} [value]
  28318. *
  28319. * @example
  28320. * setItemVisual(0, 'color', color);
  28321. * setItemVisual(0, {
  28322. * 'color': color
  28323. * });
  28324. */
  28325. listProto.setItemVisual = function (idx, key, value) {
  28326. var itemVisual = this._itemVisuals[idx] || {};
  28327. var hasItemVisual = this.hasItemVisual;
  28328. this._itemVisuals[idx] = itemVisual;
  28329. if (isObject$4(key)) {
  28330. for (var name in key) {
  28331. if (key.hasOwnProperty(name)) {
  28332. itemVisual[name] = key[name];
  28333. hasItemVisual[name] = true;
  28334. }
  28335. }
  28336. return;
  28337. }
  28338. itemVisual[key] = value;
  28339. hasItemVisual[key] = true;
  28340. };
  28341. /**
  28342. * Clear itemVisuals and list visual.
  28343. */
  28344. listProto.clearAllVisual = function () {
  28345. this._visual = {};
  28346. this._itemVisuals = [];
  28347. this.hasItemVisual = {};
  28348. };
  28349. var setItemDataAndSeriesIndex = function (child) {
  28350. child.seriesIndex = this.seriesIndex;
  28351. child.dataIndex = this.dataIndex;
  28352. child.dataType = this.dataType;
  28353. };
  28354. /**
  28355. * Set graphic element relative to data. It can be set as null
  28356. * @param {number} idx
  28357. * @param {module:zrender/Element} [el]
  28358. */
  28359. listProto.setItemGraphicEl = function (idx, el) {
  28360. var hostModel = this.hostModel;
  28361. if (el) {
  28362. // Add data index and series index for indexing the data by element
  28363. // Useful in tooltip
  28364. el.dataIndex = idx;
  28365. el.dataType = this.dataType;
  28366. el.seriesIndex = hostModel && hostModel.seriesIndex;
  28367. if (el.type === 'group') {
  28368. el.traverse(setItemDataAndSeriesIndex, el);
  28369. }
  28370. }
  28371. this._graphicEls[idx] = el;
  28372. };
  28373. /**
  28374. * @param {number} idx
  28375. * @return {module:zrender/Element}
  28376. */
  28377. listProto.getItemGraphicEl = function (idx) {
  28378. return this._graphicEls[idx];
  28379. };
  28380. /**
  28381. * @param {Function} cb
  28382. * @param {*} context
  28383. */
  28384. listProto.eachItemGraphicEl = function (cb, context) {
  28385. each$1(this._graphicEls, function (el, idx) {
  28386. if (el) {
  28387. cb && cb.call(context, el, idx);
  28388. }
  28389. });
  28390. };
  28391. /**
  28392. * Shallow clone a new list except visual and layout properties, and graph elements.
  28393. * New list only change the indices.
  28394. */
  28395. listProto.cloneShallow = function (list) {
  28396. if (!list) {
  28397. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  28398. list = new List(dimensionInfoList, this.hostModel);
  28399. }
  28400. // FIXME
  28401. list._storage = this._storage;
  28402. transferProperties(list, this);
  28403. // Clone will not change the data extent and indices
  28404. if (this._indices) {
  28405. var Ctor = this._indices.constructor;
  28406. list._indices = new Ctor(this._indices);
  28407. }
  28408. else {
  28409. list._indices = null;
  28410. }
  28411. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28412. return list;
  28413. };
  28414. /**
  28415. * Wrap some method to add more feature
  28416. * @param {string} methodName
  28417. * @param {Function} injectFunction
  28418. */
  28419. listProto.wrapMethod = function (methodName, injectFunction) {
  28420. var originalMethod = this[methodName];
  28421. if (typeof originalMethod !== 'function') {
  28422. return;
  28423. }
  28424. this.__wrappedMethods = this.__wrappedMethods || [];
  28425. this.__wrappedMethods.push(methodName);
  28426. this[methodName] = function () {
  28427. var res = originalMethod.apply(this, arguments);
  28428. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28429. };
  28430. };
  28431. // Methods that create a new list based on this list should be listed here.
  28432. // Notice that those method should `RETURN` the new list.
  28433. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  28434. // Methods that change indices of this list should be listed here.
  28435. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28436. /*
  28437. * Licensed to the Apache Software Foundation (ASF) under one
  28438. * or more contributor license agreements. See the NOTICE file
  28439. * distributed with this work for additional information
  28440. * regarding copyright ownership. The ASF licenses this file
  28441. * to you under the Apache License, Version 2.0 (the
  28442. * "License"); you may not use this file except in compliance
  28443. * with the License. You may obtain a copy of the License at
  28444. *
  28445. * http://www.apache.org/licenses/LICENSE-2.0
  28446. *
  28447. * Unless required by applicable law or agreed to in writing,
  28448. * software distributed under the License is distributed on an
  28449. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28450. * KIND, either express or implied. See the License for the
  28451. * specific language governing permissions and limitations
  28452. * under the License.
  28453. */
  28454. /**
  28455. * @deprecated
  28456. * Use `echarts/data/helper/createDimensions` instead.
  28457. */
  28458. /**
  28459. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  28460. *
  28461. * This method builds the relationship between:
  28462. * + "what the coord sys or series requires (see `sysDims`)",
  28463. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  28464. * + "what the data source provids (see `source`)".
  28465. *
  28466. * Some guess strategy will be adapted if user does not define something.
  28467. * If no 'value' dimension specified, the first no-named dimension will be
  28468. * named as 'value'.
  28469. *
  28470. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  28471. * provides not only dim template, but also default order.
  28472. * properties: 'name', 'type', 'displayName'.
  28473. * `name` of each item provides default coord name.
  28474. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  28475. * provide dims count that the sysDim required.
  28476. * [{ordinalMeta}] can be specified.
  28477. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  28478. * @param {Object} [opt]
  28479. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  28480. * For example: ['asdf', {name, type}, ...].
  28481. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  28482. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  28483. * If not specified, auto find the next available data dim.
  28484. * param source {module:data/Source}
  28485. * param dimCount {number}
  28486. * return {Object} encode Never be `null/undefined`.
  28487. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  28488. * If not specified, extra dim names will be:
  28489. * 'value', 'value0', 'value1', ...
  28490. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  28491. * If `generateCoordCount` specified, the generated dim names will be:
  28492. * `generateCoord` + 0, `generateCoord` + 1, ...
  28493. * can be Infinity, indicate that use all of the remain columns.
  28494. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  28495. * @return {Array.<module:data/DataDimensionInfo>}
  28496. */
  28497. function completeDimensions(sysDims, source, opt) {
  28498. if (!Source.isInstance(source)) {
  28499. source = Source.seriesDataToSource(source);
  28500. }
  28501. opt = opt || {};
  28502. sysDims = (sysDims || []).slice();
  28503. var dimsDef = (opt.dimsDef || []).slice();
  28504. var dataDimNameMap = createHashMap();
  28505. var coordDimNameMap = createHashMap();
  28506. // var valueCandidate;
  28507. var result = [];
  28508. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  28509. // Apply user defined dims (`name` and `type`) and init result.
  28510. for (var i = 0; i < dimCount; i++) {
  28511. var dimDefItem = dimsDef[i] = extend(
  28512. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  28513. );
  28514. var userDimName = dimDefItem.name;
  28515. var resultItem = result[i] = new DataDimensionInfo();
  28516. // Name will be applied later for avoiding duplication.
  28517. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28518. // Only if `series.dimensions` is defined in option
  28519. // displayName, will be set, and dimension will be diplayed vertically in
  28520. // tooltip by default.
  28521. resultItem.name = resultItem.displayName = userDimName;
  28522. dataDimNameMap.set(userDimName, i);
  28523. }
  28524. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28525. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28526. }
  28527. var encodeDef = opt.encodeDef;
  28528. if (!encodeDef && opt.encodeDefaulter) {
  28529. encodeDef = opt.encodeDefaulter(source, dimCount);
  28530. }
  28531. encodeDef = createHashMap(encodeDef);
  28532. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  28533. encodeDef.each(function (dataDims, coordDim) {
  28534. dataDims = normalizeToArray(dataDims).slice();
  28535. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28536. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28537. // this case.
  28538. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28539. encodeDef.set(coordDim, false);
  28540. return;
  28541. }
  28542. var validDataDims = encodeDef.set(coordDim, []);
  28543. each$1(dataDims, function (resultDimIdx, idx) {
  28544. // The input resultDimIdx can be dim name or index.
  28545. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  28546. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28547. validDataDims[idx] = resultDimIdx;
  28548. applyDim(result[resultDimIdx], coordDim, idx);
  28549. }
  28550. });
  28551. });
  28552. // Apply templetes and default order from `sysDims`.
  28553. var availDimIdx = 0;
  28554. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  28555. var coordDim;
  28556. var sysDimItem;
  28557. var sysDimItemDimsDef;
  28558. var sysDimItemOtherDims;
  28559. if (isString(sysDimItem)) {
  28560. coordDim = sysDimItem;
  28561. sysDimItem = {};
  28562. }
  28563. else {
  28564. coordDim = sysDimItem.name;
  28565. var ordinalMeta = sysDimItem.ordinalMeta;
  28566. sysDimItem.ordinalMeta = null;
  28567. sysDimItem = clone(sysDimItem);
  28568. sysDimItem.ordinalMeta = ordinalMeta;
  28569. // `coordDimIndex` should not be set directly.
  28570. sysDimItemDimsDef = sysDimItem.dimsDef;
  28571. sysDimItemOtherDims = sysDimItem.otherDims;
  28572. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  28573. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28574. }
  28575. var dataDims = encodeDef.get(coordDim);
  28576. // negative resultDimIdx means no need to mapping.
  28577. if (dataDims === false) {
  28578. return;
  28579. }
  28580. var dataDims = normalizeToArray(dataDims);
  28581. // dimensions provides default dim sequences.
  28582. if (!dataDims.length) {
  28583. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28584. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  28585. availDimIdx++;
  28586. }
  28587. availDimIdx < result.length && dataDims.push(availDimIdx++);
  28588. }
  28589. }
  28590. // Apply templates.
  28591. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  28592. var resultItem = result[resultDimIdx];
  28593. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28594. if (resultItem.name == null && sysDimItemDimsDef) {
  28595. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28596. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  28597. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28598. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28599. }
  28600. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28601. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28602. });
  28603. });
  28604. function applyDim(resultItem, coordDim, coordDimIndex) {
  28605. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  28606. resultItem.otherDims[coordDim] = coordDimIndex;
  28607. }
  28608. else {
  28609. resultItem.coordDim = coordDim;
  28610. resultItem.coordDimIndex = coordDimIndex;
  28611. coordDimNameMap.set(coordDim, true);
  28612. }
  28613. }
  28614. // Make sure the first extra dim is 'value'.
  28615. var generateCoord = opt.generateCoord;
  28616. var generateCoordCount = opt.generateCoordCount;
  28617. var fromZero = generateCoordCount != null;
  28618. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  28619. var extra = generateCoord || 'value';
  28620. // Set dim `name` and other `coordDim` and other props.
  28621. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28622. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  28623. var coordDim = resultItem.coordDim;
  28624. if (coordDim == null) {
  28625. resultItem.coordDim = genName(
  28626. extra, coordDimNameMap, fromZero
  28627. );
  28628. resultItem.coordDimIndex = 0;
  28629. if (!generateCoord || generateCoordCount <= 0) {
  28630. resultItem.isExtraCoord = true;
  28631. }
  28632. generateCoordCount--;
  28633. }
  28634. resultItem.name == null && (resultItem.name = genName(
  28635. resultItem.coordDim,
  28636. dataDimNameMap
  28637. ));
  28638. if (resultItem.type == null
  28639. && (
  28640. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  28641. // Consider the case:
  28642. // {
  28643. // dataset: {source: [
  28644. // ['2001', 123],
  28645. // ['2002', 456],
  28646. // ...
  28647. // ['The others', 987],
  28648. // ]},
  28649. // series: {type: 'pie'}
  28650. // }
  28651. // The first colum should better be treated as a "ordinal" although it
  28652. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28653. || (resultItem.isExtraCoord
  28654. && (resultItem.otherDims.itemName != null
  28655. || resultItem.otherDims.seriesName != null
  28656. )
  28657. )
  28658. )
  28659. ) {
  28660. resultItem.type = 'ordinal';
  28661. }
  28662. }
  28663. return result;
  28664. }
  28665. // ??? TODO
  28666. // Originally detect dimCount by data[0]. Should we
  28667. // optimize it to only by sysDims and dimensions and encode.
  28668. // So only necessary dims will be initialized.
  28669. // But
  28670. // (1) custom series should be considered. where other dims
  28671. // may be visited.
  28672. // (2) sometimes user need to calcualte bubble size or use visualMap
  28673. // on other dimensions besides coordSys needed.
  28674. // So, dims that is not used by system, should be shared in storage?
  28675. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28676. // Note that the result dimCount should not small than columns count
  28677. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28678. var dimCount = Math.max(
  28679. source.dimensionsDetectCount || 1,
  28680. sysDims.length,
  28681. dimsDef.length,
  28682. optDimCount || 0
  28683. );
  28684. each$1(sysDims, function (sysDimItem) {
  28685. var sysDimItemDimsDef = sysDimItem.dimsDef;
  28686. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  28687. });
  28688. return dimCount;
  28689. }
  28690. function genName(name, map$$1, fromZero) {
  28691. if (fromZero || map$$1.get(name) != null) {
  28692. var i = 0;
  28693. while (map$$1.get(name + i) != null) {
  28694. i++;
  28695. }
  28696. name += i;
  28697. }
  28698. map$$1.set(name, true);
  28699. return name;
  28700. }
  28701. /*
  28702. * Licensed to the Apache Software Foundation (ASF) under one
  28703. * or more contributor license agreements. See the NOTICE file
  28704. * distributed with this work for additional information
  28705. * regarding copyright ownership. The ASF licenses this file
  28706. * to you under the Apache License, Version 2.0 (the
  28707. * "License"); you may not use this file except in compliance
  28708. * with the License. You may obtain a copy of the License at
  28709. *
  28710. * http://www.apache.org/licenses/LICENSE-2.0
  28711. *
  28712. * Unless required by applicable law or agreed to in writing,
  28713. * software distributed under the License is distributed on an
  28714. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28715. * KIND, either express or implied. See the License for the
  28716. * specific language governing permissions and limitations
  28717. * under the License.
  28718. */
  28719. /**
  28720. * Substitute `completeDimensions`.
  28721. * `completeDimensions` is to be deprecated.
  28722. */
  28723. /**
  28724. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  28725. * @param {Object|Array} [opt]
  28726. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  28727. * @param {number} [opt.dimensionsCount]
  28728. * @param {string} [opt.generateCoord]
  28729. * @param {string} [opt.generateCoordCount]
  28730. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  28731. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  28732. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  28733. * @return {Array.<Object>} dimensionsInfo
  28734. */
  28735. var createDimensions = function (source, opt) {
  28736. opt = opt || {};
  28737. return completeDimensions(opt.coordDimensions || [], source, {
  28738. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28739. encodeDef: opt.encodeDefine || source.encodeDefine,
  28740. dimCount: opt.dimensionsCount,
  28741. encodeDefaulter: opt.encodeDefaulter,
  28742. generateCoord: opt.generateCoord,
  28743. generateCoordCount: opt.generateCoordCount
  28744. });
  28745. };
  28746. /*
  28747. * Licensed to the Apache Software Foundation (ASF) under one
  28748. * or more contributor license agreements. See the NOTICE file
  28749. * distributed with this work for additional information
  28750. * regarding copyright ownership. The ASF licenses this file
  28751. * to you under the Apache License, Version 2.0 (the
  28752. * "License"); you may not use this file except in compliance
  28753. * with the License. You may obtain a copy of the License at
  28754. *
  28755. * http://www.apache.org/licenses/LICENSE-2.0
  28756. *
  28757. * Unless required by applicable law or agreed to in writing,
  28758. * software distributed under the License is distributed on an
  28759. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28760. * KIND, either express or implied. See the License for the
  28761. * specific language governing permissions and limitations
  28762. * under the License.
  28763. */
  28764. /**
  28765. * Helper for model references.
  28766. * There are many manners to refer axis/coordSys.
  28767. */
  28768. // TODO
  28769. // merge relevant logic to this file?
  28770. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28771. /**
  28772. * @class
  28773. * For example:
  28774. * {
  28775. * coordSysName: 'cartesian2d',
  28776. * coordSysDims: ['x', 'y', ...],
  28777. * axisMap: HashMap({
  28778. * x: xAxisModel,
  28779. * y: yAxisModel
  28780. * }),
  28781. * categoryAxisMap: HashMap({
  28782. * x: xAxisModel,
  28783. * y: undefined
  28784. * }),
  28785. * // The index of the first category axis in `coordSysDims`.
  28786. * // `null/undefined` means no category axis exists.
  28787. * firstCategoryDimIndex: 1,
  28788. * // To replace user specified encode.
  28789. * }
  28790. */
  28791. function CoordSysInfo(coordSysName) {
  28792. /**
  28793. * @type {string}
  28794. */
  28795. this.coordSysName = coordSysName;
  28796. /**
  28797. * @type {Array.<string>}
  28798. */
  28799. this.coordSysDims = [];
  28800. /**
  28801. * @type {module:zrender/core/util#HashMap}
  28802. */
  28803. this.axisMap = createHashMap();
  28804. /**
  28805. * @type {module:zrender/core/util#HashMap}
  28806. */
  28807. this.categoryAxisMap = createHashMap();
  28808. /**
  28809. * @type {number}
  28810. */
  28811. this.firstCategoryDimIndex = null;
  28812. }
  28813. /**
  28814. * @return {module:model/referHelper#CoordSysInfo}
  28815. */
  28816. function getCoordSysInfoBySeries(seriesModel) {
  28817. var coordSysName = seriesModel.get('coordinateSystem');
  28818. var result = new CoordSysInfo(coordSysName);
  28819. var fetch = fetchers[coordSysName];
  28820. if (fetch) {
  28821. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28822. return result;
  28823. }
  28824. }
  28825. var fetchers = {
  28826. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28827. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28828. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28829. if (__DEV__) {
  28830. if (!xAxisModel) {
  28831. throw new Error('xAxis "' + retrieve(
  28832. seriesModel.get('xAxisIndex'),
  28833. seriesModel.get('xAxisId'),
  28834. 0
  28835. ) + '" not found');
  28836. }
  28837. if (!yAxisModel) {
  28838. throw new Error('yAxis "' + retrieve(
  28839. seriesModel.get('xAxisIndex'),
  28840. seriesModel.get('yAxisId'),
  28841. 0
  28842. ) + '" not found');
  28843. }
  28844. }
  28845. result.coordSysDims = ['x', 'y'];
  28846. axisMap.set('x', xAxisModel);
  28847. axisMap.set('y', yAxisModel);
  28848. if (isCategory(xAxisModel)) {
  28849. categoryAxisMap.set('x', xAxisModel);
  28850. result.firstCategoryDimIndex = 0;
  28851. }
  28852. if (isCategory(yAxisModel)) {
  28853. categoryAxisMap.set('y', yAxisModel);
  28854. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28855. }
  28856. },
  28857. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28858. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28859. if (__DEV__) {
  28860. if (!singleAxisModel) {
  28861. throw new Error('singleAxis should be specified.');
  28862. }
  28863. }
  28864. result.coordSysDims = ['single'];
  28865. axisMap.set('single', singleAxisModel);
  28866. if (isCategory(singleAxisModel)) {
  28867. categoryAxisMap.set('single', singleAxisModel);
  28868. result.firstCategoryDimIndex = 0;
  28869. }
  28870. },
  28871. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28872. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28873. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28874. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28875. if (__DEV__) {
  28876. if (!angleAxisModel) {
  28877. throw new Error('angleAxis option not found');
  28878. }
  28879. if (!radiusAxisModel) {
  28880. throw new Error('radiusAxis option not found');
  28881. }
  28882. }
  28883. result.coordSysDims = ['radius', 'angle'];
  28884. axisMap.set('radius', radiusAxisModel);
  28885. axisMap.set('angle', angleAxisModel);
  28886. if (isCategory(radiusAxisModel)) {
  28887. categoryAxisMap.set('radius', radiusAxisModel);
  28888. result.firstCategoryDimIndex = 0;
  28889. }
  28890. if (isCategory(angleAxisModel)) {
  28891. categoryAxisMap.set('angle', angleAxisModel);
  28892. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28893. }
  28894. },
  28895. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28896. result.coordSysDims = ['lng', 'lat'];
  28897. },
  28898. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28899. var ecModel = seriesModel.ecModel;
  28900. var parallelModel = ecModel.getComponent(
  28901. 'parallel', seriesModel.get('parallelIndex')
  28902. );
  28903. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28904. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28905. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28906. var axisDim = coordSysDims[index];
  28907. axisMap.set(axisDim, axisModel);
  28908. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28909. categoryAxisMap.set(axisDim, axisModel);
  28910. result.firstCategoryDimIndex = index;
  28911. }
  28912. });
  28913. }
  28914. };
  28915. function isCategory(axisModel) {
  28916. return axisModel.get('type') === 'category';
  28917. }
  28918. /*
  28919. * Licensed to the Apache Software Foundation (ASF) under one
  28920. * or more contributor license agreements. See the NOTICE file
  28921. * distributed with this work for additional information
  28922. * regarding copyright ownership. The ASF licenses this file
  28923. * to you under the Apache License, Version 2.0 (the
  28924. * "License"); you may not use this file except in compliance
  28925. * with the License. You may obtain a copy of the License at
  28926. *
  28927. * http://www.apache.org/licenses/LICENSE-2.0
  28928. *
  28929. * Unless required by applicable law or agreed to in writing,
  28930. * software distributed under the License is distributed on an
  28931. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28932. * KIND, either express or implied. See the License for the
  28933. * specific language governing permissions and limitations
  28934. * under the License.
  28935. */
  28936. /**
  28937. * Note that it is too complicated to support 3d stack by value
  28938. * (have to create two-dimension inverted index), so in 3d case
  28939. * we just support that stacked by index.
  28940. *
  28941. * @param {module:echarts/model/Series} seriesModel
  28942. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  28943. * The input dimensionInfoList will be modified.
  28944. * @param {Object} [opt]
  28945. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  28946. * @param {boolean} [opt.byIndex=false]
  28947. * @return {Object} calculationInfo
  28948. * {
  28949. * stackedDimension: string
  28950. * stackedByDimension: string
  28951. * isStackedByIndex: boolean
  28952. * stackedOverDimension: string
  28953. * stackResultDimension: string
  28954. * }
  28955. */
  28956. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28957. opt = opt || {};
  28958. var byIndex = opt.byIndex;
  28959. var stackedCoordDimension = opt.stackedCoordDimension;
  28960. // Compatibal: when `stack` is set as '', do not stack.
  28961. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28962. var stackedByDimInfo;
  28963. var stackedDimInfo;
  28964. var stackResultDimension;
  28965. var stackedOverDimension;
  28966. each$1(dimensionInfoList, function (dimensionInfo, index) {
  28967. if (isString(dimensionInfo)) {
  28968. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  28969. }
  28970. if (mayStack && !dimensionInfo.isExtraCoord) {
  28971. // Find the first ordinal dimension as the stackedByDimInfo.
  28972. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28973. stackedByDimInfo = dimensionInfo;
  28974. }
  28975. // Find the first stackable dimension as the stackedDimInfo.
  28976. if (!stackedDimInfo
  28977. && dimensionInfo.type !== 'ordinal'
  28978. && dimensionInfo.type !== 'time'
  28979. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  28980. ) {
  28981. stackedDimInfo = dimensionInfo;
  28982. }
  28983. }
  28984. });
  28985. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28986. // Compatible with previous design, value axis (time axis) only stack by index.
  28987. // It may make sense if the user provides elaborately constructed data.
  28988. byIndex = true;
  28989. }
  28990. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28991. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28992. // might not be a good way.
  28993. if (stackedDimInfo) {
  28994. // Use a weird name that not duplicated with other names.
  28995. stackResultDimension = '__\0ecstackresult';
  28996. stackedOverDimension = '__\0ecstackedover';
  28997. // Create inverted index to fast query index by value.
  28998. if (stackedByDimInfo) {
  28999. stackedByDimInfo.createInvertedIndices = true;
  29000. }
  29001. var stackedDimCoordDim = stackedDimInfo.coordDim;
  29002. var stackedDimType = stackedDimInfo.type;
  29003. var stackedDimCoordIndex = 0;
  29004. each$1(dimensionInfoList, function (dimensionInfo) {
  29005. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  29006. stackedDimCoordIndex++;
  29007. }
  29008. });
  29009. dimensionInfoList.push({
  29010. name: stackResultDimension,
  29011. coordDim: stackedDimCoordDim,
  29012. coordDimIndex: stackedDimCoordIndex,
  29013. type: stackedDimType,
  29014. isExtraCoord: true,
  29015. isCalculationCoord: true
  29016. });
  29017. stackedDimCoordIndex++;
  29018. dimensionInfoList.push({
  29019. name: stackedOverDimension,
  29020. // This dimension contains stack base (generally, 0), so do not set it as
  29021. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29022. coordDim: stackedOverDimension,
  29023. coordDimIndex: stackedDimCoordIndex,
  29024. type: stackedDimType,
  29025. isExtraCoord: true,
  29026. isCalculationCoord: true
  29027. });
  29028. }
  29029. return {
  29030. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29031. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29032. isStackedByIndex: byIndex,
  29033. stackedOverDimension: stackedOverDimension,
  29034. stackResultDimension: stackResultDimension
  29035. };
  29036. }
  29037. /**
  29038. * @param {module:echarts/data/List} data
  29039. * @param {string} stackedDim
  29040. */
  29041. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  29042. // Each single series only maps to one pair of axis. So we do not need to
  29043. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29044. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  29045. // && (
  29046. // stackedByDim != null
  29047. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  29048. // : data.getCalculationInfo('isStackedByIndex')
  29049. // );
  29050. }
  29051. /**
  29052. * @param {module:echarts/data/List} data
  29053. * @param {string} targetDim
  29054. * @param {string} [stackedByDim] If not input this parameter, check whether
  29055. * stacked by index.
  29056. * @return {string} dimension
  29057. */
  29058. function getStackedDimension(data, targetDim) {
  29059. return isDimensionStacked(data, targetDim)
  29060. ? data.getCalculationInfo('stackResultDimension')
  29061. : targetDim;
  29062. }
  29063. /*
  29064. * Licensed to the Apache Software Foundation (ASF) under one
  29065. * or more contributor license agreements. See the NOTICE file
  29066. * distributed with this work for additional information
  29067. * regarding copyright ownership. The ASF licenses this file
  29068. * to you under the Apache License, Version 2.0 (the
  29069. * "License"); you may not use this file except in compliance
  29070. * with the License. You may obtain a copy of the License at
  29071. *
  29072. * http://www.apache.org/licenses/LICENSE-2.0
  29073. *
  29074. * Unless required by applicable law or agreed to in writing,
  29075. * software distributed under the License is distributed on an
  29076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29077. * KIND, either express or implied. See the License for the
  29078. * specific language governing permissions and limitations
  29079. * under the License.
  29080. */
  29081. /**
  29082. * @param {module:echarts/data/Source|Array} source Or raw data.
  29083. * @param {module:echarts/model/Series} seriesModel
  29084. * @param {Object} [opt]
  29085. * @param {string} [opt.generateCoord]
  29086. * @param {boolean} [opt.useEncodeDefaulter]
  29087. */
  29088. function createListFromArray(source, seriesModel, opt) {
  29089. opt = opt || {};
  29090. if (!Source.isInstance(source)) {
  29091. source = Source.seriesDataToSource(source);
  29092. }
  29093. var coordSysName = seriesModel.get('coordinateSystem');
  29094. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29095. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29096. var coordSysDimDefs;
  29097. if (coordSysInfo) {
  29098. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29099. var dimInfo = {name: dim};
  29100. var axisModel = coordSysInfo.axisMap.get(dim);
  29101. if (axisModel) {
  29102. var axisType = axisModel.get('type');
  29103. dimInfo.type = getDimensionTypeByAxis(axisType);
  29104. // dimInfo.stackable = isStackable(axisType);
  29105. }
  29106. return dimInfo;
  29107. });
  29108. }
  29109. if (!coordSysDimDefs) {
  29110. // Get dimensions from registered coordinate system
  29111. coordSysDimDefs = (registeredCoordSys && (
  29112. registeredCoordSys.getDimensionsInfo
  29113. ? registeredCoordSys.getDimensionsInfo()
  29114. : registeredCoordSys.dimensions.slice()
  29115. )) || ['x', 'y'];
  29116. }
  29117. var dimInfoList = createDimensions(source, {
  29118. coordDimensions: coordSysDimDefs,
  29119. generateCoord: opt.generateCoord,
  29120. encodeDefaulter: opt.useEncodeDefaulter
  29121. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  29122. : null
  29123. });
  29124. var firstCategoryDimIndex;
  29125. var hasNameEncode;
  29126. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  29127. var coordDim = dimInfo.coordDim;
  29128. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29129. if (categoryAxisModel) {
  29130. if (firstCategoryDimIndex == null) {
  29131. firstCategoryDimIndex = dimIndex;
  29132. }
  29133. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29134. }
  29135. if (dimInfo.otherDims.itemName != null) {
  29136. hasNameEncode = true;
  29137. }
  29138. });
  29139. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29140. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29141. }
  29142. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  29143. var list = new List(dimInfoList, seriesModel);
  29144. list.setCalculationInfo(stackCalculationInfo);
  29145. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  29146. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29147. // Use dataIndex as ordinal value in categoryAxis
  29148. return dimIndex === firstCategoryDimIndex
  29149. ? dataIndex
  29150. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29151. }
  29152. : null;
  29153. list.hasItemOption = false;
  29154. list.initData(source, null, dimValueGetter);
  29155. return list;
  29156. }
  29157. function isNeedCompleteOrdinalData(source) {
  29158. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29159. var sampleItem = firstDataNotNull(source.data || []);
  29160. return sampleItem != null
  29161. && !isArray(getDataItemValue(sampleItem));
  29162. }
  29163. }
  29164. function firstDataNotNull(data) {
  29165. var i = 0;
  29166. while (i < data.length && data[i] == null) {
  29167. i++;
  29168. }
  29169. return data[i];
  29170. }
  29171. /*
  29172. * Licensed to the Apache Software Foundation (ASF) under one
  29173. * or more contributor license agreements. See the NOTICE file
  29174. * distributed with this work for additional information
  29175. * regarding copyright ownership. The ASF licenses this file
  29176. * to you under the Apache License, Version 2.0 (the
  29177. * "License"); you may not use this file except in compliance
  29178. * with the License. You may obtain a copy of the License at
  29179. *
  29180. * http://www.apache.org/licenses/LICENSE-2.0
  29181. *
  29182. * Unless required by applicable law or agreed to in writing,
  29183. * software distributed under the License is distributed on an
  29184. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29185. * KIND, either express or implied. See the License for the
  29186. * specific language governing permissions and limitations
  29187. * under the License.
  29188. */
  29189. /**
  29190. * // Scale class management
  29191. * @module echarts/scale/Scale
  29192. */
  29193. /**
  29194. * @param {Object} [setting]
  29195. */
  29196. function Scale(setting) {
  29197. this._setting = setting || {};
  29198. /**
  29199. * Extent
  29200. * @type {Array.<number>}
  29201. * @protected
  29202. */
  29203. this._extent = [Infinity, -Infinity];
  29204. /**
  29205. * Step is calculated in adjustExtent
  29206. * @type {Array.<number>}
  29207. * @protected
  29208. */
  29209. this._interval = 0;
  29210. this.init && this.init.apply(this, arguments);
  29211. }
  29212. /**
  29213. * Parse input val to valid inner number.
  29214. * @param {*} val
  29215. * @return {number}
  29216. */
  29217. Scale.prototype.parse = function (val) {
  29218. // Notice: This would be a trap here, If the implementation
  29219. // of this method depends on extent, and this method is used
  29220. // before extent set (like in dataZoom), it would be wrong.
  29221. // Nevertheless, parse does not depend on extent generally.
  29222. return val;
  29223. };
  29224. Scale.prototype.getSetting = function (name) {
  29225. return this._setting[name];
  29226. };
  29227. Scale.prototype.contain = function (val) {
  29228. var extent = this._extent;
  29229. return val >= extent[0] && val <= extent[1];
  29230. };
  29231. /**
  29232. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  29233. * @param {number} val
  29234. * @return {number}
  29235. */
  29236. Scale.prototype.normalize = function (val) {
  29237. var extent = this._extent;
  29238. if (extent[1] === extent[0]) {
  29239. return 0.5;
  29240. }
  29241. return (val - extent[0]) / (extent[1] - extent[0]);
  29242. };
  29243. /**
  29244. * Scale normalized value
  29245. * @param {number} val
  29246. * @return {number}
  29247. */
  29248. Scale.prototype.scale = function (val) {
  29249. var extent = this._extent;
  29250. return val * (extent[1] - extent[0]) + extent[0];
  29251. };
  29252. /**
  29253. * Set extent from data
  29254. * @param {Array.<number>} other
  29255. */
  29256. Scale.prototype.unionExtent = function (other) {
  29257. var extent = this._extent;
  29258. other[0] < extent[0] && (extent[0] = other[0]);
  29259. other[1] > extent[1] && (extent[1] = other[1]);
  29260. // not setExtent because in log axis it may transformed to power
  29261. // this.setExtent(extent[0], extent[1]);
  29262. };
  29263. /**
  29264. * Set extent from data
  29265. * @param {module:echarts/data/List} data
  29266. * @param {string} dim
  29267. */
  29268. Scale.prototype.unionExtentFromData = function (data, dim) {
  29269. this.unionExtent(data.getApproximateExtent(dim));
  29270. };
  29271. /**
  29272. * Get extent
  29273. * @return {Array.<number>}
  29274. */
  29275. Scale.prototype.getExtent = function () {
  29276. return this._extent.slice();
  29277. };
  29278. /**
  29279. * Set extent
  29280. * @param {number} start
  29281. * @param {number} end
  29282. */
  29283. Scale.prototype.setExtent = function (start, end) {
  29284. var thisExtent = this._extent;
  29285. if (!isNaN(start)) {
  29286. thisExtent[0] = start;
  29287. }
  29288. if (!isNaN(end)) {
  29289. thisExtent[1] = end;
  29290. }
  29291. };
  29292. /**
  29293. * When axis extent depends on data and no data exists,
  29294. * axis ticks should not be drawn, which is named 'blank'.
  29295. */
  29296. Scale.prototype.isBlank = function () {
  29297. return this._isBlank;
  29298. },
  29299. /**
  29300. * When axis extent depends on data and no data exists,
  29301. * axis ticks should not be drawn, which is named 'blank'.
  29302. */
  29303. Scale.prototype.setBlank = function (isBlank) {
  29304. this._isBlank = isBlank;
  29305. };
  29306. /**
  29307. * @abstract
  29308. * @param {*} tick
  29309. * @return {string} label of the tick.
  29310. */
  29311. Scale.prototype.getLabel = null;
  29312. enableClassExtend(Scale);
  29313. enableClassManagement(Scale, {
  29314. registerWhenExtend: true
  29315. });
  29316. /*
  29317. * Licensed to the Apache Software Foundation (ASF) under one
  29318. * or more contributor license agreements. See the NOTICE file
  29319. * distributed with this work for additional information
  29320. * regarding copyright ownership. The ASF licenses this file
  29321. * to you under the Apache License, Version 2.0 (the
  29322. * "License"); you may not use this file except in compliance
  29323. * with the License. You may obtain a copy of the License at
  29324. *
  29325. * http://www.apache.org/licenses/LICENSE-2.0
  29326. *
  29327. * Unless required by applicable law or agreed to in writing,
  29328. * software distributed under the License is distributed on an
  29329. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29330. * KIND, either express or implied. See the License for the
  29331. * specific language governing permissions and limitations
  29332. * under the License.
  29333. */
  29334. /**
  29335. * @constructor
  29336. * @param {Object} [opt]
  29337. * @param {Object} [opt.categories=[]]
  29338. * @param {Object} [opt.needCollect=false]
  29339. * @param {Object} [opt.deduplication=false]
  29340. */
  29341. function OrdinalMeta(opt) {
  29342. /**
  29343. * @readOnly
  29344. * @type {Array.<string>}
  29345. */
  29346. this.categories = opt.categories || [];
  29347. /**
  29348. * @private
  29349. * @type {boolean}
  29350. */
  29351. this._needCollect = opt.needCollect;
  29352. /**
  29353. * @private
  29354. * @type {boolean}
  29355. */
  29356. this._deduplication = opt.deduplication;
  29357. /**
  29358. * @private
  29359. * @type {boolean}
  29360. */
  29361. this._map;
  29362. }
  29363. /**
  29364. * @param {module:echarts/model/Model} axisModel
  29365. * @return {module:echarts/data/OrdinalMeta}
  29366. */
  29367. OrdinalMeta.createByAxisModel = function (axisModel) {
  29368. var option = axisModel.option;
  29369. var data = option.data;
  29370. var categories = data && map(data, getName);
  29371. return new OrdinalMeta({
  29372. categories: categories,
  29373. needCollect: !categories,
  29374. // deduplication is default in axis.
  29375. deduplication: option.dedplication !== false
  29376. });
  29377. };
  29378. var proto$1 = OrdinalMeta.prototype;
  29379. /**
  29380. * @param {string} category
  29381. * @return {number} ordinal
  29382. */
  29383. proto$1.getOrdinal = function (category) {
  29384. return getOrCreateMap(this).get(category);
  29385. };
  29386. /**
  29387. * @param {*} category
  29388. * @return {number} The ordinal. If not found, return NaN.
  29389. */
  29390. proto$1.parseAndCollect = function (category) {
  29391. var index;
  29392. var needCollect = this._needCollect;
  29393. // The value of category dim can be the index of the given category set.
  29394. // This feature is only supported when !needCollect, because we should
  29395. // consider a common case: a value is 2017, which is a number but is
  29396. // expected to be tread as a category. This case usually happen in dataset,
  29397. // where it happent to be no need of the index feature.
  29398. if (typeof category !== 'string' && !needCollect) {
  29399. return category;
  29400. }
  29401. // Optimize for the scenario:
  29402. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29403. // data has been ensured not duplicate and is large data.
  29404. // Notice, if a dataset dimension provide categroies, usually echarts
  29405. // should remove duplication except user tell echarts dont do that
  29406. // (set axis.deduplication = false), because echarts do not know whether
  29407. // the values in the category dimension has duplication (consider the
  29408. // parallel-aqi example)
  29409. if (needCollect && !this._deduplication) {
  29410. index = this.categories.length;
  29411. this.categories[index] = category;
  29412. return index;
  29413. }
  29414. var map$$1 = getOrCreateMap(this);
  29415. index = map$$1.get(category);
  29416. if (index == null) {
  29417. if (needCollect) {
  29418. index = this.categories.length;
  29419. this.categories[index] = category;
  29420. map$$1.set(category, index);
  29421. }
  29422. else {
  29423. index = NaN;
  29424. }
  29425. }
  29426. return index;
  29427. };
  29428. // Consider big data, do not create map until needed.
  29429. function getOrCreateMap(ordinalMeta) {
  29430. return ordinalMeta._map || (
  29431. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  29432. );
  29433. }
  29434. function getName(obj) {
  29435. if (isObject$1(obj) && obj.value != null) {
  29436. return obj.value;
  29437. }
  29438. else {
  29439. return obj + '';
  29440. }
  29441. }
  29442. /*
  29443. * Licensed to the Apache Software Foundation (ASF) under one
  29444. * or more contributor license agreements. See the NOTICE file
  29445. * distributed with this work for additional information
  29446. * regarding copyright ownership. The ASF licenses this file
  29447. * to you under the Apache License, Version 2.0 (the
  29448. * "License"); you may not use this file except in compliance
  29449. * with the License. You may obtain a copy of the License at
  29450. *
  29451. * http://www.apache.org/licenses/LICENSE-2.0
  29452. *
  29453. * Unless required by applicable law or agreed to in writing,
  29454. * software distributed under the License is distributed on an
  29455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29456. * KIND, either express or implied. See the License for the
  29457. * specific language governing permissions and limitations
  29458. * under the License.
  29459. */
  29460. /**
  29461. * Linear continuous scale
  29462. * @module echarts/coord/scale/Ordinal
  29463. *
  29464. * http://en.wikipedia.org/wiki/Level_of_measurement
  29465. */
  29466. // FIXME only one data
  29467. var scaleProto = Scale.prototype;
  29468. var OrdinalScale = Scale.extend({
  29469. type: 'ordinal',
  29470. /**
  29471. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  29472. */
  29473. init: function (ordinalMeta, extent) {
  29474. // Caution: Should not use instanceof, consider ec-extensions using
  29475. // import approach to get OrdinalMeta class.
  29476. if (!ordinalMeta || isArray(ordinalMeta)) {
  29477. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  29478. }
  29479. this._ordinalMeta = ordinalMeta;
  29480. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  29481. },
  29482. parse: function (val) {
  29483. return typeof val === 'string'
  29484. ? this._ordinalMeta.getOrdinal(val)
  29485. // val might be float.
  29486. : Math.round(val);
  29487. },
  29488. contain: function (rank) {
  29489. rank = this.parse(rank);
  29490. return scaleProto.contain.call(this, rank)
  29491. && this._ordinalMeta.categories[rank] != null;
  29492. },
  29493. /**
  29494. * Normalize given rank or name to linear [0, 1]
  29495. * @param {number|string} [val]
  29496. * @return {number}
  29497. */
  29498. normalize: function (val) {
  29499. return scaleProto.normalize.call(this, this.parse(val));
  29500. },
  29501. scale: function (val) {
  29502. return Math.round(scaleProto.scale.call(this, val));
  29503. },
  29504. /**
  29505. * @return {Array}
  29506. */
  29507. getTicks: function () {
  29508. var ticks = [];
  29509. var extent = this._extent;
  29510. var rank = extent[0];
  29511. while (rank <= extent[1]) {
  29512. ticks.push(rank);
  29513. rank++;
  29514. }
  29515. return ticks;
  29516. },
  29517. /**
  29518. * Get item on rank n
  29519. * @param {number} n
  29520. * @return {string}
  29521. */
  29522. getLabel: function (n) {
  29523. if (!this.isBlank()) {
  29524. // Note that if no data, ordinalMeta.categories is an empty array.
  29525. return this._ordinalMeta.categories[n];
  29526. }
  29527. },
  29528. /**
  29529. * @return {number}
  29530. */
  29531. count: function () {
  29532. return this._extent[1] - this._extent[0] + 1;
  29533. },
  29534. /**
  29535. * @override
  29536. */
  29537. unionExtentFromData: function (data, dim) {
  29538. this.unionExtent(data.getApproximateExtent(dim));
  29539. },
  29540. getOrdinalMeta: function () {
  29541. return this._ordinalMeta;
  29542. },
  29543. niceTicks: noop,
  29544. niceExtent: noop
  29545. });
  29546. /**
  29547. * @return {module:echarts/scale/Time}
  29548. */
  29549. OrdinalScale.create = function () {
  29550. return new OrdinalScale();
  29551. };
  29552. /*
  29553. * Licensed to the Apache Software Foundation (ASF) under one
  29554. * or more contributor license agreements. See the NOTICE file
  29555. * distributed with this work for additional information
  29556. * regarding copyright ownership. The ASF licenses this file
  29557. * to you under the Apache License, Version 2.0 (the
  29558. * "License"); you may not use this file except in compliance
  29559. * with the License. You may obtain a copy of the License at
  29560. *
  29561. * http://www.apache.org/licenses/LICENSE-2.0
  29562. *
  29563. * Unless required by applicable law or agreed to in writing,
  29564. * software distributed under the License is distributed on an
  29565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29566. * KIND, either express or implied. See the License for the
  29567. * specific language governing permissions and limitations
  29568. * under the License.
  29569. */
  29570. /**
  29571. * For testable.
  29572. */
  29573. var roundNumber$1 = round$1;
  29574. /**
  29575. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  29576. * Should be extent[0] < extent[1].
  29577. * @param {number} splitNumber splitNumber should be >= 1.
  29578. * @param {number} [minInterval]
  29579. * @param {number} [maxInterval]
  29580. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  29581. */
  29582. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29583. var result = {};
  29584. var span = extent[1] - extent[0];
  29585. var interval = result.interval = nice(span / splitNumber, true);
  29586. if (minInterval != null && interval < minInterval) {
  29587. interval = result.interval = minInterval;
  29588. }
  29589. if (maxInterval != null && interval > maxInterval) {
  29590. interval = result.interval = maxInterval;
  29591. }
  29592. // Tow more digital for tick.
  29593. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  29594. // Niced extent inside original extent
  29595. var niceTickExtent = result.niceTickExtent = [
  29596. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  29597. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  29598. ];
  29599. fixExtent(niceTickExtent, extent);
  29600. return result;
  29601. }
  29602. /**
  29603. * @param {number} interval
  29604. * @return {number} interval precision
  29605. */
  29606. function getIntervalPrecision(interval) {
  29607. // Tow more digital for tick.
  29608. return getPrecisionSafe(interval) + 2;
  29609. }
  29610. function clamp(niceTickExtent, idx, extent) {
  29611. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29612. }
  29613. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29614. function fixExtent(niceTickExtent, extent) {
  29615. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29616. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29617. clamp(niceTickExtent, 0, extent);
  29618. clamp(niceTickExtent, 1, extent);
  29619. if (niceTickExtent[0] > niceTickExtent[1]) {
  29620. niceTickExtent[0] = niceTickExtent[1];
  29621. }
  29622. }
  29623. /*
  29624. * Licensed to the Apache Software Foundation (ASF) under one
  29625. * or more contributor license agreements. See the NOTICE file
  29626. * distributed with this work for additional information
  29627. * regarding copyright ownership. The ASF licenses this file
  29628. * to you under the Apache License, Version 2.0 (the
  29629. * "License"); you may not use this file except in compliance
  29630. * with the License. You may obtain a copy of the License at
  29631. *
  29632. * http://www.apache.org/licenses/LICENSE-2.0
  29633. *
  29634. * Unless required by applicable law or agreed to in writing,
  29635. * software distributed under the License is distributed on an
  29636. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29637. * KIND, either express or implied. See the License for the
  29638. * specific language governing permissions and limitations
  29639. * under the License.
  29640. */
  29641. /**
  29642. * Interval scale
  29643. * @module echarts/scale/Interval
  29644. */
  29645. var roundNumber = round$1;
  29646. /**
  29647. * @alias module:echarts/coord/scale/Interval
  29648. * @constructor
  29649. */
  29650. var IntervalScale = Scale.extend({
  29651. type: 'interval',
  29652. _interval: 0,
  29653. _intervalPrecision: 2,
  29654. setExtent: function (start, end) {
  29655. var thisExtent = this._extent;
  29656. //start,end may be a Number like '25',so...
  29657. if (!isNaN(start)) {
  29658. thisExtent[0] = parseFloat(start);
  29659. }
  29660. if (!isNaN(end)) {
  29661. thisExtent[1] = parseFloat(end);
  29662. }
  29663. },
  29664. unionExtent: function (other) {
  29665. var extent = this._extent;
  29666. other[0] < extent[0] && (extent[0] = other[0]);
  29667. other[1] > extent[1] && (extent[1] = other[1]);
  29668. // unionExtent may called by it's sub classes
  29669. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  29670. },
  29671. /**
  29672. * Get interval
  29673. */
  29674. getInterval: function () {
  29675. return this._interval;
  29676. },
  29677. /**
  29678. * Set interval
  29679. */
  29680. setInterval: function (interval) {
  29681. this._interval = interval;
  29682. // Dropped auto calculated niceExtent and use user setted extent
  29683. // We assume user wan't to set both interval, min, max to get a better result
  29684. this._niceExtent = this._extent.slice();
  29685. this._intervalPrecision = getIntervalPrecision(interval);
  29686. },
  29687. /**
  29688. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  29689. * @return {Array.<number>}
  29690. */
  29691. getTicks: function (expandToNicedExtent) {
  29692. var interval = this._interval;
  29693. var extent = this._extent;
  29694. var niceTickExtent = this._niceExtent;
  29695. var intervalPrecision = this._intervalPrecision;
  29696. var ticks = [];
  29697. // If interval is 0, return [];
  29698. if (!interval) {
  29699. return ticks;
  29700. }
  29701. // Consider this case: using dataZoom toolbox, zoom and zoom.
  29702. var safeLimit = 10000;
  29703. if (extent[0] < niceTickExtent[0]) {
  29704. if (expandToNicedExtent) {
  29705. ticks.push(roundNumber(niceTickExtent[0] - interval, intervalPrecision));
  29706. }
  29707. else {
  29708. ticks.push(extent[0]);
  29709. }
  29710. }
  29711. var tick = niceTickExtent[0];
  29712. while (tick <= niceTickExtent[1]) {
  29713. ticks.push(tick);
  29714. // Avoid rounding error
  29715. tick = roundNumber(tick + interval, intervalPrecision);
  29716. if (tick === ticks[ticks.length - 1]) {
  29717. // Consider out of safe float point, e.g.,
  29718. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29719. break;
  29720. }
  29721. if (ticks.length > safeLimit) {
  29722. return [];
  29723. }
  29724. }
  29725. // Consider this case: the last item of ticks is smaller
  29726. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29727. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  29728. if (extent[1] > lastNiceTick) {
  29729. if (expandToNicedExtent) {
  29730. ticks.push(roundNumber(lastNiceTick + interval, intervalPrecision));
  29731. }
  29732. else {
  29733. ticks.push(extent[1]);
  29734. }
  29735. }
  29736. return ticks;
  29737. },
  29738. /**
  29739. * @param {number} [splitNumber=5]
  29740. * @return {Array.<Array.<number>>}
  29741. */
  29742. getMinorTicks: function (splitNumber) {
  29743. var ticks = this.getTicks(true);
  29744. var minorTicks = [];
  29745. var extent = this.getExtent();
  29746. for (var i = 1; i < ticks.length; i++) {
  29747. var nextTick = ticks[i];
  29748. var prevTick = ticks[i - 1];
  29749. var count = 0;
  29750. var minorTicksGroup = [];
  29751. var interval = nextTick - prevTick;
  29752. var minorInterval = interval / splitNumber;
  29753. while (count < splitNumber - 1) {
  29754. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  29755. // For the first and last interval. The count may be less than splitNumber.
  29756. if (minorTick > extent[0] && minorTick < extent[1]) {
  29757. minorTicksGroup.push(minorTick);
  29758. }
  29759. count++;
  29760. }
  29761. minorTicks.push(minorTicksGroup);
  29762. }
  29763. return minorTicks;
  29764. },
  29765. /**
  29766. * @param {number} data
  29767. * @param {Object} [opt]
  29768. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  29769. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  29770. * @return {string}
  29771. */
  29772. getLabel: function (data, opt) {
  29773. if (data == null) {
  29774. return '';
  29775. }
  29776. var precision = opt && opt.precision;
  29777. if (precision == null) {
  29778. precision = getPrecisionSafe(data) || 0;
  29779. }
  29780. else if (precision === 'auto') {
  29781. // Should be more precise then tick.
  29782. precision = this._intervalPrecision;
  29783. }
  29784. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29785. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29786. data = roundNumber(data, precision, true);
  29787. return addCommas(data);
  29788. },
  29789. /**
  29790. * Update interval and extent of intervals for nice ticks
  29791. *
  29792. * @param {number} [splitNumber = 5] Desired number of ticks
  29793. * @param {number} [minInterval]
  29794. * @param {number} [maxInterval]
  29795. */
  29796. niceTicks: function (splitNumber, minInterval, maxInterval) {
  29797. splitNumber = splitNumber || 5;
  29798. var extent = this._extent;
  29799. var span = extent[1] - extent[0];
  29800. if (!isFinite(span)) {
  29801. return;
  29802. }
  29803. // User may set axis min 0 and data are all negative
  29804. // FIXME If it needs to reverse ?
  29805. if (span < 0) {
  29806. span = -span;
  29807. extent.reverse();
  29808. }
  29809. var result = intervalScaleNiceTicks(
  29810. extent, splitNumber, minInterval, maxInterval
  29811. );
  29812. this._intervalPrecision = result.intervalPrecision;
  29813. this._interval = result.interval;
  29814. this._niceExtent = result.niceTickExtent;
  29815. },
  29816. /**
  29817. * Nice extent.
  29818. * @param {Object} opt
  29819. * @param {number} [opt.splitNumber = 5] Given approx tick number
  29820. * @param {boolean} [opt.fixMin=false]
  29821. * @param {boolean} [opt.fixMax=false]
  29822. * @param {boolean} [opt.minInterval]
  29823. * @param {boolean} [opt.maxInterval]
  29824. */
  29825. niceExtent: function (opt) {
  29826. var extent = this._extent;
  29827. // If extent start and end are same, expand them
  29828. if (extent[0] === extent[1]) {
  29829. if (extent[0] !== 0) {
  29830. // Expand extent
  29831. var expandSize = extent[0];
  29832. // In the fowllowing case
  29833. // Axis has been fixed max 100
  29834. // Plus data are all 100 and axis extent are [100, 100].
  29835. // Extend to the both side will cause expanded max is larger than fixed max.
  29836. // So only expand to the smaller side.
  29837. if (!opt.fixMax) {
  29838. extent[1] += expandSize / 2;
  29839. extent[0] -= expandSize / 2;
  29840. }
  29841. else {
  29842. extent[0] -= expandSize / 2;
  29843. }
  29844. }
  29845. else {
  29846. extent[1] = 1;
  29847. }
  29848. }
  29849. var span = extent[1] - extent[0];
  29850. // If there are no data and extent are [Infinity, -Infinity]
  29851. if (!isFinite(span)) {
  29852. extent[0] = 0;
  29853. extent[1] = 1;
  29854. }
  29855. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29856. // var extent = this._extent;
  29857. var interval = this._interval;
  29858. if (!opt.fixMin) {
  29859. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29860. }
  29861. if (!opt.fixMax) {
  29862. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29863. }
  29864. }
  29865. });
  29866. /**
  29867. * @return {module:echarts/scale/Time}
  29868. */
  29869. IntervalScale.create = function () {
  29870. return new IntervalScale();
  29871. };
  29872. /*
  29873. * Licensed to the Apache Software Foundation (ASF) under one
  29874. * or more contributor license agreements. See the NOTICE file
  29875. * distributed with this work for additional information
  29876. * regarding copyright ownership. The ASF licenses this file
  29877. * to you under the Apache License, Version 2.0 (the
  29878. * "License"); you may not use this file except in compliance
  29879. * with the License. You may obtain a copy of the License at
  29880. *
  29881. * http://www.apache.org/licenses/LICENSE-2.0
  29882. *
  29883. * Unless required by applicable law or agreed to in writing,
  29884. * software distributed under the License is distributed on an
  29885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29886. * KIND, either express or implied. See the License for the
  29887. * specific language governing permissions and limitations
  29888. * under the License.
  29889. */
  29890. /* global Float32Array */
  29891. var STACK_PREFIX = '__ec_stack_';
  29892. var LARGE_BAR_MIN_WIDTH = 0.5;
  29893. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  29894. function getSeriesStackId(seriesModel) {
  29895. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29896. }
  29897. function getAxisKey(axis) {
  29898. return axis.dim + axis.index;
  29899. }
  29900. /**
  29901. * @param {Object} opt
  29902. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  29903. * @param {number} opt.count Positive interger.
  29904. * @param {number} [opt.barWidth]
  29905. * @param {number} [opt.barMaxWidth]
  29906. * @param {number} [opt.barMinWidth]
  29907. * @param {number} [opt.barGap]
  29908. * @param {number} [opt.barCategoryGap]
  29909. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  29910. */
  29911. function prepareLayoutBarSeries(seriesType, ecModel) {
  29912. var seriesModels = [];
  29913. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29914. // Check series coordinate, do layout for cartesian2d only
  29915. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  29916. seriesModels.push(seriesModel);
  29917. }
  29918. });
  29919. return seriesModels;
  29920. }
  29921. /**
  29922. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29923. * values.
  29924. * This works for time axes, value axes, and log axes.
  29925. * For a single time axis, return value is in the form like
  29926. * {'x_0': [1000000]}.
  29927. * The value of 1000000 is in milliseconds.
  29928. */
  29929. function getValueAxesMinGaps(barSeries) {
  29930. /**
  29931. * Map from axis.index to values.
  29932. * For a single time axis, axisValues is in the form like
  29933. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29934. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29935. * series.
  29936. */
  29937. var axisValues = {};
  29938. each$1(barSeries, function (seriesModel) {
  29939. var cartesian = seriesModel.coordinateSystem;
  29940. var baseAxis = cartesian.getBaseAxis();
  29941. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29942. return;
  29943. }
  29944. var data = seriesModel.getData();
  29945. var key = baseAxis.dim + '_' + baseAxis.index;
  29946. var dim = data.mapDimension(baseAxis.dim);
  29947. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  29948. var value = data.get(dim, i);
  29949. if (!axisValues[key]) {
  29950. // No previous data for the axis
  29951. axisValues[key] = [value];
  29952. }
  29953. else {
  29954. // No value in previous series
  29955. axisValues[key].push(value);
  29956. }
  29957. // Ignore duplicated time values in the same axis
  29958. }
  29959. });
  29960. var axisMinGaps = [];
  29961. for (var key in axisValues) {
  29962. if (axisValues.hasOwnProperty(key)) {
  29963. var valuesInAxis = axisValues[key];
  29964. if (valuesInAxis) {
  29965. // Sort axis values into ascending order to calculate gaps
  29966. valuesInAxis.sort(function (a, b) {
  29967. return a - b;
  29968. });
  29969. var min = null;
  29970. for (var j = 1; j < valuesInAxis.length; ++j) {
  29971. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29972. if (delta > 0) {
  29973. // Ignore 0 delta because they are of the same axis value
  29974. min = min === null ? delta : Math.min(min, delta);
  29975. }
  29976. }
  29977. // Set to null if only have one data
  29978. axisMinGaps[key] = min;
  29979. }
  29980. }
  29981. }
  29982. return axisMinGaps;
  29983. }
  29984. function makeColumnLayout(barSeries) {
  29985. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29986. var seriesInfoList = [];
  29987. each$1(barSeries, function (seriesModel) {
  29988. var cartesian = seriesModel.coordinateSystem;
  29989. var baseAxis = cartesian.getBaseAxis();
  29990. var axisExtent = baseAxis.getExtent();
  29991. var bandWidth;
  29992. if (baseAxis.type === 'category') {
  29993. bandWidth = baseAxis.getBandWidth();
  29994. }
  29995. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29996. var key = baseAxis.dim + '_' + baseAxis.index;
  29997. var minGap = axisMinGaps[key];
  29998. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29999. var scale = baseAxis.scale.getExtent();
  30000. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30001. bandWidth = minGap
  30002. ? extentSpan / scaleSpan * minGap
  30003. : extentSpan; // When there is only one data value
  30004. }
  30005. else {
  30006. var data = seriesModel.getData();
  30007. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30008. }
  30009. var barWidth = parsePercent$1(
  30010. seriesModel.get('barWidth'), bandWidth
  30011. );
  30012. var barMaxWidth = parsePercent$1(
  30013. seriesModel.get('barMaxWidth'), bandWidth
  30014. );
  30015. var barMinWidth = parsePercent$1(
  30016. // barMinWidth by default is 1 in cartesian. Because in value axis,
  30017. // the auto-calculated bar width might be less than 1.
  30018. seriesModel.get('barMinWidth') || 1, bandWidth
  30019. );
  30020. var barGap = seriesModel.get('barGap');
  30021. var barCategoryGap = seriesModel.get('barCategoryGap');
  30022. seriesInfoList.push({
  30023. bandWidth: bandWidth,
  30024. barWidth: barWidth,
  30025. barMaxWidth: barMaxWidth,
  30026. barMinWidth: barMinWidth,
  30027. barGap: barGap,
  30028. barCategoryGap: barCategoryGap,
  30029. axisKey: getAxisKey(baseAxis),
  30030. stackId: getSeriesStackId(seriesModel)
  30031. });
  30032. });
  30033. return doCalBarWidthAndOffset(seriesInfoList);
  30034. }
  30035. function doCalBarWidthAndOffset(seriesInfoList) {
  30036. // Columns info on each category axis. Key is cartesian name
  30037. var columnsMap = {};
  30038. each$1(seriesInfoList, function (seriesInfo, idx) {
  30039. var axisKey = seriesInfo.axisKey;
  30040. var bandWidth = seriesInfo.bandWidth;
  30041. var columnsOnAxis = columnsMap[axisKey] || {
  30042. bandWidth: bandWidth,
  30043. remainedWidth: bandWidth,
  30044. autoWidthCount: 0,
  30045. categoryGap: '20%',
  30046. gap: '30%',
  30047. stacks: {}
  30048. };
  30049. var stacks = columnsOnAxis.stacks;
  30050. columnsMap[axisKey] = columnsOnAxis;
  30051. var stackId = seriesInfo.stackId;
  30052. if (!stacks[stackId]) {
  30053. columnsOnAxis.autoWidthCount++;
  30054. }
  30055. stacks[stackId] = stacks[stackId] || {
  30056. width: 0,
  30057. maxWidth: 0
  30058. };
  30059. // Caution: In a single coordinate system, these barGrid attributes
  30060. // will be shared by series. Consider that they have default values,
  30061. // only the attributes set on the last series will work.
  30062. // Do not change this fact unless there will be a break change.
  30063. var barWidth = seriesInfo.barWidth;
  30064. if (barWidth && !stacks[stackId].width) {
  30065. // See #6312, do not restrict width.
  30066. stacks[stackId].width = barWidth;
  30067. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30068. columnsOnAxis.remainedWidth -= barWidth;
  30069. }
  30070. var barMaxWidth = seriesInfo.barMaxWidth;
  30071. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30072. var barMinWidth = seriesInfo.barMinWidth;
  30073. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30074. var barGap = seriesInfo.barGap;
  30075. (barGap != null) && (columnsOnAxis.gap = barGap);
  30076. var barCategoryGap = seriesInfo.barCategoryGap;
  30077. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  30078. });
  30079. var result = {};
  30080. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  30081. result[coordSysName] = {};
  30082. var stacks = columnsOnAxis.stacks;
  30083. var bandWidth = columnsOnAxis.bandWidth;
  30084. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  30085. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30086. var remainedWidth = columnsOnAxis.remainedWidth;
  30087. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30088. var autoWidth = (remainedWidth - categoryGap)
  30089. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30090. autoWidth = Math.max(autoWidth, 0);
  30091. // Find if any auto calculated bar exceeded maxBarWidth
  30092. each$1(stacks, function (column) {
  30093. var maxWidth = column.maxWidth;
  30094. var minWidth = column.minWidth;
  30095. if (!column.width) {
  30096. var finalWidth = autoWidth;
  30097. if (maxWidth && maxWidth < finalWidth) {
  30098. finalWidth = Math.min(maxWidth, remainedWidth);
  30099. }
  30100. // `minWidth` has higher priority. `minWidth` decide that wheter the
  30101. // bar is able to be visible. So `minWidth` should not be restricted
  30102. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30103. // the extreme cases for `value` axis, bars are allowed to overlap
  30104. // with each other if `minWidth` specified.
  30105. if (minWidth && minWidth > finalWidth) {
  30106. finalWidth = minWidth;
  30107. }
  30108. if (finalWidth !== autoWidth) {
  30109. column.width = finalWidth;
  30110. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30111. autoWidthCount--;
  30112. }
  30113. }
  30114. else {
  30115. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30116. // CSS does. Becuase barWidth can be a percent value, where
  30117. // `barMaxWidth` can be used to restrict the final width.
  30118. var finalWidth = column.width;
  30119. if (maxWidth) {
  30120. finalWidth = Math.min(finalWidth, maxWidth);
  30121. }
  30122. // `minWidth` has higher priority, as described above
  30123. if (minWidth) {
  30124. finalWidth = Math.max(finalWidth, minWidth);
  30125. }
  30126. column.width = finalWidth;
  30127. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30128. autoWidthCount--;
  30129. }
  30130. });
  30131. // Recalculate width again
  30132. autoWidth = (remainedWidth - categoryGap)
  30133. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30134. autoWidth = Math.max(autoWidth, 0);
  30135. var widthSum = 0;
  30136. var lastColumn;
  30137. each$1(stacks, function (column, idx) {
  30138. if (!column.width) {
  30139. column.width = autoWidth;
  30140. }
  30141. lastColumn = column;
  30142. widthSum += column.width * (1 + barGapPercent);
  30143. });
  30144. if (lastColumn) {
  30145. widthSum -= lastColumn.width * barGapPercent;
  30146. }
  30147. var offset = -widthSum / 2;
  30148. each$1(stacks, function (column, stackId) {
  30149. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30150. bandWidth: bandWidth,
  30151. offset: offset,
  30152. width: column.width
  30153. };
  30154. offset += column.width * (1 + barGapPercent);
  30155. });
  30156. });
  30157. return result;
  30158. }
  30159. /**
  30160. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  30161. * @param {module:echarts/coord/Axis} axis
  30162. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  30163. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  30164. */
  30165. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30166. if (barWidthAndOffset && axis) {
  30167. var result = barWidthAndOffset[getAxisKey(axis)];
  30168. if (result != null && seriesModel != null) {
  30169. result = result[getSeriesStackId(seriesModel)];
  30170. }
  30171. return result;
  30172. }
  30173. }
  30174. /**
  30175. * @param {string} seriesType
  30176. * @param {module:echarts/model/Global} ecModel
  30177. */
  30178. function layout(seriesType, ecModel) {
  30179. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30180. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30181. var lastStackCoords = {};
  30182. each$1(seriesModels, function (seriesModel) {
  30183. var data = seriesModel.getData();
  30184. var cartesian = seriesModel.coordinateSystem;
  30185. var baseAxis = cartesian.getBaseAxis();
  30186. var stackId = getSeriesStackId(seriesModel);
  30187. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30188. var columnOffset = columnLayoutInfo.offset;
  30189. var columnWidth = columnLayoutInfo.width;
  30190. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30191. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30192. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  30193. data.setLayout({
  30194. bandWidth: columnLayoutInfo.bandWidth,
  30195. offset: columnOffset,
  30196. size: columnWidth
  30197. });
  30198. var valueDim = data.mapDimension(valueAxis.dim);
  30199. var baseDim = data.mapDimension(baseAxis.dim);
  30200. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  30201. var isValueAxisH = valueAxis.isHorizontal();
  30202. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  30203. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30204. var value = data.get(valueDim, idx);
  30205. var baseValue = data.get(baseDim, idx);
  30206. var sign = value >= 0 ? 'p' : 'n';
  30207. var baseCoord = valueAxisStart;
  30208. // Because of the barMinHeight, we can not use the value in
  30209. // stackResultDimension directly.
  30210. if (stacked) {
  30211. // Only ordinal axis can be stacked.
  30212. if (!lastStackCoords[stackId][baseValue]) {
  30213. lastStackCoords[stackId][baseValue] = {
  30214. p: valueAxisStart, // Positive stack
  30215. n: valueAxisStart // Negative stack
  30216. };
  30217. }
  30218. // Should also consider #4243
  30219. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30220. }
  30221. var x;
  30222. var y;
  30223. var width;
  30224. var height;
  30225. if (isValueAxisH) {
  30226. var coord = cartesian.dataToPoint([value, baseValue]);
  30227. x = baseCoord;
  30228. y = coord[1] + columnOffset;
  30229. width = coord[0] - valueAxisStart;
  30230. height = columnWidth;
  30231. if (Math.abs(width) < barMinHeight) {
  30232. width = (width < 0 ? -1 : 1) * barMinHeight;
  30233. }
  30234. // Ignore stack from NaN value
  30235. if (!isNaN(width)) {
  30236. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30237. }
  30238. }
  30239. else {
  30240. var coord = cartesian.dataToPoint([baseValue, value]);
  30241. x = coord[0] + columnOffset;
  30242. y = baseCoord;
  30243. width = columnWidth;
  30244. height = coord[1] - valueAxisStart;
  30245. if (Math.abs(height) < barMinHeight) {
  30246. // Include zero to has a positive bar
  30247. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30248. }
  30249. // Ignore stack from NaN value
  30250. if (!isNaN(height)) {
  30251. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30252. }
  30253. }
  30254. data.setItemLayout(idx, {
  30255. x: x,
  30256. y: y,
  30257. width: width,
  30258. height: height
  30259. });
  30260. }
  30261. }, this);
  30262. }
  30263. // TODO: Do not support stack in large mode yet.
  30264. var largeLayout = {
  30265. seriesType: 'bar',
  30266. plan: createRenderPlanner(),
  30267. reset: function (seriesModel) {
  30268. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30269. return;
  30270. }
  30271. var data = seriesModel.getData();
  30272. var cartesian = seriesModel.coordinateSystem;
  30273. var coordLayout = cartesian.grid.getRect();
  30274. var baseAxis = cartesian.getBaseAxis();
  30275. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30276. var valueDim = data.mapDimension(valueAxis.dim);
  30277. var baseDim = data.mapDimension(baseAxis.dim);
  30278. var valueAxisHorizontal = valueAxis.isHorizontal();
  30279. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30280. var barWidth = retrieveColumnLayout(
  30281. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  30282. ).width;
  30283. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  30284. barWidth = LARGE_BAR_MIN_WIDTH;
  30285. }
  30286. return {progress: progress};
  30287. function progress(params, data) {
  30288. var count = params.count;
  30289. var largePoints = new LargeArr(count * 2);
  30290. var largeBackgroundPoints = new LargeArr(count * 2);
  30291. var largeDataIndices = new LargeArr(count);
  30292. var dataIndex;
  30293. var coord = [];
  30294. var valuePair = [];
  30295. var pointsOffset = 0;
  30296. var idxOffset = 0;
  30297. while ((dataIndex = params.next()) != null) {
  30298. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30299. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30300. coord = cartesian.dataToPoint(valuePair, null, coord);
  30301. // Data index might not be in order, depends on `progressiveChunkMode`.
  30302. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal
  30303. ? coordLayout.x + coordLayout.width : coord[0];
  30304. largePoints[pointsOffset++] = coord[0];
  30305. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal
  30306. ? coord[1] : coordLayout.y + coordLayout.height;
  30307. largePoints[pointsOffset++] = coord[1];
  30308. largeDataIndices[idxOffset++] = dataIndex;
  30309. }
  30310. data.setLayout({
  30311. largePoints: largePoints,
  30312. largeDataIndices: largeDataIndices,
  30313. largeBackgroundPoints: largeBackgroundPoints,
  30314. barWidth: barWidth,
  30315. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  30316. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  30317. valueAxisHorizontal: valueAxisHorizontal
  30318. });
  30319. }
  30320. }
  30321. };
  30322. function isOnCartesian(seriesModel) {
  30323. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30324. }
  30325. function isInLargeMode(seriesModel) {
  30326. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30327. }
  30328. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30329. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30330. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30331. }
  30332. /*
  30333. * Licensed to the Apache Software Foundation (ASF) under one
  30334. * or more contributor license agreements. See the NOTICE file
  30335. * distributed with this work for additional information
  30336. * regarding copyright ownership. The ASF licenses this file
  30337. * to you under the Apache License, Version 2.0 (the
  30338. * "License"); you may not use this file except in compliance
  30339. * with the License. You may obtain a copy of the License at
  30340. *
  30341. * http://www.apache.org/licenses/LICENSE-2.0
  30342. *
  30343. * Unless required by applicable law or agreed to in writing,
  30344. * software distributed under the License is distributed on an
  30345. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30346. * KIND, either express or implied. See the License for the
  30347. * specific language governing permissions and limitations
  30348. * under the License.
  30349. */
  30350. /*
  30351. * A third-party license is embeded for some of the code in this file:
  30352. * The "scaleLevels" was originally copied from "d3.js" with some
  30353. * modifications made for this project.
  30354. * (See more details in the comment on the definition of "scaleLevels" below.)
  30355. * The use of the source code of this file is also subject to the terms
  30356. * and consitions of the license of "d3.js" (BSD-3Clause, see
  30357. * </licenses/LICENSE-d3>).
  30358. */
  30359. // [About UTC and local time zone]:
  30360. // In most cases, `number.parseDate` will treat input data string as local time
  30361. // (except time zone is specified in time string). And `format.formateTime` returns
  30362. // local time by default. option.useUTC is false by default. This design have
  30363. // concidered these common case:
  30364. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  30365. // in local time by default.
  30366. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  30367. // as its original time, without any time difference.
  30368. var intervalScaleProto = IntervalScale.prototype;
  30369. var mathCeil = Math.ceil;
  30370. var mathFloor = Math.floor;
  30371. var ONE_SECOND = 1000;
  30372. var ONE_MINUTE = ONE_SECOND * 60;
  30373. var ONE_HOUR = ONE_MINUTE * 60;
  30374. var ONE_DAY = ONE_HOUR * 24;
  30375. // FIXME 公用?
  30376. var bisect = function (a, x, lo, hi) {
  30377. while (lo < hi) {
  30378. var mid = lo + hi >>> 1;
  30379. if (a[mid][1] < x) {
  30380. lo = mid + 1;
  30381. }
  30382. else {
  30383. hi = mid;
  30384. }
  30385. }
  30386. return lo;
  30387. };
  30388. /**
  30389. * @alias module:echarts/coord/scale/Time
  30390. * @constructor
  30391. */
  30392. var TimeScale = IntervalScale.extend({
  30393. type: 'time',
  30394. /**
  30395. * @override
  30396. */
  30397. getLabel: function (val) {
  30398. var stepLvl = this._stepLvl;
  30399. var date = new Date(val);
  30400. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  30401. },
  30402. /**
  30403. * @override
  30404. */
  30405. niceExtent: function (opt) {
  30406. var extent = this._extent;
  30407. // If extent start and end are same, expand them
  30408. if (extent[0] === extent[1]) {
  30409. // Expand extent
  30410. extent[0] -= ONE_DAY;
  30411. extent[1] += ONE_DAY;
  30412. }
  30413. // If there are no data and extent are [Infinity, -Infinity]
  30414. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30415. var d = new Date();
  30416. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30417. extent[0] = extent[1] - ONE_DAY;
  30418. }
  30419. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30420. // var extent = this._extent;
  30421. var interval = this._interval;
  30422. if (!opt.fixMin) {
  30423. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  30424. }
  30425. if (!opt.fixMax) {
  30426. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  30427. }
  30428. },
  30429. /**
  30430. * @override
  30431. */
  30432. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  30433. approxTickNum = approxTickNum || 10;
  30434. var extent = this._extent;
  30435. var span = extent[1] - extent[0];
  30436. var approxInterval = span / approxTickNum;
  30437. if (minInterval != null && approxInterval < minInterval) {
  30438. approxInterval = minInterval;
  30439. }
  30440. if (maxInterval != null && approxInterval > maxInterval) {
  30441. approxInterval = maxInterval;
  30442. }
  30443. var scaleLevelsLen = scaleLevels.length;
  30444. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  30445. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  30446. var interval = level[1];
  30447. // Same with interval scale if span is much larger than 1 year
  30448. if (level[0] === 'year') {
  30449. var yearSpan = span / interval;
  30450. // From "Nice Numbers for Graph Labels" of Graphic Gems
  30451. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  30452. var yearStep = nice(yearSpan / approxTickNum, true);
  30453. interval *= yearStep;
  30454. }
  30455. var timezoneOffset = this.getSetting('useUTC')
  30456. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  30457. var niceExtent = [
  30458. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  30459. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  30460. ];
  30461. fixExtent(niceExtent, extent);
  30462. this._stepLvl = level;
  30463. // Interval will be used in getTicks
  30464. this._interval = interval;
  30465. this._niceExtent = niceExtent;
  30466. },
  30467. parse: function (val) {
  30468. // val might be float.
  30469. return +parseDate(val);
  30470. }
  30471. });
  30472. each$1(['contain', 'normalize'], function (methodName) {
  30473. TimeScale.prototype[methodName] = function (val) {
  30474. return intervalScaleProto[methodName].call(this, this.parse(val));
  30475. };
  30476. });
  30477. /**
  30478. * This implementation was originally copied from "d3.js"
  30479. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30480. * with some modifications made for this program.
  30481. * See the license statement at the head of this file.
  30482. */
  30483. var scaleLevels = [
  30484. // Format interval
  30485. ['hh:mm:ss', ONE_SECOND], // 1s
  30486. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  30487. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  30488. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  30489. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  30490. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  30491. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  30492. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  30493. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  30494. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  30495. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  30496. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  30497. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  30498. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  30499. ['MM-dd\nyyyy', ONE_DAY], // 1d
  30500. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  30501. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  30502. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  30503. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  30504. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  30505. ['week', ONE_DAY * 7], // 7d
  30506. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  30507. ['week', ONE_DAY * 14], // 2w
  30508. ['week', ONE_DAY * 21], // 3w
  30509. ['month', ONE_DAY * 31], // 1M
  30510. ['week', ONE_DAY * 42], // 6w
  30511. ['month', ONE_DAY * 62], // 2M
  30512. ['week', ONE_DAY * 70], // 10w
  30513. ['quarter', ONE_DAY * 95], // 3M
  30514. ['month', ONE_DAY * 31 * 4], // 4M
  30515. ['month', ONE_DAY * 31 * 5], // 5M
  30516. ['half-year', ONE_DAY * 380 / 2], // 6M
  30517. ['month', ONE_DAY * 31 * 8], // 8M
  30518. ['month', ONE_DAY * 31 * 10], // 10M
  30519. ['year', ONE_DAY * 380] // 1Y
  30520. ];
  30521. /**
  30522. * @param {module:echarts/model/Model}
  30523. * @return {module:echarts/scale/Time}
  30524. */
  30525. TimeScale.create = function (model) {
  30526. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  30527. };
  30528. /*
  30529. * Licensed to the Apache Software Foundation (ASF) under one
  30530. * or more contributor license agreements. See the NOTICE file
  30531. * distributed with this work for additional information
  30532. * regarding copyright ownership. The ASF licenses this file
  30533. * to you under the Apache License, Version 2.0 (the
  30534. * "License"); you may not use this file except in compliance
  30535. * with the License. You may obtain a copy of the License at
  30536. *
  30537. * http://www.apache.org/licenses/LICENSE-2.0
  30538. *
  30539. * Unless required by applicable law or agreed to in writing,
  30540. * software distributed under the License is distributed on an
  30541. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30542. * KIND, either express or implied. See the License for the
  30543. * specific language governing permissions and limitations
  30544. * under the License.
  30545. */
  30546. /**
  30547. * Log scale
  30548. * @module echarts/scale/Log
  30549. */
  30550. // Use some method of IntervalScale
  30551. var scaleProto$1 = Scale.prototype;
  30552. var intervalScaleProto$1 = IntervalScale.prototype;
  30553. var getPrecisionSafe$1 = getPrecisionSafe;
  30554. var roundingErrorFix = round$1;
  30555. var mathFloor$1 = Math.floor;
  30556. var mathCeil$1 = Math.ceil;
  30557. var mathPow$1 = Math.pow;
  30558. var mathLog = Math.log;
  30559. var LogScale = Scale.extend({
  30560. type: 'log',
  30561. base: 10,
  30562. $constructor: function () {
  30563. Scale.apply(this, arguments);
  30564. this._originalScale = new IntervalScale();
  30565. },
  30566. /**
  30567. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  30568. * @return {Array.<number>}
  30569. */
  30570. getTicks: function (expandToNicedExtent) {
  30571. var originalScale = this._originalScale;
  30572. var extent = this._extent;
  30573. var originalExtent = originalScale.getExtent();
  30574. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  30575. var powVal = round$1(mathPow$1(this.base, val));
  30576. // Fix #4158
  30577. powVal = (val === extent[0] && originalScale.__fixMin)
  30578. ? fixRoundingError(powVal, originalExtent[0])
  30579. : powVal;
  30580. powVal = (val === extent[1] && originalScale.__fixMax)
  30581. ? fixRoundingError(powVal, originalExtent[1])
  30582. : powVal;
  30583. return powVal;
  30584. }, this);
  30585. },
  30586. /**
  30587. * @param {number} splitNumber
  30588. * @return {Array.<Array.<number>>}
  30589. */
  30590. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  30591. /**
  30592. * @param {number} val
  30593. * @return {string}
  30594. */
  30595. getLabel: intervalScaleProto$1.getLabel,
  30596. /**
  30597. * @param {number} val
  30598. * @return {number}
  30599. */
  30600. scale: function (val) {
  30601. val = scaleProto$1.scale.call(this, val);
  30602. return mathPow$1(this.base, val);
  30603. },
  30604. /**
  30605. * @param {number} start
  30606. * @param {number} end
  30607. */
  30608. setExtent: function (start, end) {
  30609. var base = this.base;
  30610. start = mathLog(start) / mathLog(base);
  30611. end = mathLog(end) / mathLog(base);
  30612. intervalScaleProto$1.setExtent.call(this, start, end);
  30613. },
  30614. /**
  30615. * @return {number} end
  30616. */
  30617. getExtent: function () {
  30618. var base = this.base;
  30619. var extent = scaleProto$1.getExtent.call(this);
  30620. extent[0] = mathPow$1(base, extent[0]);
  30621. extent[1] = mathPow$1(base, extent[1]);
  30622. // Fix #4158
  30623. var originalScale = this._originalScale;
  30624. var originalExtent = originalScale.getExtent();
  30625. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30626. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30627. return extent;
  30628. },
  30629. /**
  30630. * @param {Array.<number>} extent
  30631. */
  30632. unionExtent: function (extent) {
  30633. this._originalScale.unionExtent(extent);
  30634. var base = this.base;
  30635. extent[0] = mathLog(extent[0]) / mathLog(base);
  30636. extent[1] = mathLog(extent[1]) / mathLog(base);
  30637. scaleProto$1.unionExtent.call(this, extent);
  30638. },
  30639. /**
  30640. * @override
  30641. */
  30642. unionExtentFromData: function (data, dim) {
  30643. // TODO
  30644. // filter value that <= 0
  30645. this.unionExtent(data.getApproximateExtent(dim));
  30646. },
  30647. /**
  30648. * Update interval and extent of intervals for nice ticks
  30649. * @param {number} [approxTickNum = 10] Given approx tick number
  30650. */
  30651. niceTicks: function (approxTickNum) {
  30652. approxTickNum = approxTickNum || 10;
  30653. var extent = this._extent;
  30654. var span = extent[1] - extent[0];
  30655. if (span === Infinity || span <= 0) {
  30656. return;
  30657. }
  30658. var interval = quantity(span);
  30659. var err = approxTickNum / span * interval;
  30660. // Filter ticks to get closer to the desired count.
  30661. if (err <= 0.5) {
  30662. interval *= 10;
  30663. }
  30664. // Interval should be integer
  30665. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30666. interval *= 10;
  30667. }
  30668. var niceExtent = [
  30669. round$1(mathCeil$1(extent[0] / interval) * interval),
  30670. round$1(mathFloor$1(extent[1] / interval) * interval)
  30671. ];
  30672. this._interval = interval;
  30673. this._niceExtent = niceExtent;
  30674. },
  30675. /**
  30676. * Nice extent.
  30677. * @override
  30678. */
  30679. niceExtent: function (opt) {
  30680. intervalScaleProto$1.niceExtent.call(this, opt);
  30681. var originalScale = this._originalScale;
  30682. originalScale.__fixMin = opt.fixMin;
  30683. originalScale.__fixMax = opt.fixMax;
  30684. }
  30685. });
  30686. each$1(['contain', 'normalize'], function (methodName) {
  30687. LogScale.prototype[methodName] = function (val) {
  30688. val = mathLog(val) / mathLog(this.base);
  30689. return scaleProto$1[methodName].call(this, val);
  30690. };
  30691. });
  30692. LogScale.create = function () {
  30693. return new LogScale();
  30694. };
  30695. function fixRoundingError(val, originalVal) {
  30696. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  30697. }
  30698. /*
  30699. * Licensed to the Apache Software Foundation (ASF) under one
  30700. * or more contributor license agreements. See the NOTICE file
  30701. * distributed with this work for additional information
  30702. * regarding copyright ownership. The ASF licenses this file
  30703. * to you under the Apache License, Version 2.0 (the
  30704. * "License"); you may not use this file except in compliance
  30705. * with the License. You may obtain a copy of the License at
  30706. *
  30707. * http://www.apache.org/licenses/LICENSE-2.0
  30708. *
  30709. * Unless required by applicable law or agreed to in writing,
  30710. * software distributed under the License is distributed on an
  30711. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30712. * KIND, either express or implied. See the License for the
  30713. * specific language governing permissions and limitations
  30714. * under the License.
  30715. */
  30716. /**
  30717. * Get axis scale extent before niced.
  30718. * Item of returned array can only be number (including Infinity and NaN).
  30719. */
  30720. function getScaleExtent(scale, model) {
  30721. var scaleType = scale.type;
  30722. var min = model.getMin();
  30723. var max = model.getMax();
  30724. var originalExtent = scale.getExtent();
  30725. var axisDataLen;
  30726. var boundaryGap;
  30727. var span;
  30728. if (scaleType === 'ordinal') {
  30729. axisDataLen = model.getCategories().length;
  30730. }
  30731. else {
  30732. boundaryGap = model.get('boundaryGap');
  30733. if (!isArray(boundaryGap)) {
  30734. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  30735. }
  30736. if (typeof boundaryGap[0] === 'boolean') {
  30737. if (__DEV__) {
  30738. console.warn('Boolean type for boundaryGap is only '
  30739. + 'allowed for ordinal axis. Please use string in '
  30740. + 'percentage instead, e.g., "20%". Currently, '
  30741. + 'boundaryGap is set to be 0.');
  30742. }
  30743. boundaryGap = [0, 0];
  30744. }
  30745. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  30746. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  30747. span = (originalExtent[1] - originalExtent[0])
  30748. || Math.abs(originalExtent[0]);
  30749. }
  30750. // Notice: When min/max is not set (that is, when there are null/undefined,
  30751. // which is the most common case), these cases should be ensured:
  30752. // (1) For 'ordinal', show all axis.data.
  30753. // (2) For others:
  30754. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30755. // disabled).
  30756. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30757. // be the result that originalExtent enlarged by boundaryGap.
  30758. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30759. // FIXME
  30760. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  30761. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  30762. // that the results processed by boundaryGap are positive/negative?
  30763. if (min === 'dataMin') {
  30764. min = originalExtent[0];
  30765. }
  30766. else if (typeof min === 'function') {
  30767. min = min({
  30768. min: originalExtent[0],
  30769. max: originalExtent[1]
  30770. });
  30771. }
  30772. if (max === 'dataMax') {
  30773. max = originalExtent[1];
  30774. }
  30775. else if (typeof max === 'function') {
  30776. max = max({
  30777. min: originalExtent[0],
  30778. max: originalExtent[1]
  30779. });
  30780. }
  30781. var fixMin = min != null;
  30782. var fixMax = max != null;
  30783. if (min == null) {
  30784. min = scaleType === 'ordinal'
  30785. ? (axisDataLen ? 0 : NaN)
  30786. : originalExtent[0] - boundaryGap[0] * span;
  30787. }
  30788. if (max == null) {
  30789. max = scaleType === 'ordinal'
  30790. ? (axisDataLen ? axisDataLen - 1 : NaN)
  30791. : originalExtent[1] + boundaryGap[1] * span;
  30792. }
  30793. (min == null || !isFinite(min)) && (min = NaN);
  30794. (max == null || !isFinite(max)) && (max = NaN);
  30795. scale.setBlank(
  30796. eqNaN(min)
  30797. || eqNaN(max)
  30798. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  30799. );
  30800. // Evaluate if axis needs cross zero
  30801. if (model.getNeedCrossZero()) {
  30802. // Axis is over zero and min is not set
  30803. if (min > 0 && max > 0 && !fixMin) {
  30804. min = 0;
  30805. }
  30806. // Axis is under zero and max is not set
  30807. if (min < 0 && max < 0 && !fixMax) {
  30808. max = 0;
  30809. }
  30810. }
  30811. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  30812. // is base axis
  30813. // FIXME
  30814. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30815. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30816. // Should not depend on series type `bar`?
  30817. // (3) Fix that might overlap when using dataZoom.
  30818. // (4) Consider other chart types using `barGrid`?
  30819. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30820. var ecModel = model.ecModel;
  30821. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  30822. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30823. var isBaseAxisAndHasBarSeries;
  30824. each$1(barSeriesModels, function (seriesModel) {
  30825. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  30826. });
  30827. if (isBaseAxisAndHasBarSeries) {
  30828. // Calculate placement of bars on axis
  30829. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  30830. // Adjust axis min and max to account for overflow
  30831. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30832. min = adjustedScale.min;
  30833. max = adjustedScale.max;
  30834. }
  30835. }
  30836. return {
  30837. extent: [min, max],
  30838. // "fix" means "fixed", the value should not be
  30839. // changed in the subsequent steps.
  30840. fixMin: fixMin,
  30841. fixMax: fixMax
  30842. };
  30843. }
  30844. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  30845. // Get Axis Length
  30846. var axisExtent = model.axis.getExtent();
  30847. var axisLength = axisExtent[1] - axisExtent[0];
  30848. // Get bars on current base axis and calculate min and max overflow
  30849. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30850. if (barsOnCurrentAxis === undefined) {
  30851. return {min: min, max: max};
  30852. }
  30853. var minOverflow = Infinity;
  30854. each$1(barsOnCurrentAxis, function (item) {
  30855. minOverflow = Math.min(item.offset, minOverflow);
  30856. });
  30857. var maxOverflow = -Infinity;
  30858. each$1(barsOnCurrentAxis, function (item) {
  30859. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30860. });
  30861. minOverflow = Math.abs(minOverflow);
  30862. maxOverflow = Math.abs(maxOverflow);
  30863. var totalOverFlow = minOverflow + maxOverflow;
  30864. // Calulate required buffer based on old range and overflow
  30865. var oldRange = max - min;
  30866. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  30867. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  30868. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30869. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30870. return {min: min, max: max};
  30871. }
  30872. function niceScaleExtent(scale, model) {
  30873. var extentInfo = getScaleExtent(scale, model);
  30874. var extent = extentInfo.extent;
  30875. var splitNumber = model.get('splitNumber');
  30876. if (scale.type === 'log') {
  30877. scale.base = model.get('logBase');
  30878. }
  30879. var scaleType = scale.type;
  30880. scale.setExtent(extent[0], extent[1]);
  30881. scale.niceExtent({
  30882. splitNumber: splitNumber,
  30883. fixMin: extentInfo.fixMin,
  30884. fixMax: extentInfo.fixMax,
  30885. minInterval: (scaleType === 'interval' || scaleType === 'time')
  30886. ? model.get('minInterval') : null,
  30887. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  30888. ? model.get('maxInterval') : null
  30889. });
  30890. // If some one specified the min, max. And the default calculated interval
  30891. // is not good enough. He can specify the interval. It is often appeared
  30892. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30893. // to be 60.
  30894. // FIXME
  30895. var interval = model.get('interval');
  30896. if (interval != null) {
  30897. scale.setInterval && scale.setInterval(interval);
  30898. }
  30899. }
  30900. /**
  30901. * @param {module:echarts/model/Model} model
  30902. * @param {string} [axisType] Default retrieve from model.type
  30903. * @return {module:echarts/scale/*}
  30904. */
  30905. function createScaleByModel(model, axisType) {
  30906. axisType = axisType || model.get('type');
  30907. if (axisType) {
  30908. switch (axisType) {
  30909. // Buildin scale
  30910. case 'category':
  30911. return new OrdinalScale(
  30912. model.getOrdinalMeta
  30913. ? model.getOrdinalMeta()
  30914. : model.getCategories(),
  30915. [Infinity, -Infinity]
  30916. );
  30917. case 'value':
  30918. return new IntervalScale();
  30919. // Extended scale, like time and log
  30920. default:
  30921. return (Scale.getClass(axisType) || IntervalScale).create(model);
  30922. }
  30923. }
  30924. }
  30925. /**
  30926. * Check if the axis corss 0
  30927. */
  30928. function ifAxisCrossZero(axis) {
  30929. var dataExtent = axis.scale.getExtent();
  30930. var min = dataExtent[0];
  30931. var max = dataExtent[1];
  30932. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  30933. }
  30934. /**
  30935. * @param {module:echarts/coord/Axis} axis
  30936. * @return {Function} Label formatter function.
  30937. * param: {number} tickValue,
  30938. * param: {number} idx, the index in all ticks.
  30939. * If category axis, this param is not requied.
  30940. * return: {string} label string.
  30941. */
  30942. function makeLabelFormatter(axis) {
  30943. var labelFormatter = axis.getLabelModel().get('formatter');
  30944. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  30945. if (typeof labelFormatter === 'string') {
  30946. labelFormatter = (function (tpl) {
  30947. return function (val) {
  30948. // For category axis, get raw value; for numeric axis,
  30949. // get foramtted label like '1,333,444'.
  30950. val = axis.scale.getLabel(val);
  30951. return tpl.replace('{value}', val != null ? val : '');
  30952. };
  30953. })(labelFormatter);
  30954. // Consider empty array
  30955. return labelFormatter;
  30956. }
  30957. else if (typeof labelFormatter === 'function') {
  30958. return function (tickValue, idx) {
  30959. // The original intention of `idx` is "the index of the tick in all ticks".
  30960. // But the previous implementation of category axis do not consider the
  30961. // `axisLabel.interval`, which cause that, for example, the `interval` is
  30962. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  30963. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  30964. // the definition here for back compatibility.
  30965. if (categoryTickStart != null) {
  30966. idx = tickValue - categoryTickStart;
  30967. }
  30968. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  30969. };
  30970. }
  30971. else {
  30972. return function (tick) {
  30973. return axis.scale.getLabel(tick);
  30974. };
  30975. }
  30976. }
  30977. function getAxisRawValue(axis, value) {
  30978. // In category axis with data zoom, tick is not the original
  30979. // index of axis.data. So tick should not be exposed to user
  30980. // in category axis.
  30981. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  30982. }
  30983. /**
  30984. * @param {module:echarts/coord/Axis} axis
  30985. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  30986. */
  30987. function estimateLabelUnionRect(axis) {
  30988. var axisModel = axis.model;
  30989. var scale = axis.scale;
  30990. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  30991. return;
  30992. }
  30993. var isCategory = axis.type === 'category';
  30994. var realNumberScaleTicks;
  30995. var tickCount;
  30996. var categoryScaleExtent = scale.getExtent();
  30997. // Optimize for large category data, avoid call `getTicks()`.
  30998. if (isCategory) {
  30999. tickCount = scale.count();
  31000. }
  31001. else {
  31002. realNumberScaleTicks = scale.getTicks();
  31003. tickCount = realNumberScaleTicks.length;
  31004. }
  31005. var axisLabelModel = axis.getLabelModel();
  31006. var labelFormatter = makeLabelFormatter(axis);
  31007. var rect;
  31008. var step = 1;
  31009. // Simple optimization for large amount of labels
  31010. if (tickCount > 40) {
  31011. step = Math.ceil(tickCount / 40);
  31012. }
  31013. for (var i = 0; i < tickCount; i += step) {
  31014. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  31015. var label = labelFormatter(tickValue);
  31016. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31017. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31018. rect ? rect.union(singleRect) : (rect = singleRect);
  31019. }
  31020. return rect;
  31021. }
  31022. function rotateTextRect(textRect, rotate) {
  31023. var rotateRadians = rotate * Math.PI / 180;
  31024. var boundingBox = textRect.plain();
  31025. var beforeWidth = boundingBox.width;
  31026. var beforeHeight = boundingBox.height;
  31027. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  31028. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  31029. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  31030. return rotatedRect;
  31031. }
  31032. /**
  31033. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  31034. * @return {number|String} Can be null|'auto'|number|function
  31035. */
  31036. function getOptionCategoryInterval(model) {
  31037. var interval = model.get('interval');
  31038. return interval == null ? 'auto' : interval;
  31039. }
  31040. /**
  31041. * Set `categoryInterval` as 0 implicitly indicates that
  31042. * show all labels reguardless of overlap.
  31043. * @param {Object} axis axisModel.axis
  31044. * @return {boolean}
  31045. */
  31046. function shouldShowAllLabels(axis) {
  31047. return axis.type === 'category'
  31048. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31049. }
  31050. /*
  31051. * Licensed to the Apache Software Foundation (ASF) under one
  31052. * or more contributor license agreements. See the NOTICE file
  31053. * distributed with this work for additional information
  31054. * regarding copyright ownership. The ASF licenses this file
  31055. * to you under the Apache License, Version 2.0 (the
  31056. * "License"); you may not use this file except in compliance
  31057. * with the License. You may obtain a copy of the License at
  31058. *
  31059. * http://www.apache.org/licenses/LICENSE-2.0
  31060. *
  31061. * Unless required by applicable law or agreed to in writing,
  31062. * software distributed under the License is distributed on an
  31063. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31064. * KIND, either express or implied. See the License for the
  31065. * specific language governing permissions and limitations
  31066. * under the License.
  31067. */
  31068. // import * as axisHelper from './axisHelper';
  31069. var axisModelCommonMixin = {
  31070. /**
  31071. * @param {boolean} origin
  31072. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  31073. */
  31074. getMin: function (origin) {
  31075. var option = this.option;
  31076. var min = (!origin && option.rangeStart != null)
  31077. ? option.rangeStart : option.min;
  31078. if (this.axis
  31079. && min != null
  31080. && min !== 'dataMin'
  31081. && typeof min !== 'function'
  31082. && !eqNaN(min)
  31083. ) {
  31084. min = this.axis.scale.parse(min);
  31085. }
  31086. return min;
  31087. },
  31088. /**
  31089. * @param {boolean} origin
  31090. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  31091. */
  31092. getMax: function (origin) {
  31093. var option = this.option;
  31094. var max = (!origin && option.rangeEnd != null)
  31095. ? option.rangeEnd : option.max;
  31096. if (this.axis
  31097. && max != null
  31098. && max !== 'dataMax'
  31099. && typeof max !== 'function'
  31100. && !eqNaN(max)
  31101. ) {
  31102. max = this.axis.scale.parse(max);
  31103. }
  31104. return max;
  31105. },
  31106. /**
  31107. * @return {boolean}
  31108. */
  31109. getNeedCrossZero: function () {
  31110. var option = this.option;
  31111. return (option.rangeStart != null || option.rangeEnd != null)
  31112. ? false : !option.scale;
  31113. },
  31114. /**
  31115. * Should be implemented by each axis model if necessary.
  31116. * @return {module:echarts/model/Component} coordinate system model
  31117. */
  31118. getCoordSysModel: noop,
  31119. /**
  31120. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  31121. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  31122. */
  31123. setRange: function (rangeStart, rangeEnd) {
  31124. this.option.rangeStart = rangeStart;
  31125. this.option.rangeEnd = rangeEnd;
  31126. },
  31127. /**
  31128. * Reset range
  31129. */
  31130. resetRange: function () {
  31131. // rangeStart and rangeEnd is readonly.
  31132. this.option.rangeStart = this.option.rangeEnd = null;
  31133. }
  31134. };
  31135. /*
  31136. * Licensed to the Apache Software Foundation (ASF) under one
  31137. * or more contributor license agreements. See the NOTICE file
  31138. * distributed with this work for additional information
  31139. * regarding copyright ownership. The ASF licenses this file
  31140. * to you under the Apache License, Version 2.0 (the
  31141. * "License"); you may not use this file except in compliance
  31142. * with the License. You may obtain a copy of the License at
  31143. *
  31144. * http://www.apache.org/licenses/LICENSE-2.0
  31145. *
  31146. * Unless required by applicable law or agreed to in writing,
  31147. * software distributed under the License is distributed on an
  31148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31149. * KIND, either express or implied. See the License for the
  31150. * specific language governing permissions and limitations
  31151. * under the License.
  31152. */
  31153. // Symbol factory
  31154. /**
  31155. * Triangle shape
  31156. * @inner
  31157. */
  31158. var Triangle = extendShape({
  31159. type: 'triangle',
  31160. shape: {
  31161. cx: 0,
  31162. cy: 0,
  31163. width: 0,
  31164. height: 0
  31165. },
  31166. buildPath: function (path, shape) {
  31167. var cx = shape.cx;
  31168. var cy = shape.cy;
  31169. var width = shape.width / 2;
  31170. var height = shape.height / 2;
  31171. path.moveTo(cx, cy - height);
  31172. path.lineTo(cx + width, cy + height);
  31173. path.lineTo(cx - width, cy + height);
  31174. path.closePath();
  31175. }
  31176. });
  31177. /**
  31178. * Diamond shape
  31179. * @inner
  31180. */
  31181. var Diamond = extendShape({
  31182. type: 'diamond',
  31183. shape: {
  31184. cx: 0,
  31185. cy: 0,
  31186. width: 0,
  31187. height: 0
  31188. },
  31189. buildPath: function (path, shape) {
  31190. var cx = shape.cx;
  31191. var cy = shape.cy;
  31192. var width = shape.width / 2;
  31193. var height = shape.height / 2;
  31194. path.moveTo(cx, cy - height);
  31195. path.lineTo(cx + width, cy);
  31196. path.lineTo(cx, cy + height);
  31197. path.lineTo(cx - width, cy);
  31198. path.closePath();
  31199. }
  31200. });
  31201. /**
  31202. * Pin shape
  31203. * @inner
  31204. */
  31205. var Pin = extendShape({
  31206. type: 'pin',
  31207. shape: {
  31208. // x, y on the cusp
  31209. x: 0,
  31210. y: 0,
  31211. width: 0,
  31212. height: 0
  31213. },
  31214. buildPath: function (path, shape) {
  31215. var x = shape.x;
  31216. var y = shape.y;
  31217. var w = shape.width / 5 * 3;
  31218. // Height must be larger than width
  31219. var h = Math.max(w, shape.height);
  31220. var r = w / 2;
  31221. // Dist on y with tangent point and circle center
  31222. var dy = r * r / (h - r);
  31223. var cy = y - h + r + dy;
  31224. var angle = Math.asin(dy / r);
  31225. // Dist on x with tangent point and circle center
  31226. var dx = Math.cos(angle) * r;
  31227. var tanX = Math.sin(angle);
  31228. var tanY = Math.cos(angle);
  31229. var cpLen = r * 0.6;
  31230. var cpLen2 = r * 0.7;
  31231. path.moveTo(x - dx, cy + dy);
  31232. path.arc(
  31233. x, cy, r,
  31234. Math.PI - angle,
  31235. Math.PI * 2 + angle
  31236. );
  31237. path.bezierCurveTo(
  31238. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  31239. x, y - cpLen2,
  31240. x, y
  31241. );
  31242. path.bezierCurveTo(
  31243. x, y - cpLen2,
  31244. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  31245. x - dx, cy + dy
  31246. );
  31247. path.closePath();
  31248. }
  31249. });
  31250. /**
  31251. * Arrow shape
  31252. * @inner
  31253. */
  31254. var Arrow = extendShape({
  31255. type: 'arrow',
  31256. shape: {
  31257. x: 0,
  31258. y: 0,
  31259. width: 0,
  31260. height: 0
  31261. },
  31262. buildPath: function (ctx, shape) {
  31263. var height = shape.height;
  31264. var width = shape.width;
  31265. var x = shape.x;
  31266. var y = shape.y;
  31267. var dx = width / 3 * 2;
  31268. ctx.moveTo(x, y);
  31269. ctx.lineTo(x + dx, y + height);
  31270. ctx.lineTo(x, y + height / 4 * 3);
  31271. ctx.lineTo(x - dx, y + height);
  31272. ctx.lineTo(x, y);
  31273. ctx.closePath();
  31274. }
  31275. });
  31276. /**
  31277. * Map of path contructors
  31278. * @type {Object.<string, module:zrender/graphic/Path>}
  31279. */
  31280. var symbolCtors = {
  31281. line: Line,
  31282. rect: Rect,
  31283. roundRect: Rect,
  31284. square: Rect,
  31285. circle: Circle,
  31286. diamond: Diamond,
  31287. pin: Pin,
  31288. arrow: Arrow,
  31289. triangle: Triangle
  31290. };
  31291. var symbolShapeMakers = {
  31292. line: function (x, y, w, h, shape) {
  31293. // FIXME
  31294. shape.x1 = x;
  31295. shape.y1 = y + h / 2;
  31296. shape.x2 = x + w;
  31297. shape.y2 = y + h / 2;
  31298. },
  31299. rect: function (x, y, w, h, shape) {
  31300. shape.x = x;
  31301. shape.y = y;
  31302. shape.width = w;
  31303. shape.height = h;
  31304. },
  31305. roundRect: function (x, y, w, h, shape) {
  31306. shape.x = x;
  31307. shape.y = y;
  31308. shape.width = w;
  31309. shape.height = h;
  31310. shape.r = Math.min(w, h) / 4;
  31311. },
  31312. square: function (x, y, w, h, shape) {
  31313. var size = Math.min(w, h);
  31314. shape.x = x;
  31315. shape.y = y;
  31316. shape.width = size;
  31317. shape.height = size;
  31318. },
  31319. circle: function (x, y, w, h, shape) {
  31320. // Put circle in the center of square
  31321. shape.cx = x + w / 2;
  31322. shape.cy = y + h / 2;
  31323. shape.r = Math.min(w, h) / 2;
  31324. },
  31325. diamond: function (x, y, w, h, shape) {
  31326. shape.cx = x + w / 2;
  31327. shape.cy = y + h / 2;
  31328. shape.width = w;
  31329. shape.height = h;
  31330. },
  31331. pin: function (x, y, w, h, shape) {
  31332. shape.x = x + w / 2;
  31333. shape.y = y + h / 2;
  31334. shape.width = w;
  31335. shape.height = h;
  31336. },
  31337. arrow: function (x, y, w, h, shape) {
  31338. shape.x = x + w / 2;
  31339. shape.y = y + h / 2;
  31340. shape.width = w;
  31341. shape.height = h;
  31342. },
  31343. triangle: function (x, y, w, h, shape) {
  31344. shape.cx = x + w / 2;
  31345. shape.cy = y + h / 2;
  31346. shape.width = w;
  31347. shape.height = h;
  31348. }
  31349. };
  31350. var symbolBuildProxies = {};
  31351. each$1(symbolCtors, function (Ctor, name) {
  31352. symbolBuildProxies[name] = new Ctor();
  31353. });
  31354. var SymbolClz = extendShape({
  31355. type: 'symbol',
  31356. shape: {
  31357. symbolType: '',
  31358. x: 0,
  31359. y: 0,
  31360. width: 0,
  31361. height: 0
  31362. },
  31363. calculateTextPosition: function (out, style, rect) {
  31364. var res = calculateTextPosition(out, style, rect);
  31365. var shape = this.shape;
  31366. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  31367. res.y = rect.y + rect.height * 0.4;
  31368. }
  31369. return res;
  31370. },
  31371. buildPath: function (ctx, shape, inBundle) {
  31372. var symbolType = shape.symbolType;
  31373. if (symbolType !== 'none') {
  31374. var proxySymbol = symbolBuildProxies[symbolType];
  31375. if (!proxySymbol) {
  31376. // Default rect
  31377. symbolType = 'rect';
  31378. proxySymbol = symbolBuildProxies[symbolType];
  31379. }
  31380. symbolShapeMakers[symbolType](
  31381. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  31382. );
  31383. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  31384. }
  31385. }
  31386. });
  31387. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  31388. function symbolPathSetColor(color, innerColor) {
  31389. if (this.type !== 'image') {
  31390. var symbolStyle = this.style;
  31391. var symbolShape = this.shape;
  31392. if (symbolShape && symbolShape.symbolType === 'line') {
  31393. symbolStyle.stroke = color;
  31394. }
  31395. else if (this.__isEmptyBrush) {
  31396. symbolStyle.stroke = color;
  31397. symbolStyle.fill = innerColor || '#fff';
  31398. }
  31399. else {
  31400. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  31401. symbolStyle.fill && (symbolStyle.fill = color);
  31402. symbolStyle.stroke && (symbolStyle.stroke = color);
  31403. }
  31404. this.dirty(false);
  31405. }
  31406. }
  31407. /**
  31408. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  31409. * @param {string} symbolType
  31410. * @param {number} x
  31411. * @param {number} y
  31412. * @param {number} w
  31413. * @param {number} h
  31414. * @param {string} color
  31415. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  31416. * for path and image only.
  31417. */
  31418. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  31419. // TODO Support image object, DynamicImage.
  31420. var isEmpty = symbolType.indexOf('empty') === 0;
  31421. if (isEmpty) {
  31422. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  31423. }
  31424. var symbolPath;
  31425. if (symbolType.indexOf('image://') === 0) {
  31426. symbolPath = makeImage(
  31427. symbolType.slice(8),
  31428. new BoundingRect(x, y, w, h),
  31429. keepAspect ? 'center' : 'cover'
  31430. );
  31431. }
  31432. else if (symbolType.indexOf('path://') === 0) {
  31433. symbolPath = makePath(
  31434. symbolType.slice(7),
  31435. {},
  31436. new BoundingRect(x, y, w, h),
  31437. keepAspect ? 'center' : 'cover'
  31438. );
  31439. }
  31440. else {
  31441. symbolPath = new SymbolClz({
  31442. shape: {
  31443. symbolType: symbolType,
  31444. x: x,
  31445. y: y,
  31446. width: w,
  31447. height: h
  31448. }
  31449. });
  31450. }
  31451. symbolPath.__isEmptyBrush = isEmpty;
  31452. symbolPath.setColor = symbolPathSetColor;
  31453. symbolPath.setColor(color);
  31454. return symbolPath;
  31455. }
  31456. /*
  31457. * Licensed to the Apache Software Foundation (ASF) under one
  31458. * or more contributor license agreements. See the NOTICE file
  31459. * distributed with this work for additional information
  31460. * regarding copyright ownership. The ASF licenses this file
  31461. * to you under the Apache License, Version 2.0 (the
  31462. * "License"); you may not use this file except in compliance
  31463. * with the License. You may obtain a copy of the License at
  31464. *
  31465. * http://www.apache.org/licenses/LICENSE-2.0
  31466. *
  31467. * Unless required by applicable law or agreed to in writing,
  31468. * software distributed under the License is distributed on an
  31469. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31470. * KIND, either express or implied. See the License for the
  31471. * specific language governing permissions and limitations
  31472. * under the License.
  31473. */
  31474. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  31475. /**
  31476. * Create a muti dimension List structure from seriesModel.
  31477. * @param {module:echarts/model/Model} seriesModel
  31478. * @return {module:echarts/data/List} list
  31479. */
  31480. function createList(seriesModel) {
  31481. return createListFromArray(seriesModel.getSource(), seriesModel);
  31482. }
  31483. var dataStack$1 = {
  31484. isDimensionStacked: isDimensionStacked,
  31485. enableDataStack: enableDataStack,
  31486. getStackedDimension: getStackedDimension
  31487. };
  31488. /**
  31489. * Create scale
  31490. * @param {Array.<number>} dataExtent
  31491. * @param {Object|module:echarts/Model} option
  31492. */
  31493. function createScale(dataExtent, option) {
  31494. var axisModel = option;
  31495. if (!Model.isInstance(option)) {
  31496. axisModel = new Model(option);
  31497. mixin(axisModel, axisModelCommonMixin);
  31498. }
  31499. var scale = createScaleByModel(axisModel);
  31500. scale.setExtent(dataExtent[0], dataExtent[1]);
  31501. niceScaleExtent(scale, axisModel);
  31502. return scale;
  31503. }
  31504. /**
  31505. * Mixin common methods to axis model,
  31506. *
  31507. * Inlcude methods
  31508. * `getFormattedLabels() => Array.<string>`
  31509. * `getCategories() => Array.<string>`
  31510. * `getMin(origin: boolean) => number`
  31511. * `getMax(origin: boolean) => number`
  31512. * `getNeedCrossZero() => boolean`
  31513. * `setRange(start: number, end: number)`
  31514. * `resetRange()`
  31515. */
  31516. function mixinAxisModelCommonMethods(Model$$1) {
  31517. mixin(Model$$1, axisModelCommonMixin);
  31518. }
  31519. var helper = (Object.freeze || Object)({
  31520. createList: createList,
  31521. getLayoutRect: getLayoutRect,
  31522. dataStack: dataStack$1,
  31523. createScale: createScale,
  31524. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31525. completeDimensions: completeDimensions,
  31526. createDimensions: createDimensions,
  31527. createSymbol: createSymbol
  31528. });
  31529. var EPSILON$3 = 1e-8;
  31530. function isAroundEqual$1(a, b) {
  31531. return Math.abs(a - b) < EPSILON$3;
  31532. }
  31533. function contain$1(points, x, y) {
  31534. var w = 0;
  31535. var p = points[0];
  31536. if (!p) {
  31537. return false;
  31538. }
  31539. for (var i = 1; i < points.length; i++) {
  31540. var p2 = points[i];
  31541. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31542. p = p2;
  31543. }
  31544. // Close polygon
  31545. var p0 = points[0];
  31546. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31547. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31548. }
  31549. return w !== 0;
  31550. }
  31551. /*
  31552. * Licensed to the Apache Software Foundation (ASF) under one
  31553. * or more contributor license agreements. See the NOTICE file
  31554. * distributed with this work for additional information
  31555. * regarding copyright ownership. The ASF licenses this file
  31556. * to you under the Apache License, Version 2.0 (the
  31557. * "License"); you may not use this file except in compliance
  31558. * with the License. You may obtain a copy of the License at
  31559. *
  31560. * http://www.apache.org/licenses/LICENSE-2.0
  31561. *
  31562. * Unless required by applicable law or agreed to in writing,
  31563. * software distributed under the License is distributed on an
  31564. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31565. * KIND, either express or implied. See the License for the
  31566. * specific language governing permissions and limitations
  31567. * under the License.
  31568. */
  31569. /**
  31570. * @module echarts/coord/geo/Region
  31571. */
  31572. /**
  31573. * @param {string|Region} name
  31574. * @param {Array} geometries
  31575. * @param {Array.<number>} cp
  31576. */
  31577. function Region(name, geometries, cp) {
  31578. /**
  31579. * @type {string}
  31580. * @readOnly
  31581. */
  31582. this.name = name;
  31583. /**
  31584. * @type {Array.<Array>}
  31585. * @readOnly
  31586. */
  31587. this.geometries = geometries;
  31588. if (!cp) {
  31589. var rect = this.getBoundingRect();
  31590. cp = [
  31591. rect.x + rect.width / 2,
  31592. rect.y + rect.height / 2
  31593. ];
  31594. }
  31595. else {
  31596. cp = [cp[0], cp[1]];
  31597. }
  31598. /**
  31599. * @type {Array.<number>}
  31600. */
  31601. this.center = cp;
  31602. }
  31603. Region.prototype = {
  31604. constructor: Region,
  31605. properties: null,
  31606. /**
  31607. * @return {module:zrender/core/BoundingRect}
  31608. */
  31609. getBoundingRect: function () {
  31610. var rect = this._rect;
  31611. if (rect) {
  31612. return rect;
  31613. }
  31614. var MAX_NUMBER = Number.MAX_VALUE;
  31615. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  31616. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  31617. var min2 = [];
  31618. var max2 = [];
  31619. var geometries = this.geometries;
  31620. for (var i = 0; i < geometries.length; i++) {
  31621. // Only support polygon
  31622. if (geometries[i].type !== 'polygon') {
  31623. continue;
  31624. }
  31625. // Doesn't consider hole
  31626. var exterior = geometries[i].exterior;
  31627. fromPoints(exterior, min2, max2);
  31628. min(min$$1, min$$1, min2);
  31629. max(max$$1, max$$1, max2);
  31630. }
  31631. // No data
  31632. if (i === 0) {
  31633. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  31634. }
  31635. return (this._rect = new BoundingRect(
  31636. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  31637. ));
  31638. },
  31639. /**
  31640. * @param {<Array.<number>} coord
  31641. * @return {boolean}
  31642. */
  31643. contain: function (coord) {
  31644. var rect = this.getBoundingRect();
  31645. var geometries = this.geometries;
  31646. if (!rect.contain(coord[0], coord[1])) {
  31647. return false;
  31648. }
  31649. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  31650. // Only support polygon.
  31651. if (geometries[i].type !== 'polygon') {
  31652. continue;
  31653. }
  31654. var exterior = geometries[i].exterior;
  31655. var interiors = geometries[i].interiors;
  31656. if (contain$1(exterior, coord[0], coord[1])) {
  31657. // Not in the region if point is in the hole.
  31658. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31659. if (contain$1(interiors[k])) {
  31660. continue loopGeo;
  31661. }
  31662. }
  31663. return true;
  31664. }
  31665. }
  31666. return false;
  31667. },
  31668. transformTo: function (x, y, width, height) {
  31669. var rect = this.getBoundingRect();
  31670. var aspect = rect.width / rect.height;
  31671. if (!width) {
  31672. width = aspect * height;
  31673. }
  31674. else if (!height) {
  31675. height = width / aspect;
  31676. }
  31677. var target = new BoundingRect(x, y, width, height);
  31678. var transform = rect.calculateTransform(target);
  31679. var geometries = this.geometries;
  31680. for (var i = 0; i < geometries.length; i++) {
  31681. // Only support polygon.
  31682. if (geometries[i].type !== 'polygon') {
  31683. continue;
  31684. }
  31685. var exterior = geometries[i].exterior;
  31686. var interiors = geometries[i].interiors;
  31687. for (var p = 0; p < exterior.length; p++) {
  31688. applyTransform(exterior[p], exterior[p], transform);
  31689. }
  31690. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  31691. for (var p = 0; p < interiors[h].length; p++) {
  31692. applyTransform(interiors[h][p], interiors[h][p], transform);
  31693. }
  31694. }
  31695. }
  31696. rect = this._rect;
  31697. rect.copy(target);
  31698. // Update center
  31699. this.center = [
  31700. rect.x + rect.width / 2,
  31701. rect.y + rect.height / 2
  31702. ];
  31703. },
  31704. cloneShallow: function (name) {
  31705. name == null && (name = this.name);
  31706. var newRegion = new Region(name, this.geometries, this.center);
  31707. newRegion._rect = this._rect;
  31708. newRegion.transformTo = null; // Simply avoid to be called.
  31709. return newRegion;
  31710. }
  31711. };
  31712. /*
  31713. * Licensed to the Apache Software Foundation (ASF) under one
  31714. * or more contributor license agreements. See the NOTICE file
  31715. * distributed with this work for additional information
  31716. * regarding copyright ownership. The ASF licenses this file
  31717. * to you under the Apache License, Version 2.0 (the
  31718. * "License"); you may not use this file except in compliance
  31719. * with the License. You may obtain a copy of the License at
  31720. *
  31721. * http://www.apache.org/licenses/LICENSE-2.0
  31722. *
  31723. * Unless required by applicable law or agreed to in writing,
  31724. * software distributed under the License is distributed on an
  31725. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31726. * KIND, either express or implied. See the License for the
  31727. * specific language governing permissions and limitations
  31728. * under the License.
  31729. */
  31730. /**
  31731. * Parse and decode geo json
  31732. * @module echarts/coord/geo/parseGeoJson
  31733. */
  31734. function decode(json) {
  31735. if (!json.UTF8Encoding) {
  31736. return json;
  31737. }
  31738. var encodeScale = json.UTF8Scale;
  31739. if (encodeScale == null) {
  31740. encodeScale = 1024;
  31741. }
  31742. var features = json.features;
  31743. for (var f = 0; f < features.length; f++) {
  31744. var feature = features[f];
  31745. var geometry = feature.geometry;
  31746. var coordinates = geometry.coordinates;
  31747. var encodeOffsets = geometry.encodeOffsets;
  31748. for (var c = 0; c < coordinates.length; c++) {
  31749. var coordinate = coordinates[c];
  31750. if (geometry.type === 'Polygon') {
  31751. coordinates[c] = decodePolygon(
  31752. coordinate,
  31753. encodeOffsets[c],
  31754. encodeScale
  31755. );
  31756. }
  31757. else if (geometry.type === 'MultiPolygon') {
  31758. for (var c2 = 0; c2 < coordinate.length; c2++) {
  31759. var polygon = coordinate[c2];
  31760. coordinate[c2] = decodePolygon(
  31761. polygon,
  31762. encodeOffsets[c][c2],
  31763. encodeScale
  31764. );
  31765. }
  31766. }
  31767. }
  31768. }
  31769. // Has been decoded
  31770. json.UTF8Encoding = false;
  31771. return json;
  31772. }
  31773. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  31774. var result = [];
  31775. var prevX = encodeOffsets[0];
  31776. var prevY = encodeOffsets[1];
  31777. for (var i = 0; i < coordinate.length; i += 2) {
  31778. var x = coordinate.charCodeAt(i) - 64;
  31779. var y = coordinate.charCodeAt(i + 1) - 64;
  31780. // ZigZag decoding
  31781. x = (x >> 1) ^ (-(x & 1));
  31782. y = (y >> 1) ^ (-(y & 1));
  31783. // Delta deocding
  31784. x += prevX;
  31785. y += prevY;
  31786. prevX = x;
  31787. prevY = y;
  31788. // Dequantize
  31789. result.push([x / encodeScale, y / encodeScale]);
  31790. }
  31791. return result;
  31792. }
  31793. /**
  31794. * @alias module:echarts/coord/geo/parseGeoJson
  31795. * @param {Object} geoJson
  31796. * @param {string} nameProperty
  31797. * @return {module:zrender/container/Group}
  31798. */
  31799. var parseGeoJSON = function (geoJson, nameProperty) {
  31800. decode(geoJson);
  31801. return map(filter(geoJson.features, function (featureObj) {
  31802. // Output of mapshaper may have geometry null
  31803. return featureObj.geometry
  31804. && featureObj.properties
  31805. && featureObj.geometry.coordinates.length > 0;
  31806. }), function (featureObj) {
  31807. var properties = featureObj.properties;
  31808. var geo = featureObj.geometry;
  31809. var coordinates = geo.coordinates;
  31810. var geometries = [];
  31811. if (geo.type === 'Polygon') {
  31812. geometries.push({
  31813. type: 'polygon',
  31814. // According to the GeoJSON specification.
  31815. // First must be exterior, and the rest are all interior(holes).
  31816. exterior: coordinates[0],
  31817. interiors: coordinates.slice(1)
  31818. });
  31819. }
  31820. if (geo.type === 'MultiPolygon') {
  31821. each$1(coordinates, function (item) {
  31822. if (item[0]) {
  31823. geometries.push({
  31824. type: 'polygon',
  31825. exterior: item[0],
  31826. interiors: item.slice(1)
  31827. });
  31828. }
  31829. });
  31830. }
  31831. var region = new Region(
  31832. properties[nameProperty || 'name'],
  31833. geometries,
  31834. properties.cp
  31835. );
  31836. region.properties = properties;
  31837. return region;
  31838. });
  31839. };
  31840. /*
  31841. * Licensed to the Apache Software Foundation (ASF) under one
  31842. * or more contributor license agreements. See the NOTICE file
  31843. * distributed with this work for additional information
  31844. * regarding copyright ownership. The ASF licenses this file
  31845. * to you under the Apache License, Version 2.0 (the
  31846. * "License"); you may not use this file except in compliance
  31847. * with the License. You may obtain a copy of the License at
  31848. *
  31849. * http://www.apache.org/licenses/LICENSE-2.0
  31850. *
  31851. * Unless required by applicable law or agreed to in writing,
  31852. * software distributed under the License is distributed on an
  31853. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31854. * KIND, either express or implied. See the License for the
  31855. * specific language governing permissions and limitations
  31856. * under the License.
  31857. */
  31858. var inner$6 = makeInner();
  31859. /**
  31860. * @param {module:echats/coord/Axis} axis
  31861. * @return {Object} {
  31862. * labels: [{
  31863. * formattedLabel: string,
  31864. * rawLabel: string,
  31865. * tickValue: number
  31866. * }, ...],
  31867. * labelCategoryInterval: number
  31868. * }
  31869. */
  31870. function createAxisLabels(axis) {
  31871. // Only ordinal scale support tick interval
  31872. return axis.type === 'category'
  31873. ? makeCategoryLabels(axis)
  31874. : makeRealNumberLabels(axis);
  31875. }
  31876. /**
  31877. * @param {module:echats/coord/Axis} axis
  31878. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31879. * @return {Object} {
  31880. * ticks: Array.<number>
  31881. * tickCategoryInterval: number
  31882. * }
  31883. */
  31884. function createAxisTicks(axis, tickModel) {
  31885. // Only ordinal scale support tick interval
  31886. return axis.type === 'category'
  31887. ? makeCategoryTicks(axis, tickModel)
  31888. : {ticks: axis.scale.getTicks()};
  31889. }
  31890. function makeCategoryLabels(axis) {
  31891. var labelModel = axis.getLabelModel();
  31892. var result = makeCategoryLabelsActually(axis, labelModel);
  31893. return (!labelModel.get('show') || axis.scale.isBlank())
  31894. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  31895. : result;
  31896. }
  31897. function makeCategoryLabelsActually(axis, labelModel) {
  31898. var labelsCache = getListCache(axis, 'labels');
  31899. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31900. var result = listCacheGet(labelsCache, optionLabelInterval);
  31901. if (result) {
  31902. return result;
  31903. }
  31904. var labels;
  31905. var numericLabelInterval;
  31906. if (isFunction$1(optionLabelInterval)) {
  31907. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31908. }
  31909. else {
  31910. numericLabelInterval = optionLabelInterval === 'auto'
  31911. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31912. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31913. }
  31914. // Cache to avoid calling interval function repeatly.
  31915. return listCacheSet(labelsCache, optionLabelInterval, {
  31916. labels: labels, labelCategoryInterval: numericLabelInterval
  31917. });
  31918. }
  31919. function makeCategoryTicks(axis, tickModel) {
  31920. var ticksCache = getListCache(axis, 'ticks');
  31921. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31922. var result = listCacheGet(ticksCache, optionTickInterval);
  31923. if (result) {
  31924. return result;
  31925. }
  31926. var ticks;
  31927. var tickCategoryInterval;
  31928. // Optimize for the case that large category data and no label displayed,
  31929. // we should not return all ticks.
  31930. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31931. ticks = [];
  31932. }
  31933. if (isFunction$1(optionTickInterval)) {
  31934. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31935. }
  31936. // Always use label interval by default despite label show. Consider this
  31937. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31938. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31939. else if (optionTickInterval === 'auto') {
  31940. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31941. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31942. ticks = map(labelsResult.labels, function (labelItem) {
  31943. return labelItem.tickValue;
  31944. });
  31945. }
  31946. else {
  31947. tickCategoryInterval = optionTickInterval;
  31948. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31949. }
  31950. // Cache to avoid calling interval function repeatly.
  31951. return listCacheSet(ticksCache, optionTickInterval, {
  31952. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  31953. });
  31954. }
  31955. function makeRealNumberLabels(axis) {
  31956. var ticks = axis.scale.getTicks();
  31957. var labelFormatter = makeLabelFormatter(axis);
  31958. return {
  31959. labels: map(ticks, function (tickValue, idx) {
  31960. return {
  31961. formattedLabel: labelFormatter(tickValue, idx),
  31962. rawLabel: axis.scale.getLabel(tickValue),
  31963. tickValue: tickValue
  31964. };
  31965. })
  31966. };
  31967. }
  31968. // Large category data calculation is performence sensitive, and ticks and label
  31969. // probably be fetched by multiple times. So we cache the result.
  31970. // axis is created each time during a ec process, so we do not need to clear cache.
  31971. function getListCache(axis, prop) {
  31972. // Because key can be funciton, and cache size always be small, we use array cache.
  31973. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  31974. }
  31975. function listCacheGet(cache, key) {
  31976. for (var i = 0; i < cache.length; i++) {
  31977. if (cache[i].key === key) {
  31978. return cache[i].value;
  31979. }
  31980. }
  31981. }
  31982. function listCacheSet(cache, key, value) {
  31983. cache.push({key: key, value: value});
  31984. return value;
  31985. }
  31986. function makeAutoCategoryInterval(axis) {
  31987. var result = inner$6(axis).autoInterval;
  31988. return result != null
  31989. ? result
  31990. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  31991. }
  31992. /**
  31993. * Calculate interval for category axis ticks and labels.
  31994. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31995. * should be implemented in axis.
  31996. */
  31997. function calculateCategoryInterval(axis) {
  31998. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31999. var labelFormatter = makeLabelFormatter(axis);
  32000. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32001. var ordinalScale = axis.scale;
  32002. var ordinalExtent = ordinalScale.getExtent();
  32003. // Providing this method is for optimization:
  32004. // avoid generating a long array by `getTicks`
  32005. // in large category data case.
  32006. var tickCount = ordinalScale.count();
  32007. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32008. return 0;
  32009. }
  32010. var step = 1;
  32011. // Simple optimization. Empirical value: tick count should less than 40.
  32012. if (tickCount > 40) {
  32013. step = Math.max(1, Math.floor(tickCount / 40));
  32014. }
  32015. var tickValue = ordinalExtent[0];
  32016. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32017. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32018. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32019. var maxW = 0;
  32020. var maxH = 0;
  32021. // Caution: Performance sensitive for large category data.
  32022. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32023. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32024. var width = 0;
  32025. var height = 0;
  32026. // Not precise, do not consider align and vertical align
  32027. // and each distance from axis line yet.
  32028. var rect = getBoundingRect(
  32029. labelFormatter(tickValue), params.font, 'center', 'top'
  32030. );
  32031. // Magic number
  32032. width = rect.width * 1.3;
  32033. height = rect.height * 1.3;
  32034. // Min size, void long loop.
  32035. maxW = Math.max(maxW, width, 7);
  32036. maxH = Math.max(maxH, height, 7);
  32037. }
  32038. var dw = maxW / unitW;
  32039. var dh = maxH / unitH;
  32040. // 0/0 is NaN, 1/0 is Infinity.
  32041. isNaN(dw) && (dw = Infinity);
  32042. isNaN(dh) && (dh = Infinity);
  32043. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32044. var cache = inner$6(axis.model);
  32045. var axisExtent = axis.getExtent();
  32046. var lastAutoInterval = cache.lastAutoInterval;
  32047. var lastTickCount = cache.lastTickCount;
  32048. // Use cache to keep interval stable while moving zoom window,
  32049. // otherwise the calculated interval might jitter when the zoom
  32050. // window size is close to the interval-changing size.
  32051. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32052. // The jitter will cause that sometimes the displayed labels are
  32053. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32054. if (lastAutoInterval != null
  32055. && lastTickCount != null
  32056. && Math.abs(lastAutoInterval - interval) <= 1
  32057. && Math.abs(lastTickCount - tickCount) <= 1
  32058. // Always choose the bigger one, otherwise the critical
  32059. // point is not the same when zooming in or zooming out.
  32060. && lastAutoInterval > interval
  32061. // If the axis change is caused by chart resize, the cache should not
  32062. // be used. Otherwise some hiden labels might not be shown again.
  32063. && cache.axisExtend0 === axisExtent[0]
  32064. && cache.axisExtend1 === axisExtent[1]
  32065. ) {
  32066. interval = lastAutoInterval;
  32067. }
  32068. // Only update cache if cache not used, otherwise the
  32069. // changing of interval is too insensitive.
  32070. else {
  32071. cache.lastTickCount = tickCount;
  32072. cache.lastAutoInterval = interval;
  32073. cache.axisExtend0 = axisExtent[0];
  32074. cache.axisExtend1 = axisExtent[1];
  32075. }
  32076. return interval;
  32077. }
  32078. function fetchAutoCategoryIntervalCalculationParams(axis) {
  32079. var labelModel = axis.getLabelModel();
  32080. return {
  32081. axisRotate: axis.getRotate
  32082. ? axis.getRotate()
  32083. : (axis.isHorizontal && !axis.isHorizontal())
  32084. ? 90
  32085. : 0,
  32086. labelRotate: labelModel.get('rotate') || 0,
  32087. font: labelModel.getFont()
  32088. };
  32089. }
  32090. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32091. var labelFormatter = makeLabelFormatter(axis);
  32092. var ordinalScale = axis.scale;
  32093. var ordinalExtent = ordinalScale.getExtent();
  32094. var labelModel = axis.getLabelModel();
  32095. var result = [];
  32096. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32097. var step = Math.max((categoryInterval || 0) + 1, 1);
  32098. var startTick = ordinalExtent[0];
  32099. var tickCount = ordinalScale.count();
  32100. // Calculate start tick based on zero if possible to keep label consistent
  32101. // while zooming and moving while interval > 0. Otherwise the selection
  32102. // of displayable ticks and symbols probably keep changing.
  32103. // 3 is empirical value.
  32104. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32105. startTick = Math.round(Math.ceil(startTick / step) * step);
  32106. }
  32107. // (1) Only add min max label here but leave overlap checking
  32108. // to render stage, which also ensure the returned list
  32109. // suitable for splitLine and splitArea rendering.
  32110. // (2) Scales except category always contain min max label so
  32111. // do not need to perform this process.
  32112. var showAllLabel = shouldShowAllLabels(axis);
  32113. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32114. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32115. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32116. addItem(ordinalExtent[0]);
  32117. }
  32118. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32119. var tickValue = startTick;
  32120. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32121. addItem(tickValue);
  32122. }
  32123. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32124. addItem(ordinalExtent[1]);
  32125. }
  32126. function addItem(tVal) {
  32127. result.push(onlyTick
  32128. ? tVal
  32129. : {
  32130. formattedLabel: labelFormatter(tVal),
  32131. rawLabel: ordinalScale.getLabel(tVal),
  32132. tickValue: tVal
  32133. }
  32134. );
  32135. }
  32136. return result;
  32137. }
  32138. // When interval is function, the result `false` means ignore the tick.
  32139. // It is time consuming for large category data.
  32140. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32141. var ordinalScale = axis.scale;
  32142. var labelFormatter = makeLabelFormatter(axis);
  32143. var result = [];
  32144. each$1(ordinalScale.getTicks(), function (tickValue) {
  32145. var rawLabel = ordinalScale.getLabel(tickValue);
  32146. if (categoryInterval(tickValue, rawLabel)) {
  32147. result.push(onlyTick
  32148. ? tickValue
  32149. : {
  32150. formattedLabel: labelFormatter(tickValue),
  32151. rawLabel: rawLabel,
  32152. tickValue: tickValue
  32153. }
  32154. );
  32155. }
  32156. });
  32157. return result;
  32158. }
  32159. /*
  32160. * Licensed to the Apache Software Foundation (ASF) under one
  32161. * or more contributor license agreements. See the NOTICE file
  32162. * distributed with this work for additional information
  32163. * regarding copyright ownership. The ASF licenses this file
  32164. * to you under the Apache License, Version 2.0 (the
  32165. * "License"); you may not use this file except in compliance
  32166. * with the License. You may obtain a copy of the License at
  32167. *
  32168. * http://www.apache.org/licenses/LICENSE-2.0
  32169. *
  32170. * Unless required by applicable law or agreed to in writing,
  32171. * software distributed under the License is distributed on an
  32172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32173. * KIND, either express or implied. See the License for the
  32174. * specific language governing permissions and limitations
  32175. * under the License.
  32176. */
  32177. var NORMALIZED_EXTENT = [0, 1];
  32178. /**
  32179. * Base class of Axis.
  32180. * @constructor
  32181. */
  32182. var Axis = function (dim, scale, extent) {
  32183. /**
  32184. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  32185. * @type {string}
  32186. */
  32187. this.dim = dim;
  32188. /**
  32189. * Axis scale
  32190. * @type {module:echarts/coord/scale/*}
  32191. */
  32192. this.scale = scale;
  32193. /**
  32194. * @type {Array.<number>}
  32195. * @private
  32196. */
  32197. this._extent = extent || [0, 0];
  32198. /**
  32199. * @type {boolean}
  32200. */
  32201. this.inverse = false;
  32202. /**
  32203. * Usually true when axis has a ordinal scale
  32204. * @type {boolean}
  32205. */
  32206. this.onBand = false;
  32207. };
  32208. Axis.prototype = {
  32209. constructor: Axis,
  32210. /**
  32211. * If axis extent contain given coord
  32212. * @param {number} coord
  32213. * @return {boolean}
  32214. */
  32215. contain: function (coord) {
  32216. var extent = this._extent;
  32217. var min = Math.min(extent[0], extent[1]);
  32218. var max = Math.max(extent[0], extent[1]);
  32219. return coord >= min && coord <= max;
  32220. },
  32221. /**
  32222. * If axis extent contain given data
  32223. * @param {number} data
  32224. * @return {boolean}
  32225. */
  32226. containData: function (data) {
  32227. return this.scale.contain(data);
  32228. },
  32229. /**
  32230. * Get coord extent.
  32231. * @return {Array.<number>}
  32232. */
  32233. getExtent: function () {
  32234. return this._extent.slice();
  32235. },
  32236. /**
  32237. * Get precision used for formatting
  32238. * @param {Array.<number>} [dataExtent]
  32239. * @return {number}
  32240. */
  32241. getPixelPrecision: function (dataExtent) {
  32242. return getPixelPrecision(
  32243. dataExtent || this.scale.getExtent(),
  32244. this._extent
  32245. );
  32246. },
  32247. /**
  32248. * Set coord extent
  32249. * @param {number} start
  32250. * @param {number} end
  32251. */
  32252. setExtent: function (start, end) {
  32253. var extent = this._extent;
  32254. extent[0] = start;
  32255. extent[1] = end;
  32256. },
  32257. /**
  32258. * Convert data to coord. Data is the rank if it has an ordinal scale
  32259. * @param {number} data
  32260. * @param {boolean} clamp
  32261. * @return {number}
  32262. */
  32263. dataToCoord: function (data, clamp) {
  32264. var extent = this._extent;
  32265. var scale = this.scale;
  32266. data = scale.normalize(data);
  32267. if (this.onBand && scale.type === 'ordinal') {
  32268. extent = extent.slice();
  32269. fixExtentWithBands(extent, scale.count());
  32270. }
  32271. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32272. },
  32273. /**
  32274. * Convert coord to data. Data is the rank if it has an ordinal scale
  32275. * @param {number} coord
  32276. * @param {boolean} clamp
  32277. * @return {number}
  32278. */
  32279. coordToData: function (coord, clamp) {
  32280. var extent = this._extent;
  32281. var scale = this.scale;
  32282. if (this.onBand && scale.type === 'ordinal') {
  32283. extent = extent.slice();
  32284. fixExtentWithBands(extent, scale.count());
  32285. }
  32286. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32287. return this.scale.scale(t);
  32288. },
  32289. /**
  32290. * Convert pixel point to data in axis
  32291. * @param {Array.<number>} point
  32292. * @param {boolean} clamp
  32293. * @return {number} data
  32294. */
  32295. pointToData: function (point, clamp) {
  32296. // Should be implemented in derived class if necessary.
  32297. },
  32298. /**
  32299. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32300. * `axis.getTicksCoords` considers `onBand`, which is used by
  32301. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32302. * @param {Object} [opt]
  32303. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  32304. * @param {boolean} [opt.clamp] If `true`, the first and the last
  32305. * tick must be at the axis end points. Otherwise, clip ticks
  32306. * that outside the axis extent.
  32307. * @return {Array.<Object>} [{
  32308. * coord: ...,
  32309. * tickValue: ...
  32310. * }, ...]
  32311. */
  32312. getTicksCoords: function (opt) {
  32313. opt = opt || {};
  32314. var tickModel = opt.tickModel || this.getTickModel();
  32315. var result = createAxisTicks(this, tickModel);
  32316. var ticks = result.ticks;
  32317. var ticksCoords = map(ticks, function (tickValue) {
  32318. return {
  32319. coord: this.dataToCoord(tickValue),
  32320. tickValue: tickValue
  32321. };
  32322. }, this);
  32323. var alignWithLabel = tickModel.get('alignWithLabel');
  32324. fixOnBandTicksCoords(
  32325. this, ticksCoords, alignWithLabel, opt.clamp
  32326. );
  32327. return ticksCoords;
  32328. },
  32329. /**
  32330. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  32331. */
  32332. getMinorTicksCoords: function () {
  32333. if (this.scale.type === 'ordinal') {
  32334. // Category axis doesn't support minor ticks
  32335. return [];
  32336. }
  32337. var minorTickModel = this.model.getModel('minorTick');
  32338. var splitNumber = minorTickModel.get('splitNumber');
  32339. // Protection.
  32340. if (!(splitNumber > 0 && splitNumber < 100)) {
  32341. splitNumber = 5;
  32342. }
  32343. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32344. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32345. return map(minorTicksGroup, function (minorTick) {
  32346. return {
  32347. coord: this.dataToCoord(minorTick),
  32348. tickValue: minorTick
  32349. };
  32350. }, this);
  32351. }, this);
  32352. return minorTicksCoords;
  32353. },
  32354. /**
  32355. * @return {Array.<Object>} [{
  32356. * formattedLabel: string,
  32357. * rawLabel: axis.scale.getLabel(tickValue)
  32358. * tickValue: number
  32359. * }, ...]
  32360. */
  32361. getViewLabels: function () {
  32362. return createAxisLabels(this).labels;
  32363. },
  32364. /**
  32365. * @return {module:echarts/coord/model/Model}
  32366. */
  32367. getLabelModel: function () {
  32368. return this.model.getModel('axisLabel');
  32369. },
  32370. /**
  32371. * Notice here we only get the default tick model. For splitLine
  32372. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32373. * manually when calling `getTicksCoords`.
  32374. * In GL, this method may be overrided to:
  32375. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32376. * @return {module:echarts/coord/model/Model}
  32377. */
  32378. getTickModel: function () {
  32379. return this.model.getModel('axisTick');
  32380. },
  32381. /**
  32382. * Get width of band
  32383. * @return {number}
  32384. */
  32385. getBandWidth: function () {
  32386. var axisExtent = this._extent;
  32387. var dataExtent = this.scale.getExtent();
  32388. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32389. // Fix #2728, avoid NaN when only one data.
  32390. len === 0 && (len = 1);
  32391. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32392. return Math.abs(size) / len;
  32393. },
  32394. /**
  32395. * @abstract
  32396. * @return {boolean} Is horizontal
  32397. */
  32398. isHorizontal: null,
  32399. /**
  32400. * @abstract
  32401. * @return {number} Get axis rotate, by degree.
  32402. */
  32403. getRotate: null,
  32404. /**
  32405. * Only be called in category axis.
  32406. * Can be overrided, consider other axes like in 3D.
  32407. * @return {number} Auto interval for cateogry axis tick and label
  32408. */
  32409. calculateCategoryInterval: function () {
  32410. return calculateCategoryInterval(this);
  32411. }
  32412. };
  32413. function fixExtentWithBands(extent, nTick) {
  32414. var size = extent[1] - extent[0];
  32415. var len = nTick;
  32416. var margin = size / len / 2;
  32417. extent[0] += margin;
  32418. extent[1] -= margin;
  32419. }
  32420. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32421. // |---1---|---2---|---3---|---4---|.
  32422. // So the displayed ticks and splitLine/splitArea should between
  32423. // each data item, otherwise cause misleading (e.g., split tow bars
  32424. // of a single data item when there are two bar series).
  32425. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32426. // splitLine/spliteArea should layout appropriately corresponding
  32427. // to displayed labels. (So we should not use `getBandWidth` in this
  32428. // case).
  32429. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32430. var ticksLen = ticksCoords.length;
  32431. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32432. return;
  32433. }
  32434. var axisExtent = axis.getExtent();
  32435. var last;
  32436. var diffSize;
  32437. if (ticksLen === 1) {
  32438. ticksCoords[0].coord = axisExtent[0];
  32439. last = ticksCoords[1] = {coord: axisExtent[0]};
  32440. }
  32441. else {
  32442. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32443. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32444. each$1(ticksCoords, function (ticksItem) {
  32445. ticksItem.coord -= shift / 2;
  32446. });
  32447. var dataExtent = axis.scale.getExtent();
  32448. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32449. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  32450. ticksCoords.push(last);
  32451. }
  32452. var inverse = axisExtent[0] > axisExtent[1];
  32453. // Handling clamp.
  32454. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32455. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  32456. }
  32457. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32458. ticksCoords.unshift({coord: axisExtent[0]});
  32459. }
  32460. if (littleThan(axisExtent[1], last.coord)) {
  32461. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  32462. }
  32463. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32464. ticksCoords.push({coord: axisExtent[1]});
  32465. }
  32466. function littleThan(a, b) {
  32467. // Avoid rounding error cause calculated tick coord different with extent.
  32468. // It may cause an extra unecessary tick added.
  32469. a = round$1(a);
  32470. b = round$1(b);
  32471. return inverse ? a > b : a < b;
  32472. }
  32473. }
  32474. /*
  32475. * Licensed to the Apache Software Foundation (ASF) under one
  32476. * or more contributor license agreements. See the NOTICE file
  32477. * distributed with this work for additional information
  32478. * regarding copyright ownership. The ASF licenses this file
  32479. * to you under the Apache License, Version 2.0 (the
  32480. * "License"); you may not use this file except in compliance
  32481. * with the License. You may obtain a copy of the License at
  32482. *
  32483. * http://www.apache.org/licenses/LICENSE-2.0
  32484. *
  32485. * Unless required by applicable law or agreed to in writing,
  32486. * software distributed under the License is distributed on an
  32487. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32488. * KIND, either express or implied. See the License for the
  32489. * specific language governing permissions and limitations
  32490. * under the License.
  32491. */
  32492. /**
  32493. * Do not mount those modules on 'src/echarts' for better tree shaking.
  32494. */
  32495. var parseGeoJson = parseGeoJSON;
  32496. var ecUtil = {};
  32497. each$1(
  32498. [
  32499. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  32500. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  32501. 'extend', 'defaults', 'clone', 'merge'
  32502. ],
  32503. function (name) {
  32504. ecUtil[name] = zrUtil[name];
  32505. }
  32506. );
  32507. var graphic$1 = {};
  32508. each$1(
  32509. [
  32510. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  32511. 'mergePath', 'resizePath', 'createIcon',
  32512. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  32513. 'getFont', 'updateProps', 'initProps', 'getTransform',
  32514. 'clipPointsByRect', 'clipRectByRect',
  32515. 'registerShape', 'getShapeClass',
  32516. 'Group',
  32517. 'Image',
  32518. 'Text',
  32519. 'Circle',
  32520. 'Sector',
  32521. 'Ring',
  32522. 'Polygon',
  32523. 'Polyline',
  32524. 'Rect',
  32525. 'Line',
  32526. 'BezierCurve',
  32527. 'Arc',
  32528. 'IncrementalDisplayable',
  32529. 'CompoundPath',
  32530. 'LinearGradient',
  32531. 'RadialGradient',
  32532. 'BoundingRect'
  32533. ],
  32534. function (name) {
  32535. graphic$1[name] = graphic[name];
  32536. }
  32537. );
  32538. /*
  32539. * Licensed to the Apache Software Foundation (ASF) under one
  32540. * or more contributor license agreements. See the NOTICE file
  32541. * distributed with this work for additional information
  32542. * regarding copyright ownership. The ASF licenses this file
  32543. * to you under the Apache License, Version 2.0 (the
  32544. * "License"); you may not use this file except in compliance
  32545. * with the License. You may obtain a copy of the License at
  32546. *
  32547. * http://www.apache.org/licenses/LICENSE-2.0
  32548. *
  32549. * Unless required by applicable law or agreed to in writing,
  32550. * software distributed under the License is distributed on an
  32551. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32552. * KIND, either express or implied. See the License for the
  32553. * specific language governing permissions and limitations
  32554. * under the License.
  32555. */
  32556. SeriesModel.extend({
  32557. type: 'series.line',
  32558. dependencies: ['grid', 'polar'],
  32559. getInitialData: function (option, ecModel) {
  32560. if (__DEV__) {
  32561. var coordSys = option.coordinateSystem;
  32562. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  32563. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  32564. }
  32565. }
  32566. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  32567. },
  32568. defaultOption: {
  32569. zlevel: 0,
  32570. z: 2,
  32571. coordinateSystem: 'cartesian2d',
  32572. legendHoverLink: true,
  32573. hoverAnimation: true,
  32574. // stack: null
  32575. // xAxisIndex: 0,
  32576. // yAxisIndex: 0,
  32577. // polarIndex: 0,
  32578. // If clip the overflow value
  32579. clip: true,
  32580. // cursor: null,
  32581. label: {
  32582. position: 'top'
  32583. },
  32584. // itemStyle: {
  32585. // },
  32586. lineStyle: {
  32587. width: 2,
  32588. type: 'solid'
  32589. },
  32590. // areaStyle: {
  32591. // origin of areaStyle. Valid values:
  32592. // `'auto'/null/undefined`: from axisLine to data
  32593. // `'start'`: from min to data
  32594. // `'end'`: from data to max
  32595. // origin: 'auto'
  32596. // },
  32597. // false, 'start', 'end', 'middle'
  32598. step: false,
  32599. // Disabled if step is true
  32600. smooth: false,
  32601. smoothMonotone: null,
  32602. symbol: 'emptyCircle',
  32603. symbolSize: 4,
  32604. symbolRotate: null,
  32605. showSymbol: true,
  32606. // `false`: follow the label interval strategy.
  32607. // `true`: show all symbols.
  32608. // `'auto'`: If possible, show all symbols, otherwise
  32609. // follow the label interval strategy.
  32610. showAllSymbol: 'auto',
  32611. // Whether to connect break point.
  32612. connectNulls: false,
  32613. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  32614. sampling: 'none',
  32615. animationEasing: 'linear',
  32616. // Disable progressive
  32617. progressive: 0,
  32618. hoverLayerThreshold: Infinity
  32619. }
  32620. });
  32621. /*
  32622. * Licensed to the Apache Software Foundation (ASF) under one
  32623. * or more contributor license agreements. See the NOTICE file
  32624. * distributed with this work for additional information
  32625. * regarding copyright ownership. The ASF licenses this file
  32626. * to you under the Apache License, Version 2.0 (the
  32627. * "License"); you may not use this file except in compliance
  32628. * with the License. You may obtain a copy of the License at
  32629. *
  32630. * http://www.apache.org/licenses/LICENSE-2.0
  32631. *
  32632. * Unless required by applicable law or agreed to in writing,
  32633. * software distributed under the License is distributed on an
  32634. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32635. * KIND, either express or implied. See the License for the
  32636. * specific language governing permissions and limitations
  32637. * under the License.
  32638. */
  32639. /**
  32640. * @param {module:echarts/data/List} data
  32641. * @param {number} dataIndex
  32642. * @return {string} label string. Not null/undefined
  32643. */
  32644. function getDefaultLabel(data, dataIndex) {
  32645. var labelDims = data.mapDimension('defaultedLabel', true);
  32646. var len = labelDims.length;
  32647. // Simple optimization (in lots of cases, label dims length is 1)
  32648. if (len === 1) {
  32649. return retrieveRawValue(data, dataIndex, labelDims[0]);
  32650. }
  32651. else if (len) {
  32652. var vals = [];
  32653. for (var i = 0; i < labelDims.length; i++) {
  32654. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  32655. vals.push(val);
  32656. }
  32657. return vals.join(' ');
  32658. }
  32659. }
  32660. /*
  32661. * Licensed to the Apache Software Foundation (ASF) under one
  32662. * or more contributor license agreements. See the NOTICE file
  32663. * distributed with this work for additional information
  32664. * regarding copyright ownership. The ASF licenses this file
  32665. * to you under the Apache License, Version 2.0 (the
  32666. * "License"); you may not use this file except in compliance
  32667. * with the License. You may obtain a copy of the License at
  32668. *
  32669. * http://www.apache.org/licenses/LICENSE-2.0
  32670. *
  32671. * Unless required by applicable law or agreed to in writing,
  32672. * software distributed under the License is distributed on an
  32673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32674. * KIND, either express or implied. See the License for the
  32675. * specific language governing permissions and limitations
  32676. * under the License.
  32677. */
  32678. /**
  32679. * @module echarts/chart/helper/Symbol
  32680. */
  32681. /**
  32682. * @constructor
  32683. * @alias {module:echarts/chart/helper/Symbol}
  32684. * @param {module:echarts/data/List} data
  32685. * @param {number} idx
  32686. * @extends {module:zrender/graphic/Group}
  32687. */
  32688. function SymbolClz$1(data, idx, seriesScope) {
  32689. Group.call(this);
  32690. this.updateData(data, idx, seriesScope);
  32691. }
  32692. var symbolProto = SymbolClz$1.prototype;
  32693. /**
  32694. * @public
  32695. * @static
  32696. * @param {module:echarts/data/List} data
  32697. * @param {number} dataIndex
  32698. * @return {Array.<number>} [width, height]
  32699. */
  32700. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  32701. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  32702. return symbolSize instanceof Array
  32703. ? symbolSize.slice()
  32704. : [+symbolSize, +symbolSize];
  32705. };
  32706. function getScale(symbolSize) {
  32707. return [symbolSize[0] / 2, symbolSize[1] / 2];
  32708. }
  32709. function driftSymbol(dx, dy) {
  32710. this.parent.drift(dx, dy);
  32711. }
  32712. symbolProto._createSymbol = function (
  32713. symbolType,
  32714. data,
  32715. idx,
  32716. symbolSize,
  32717. keepAspect
  32718. ) {
  32719. // Remove paths created before
  32720. this.removeAll();
  32721. var color = data.getItemVisual(idx, 'color');
  32722. // var symbolPath = createSymbol(
  32723. // symbolType, -0.5, -0.5, 1, 1, color
  32724. // );
  32725. // If width/height are set too small (e.g., set to 1) on ios10
  32726. // and macOS Sierra, a circle stroke become a rect, no matter what
  32727. // the scale is set. So we set width/height as 2. See #4150.
  32728. var symbolPath = createSymbol(
  32729. symbolType, -1, -1, 2, 2, color, keepAspect
  32730. );
  32731. symbolPath.attr({
  32732. z2: 100,
  32733. culling: true,
  32734. scale: getScale(symbolSize)
  32735. });
  32736. // Rewrite drift method
  32737. symbolPath.drift = driftSymbol;
  32738. this._symbolType = symbolType;
  32739. this.add(symbolPath);
  32740. };
  32741. /**
  32742. * Stop animation
  32743. * @param {boolean} toLastFrame
  32744. */
  32745. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  32746. this.childAt(0).stopAnimation(toLastFrame);
  32747. };
  32748. /**
  32749. * FIXME:
  32750. * Caution: This method breaks the encapsulation of this module,
  32751. * but it indeed brings convenience. So do not use the method
  32752. * unless you detailedly know all the implements of `Symbol`,
  32753. * especially animation.
  32754. *
  32755. * Get symbol path element.
  32756. */
  32757. symbolProto.getSymbolPath = function () {
  32758. return this.childAt(0);
  32759. };
  32760. /**
  32761. * Get scale(aka, current symbol size).
  32762. * Including the change caused by animation
  32763. */
  32764. symbolProto.getScale = function () {
  32765. return this.childAt(0).scale;
  32766. };
  32767. /**
  32768. * Highlight symbol
  32769. */
  32770. symbolProto.highlight = function () {
  32771. this.childAt(0).trigger('emphasis');
  32772. };
  32773. /**
  32774. * Downplay symbol
  32775. */
  32776. symbolProto.downplay = function () {
  32777. this.childAt(0).trigger('normal');
  32778. };
  32779. /**
  32780. * @param {number} zlevel
  32781. * @param {number} z
  32782. */
  32783. symbolProto.setZ = function (zlevel, z) {
  32784. var symbolPath = this.childAt(0);
  32785. symbolPath.zlevel = zlevel;
  32786. symbolPath.z = z;
  32787. };
  32788. symbolProto.setDraggable = function (draggable) {
  32789. var symbolPath = this.childAt(0);
  32790. symbolPath.draggable = draggable;
  32791. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  32792. };
  32793. /**
  32794. * Update symbol properties
  32795. * @param {module:echarts/data/List} data
  32796. * @param {number} idx
  32797. * @param {Object} [seriesScope]
  32798. * @param {Object} [seriesScope.itemStyle]
  32799. * @param {Object} [seriesScope.hoverItemStyle]
  32800. * @param {Object} [seriesScope.symbolRotate]
  32801. * @param {Object} [seriesScope.symbolOffset]
  32802. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  32803. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  32804. * @param {boolean} [seriesScope.hoverAnimation]
  32805. * @param {Object} [seriesScope.cursorStyle]
  32806. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  32807. * @param {string} [seriesScope.symbolInnerColor]
  32808. * @param {Object} [seriesScope.fadeIn=false]
  32809. */
  32810. symbolProto.updateData = function (data, idx, seriesScope) {
  32811. this.silent = false;
  32812. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  32813. var seriesModel = data.hostModel;
  32814. var symbolSize = getSymbolSize(data, idx);
  32815. var isInit = symbolType !== this._symbolType;
  32816. if (isInit) {
  32817. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  32818. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  32819. }
  32820. else {
  32821. var symbolPath = this.childAt(0);
  32822. symbolPath.silent = false;
  32823. updateProps(symbolPath, {
  32824. scale: getScale(symbolSize)
  32825. }, seriesModel, idx);
  32826. }
  32827. this._updateCommon(data, idx, symbolSize, seriesScope);
  32828. if (isInit) {
  32829. var symbolPath = this.childAt(0);
  32830. var fadeIn = seriesScope && seriesScope.fadeIn;
  32831. var target = {scale: symbolPath.scale.slice()};
  32832. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  32833. symbolPath.scale = [0, 0];
  32834. fadeIn && (symbolPath.style.opacity = 0);
  32835. initProps(symbolPath, target, seriesModel, idx);
  32836. }
  32837. this._seriesModel = seriesModel;
  32838. };
  32839. // Update common properties
  32840. var normalStyleAccessPath = ['itemStyle'];
  32841. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  32842. var normalLabelAccessPath = ['label'];
  32843. var emphasisLabelAccessPath = ['emphasis', 'label'];
  32844. /**
  32845. * @param {module:echarts/data/List} data
  32846. * @param {number} idx
  32847. * @param {Array.<number>} symbolSize
  32848. * @param {Object} [seriesScope]
  32849. */
  32850. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  32851. var symbolPath = this.childAt(0);
  32852. var seriesModel = data.hostModel;
  32853. var color = data.getItemVisual(idx, 'color');
  32854. // Reset style
  32855. if (symbolPath.type !== 'image') {
  32856. symbolPath.useStyle({
  32857. strokeNoScale: true
  32858. });
  32859. }
  32860. else {
  32861. symbolPath.setStyle({
  32862. opacity: 1,
  32863. shadowBlur: null,
  32864. shadowOffsetX: null,
  32865. shadowOffsetY: null,
  32866. shadowColor: null
  32867. });
  32868. }
  32869. var itemStyle = seriesScope && seriesScope.itemStyle;
  32870. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  32871. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  32872. var labelModel = seriesScope && seriesScope.labelModel;
  32873. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  32874. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  32875. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  32876. if (!seriesScope || data.hasItemOption) {
  32877. var itemModel = (seriesScope && seriesScope.itemModel)
  32878. ? seriesScope.itemModel : data.getItemModel(idx);
  32879. // Color must be excluded.
  32880. // Because symbol provide setColor individually to set fill and stroke
  32881. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  32882. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  32883. symbolOffset = itemModel.getShallow('symbolOffset');
  32884. labelModel = itemModel.getModel(normalLabelAccessPath);
  32885. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  32886. hoverAnimation = itemModel.getShallow('hoverAnimation');
  32887. cursorStyle = itemModel.getShallow('cursor');
  32888. }
  32889. else {
  32890. hoverItemStyle = extend({}, hoverItemStyle);
  32891. }
  32892. var elStyle = symbolPath.style;
  32893. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  32894. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  32895. if (symbolOffset) {
  32896. symbolPath.attr('position', [
  32897. parsePercent$1(symbolOffset[0], symbolSize[0]),
  32898. parsePercent$1(symbolOffset[1], symbolSize[1])
  32899. ]);
  32900. }
  32901. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  32902. // PENDING setColor before setStyle!!!
  32903. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  32904. symbolPath.setStyle(itemStyle);
  32905. var opacity = data.getItemVisual(idx, 'opacity');
  32906. if (opacity != null) {
  32907. elStyle.opacity = opacity;
  32908. }
  32909. var liftZ = data.getItemVisual(idx, 'liftZ');
  32910. var z2Origin = symbolPath.__z2Origin;
  32911. if (liftZ != null) {
  32912. if (z2Origin == null) {
  32913. symbolPath.__z2Origin = symbolPath.z2;
  32914. symbolPath.z2 += liftZ;
  32915. }
  32916. }
  32917. else if (z2Origin != null) {
  32918. symbolPath.z2 = z2Origin;
  32919. symbolPath.__z2Origin = null;
  32920. }
  32921. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  32922. setLabelStyle(
  32923. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  32924. {
  32925. labelFetcher: seriesModel,
  32926. labelDataIndex: idx,
  32927. defaultText: getLabelDefaultText,
  32928. isRectText: true,
  32929. autoColor: color
  32930. }
  32931. );
  32932. // Do not execute util needed.
  32933. function getLabelDefaultText(idx, opt) {
  32934. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  32935. }
  32936. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  32937. symbolPath.hoverStyle = hoverItemStyle;
  32938. symbolPath.highDownOnUpdate = (
  32939. hoverAnimation && seriesModel.isAnimationEnabled()
  32940. ) ? highDownOnUpdate : null;
  32941. setHoverStyle(symbolPath);
  32942. };
  32943. function highDownOnUpdate(fromState, toState) {
  32944. // Do not support this hover animation util some scenario required.
  32945. // Animation can only be supported in hover layer when using `el.incremetal`.
  32946. if (this.incremental || this.useHoverLayer) {
  32947. return;
  32948. }
  32949. if (toState === 'emphasis') {
  32950. var scale = this.__symbolOriginalScale;
  32951. var ratio = scale[1] / scale[0];
  32952. var emphasisOpt = {
  32953. scale: [
  32954. Math.max(scale[0] * 1.1, scale[0] + 3),
  32955. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  32956. ]
  32957. };
  32958. // FIXME
  32959. // modify it after support stop specified animation.
  32960. // toState === fromState
  32961. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  32962. this.animateTo(emphasisOpt, 400, 'elasticOut');
  32963. }
  32964. else if (toState === 'normal') {
  32965. this.animateTo({
  32966. scale: this.__symbolOriginalScale
  32967. }, 400, 'elasticOut');
  32968. }
  32969. }
  32970. /**
  32971. * @param {Function} cb
  32972. * @param {Object} [opt]
  32973. * @param {Object} [opt.keepLabel=true]
  32974. */
  32975. symbolProto.fadeOut = function (cb, opt) {
  32976. var symbolPath = this.childAt(0);
  32977. // Avoid mistaken hover when fading out
  32978. this.silent = symbolPath.silent = true;
  32979. // Not show text when animating
  32980. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  32981. updateProps(
  32982. symbolPath,
  32983. {
  32984. style: {opacity: 0},
  32985. scale: [0, 0]
  32986. },
  32987. this._seriesModel,
  32988. this.dataIndex,
  32989. cb
  32990. );
  32991. };
  32992. inherits(SymbolClz$1, Group);
  32993. /*
  32994. * Licensed to the Apache Software Foundation (ASF) under one
  32995. * or more contributor license agreements. See the NOTICE file
  32996. * distributed with this work for additional information
  32997. * regarding copyright ownership. The ASF licenses this file
  32998. * to you under the Apache License, Version 2.0 (the
  32999. * "License"); you may not use this file except in compliance
  33000. * with the License. You may obtain a copy of the License at
  33001. *
  33002. * http://www.apache.org/licenses/LICENSE-2.0
  33003. *
  33004. * Unless required by applicable law or agreed to in writing,
  33005. * software distributed under the License is distributed on an
  33006. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33007. * KIND, either express or implied. See the License for the
  33008. * specific language governing permissions and limitations
  33009. * under the License.
  33010. */
  33011. /**
  33012. * @module echarts/chart/helper/SymbolDraw
  33013. */
  33014. /**
  33015. * @constructor
  33016. * @alias module:echarts/chart/helper/SymbolDraw
  33017. * @param {module:zrender/graphic/Group} [symbolCtor]
  33018. */
  33019. function SymbolDraw(symbolCtor) {
  33020. this.group = new Group();
  33021. this._symbolCtor = symbolCtor || SymbolClz$1;
  33022. }
  33023. var symbolDrawProto = SymbolDraw.prototype;
  33024. function symbolNeedsDraw(data, point, idx, opt) {
  33025. return point && !isNaN(point[0]) && !isNaN(point[1])
  33026. && !(opt.isIgnore && opt.isIgnore(idx))
  33027. // We do not set clipShape on group, because it will cut part of
  33028. // the symbol element shape. We use the same clip shape here as
  33029. // the line clip.
  33030. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  33031. && data.getItemVisual(idx, 'symbol') !== 'none';
  33032. }
  33033. /**
  33034. * Update symbols draw by new data
  33035. * @param {module:echarts/data/List} data
  33036. * @param {Object} [opt] Or isIgnore
  33037. * @param {Function} [opt.isIgnore]
  33038. * @param {Object} [opt.clipShape]
  33039. */
  33040. symbolDrawProto.updateData = function (data, opt) {
  33041. opt = normalizeUpdateOpt(opt);
  33042. var group = this.group;
  33043. var seriesModel = data.hostModel;
  33044. var oldData = this._data;
  33045. var SymbolCtor = this._symbolCtor;
  33046. var seriesScope = makeSeriesScope(data);
  33047. // There is no oldLineData only when first rendering or switching from
  33048. // stream mode to normal mode, where previous elements should be removed.
  33049. if (!oldData) {
  33050. group.removeAll();
  33051. }
  33052. data.diff(oldData)
  33053. .add(function (newIdx) {
  33054. var point = data.getItemLayout(newIdx);
  33055. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  33056. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  33057. symbolEl.attr('position', point);
  33058. data.setItemGraphicEl(newIdx, symbolEl);
  33059. group.add(symbolEl);
  33060. }
  33061. })
  33062. .update(function (newIdx, oldIdx) {
  33063. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  33064. var point = data.getItemLayout(newIdx);
  33065. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  33066. group.remove(symbolEl);
  33067. return;
  33068. }
  33069. if (!symbolEl) {
  33070. symbolEl = new SymbolCtor(data, newIdx);
  33071. symbolEl.attr('position', point);
  33072. }
  33073. else {
  33074. symbolEl.updateData(data, newIdx, seriesScope);
  33075. updateProps(symbolEl, {
  33076. position: point
  33077. }, seriesModel);
  33078. }
  33079. // Add back
  33080. group.add(symbolEl);
  33081. data.setItemGraphicEl(newIdx, symbolEl);
  33082. })
  33083. .remove(function (oldIdx) {
  33084. var el = oldData.getItemGraphicEl(oldIdx);
  33085. el && el.fadeOut(function () {
  33086. group.remove(el);
  33087. });
  33088. })
  33089. .execute();
  33090. this._data = data;
  33091. };
  33092. symbolDrawProto.isPersistent = function () {
  33093. return true;
  33094. };
  33095. symbolDrawProto.updateLayout = function () {
  33096. var data = this._data;
  33097. if (data) {
  33098. // Not use animation
  33099. data.eachItemGraphicEl(function (el, idx) {
  33100. var point = data.getItemLayout(idx);
  33101. el.attr('position', point);
  33102. });
  33103. }
  33104. };
  33105. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  33106. this._seriesScope = makeSeriesScope(data);
  33107. this._data = null;
  33108. this.group.removeAll();
  33109. };
  33110. /**
  33111. * Update symbols draw by new data
  33112. * @param {module:echarts/data/List} data
  33113. * @param {Object} [opt] Or isIgnore
  33114. * @param {Function} [opt.isIgnore]
  33115. * @param {Object} [opt.clipShape]
  33116. */
  33117. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  33118. opt = normalizeUpdateOpt(opt);
  33119. function updateIncrementalAndHover(el) {
  33120. if (!el.isGroup) {
  33121. el.incremental = el.useHoverLayer = true;
  33122. }
  33123. }
  33124. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  33125. var point = data.getItemLayout(idx);
  33126. if (symbolNeedsDraw(data, point, idx, opt)) {
  33127. var el = new this._symbolCtor(data, idx, this._seriesScope);
  33128. el.traverse(updateIncrementalAndHover);
  33129. el.attr('position', point);
  33130. this.group.add(el);
  33131. data.setItemGraphicEl(idx, el);
  33132. }
  33133. }
  33134. };
  33135. function normalizeUpdateOpt(opt) {
  33136. if (opt != null && !isObject$1(opt)) {
  33137. opt = {isIgnore: opt};
  33138. }
  33139. return opt || {};
  33140. }
  33141. symbolDrawProto.remove = function (enableAnimation) {
  33142. var group = this.group;
  33143. var data = this._data;
  33144. // Incremental model do not have this._data.
  33145. if (data && enableAnimation) {
  33146. data.eachItemGraphicEl(function (el) {
  33147. el.fadeOut(function () {
  33148. group.remove(el);
  33149. });
  33150. });
  33151. }
  33152. else {
  33153. group.removeAll();
  33154. }
  33155. };
  33156. function makeSeriesScope(data) {
  33157. var seriesModel = data.hostModel;
  33158. return {
  33159. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  33160. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  33161. symbolRotate: seriesModel.get('symbolRotate'),
  33162. symbolOffset: seriesModel.get('symbolOffset'),
  33163. hoverAnimation: seriesModel.get('hoverAnimation'),
  33164. labelModel: seriesModel.getModel('label'),
  33165. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  33166. cursorStyle: seriesModel.get('cursor')
  33167. };
  33168. }
  33169. /*
  33170. * Licensed to the Apache Software Foundation (ASF) under one
  33171. * or more contributor license agreements. See the NOTICE file
  33172. * distributed with this work for additional information
  33173. * regarding copyright ownership. The ASF licenses this file
  33174. * to you under the Apache License, Version 2.0 (the
  33175. * "License"); you may not use this file except in compliance
  33176. * with the License. You may obtain a copy of the License at
  33177. *
  33178. * http://www.apache.org/licenses/LICENSE-2.0
  33179. *
  33180. * Unless required by applicable law or agreed to in writing,
  33181. * software distributed under the License is distributed on an
  33182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33183. * KIND, either express or implied. See the License for the
  33184. * specific language governing permissions and limitations
  33185. * under the License.
  33186. */
  33187. /**
  33188. * @param {Object} coordSys
  33189. * @param {module:echarts/data/List} data
  33190. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  33191. */
  33192. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  33193. var baseAxis = coordSys.getBaseAxis();
  33194. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33195. var valueStart = getValueStart(valueAxis, valueOrigin);
  33196. var baseAxisDim = baseAxis.dim;
  33197. var valueAxisDim = valueAxis.dim;
  33198. var valueDim = data.mapDimension(valueAxisDim);
  33199. var baseDim = data.mapDimension(baseAxisDim);
  33200. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  33201. var dims = map(coordSys.dimensions, function (coordDim) {
  33202. return data.mapDimension(coordDim);
  33203. });
  33204. var stacked;
  33205. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33206. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  33207. dims[0] = stackResultDim;
  33208. }
  33209. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  33210. dims[1] = stackResultDim;
  33211. }
  33212. return {
  33213. dataDimsForPoint: dims,
  33214. valueStart: valueStart,
  33215. valueAxisDim: valueAxisDim,
  33216. baseAxisDim: baseAxisDim,
  33217. stacked: !!stacked,
  33218. valueDim: valueDim,
  33219. baseDim: baseDim,
  33220. baseDataOffset: baseDataOffset,
  33221. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33222. };
  33223. }
  33224. function getValueStart(valueAxis, valueOrigin) {
  33225. var valueStart = 0;
  33226. var extent = valueAxis.scale.getExtent();
  33227. if (valueOrigin === 'start') {
  33228. valueStart = extent[0];
  33229. }
  33230. else if (valueOrigin === 'end') {
  33231. valueStart = extent[1];
  33232. }
  33233. // auto
  33234. else {
  33235. // Both positive
  33236. if (extent[0] > 0) {
  33237. valueStart = extent[0];
  33238. }
  33239. // Both negative
  33240. else if (extent[1] < 0) {
  33241. valueStart = extent[1];
  33242. }
  33243. // If is one positive, and one negative, onZero shall be true
  33244. }
  33245. return valueStart;
  33246. }
  33247. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  33248. var value = NaN;
  33249. if (dataCoordInfo.stacked) {
  33250. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  33251. }
  33252. if (isNaN(value)) {
  33253. value = dataCoordInfo.valueStart;
  33254. }
  33255. var baseDataOffset = dataCoordInfo.baseDataOffset;
  33256. var stackedData = [];
  33257. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  33258. stackedData[1 - baseDataOffset] = value;
  33259. return coordSys.dataToPoint(stackedData);
  33260. }
  33261. /*
  33262. * Licensed to the Apache Software Foundation (ASF) under one
  33263. * or more contributor license agreements. See the NOTICE file
  33264. * distributed with this work for additional information
  33265. * regarding copyright ownership. The ASF licenses this file
  33266. * to you under the Apache License, Version 2.0 (the
  33267. * "License"); you may not use this file except in compliance
  33268. * with the License. You may obtain a copy of the License at
  33269. *
  33270. * http://www.apache.org/licenses/LICENSE-2.0
  33271. *
  33272. * Unless required by applicable law or agreed to in writing,
  33273. * software distributed under the License is distributed on an
  33274. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33275. * KIND, either express or implied. See the License for the
  33276. * specific language governing permissions and limitations
  33277. * under the License.
  33278. */
  33279. // var arrayDiff = require('zrender/src/core/arrayDiff');
  33280. // 'zrender/src/core/arrayDiff' has been used before, but it did
  33281. // not do well in performance when roam with fixed dataZoom window.
  33282. // function convertToIntId(newIdList, oldIdList) {
  33283. // // Generate int id instead of string id.
  33284. // // Compare string maybe slow in score function of arrDiff
  33285. // // Assume id in idList are all unique
  33286. // var idIndicesMap = {};
  33287. // var idx = 0;
  33288. // for (var i = 0; i < newIdList.length; i++) {
  33289. // idIndicesMap[newIdList[i]] = idx;
  33290. // newIdList[i] = idx++;
  33291. // }
  33292. // for (var i = 0; i < oldIdList.length; i++) {
  33293. // var oldId = oldIdList[i];
  33294. // // Same with newIdList
  33295. // if (idIndicesMap[oldId]) {
  33296. // oldIdList[i] = idIndicesMap[oldId];
  33297. // }
  33298. // else {
  33299. // oldIdList[i] = idx++;
  33300. // }
  33301. // }
  33302. // }
  33303. function diffData(oldData, newData) {
  33304. var diffResult = [];
  33305. newData.diff(oldData)
  33306. .add(function (idx) {
  33307. diffResult.push({cmd: '+', idx: idx});
  33308. })
  33309. .update(function (newIdx, oldIdx) {
  33310. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  33311. })
  33312. .remove(function (idx) {
  33313. diffResult.push({cmd: '-', idx: idx});
  33314. })
  33315. .execute();
  33316. return diffResult;
  33317. }
  33318. var lineAnimationDiff = function (
  33319. oldData, newData,
  33320. oldStackedOnPoints, newStackedOnPoints,
  33321. oldCoordSys, newCoordSys,
  33322. oldValueOrigin, newValueOrigin
  33323. ) {
  33324. var diff = diffData(oldData, newData);
  33325. // var newIdList = newData.mapArray(newData.getId);
  33326. // var oldIdList = oldData.mapArray(oldData.getId);
  33327. // convertToIntId(newIdList, oldIdList);
  33328. // // FIXME One data ?
  33329. // diff = arrayDiff(oldIdList, newIdList);
  33330. var currPoints = [];
  33331. var nextPoints = [];
  33332. // Points for stacking base line
  33333. var currStackedPoints = [];
  33334. var nextStackedPoints = [];
  33335. var status = [];
  33336. var sortedIndices = [];
  33337. var rawIndices = [];
  33338. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  33339. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  33340. for (var i = 0; i < diff.length; i++) {
  33341. var diffItem = diff[i];
  33342. var pointAdded = true;
  33343. // FIXME, animation is not so perfect when dataZoom window moves fast
  33344. // Which is in case remvoing or add more than one data in the tail or head
  33345. switch (diffItem.cmd) {
  33346. case '=':
  33347. var currentPt = oldData.getItemLayout(diffItem.idx);
  33348. var nextPt = newData.getItemLayout(diffItem.idx1);
  33349. // If previous data is NaN, use next point directly
  33350. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  33351. currentPt = nextPt.slice();
  33352. }
  33353. currPoints.push(currentPt);
  33354. nextPoints.push(nextPt);
  33355. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  33356. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  33357. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  33358. break;
  33359. case '+':
  33360. var idx = diffItem.idx;
  33361. currPoints.push(
  33362. oldCoordSys.dataToPoint([
  33363. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  33364. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  33365. ])
  33366. );
  33367. nextPoints.push(newData.getItemLayout(idx).slice());
  33368. currStackedPoints.push(
  33369. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  33370. );
  33371. nextStackedPoints.push(newStackedOnPoints[idx]);
  33372. rawIndices.push(newData.getRawIndex(idx));
  33373. break;
  33374. case '-':
  33375. var idx = diffItem.idx;
  33376. var rawIndex = oldData.getRawIndex(idx);
  33377. // Data is replaced. In the case of dynamic data queue
  33378. // FIXME FIXME FIXME
  33379. if (rawIndex !== idx) {
  33380. currPoints.push(oldData.getItemLayout(idx));
  33381. nextPoints.push(newCoordSys.dataToPoint([
  33382. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  33383. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  33384. ]));
  33385. currStackedPoints.push(oldStackedOnPoints[idx]);
  33386. nextStackedPoints.push(
  33387. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  33388. );
  33389. rawIndices.push(rawIndex);
  33390. }
  33391. else {
  33392. pointAdded = false;
  33393. }
  33394. }
  33395. // Original indices
  33396. if (pointAdded) {
  33397. status.push(diffItem);
  33398. sortedIndices.push(sortedIndices.length);
  33399. }
  33400. }
  33401. // Diff result may be crossed if all items are changed
  33402. // Sort by data index
  33403. sortedIndices.sort(function (a, b) {
  33404. return rawIndices[a] - rawIndices[b];
  33405. });
  33406. var sortedCurrPoints = [];
  33407. var sortedNextPoints = [];
  33408. var sortedCurrStackedPoints = [];
  33409. var sortedNextStackedPoints = [];
  33410. var sortedStatus = [];
  33411. for (var i = 0; i < sortedIndices.length; i++) {
  33412. var idx = sortedIndices[i];
  33413. sortedCurrPoints[i] = currPoints[idx];
  33414. sortedNextPoints[i] = nextPoints[idx];
  33415. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  33416. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  33417. sortedStatus[i] = status[idx];
  33418. }
  33419. return {
  33420. current: sortedCurrPoints,
  33421. next: sortedNextPoints,
  33422. stackedOnCurrent: sortedCurrStackedPoints,
  33423. stackedOnNext: sortedNextStackedPoints,
  33424. status: sortedStatus
  33425. };
  33426. };
  33427. /*
  33428. * Licensed to the Apache Software Foundation (ASF) under one
  33429. * or more contributor license agreements. See the NOTICE file
  33430. * distributed with this work for additional information
  33431. * regarding copyright ownership. The ASF licenses this file
  33432. * to you under the Apache License, Version 2.0 (the
  33433. * "License"); you may not use this file except in compliance
  33434. * with the License. You may obtain a copy of the License at
  33435. *
  33436. * http://www.apache.org/licenses/LICENSE-2.0
  33437. *
  33438. * Unless required by applicable law or agreed to in writing,
  33439. * software distributed under the License is distributed on an
  33440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33441. * KIND, either express or implied. See the License for the
  33442. * specific language governing permissions and limitations
  33443. * under the License.
  33444. */
  33445. // Poly path support NaN point
  33446. var vec2Min = min;
  33447. var vec2Max = max;
  33448. var scaleAndAdd$1 = scaleAndAdd;
  33449. var v2Copy = copy;
  33450. // Temporary variable
  33451. var v = [];
  33452. var cp0 = [];
  33453. var cp1 = [];
  33454. function isPointNull(p) {
  33455. return isNaN(p[0]) || isNaN(p[1]);
  33456. }
  33457. function drawSegment(
  33458. ctx, points, start, segLen, allLen,
  33459. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33460. ) {
  33461. // if (smoothMonotone == null) {
  33462. // if (isMono(points, 'x')) {
  33463. // return drawMono(ctx, points, start, segLen, allLen,
  33464. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  33465. // }
  33466. // else if (isMono(points, 'y')) {
  33467. // return drawMono(ctx, points, start, segLen, allLen,
  33468. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  33469. // }
  33470. // else {
  33471. // return drawNonMono.apply(this, arguments);
  33472. // }
  33473. // }
  33474. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  33475. // return drawMono.apply(this, arguments);
  33476. // }
  33477. // else {
  33478. // return drawNonMono.apply(this, arguments);
  33479. // }
  33480. if (smoothMonotone === 'none' || !smoothMonotone) {
  33481. return drawNonMono.apply(this, arguments);
  33482. }
  33483. else {
  33484. return drawMono.apply(this, arguments);
  33485. }
  33486. }
  33487. /**
  33488. * Check if points is in monotone.
  33489. *
  33490. * @param {number[][]} points Array of points which is in [x, y] form
  33491. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  33492. * dimension that is checking.
  33493. * If is 'none', `drawNonMono` should be
  33494. * called.
  33495. * If is undefined, either being monotone
  33496. * in 'x' or 'y' will call `drawMono`.
  33497. */
  33498. // function isMono(points, smoothMonotone) {
  33499. // if (points.length <= 1) {
  33500. // return true;
  33501. // }
  33502. // var dim = smoothMonotone === 'x' ? 0 : 1;
  33503. // var last = points[0][dim];
  33504. // var lastDiff = 0;
  33505. // for (var i = 1; i < points.length; ++i) {
  33506. // var diff = points[i][dim] - last;
  33507. // if (!isNaN(diff) && !isNaN(lastDiff)
  33508. // && diff !== 0 && lastDiff !== 0
  33509. // && ((diff >= 0) !== (lastDiff >= 0))
  33510. // ) {
  33511. // return false;
  33512. // }
  33513. // if (!isNaN(diff) && diff !== 0) {
  33514. // lastDiff = diff;
  33515. // last = points[i][dim];
  33516. // }
  33517. // }
  33518. // return true;
  33519. // }
  33520. /**
  33521. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  33522. * control points will be used. This should be used when points are monotone
  33523. * either in x or y dimension.
  33524. */
  33525. function drawMono(
  33526. ctx, points, start, segLen, allLen,
  33527. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33528. ) {
  33529. var prevIdx = 0;
  33530. var idx = start;
  33531. for (var k = 0; k < segLen; k++) {
  33532. var p = points[idx];
  33533. if (idx >= allLen || idx < 0) {
  33534. break;
  33535. }
  33536. if (isPointNull(p)) {
  33537. if (connectNulls) {
  33538. idx += dir;
  33539. continue;
  33540. }
  33541. break;
  33542. }
  33543. if (idx === start) {
  33544. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33545. }
  33546. else {
  33547. if (smooth > 0) {
  33548. var prevP = points[prevIdx];
  33549. var dim = smoothMonotone === 'y' ? 1 : 0;
  33550. // Length of control point to p, either in x or y, but not both
  33551. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  33552. v2Copy(cp0, prevP);
  33553. cp0[dim] = prevP[dim] + ctrlLen;
  33554. v2Copy(cp1, p);
  33555. cp1[dim] = p[dim] - ctrlLen;
  33556. ctx.bezierCurveTo(
  33557. cp0[0], cp0[1],
  33558. cp1[0], cp1[1],
  33559. p[0], p[1]
  33560. );
  33561. }
  33562. else {
  33563. ctx.lineTo(p[0], p[1]);
  33564. }
  33565. }
  33566. prevIdx = idx;
  33567. idx += dir;
  33568. }
  33569. return k;
  33570. }
  33571. /**
  33572. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  33573. * situations. This should be used when points are non-monotone neither in x or
  33574. * y dimension.
  33575. */
  33576. function drawNonMono(
  33577. ctx, points, start, segLen, allLen,
  33578. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33579. ) {
  33580. var prevIdx = 0;
  33581. var idx = start;
  33582. for (var k = 0; k < segLen; k++) {
  33583. var p = points[idx];
  33584. if (idx >= allLen || idx < 0) {
  33585. break;
  33586. }
  33587. if (isPointNull(p)) {
  33588. if (connectNulls) {
  33589. idx += dir;
  33590. continue;
  33591. }
  33592. break;
  33593. }
  33594. if (idx === start) {
  33595. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33596. v2Copy(cp0, p);
  33597. }
  33598. else {
  33599. if (smooth > 0) {
  33600. var nextIdx = idx + dir;
  33601. var nextP = points[nextIdx];
  33602. if (connectNulls) {
  33603. // Find next point not null
  33604. while (nextP && isPointNull(points[nextIdx])) {
  33605. nextIdx += dir;
  33606. nextP = points[nextIdx];
  33607. }
  33608. }
  33609. var ratioNextSeg = 0.5;
  33610. var prevP = points[prevIdx];
  33611. var nextP = points[nextIdx];
  33612. // Last point
  33613. if (!nextP || isPointNull(nextP)) {
  33614. v2Copy(cp1, p);
  33615. }
  33616. else {
  33617. // If next data is null in not connect case
  33618. if (isPointNull(nextP) && !connectNulls) {
  33619. nextP = p;
  33620. }
  33621. sub(v, nextP, prevP);
  33622. var lenPrevSeg;
  33623. var lenNextSeg;
  33624. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  33625. var dim = smoothMonotone === 'x' ? 0 : 1;
  33626. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  33627. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  33628. }
  33629. else {
  33630. lenPrevSeg = dist(p, prevP);
  33631. lenNextSeg = dist(p, nextP);
  33632. }
  33633. // Use ratio of seg length
  33634. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  33635. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  33636. }
  33637. // Smooth constraint
  33638. vec2Min(cp0, cp0, smoothMax);
  33639. vec2Max(cp0, cp0, smoothMin);
  33640. vec2Min(cp1, cp1, smoothMax);
  33641. vec2Max(cp1, cp1, smoothMin);
  33642. ctx.bezierCurveTo(
  33643. cp0[0], cp0[1],
  33644. cp1[0], cp1[1],
  33645. p[0], p[1]
  33646. );
  33647. // cp0 of next segment
  33648. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  33649. }
  33650. else {
  33651. ctx.lineTo(p[0], p[1]);
  33652. }
  33653. }
  33654. prevIdx = idx;
  33655. idx += dir;
  33656. }
  33657. return k;
  33658. }
  33659. function getBoundingBox(points, smoothConstraint) {
  33660. var ptMin = [Infinity, Infinity];
  33661. var ptMax = [-Infinity, -Infinity];
  33662. if (smoothConstraint) {
  33663. for (var i = 0; i < points.length; i++) {
  33664. var pt = points[i];
  33665. if (pt[0] < ptMin[0]) {
  33666. ptMin[0] = pt[0];
  33667. }
  33668. if (pt[1] < ptMin[1]) {
  33669. ptMin[1] = pt[1];
  33670. }
  33671. if (pt[0] > ptMax[0]) {
  33672. ptMax[0] = pt[0];
  33673. }
  33674. if (pt[1] > ptMax[1]) {
  33675. ptMax[1] = pt[1];
  33676. }
  33677. }
  33678. }
  33679. return {
  33680. min: smoothConstraint ? ptMin : ptMax,
  33681. max: smoothConstraint ? ptMax : ptMin
  33682. };
  33683. }
  33684. var Polyline$1 = Path.extend({
  33685. type: 'ec-polyline',
  33686. shape: {
  33687. points: [],
  33688. smooth: 0,
  33689. smoothConstraint: true,
  33690. smoothMonotone: null,
  33691. connectNulls: false
  33692. },
  33693. style: {
  33694. fill: null,
  33695. stroke: '#000'
  33696. },
  33697. brush: fixClipWithShadow(Path.prototype.brush),
  33698. buildPath: function (ctx, shape) {
  33699. var points = shape.points;
  33700. var i = 0;
  33701. var len$$1 = points.length;
  33702. var result = getBoundingBox(points, shape.smoothConstraint);
  33703. if (shape.connectNulls) {
  33704. // Must remove first and last null values avoid draw error in polygon
  33705. for (; len$$1 > 0; len$$1--) {
  33706. if (!isPointNull(points[len$$1 - 1])) {
  33707. break;
  33708. }
  33709. }
  33710. for (; i < len$$1; i++) {
  33711. if (!isPointNull(points[i])) {
  33712. break;
  33713. }
  33714. }
  33715. }
  33716. while (i < len$$1) {
  33717. i += drawSegment(
  33718. ctx, points, i, len$$1, len$$1,
  33719. 1, result.min, result.max, shape.smooth,
  33720. shape.smoothMonotone, shape.connectNulls
  33721. ) + 1;
  33722. }
  33723. }
  33724. });
  33725. var Polygon$1 = Path.extend({
  33726. type: 'ec-polygon',
  33727. shape: {
  33728. points: [],
  33729. // Offset between stacked base points and points
  33730. stackedOnPoints: [],
  33731. smooth: 0,
  33732. stackedOnSmooth: 0,
  33733. smoothConstraint: true,
  33734. smoothMonotone: null,
  33735. connectNulls: false
  33736. },
  33737. brush: fixClipWithShadow(Path.prototype.brush),
  33738. buildPath: function (ctx, shape) {
  33739. var points = shape.points;
  33740. var stackedOnPoints = shape.stackedOnPoints;
  33741. var i = 0;
  33742. var len$$1 = points.length;
  33743. var smoothMonotone = shape.smoothMonotone;
  33744. var bbox = getBoundingBox(points, shape.smoothConstraint);
  33745. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  33746. if (shape.connectNulls) {
  33747. // Must remove first and last null values avoid draw error in polygon
  33748. for (; len$$1 > 0; len$$1--) {
  33749. if (!isPointNull(points[len$$1 - 1])) {
  33750. break;
  33751. }
  33752. }
  33753. for (; i < len$$1; i++) {
  33754. if (!isPointNull(points[i])) {
  33755. break;
  33756. }
  33757. }
  33758. }
  33759. while (i < len$$1) {
  33760. var k = drawSegment(
  33761. ctx, points, i, len$$1, len$$1,
  33762. 1, bbox.min, bbox.max, shape.smooth,
  33763. smoothMonotone, shape.connectNulls
  33764. );
  33765. drawSegment(
  33766. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  33767. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  33768. smoothMonotone, shape.connectNulls
  33769. );
  33770. i += k + 1;
  33771. ctx.closePath();
  33772. }
  33773. }
  33774. });
  33775. /*
  33776. * Licensed to the Apache Software Foundation (ASF) under one
  33777. * or more contributor license agreements. See the NOTICE file
  33778. * distributed with this work for additional information
  33779. * regarding copyright ownership. The ASF licenses this file
  33780. * to you under the Apache License, Version 2.0 (the
  33781. * "License"); you may not use this file except in compliance
  33782. * with the License. You may obtain a copy of the License at
  33783. *
  33784. * http://www.apache.org/licenses/LICENSE-2.0
  33785. *
  33786. * Unless required by applicable law or agreed to in writing,
  33787. * software distributed under the License is distributed on an
  33788. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33789. * KIND, either express or implied. See the License for the
  33790. * specific language governing permissions and limitations
  33791. * under the License.
  33792. */
  33793. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  33794. var rect = cartesian.getArea();
  33795. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  33796. var x = rect.x;
  33797. var y = rect.y;
  33798. var width = rect.width;
  33799. var height = rect.height;
  33800. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  33801. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  33802. x -= lineWidth / 2;
  33803. y -= lineWidth / 2;
  33804. width += lineWidth;
  33805. height += lineWidth;
  33806. // fix: https://github.com/apache/incubator-echarts/issues/11369
  33807. x = Math.floor(x);
  33808. width = Math.round(width);
  33809. var clipPath = new Rect({
  33810. shape: {
  33811. x: x,
  33812. y: y,
  33813. width: width,
  33814. height: height
  33815. }
  33816. });
  33817. if (hasAnimation) {
  33818. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  33819. initProps(clipPath, {
  33820. shape: {
  33821. width: width,
  33822. height: height
  33823. }
  33824. }, seriesModel);
  33825. }
  33826. return clipPath;
  33827. }
  33828. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  33829. var sectorArea = polar.getArea();
  33830. // Avoid float number rounding error for symbol on the edge of axis extent.
  33831. var clipPath = new Sector({
  33832. shape: {
  33833. cx: round$1(polar.cx, 1),
  33834. cy: round$1(polar.cy, 1),
  33835. r0: round$1(sectorArea.r0, 1),
  33836. r: round$1(sectorArea.r, 1),
  33837. startAngle: sectorArea.startAngle,
  33838. endAngle: sectorArea.endAngle,
  33839. clockwise: sectorArea.clockwise
  33840. }
  33841. });
  33842. if (hasAnimation) {
  33843. clipPath.shape.endAngle = sectorArea.startAngle;
  33844. initProps(clipPath, {
  33845. shape: {
  33846. endAngle: sectorArea.endAngle
  33847. }
  33848. }, seriesModel);
  33849. }
  33850. return clipPath;
  33851. }
  33852. function createClipPath(coordSys, hasAnimation, seriesModel) {
  33853. if (!coordSys) {
  33854. return null;
  33855. }
  33856. else if (coordSys.type === 'polar') {
  33857. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33858. }
  33859. else if (coordSys.type === 'cartesian2d') {
  33860. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  33861. }
  33862. return null;
  33863. }
  33864. /*
  33865. * Licensed to the Apache Software Foundation (ASF) under one
  33866. * or more contributor license agreements. See the NOTICE file
  33867. * distributed with this work for additional information
  33868. * regarding copyright ownership. The ASF licenses this file
  33869. * to you under the Apache License, Version 2.0 (the
  33870. * "License"); you may not use this file except in compliance
  33871. * with the License. You may obtain a copy of the License at
  33872. *
  33873. * http://www.apache.org/licenses/LICENSE-2.0
  33874. *
  33875. * Unless required by applicable law or agreed to in writing,
  33876. * software distributed under the License is distributed on an
  33877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33878. * KIND, either express or implied. See the License for the
  33879. * specific language governing permissions and limitations
  33880. * under the License.
  33881. */
  33882. // FIXME step not support polar
  33883. function isPointsSame(points1, points2) {
  33884. if (points1.length !== points2.length) {
  33885. return;
  33886. }
  33887. for (var i = 0; i < points1.length; i++) {
  33888. var p1 = points1[i];
  33889. var p2 = points2[i];
  33890. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  33891. return;
  33892. }
  33893. }
  33894. return true;
  33895. }
  33896. function getBoundingDiff(points1, points2) {
  33897. var min1 = [];
  33898. var max1 = [];
  33899. var min2 = [];
  33900. var max2 = [];
  33901. fromPoints(points1, min1, max1);
  33902. fromPoints(points2, min2, max2);
  33903. // Get a max value from each corner of two boundings.
  33904. return Math.max(
  33905. Math.abs(min1[0] - min2[0]),
  33906. Math.abs(min1[1] - min2[1]),
  33907. Math.abs(max1[0] - max2[0]),
  33908. Math.abs(max1[1] - max2[1])
  33909. );
  33910. }
  33911. function getSmooth(smooth) {
  33912. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  33913. }
  33914. /**
  33915. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  33916. * @param {module:echarts/data/List} data
  33917. * @param {Object} dataCoordInfo
  33918. * @param {Array.<Array.<number>>} points
  33919. */
  33920. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  33921. if (!dataCoordInfo.valueDim) {
  33922. return [];
  33923. }
  33924. var points = [];
  33925. for (var idx = 0, len = data.count(); idx < len; idx++) {
  33926. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  33927. }
  33928. return points;
  33929. }
  33930. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  33931. var baseAxis = coordSys.getBaseAxis();
  33932. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  33933. var stepPoints = [];
  33934. for (var i = 0; i < points.length - 1; i++) {
  33935. var nextPt = points[i + 1];
  33936. var pt = points[i];
  33937. stepPoints.push(pt);
  33938. var stepPt = [];
  33939. switch (stepTurnAt) {
  33940. case 'end':
  33941. stepPt[baseIndex] = nextPt[baseIndex];
  33942. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33943. // default is start
  33944. stepPoints.push(stepPt);
  33945. break;
  33946. case 'middle':
  33947. // default is start
  33948. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  33949. var stepPt2 = [];
  33950. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  33951. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33952. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  33953. stepPoints.push(stepPt);
  33954. stepPoints.push(stepPt2);
  33955. break;
  33956. default:
  33957. stepPt[baseIndex] = pt[baseIndex];
  33958. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  33959. // default is start
  33960. stepPoints.push(stepPt);
  33961. }
  33962. }
  33963. // Last points
  33964. points[i] && stepPoints.push(points[i]);
  33965. return stepPoints;
  33966. }
  33967. function getVisualGradient(data, coordSys) {
  33968. var visualMetaList = data.getVisual('visualMeta');
  33969. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  33970. // When data.count() is 0, gradient range can not be calculated.
  33971. return;
  33972. }
  33973. if (coordSys.type !== 'cartesian2d') {
  33974. if (__DEV__) {
  33975. console.warn('Visual map on line style is only supported on cartesian2d.');
  33976. }
  33977. return;
  33978. }
  33979. var coordDim;
  33980. var visualMeta;
  33981. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  33982. var dimIndex = visualMetaList[i].dimension;
  33983. var dimName = data.dimensions[dimIndex];
  33984. var dimInfo = data.getDimensionInfo(dimName);
  33985. coordDim = dimInfo && dimInfo.coordDim;
  33986. // Can only be x or y
  33987. if (coordDim === 'x' || coordDim === 'y') {
  33988. visualMeta = visualMetaList[i];
  33989. break;
  33990. }
  33991. }
  33992. if (!visualMeta) {
  33993. if (__DEV__) {
  33994. console.warn('Visual map on line style only support x or y dimension.');
  33995. }
  33996. return;
  33997. }
  33998. // If the area to be rendered is bigger than area defined by LinearGradient,
  33999. // the canvas spec prescribes that the color of the first stop and the last
  34000. // stop should be used. But if two stops are added at offset 0, in effect
  34001. // browsers use the color of the second stop to render area outside
  34002. // LinearGradient. So we can only infinitesimally extend area defined in
  34003. // LinearGradient to render `outerColors`.
  34004. var axis = coordSys.getAxis(coordDim);
  34005. // dataToCoor mapping may not be linear, but must be monotonic.
  34006. var colorStops = map(visualMeta.stops, function (stop) {
  34007. return {
  34008. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  34009. color: stop.color
  34010. };
  34011. });
  34012. var stopLen = colorStops.length;
  34013. var outerColors = visualMeta.outerColors.slice();
  34014. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  34015. colorStops.reverse();
  34016. outerColors.reverse();
  34017. }
  34018. var tinyExtent = 10; // Arbitrary value: 10px
  34019. var minCoord = colorStops[0].coord - tinyExtent;
  34020. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  34021. var coordSpan = maxCoord - minCoord;
  34022. if (coordSpan < 1e-3) {
  34023. return 'transparent';
  34024. }
  34025. each$1(colorStops, function (stop) {
  34026. stop.offset = (stop.coord - minCoord) / coordSpan;
  34027. });
  34028. colorStops.push({
  34029. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  34030. color: outerColors[1] || 'transparent'
  34031. });
  34032. colorStops.unshift({ // notice colorStops.length have been changed.
  34033. offset: stopLen ? colorStops[0].offset : 0.5,
  34034. color: outerColors[0] || 'transparent'
  34035. });
  34036. // zrUtil.each(colorStops, function (colorStop) {
  34037. // // Make sure each offset has rounded px to avoid not sharp edge
  34038. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  34039. // });
  34040. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  34041. gradient[coordDim] = minCoord;
  34042. gradient[coordDim + '2'] = maxCoord;
  34043. return gradient;
  34044. }
  34045. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  34046. var showAllSymbol = seriesModel.get('showAllSymbol');
  34047. var isAuto = showAllSymbol === 'auto';
  34048. if (showAllSymbol && !isAuto) {
  34049. return;
  34050. }
  34051. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  34052. if (!categoryAxis) {
  34053. return;
  34054. }
  34055. // Note that category label interval strategy might bring some weird effect
  34056. // in some scenario: users may wonder why some of the symbols are not
  34057. // displayed. So we show all symbols as possible as we can.
  34058. if (isAuto
  34059. // Simplify the logic, do not determine label overlap here.
  34060. && canShowAllSymbolForCategory(categoryAxis, data)
  34061. ) {
  34062. return;
  34063. }
  34064. // Otherwise follow the label interval strategy on category axis.
  34065. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  34066. var labelMap = {};
  34067. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  34068. labelMap[labelItem.tickValue] = 1;
  34069. });
  34070. return function (dataIndex) {
  34071. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  34072. };
  34073. }
  34074. function canShowAllSymbolForCategory(categoryAxis, data) {
  34075. // In mose cases, line is monotonous on category axis, and the label size
  34076. // is close with each other. So we check the symbol size and some of the
  34077. // label size alone with the category axis to estimate whether all symbol
  34078. // can be shown without overlap.
  34079. var axisExtent = categoryAxis.getExtent();
  34080. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  34081. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  34082. // Sampling some points, max 5.
  34083. var dataLen = data.count();
  34084. var step = Math.max(1, Math.round(dataLen / 5));
  34085. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  34086. if (SymbolClz$1.getSymbolSize(
  34087. data, dataIndex
  34088. // Only for cartesian, where `isHorizontal` exists.
  34089. )[categoryAxis.isHorizontal() ? 1 : 0]
  34090. // Empirical number
  34091. * 1.5 > availSize
  34092. ) {
  34093. return false;
  34094. }
  34095. }
  34096. return true;
  34097. }
  34098. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  34099. if (coordSys.type === 'cartesian2d') {
  34100. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  34101. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  34102. // Expand clip shape to avoid clipping when line value exceeds axis
  34103. if (!seriesModel.get('clip', true)) {
  34104. var rectShape = clipPath.shape;
  34105. var expandSize = Math.max(rectShape.width, rectShape.height);
  34106. if (isHorizontal) {
  34107. rectShape.y -= expandSize;
  34108. rectShape.height += expandSize * 2;
  34109. }
  34110. else {
  34111. rectShape.x -= expandSize;
  34112. rectShape.width += expandSize * 2;
  34113. }
  34114. }
  34115. return clipPath;
  34116. }
  34117. else {
  34118. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  34119. }
  34120. }
  34121. Chart.extend({
  34122. type: 'line',
  34123. init: function () {
  34124. var lineGroup = new Group();
  34125. var symbolDraw = new SymbolDraw();
  34126. this.group.add(symbolDraw.group);
  34127. this._symbolDraw = symbolDraw;
  34128. this._lineGroup = lineGroup;
  34129. },
  34130. render: function (seriesModel, ecModel, api) {
  34131. var coordSys = seriesModel.coordinateSystem;
  34132. var group = this.group;
  34133. var data = seriesModel.getData();
  34134. var lineStyleModel = seriesModel.getModel('lineStyle');
  34135. var areaStyleModel = seriesModel.getModel('areaStyle');
  34136. var points = data.mapArray(data.getItemLayout);
  34137. var isCoordSysPolar = coordSys.type === 'polar';
  34138. var prevCoordSys = this._coordSys;
  34139. var symbolDraw = this._symbolDraw;
  34140. var polyline = this._polyline;
  34141. var polygon = this._polygon;
  34142. var lineGroup = this._lineGroup;
  34143. var hasAnimation = seriesModel.get('animation');
  34144. var isAreaChart = !areaStyleModel.isEmpty();
  34145. var valueOrigin = areaStyleModel.get('origin');
  34146. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  34147. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  34148. var showSymbol = seriesModel.get('showSymbol');
  34149. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  34150. && getIsIgnoreFunc(seriesModel, data, coordSys);
  34151. // Remove temporary symbols
  34152. var oldData = this._data;
  34153. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34154. if (el.__temp) {
  34155. group.remove(el);
  34156. oldData.setItemGraphicEl(idx, null);
  34157. }
  34158. });
  34159. // Remove previous created symbols if showSymbol changed to false
  34160. if (!showSymbol) {
  34161. symbolDraw.remove();
  34162. }
  34163. group.add(lineGroup);
  34164. // FIXME step not support polar
  34165. var step = !isCoordSysPolar && seriesModel.get('step');
  34166. var clipShapeForSymbol;
  34167. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  34168. clipShapeForSymbol = coordSys.getArea();
  34169. // Avoid float number rounding error for symbol on the edge of axis extent.
  34170. // See #7913 and `test/dataZoom-clip.html`.
  34171. if (clipShapeForSymbol.width != null) {
  34172. clipShapeForSymbol.x -= 0.1;
  34173. clipShapeForSymbol.y -= 0.1;
  34174. clipShapeForSymbol.width += 0.2;
  34175. clipShapeForSymbol.height += 0.2;
  34176. }
  34177. else if (clipShapeForSymbol.r0) {
  34178. clipShapeForSymbol.r0 -= 0.5;
  34179. clipShapeForSymbol.r1 += 0.5;
  34180. }
  34181. }
  34182. this._clipShapeForSymbol = clipShapeForSymbol;
  34183. // Initialization animation or coordinate system changed
  34184. if (
  34185. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  34186. ) {
  34187. showSymbol && symbolDraw.updateData(data, {
  34188. isIgnore: isIgnoreFunc,
  34189. clipShape: clipShapeForSymbol
  34190. });
  34191. if (step) {
  34192. // TODO If stacked series is not step
  34193. points = turnPointsIntoStep(points, coordSys, step);
  34194. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34195. }
  34196. polyline = this._newPolyline(points, coordSys, hasAnimation);
  34197. if (isAreaChart) {
  34198. polygon = this._newPolygon(
  34199. points, stackedOnPoints,
  34200. coordSys, hasAnimation
  34201. );
  34202. }
  34203. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  34204. }
  34205. else {
  34206. if (isAreaChart && !polygon) {
  34207. // If areaStyle is added
  34208. polygon = this._newPolygon(
  34209. points, stackedOnPoints,
  34210. coordSys, hasAnimation
  34211. );
  34212. }
  34213. else if (polygon && !isAreaChart) {
  34214. // If areaStyle is removed
  34215. lineGroup.remove(polygon);
  34216. polygon = this._polygon = null;
  34217. }
  34218. // Update clipPath
  34219. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  34220. // Always update, or it is wrong in the case turning on legend
  34221. // because points are not changed
  34222. showSymbol && symbolDraw.updateData(data, {
  34223. isIgnore: isIgnoreFunc,
  34224. clipShape: clipShapeForSymbol
  34225. });
  34226. // Stop symbol animation and sync with line points
  34227. // FIXME performance?
  34228. data.eachItemGraphicEl(function (el) {
  34229. el.stopAnimation(true);
  34230. });
  34231. // In the case data zoom triggerred refreshing frequently
  34232. // Data may not change if line has a category axis. So it should animate nothing
  34233. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  34234. || !isPointsSame(this._points, points)
  34235. ) {
  34236. if (hasAnimation) {
  34237. this._updateAnimation(
  34238. data, stackedOnPoints, coordSys, api, step, valueOrigin
  34239. );
  34240. }
  34241. else {
  34242. // Not do it in update with animation
  34243. if (step) {
  34244. // TODO If stacked series is not step
  34245. points = turnPointsIntoStep(points, coordSys, step);
  34246. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34247. }
  34248. polyline.setShape({
  34249. points: points
  34250. });
  34251. polygon && polygon.setShape({
  34252. points: points,
  34253. stackedOnPoints: stackedOnPoints
  34254. });
  34255. }
  34256. }
  34257. }
  34258. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  34259. polyline.useStyle(defaults(
  34260. // Use color in lineStyle first
  34261. lineStyleModel.getLineStyle(),
  34262. {
  34263. fill: 'none',
  34264. stroke: visualColor,
  34265. lineJoin: 'bevel'
  34266. }
  34267. ));
  34268. var smooth = seriesModel.get('smooth');
  34269. smooth = getSmooth(seriesModel.get('smooth'));
  34270. polyline.setShape({
  34271. smooth: smooth,
  34272. smoothMonotone: seriesModel.get('smoothMonotone'),
  34273. connectNulls: seriesModel.get('connectNulls')
  34274. });
  34275. if (polygon) {
  34276. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34277. var stackedOnSmooth = 0;
  34278. polygon.useStyle(defaults(
  34279. areaStyleModel.getAreaStyle(),
  34280. {
  34281. fill: visualColor,
  34282. opacity: 0.7,
  34283. lineJoin: 'bevel'
  34284. }
  34285. ));
  34286. if (stackedOnSeries) {
  34287. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34288. }
  34289. polygon.setShape({
  34290. smooth: smooth,
  34291. stackedOnSmooth: stackedOnSmooth,
  34292. smoothMonotone: seriesModel.get('smoothMonotone'),
  34293. connectNulls: seriesModel.get('connectNulls')
  34294. });
  34295. }
  34296. this._data = data;
  34297. // Save the coordinate system for transition animation when data changed
  34298. this._coordSys = coordSys;
  34299. this._stackedOnPoints = stackedOnPoints;
  34300. this._points = points;
  34301. this._step = step;
  34302. this._valueOrigin = valueOrigin;
  34303. },
  34304. dispose: function () {},
  34305. highlight: function (seriesModel, ecModel, api, payload) {
  34306. var data = seriesModel.getData();
  34307. var dataIndex = queryDataIndex(data, payload);
  34308. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34309. var symbol = data.getItemGraphicEl(dataIndex);
  34310. if (!symbol) {
  34311. // Create a temporary symbol if it is not exists
  34312. var pt = data.getItemLayout(dataIndex);
  34313. if (!pt) {
  34314. // Null data
  34315. return;
  34316. }
  34317. // fix #11360: should't draw symbol outside clipShapeForSymbol
  34318. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  34319. return;
  34320. }
  34321. symbol = new SymbolClz$1(data, dataIndex);
  34322. symbol.position = pt;
  34323. symbol.setZ(
  34324. seriesModel.get('zlevel'),
  34325. seriesModel.get('z')
  34326. );
  34327. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  34328. symbol.__temp = true;
  34329. data.setItemGraphicEl(dataIndex, symbol);
  34330. // Stop scale animation
  34331. symbol.stopSymbolAnimation(true);
  34332. this.group.add(symbol);
  34333. }
  34334. symbol.highlight();
  34335. }
  34336. else {
  34337. // Highlight whole series
  34338. Chart.prototype.highlight.call(
  34339. this, seriesModel, ecModel, api, payload
  34340. );
  34341. }
  34342. },
  34343. downplay: function (seriesModel, ecModel, api, payload) {
  34344. var data = seriesModel.getData();
  34345. var dataIndex = queryDataIndex(data, payload);
  34346. if (dataIndex != null && dataIndex >= 0) {
  34347. var symbol = data.getItemGraphicEl(dataIndex);
  34348. if (symbol) {
  34349. if (symbol.__temp) {
  34350. data.setItemGraphicEl(dataIndex, null);
  34351. this.group.remove(symbol);
  34352. }
  34353. else {
  34354. symbol.downplay();
  34355. }
  34356. }
  34357. }
  34358. else {
  34359. // FIXME
  34360. // can not downplay completely.
  34361. // Downplay whole series
  34362. Chart.prototype.downplay.call(
  34363. this, seriesModel, ecModel, api, payload
  34364. );
  34365. }
  34366. },
  34367. /**
  34368. * @param {module:zrender/container/Group} group
  34369. * @param {Array.<Array.<number>>} points
  34370. * @private
  34371. */
  34372. _newPolyline: function (points) {
  34373. var polyline = this._polyline;
  34374. // Remove previous created polyline
  34375. if (polyline) {
  34376. this._lineGroup.remove(polyline);
  34377. }
  34378. polyline = new Polyline$1({
  34379. shape: {
  34380. points: points
  34381. },
  34382. silent: true,
  34383. z2: 10
  34384. });
  34385. this._lineGroup.add(polyline);
  34386. this._polyline = polyline;
  34387. return polyline;
  34388. },
  34389. /**
  34390. * @param {module:zrender/container/Group} group
  34391. * @param {Array.<Array.<number>>} stackedOnPoints
  34392. * @param {Array.<Array.<number>>} points
  34393. * @private
  34394. */
  34395. _newPolygon: function (points, stackedOnPoints) {
  34396. var polygon = this._polygon;
  34397. // Remove previous created polygon
  34398. if (polygon) {
  34399. this._lineGroup.remove(polygon);
  34400. }
  34401. polygon = new Polygon$1({
  34402. shape: {
  34403. points: points,
  34404. stackedOnPoints: stackedOnPoints
  34405. },
  34406. silent: true
  34407. });
  34408. this._lineGroup.add(polygon);
  34409. this._polygon = polygon;
  34410. return polygon;
  34411. },
  34412. /**
  34413. * @private
  34414. */
  34415. // FIXME Two value axis
  34416. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34417. var polyline = this._polyline;
  34418. var polygon = this._polygon;
  34419. var seriesModel = data.hostModel;
  34420. var diff = lineAnimationDiff(
  34421. this._data, data,
  34422. this._stackedOnPoints, stackedOnPoints,
  34423. this._coordSys, coordSys,
  34424. this._valueOrigin, valueOrigin
  34425. );
  34426. var current = diff.current;
  34427. var stackedOnCurrent = diff.stackedOnCurrent;
  34428. var next = diff.next;
  34429. var stackedOnNext = diff.stackedOnNext;
  34430. if (step) {
  34431. // TODO If stacked series is not step
  34432. current = turnPointsIntoStep(diff.current, coordSys, step);
  34433. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34434. next = turnPointsIntoStep(diff.next, coordSys, step);
  34435. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34436. }
  34437. // Don't apply animation if diff is large.
  34438. // For better result and avoid memory explosion problems like
  34439. // https://github.com/apache/incubator-echarts/issues/12229
  34440. if (getBoundingDiff(current, next) > 3000
  34441. || (polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000)
  34442. ) {
  34443. polyline.setShape({
  34444. points: next
  34445. });
  34446. if (polygon) {
  34447. polygon.setShape({
  34448. points: next,
  34449. stackedOnPoints: stackedOnNext
  34450. });
  34451. }
  34452. return;
  34453. }
  34454. // `diff.current` is subset of `current` (which should be ensured by
  34455. // turnPointsIntoStep), so points in `__points` can be updated when
  34456. // points in `current` are update during animation.
  34457. polyline.shape.__points = diff.current;
  34458. polyline.shape.points = current;
  34459. updateProps(polyline, {
  34460. shape: {
  34461. points: next
  34462. }
  34463. }, seriesModel);
  34464. if (polygon) {
  34465. polygon.setShape({
  34466. points: current,
  34467. stackedOnPoints: stackedOnCurrent
  34468. });
  34469. updateProps(polygon, {
  34470. shape: {
  34471. points: next,
  34472. stackedOnPoints: stackedOnNext
  34473. }
  34474. }, seriesModel);
  34475. }
  34476. var updatedDataInfo = [];
  34477. var diffStatus = diff.status;
  34478. for (var i = 0; i < diffStatus.length; i++) {
  34479. var cmd = diffStatus[i].cmd;
  34480. if (cmd === '=') {
  34481. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  34482. if (el) {
  34483. updatedDataInfo.push({
  34484. el: el,
  34485. ptIdx: i // Index of points
  34486. });
  34487. }
  34488. }
  34489. }
  34490. if (polyline.animators && polyline.animators.length) {
  34491. polyline.animators[0].during(function () {
  34492. for (var i = 0; i < updatedDataInfo.length; i++) {
  34493. var el = updatedDataInfo[i].el;
  34494. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  34495. }
  34496. });
  34497. }
  34498. },
  34499. remove: function (ecModel) {
  34500. var group = this.group;
  34501. var oldData = this._data;
  34502. this._lineGroup.removeAll();
  34503. this._symbolDraw.remove(true);
  34504. // Remove temporary created elements when highlighting
  34505. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34506. if (el.__temp) {
  34507. group.remove(el);
  34508. oldData.setItemGraphicEl(idx, null);
  34509. }
  34510. });
  34511. this._polyline =
  34512. this._polygon =
  34513. this._coordSys =
  34514. this._points =
  34515. this._stackedOnPoints =
  34516. this._data = null;
  34517. }
  34518. });
  34519. /*
  34520. * Licensed to the Apache Software Foundation (ASF) under one
  34521. * or more contributor license agreements. See the NOTICE file
  34522. * distributed with this work for additional information
  34523. * regarding copyright ownership. The ASF licenses this file
  34524. * to you under the Apache License, Version 2.0 (the
  34525. * "License"); you may not use this file except in compliance
  34526. * with the License. You may obtain a copy of the License at
  34527. *
  34528. * http://www.apache.org/licenses/LICENSE-2.0
  34529. *
  34530. * Unless required by applicable law or agreed to in writing,
  34531. * software distributed under the License is distributed on an
  34532. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34533. * KIND, either express or implied. See the License for the
  34534. * specific language governing permissions and limitations
  34535. * under the License.
  34536. */
  34537. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  34538. // Encoding visual for all series include which is filtered for legend drawing
  34539. return {
  34540. seriesType: seriesType,
  34541. // For legend.
  34542. performRawSeries: true,
  34543. reset: function (seriesModel, ecModel, api) {
  34544. var data = seriesModel.getData();
  34545. var symbolType = seriesModel.get('symbol');
  34546. var symbolSize = seriesModel.get('symbolSize');
  34547. var keepAspect = seriesModel.get('symbolKeepAspect');
  34548. var symbolRotate = seriesModel.get('symbolRotate');
  34549. var hasSymbolTypeCallback = isFunction$1(symbolType);
  34550. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  34551. var hasSymbolRotateCallback = isFunction$1(symbolRotate);
  34552. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback;
  34553. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  34554. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  34555. data.setVisual({
  34556. legendSymbol: legendSymbol || seriesSymbol,
  34557. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  34558. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  34559. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  34560. // some cases but generally it is not recommanded.
  34561. symbol: seriesSymbol,
  34562. symbolSize: seriesSymbolSize,
  34563. symbolKeepAspect: keepAspect,
  34564. symbolRotate: symbolRotate
  34565. });
  34566. // Only visible series has each data be visual encoded
  34567. if (ecModel.isSeriesFiltered(seriesModel)) {
  34568. return;
  34569. }
  34570. function dataEach(data, idx) {
  34571. if (hasCallback) {
  34572. var rawValue = seriesModel.getRawValue(idx);
  34573. var params = seriesModel.getDataParams(idx);
  34574. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  34575. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  34576. hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params));
  34577. }
  34578. if (data.hasItemOption) {
  34579. var itemModel = data.getItemModel(idx);
  34580. var itemSymbolType = itemModel.getShallow('symbol', true);
  34581. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  34582. var itemSymbolRotate = itemModel.getShallow('symbolRotate', true);
  34583. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  34584. // If has item symbol
  34585. if (itemSymbolType != null) {
  34586. data.setItemVisual(idx, 'symbol', itemSymbolType);
  34587. }
  34588. if (itemSymbolSize != null) {
  34589. // PENDING Transform symbolSize ?
  34590. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  34591. }
  34592. if (itemSymbolRotate != null) {
  34593. data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate);
  34594. }
  34595. if (itemSymbolKeepAspect != null) {
  34596. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  34597. }
  34598. }
  34599. }
  34600. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  34601. }
  34602. };
  34603. };
  34604. /*
  34605. * Licensed to the Apache Software Foundation (ASF) under one
  34606. * or more contributor license agreements. See the NOTICE file
  34607. * distributed with this work for additional information
  34608. * regarding copyright ownership. The ASF licenses this file
  34609. * to you under the Apache License, Version 2.0 (the
  34610. * "License"); you may not use this file except in compliance
  34611. * with the License. You may obtain a copy of the License at
  34612. *
  34613. * http://www.apache.org/licenses/LICENSE-2.0
  34614. *
  34615. * Unless required by applicable law or agreed to in writing,
  34616. * software distributed under the License is distributed on an
  34617. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34618. * KIND, either express or implied. See the License for the
  34619. * specific language governing permissions and limitations
  34620. * under the License.
  34621. */
  34622. /* global Float32Array */
  34623. var pointsLayout = function (seriesType) {
  34624. return {
  34625. seriesType: seriesType,
  34626. plan: createRenderPlanner(),
  34627. reset: function (seriesModel) {
  34628. var data = seriesModel.getData();
  34629. var coordSys = seriesModel.coordinateSystem;
  34630. var pipelineContext = seriesModel.pipelineContext;
  34631. var isLargeRender = pipelineContext.large;
  34632. if (!coordSys) {
  34633. return;
  34634. }
  34635. var dims = map(coordSys.dimensions, function (dim) {
  34636. return data.mapDimension(dim);
  34637. }).slice(0, 2);
  34638. var dimLen = dims.length;
  34639. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  34640. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  34641. dims[0] = stackResultDim;
  34642. }
  34643. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  34644. dims[1] = stackResultDim;
  34645. }
  34646. function progress(params, data) {
  34647. var segCount = params.end - params.start;
  34648. var points = isLargeRender && new Float32Array(segCount * dimLen);
  34649. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  34650. var point;
  34651. if (dimLen === 1) {
  34652. var x = data.get(dims[0], i);
  34653. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  34654. }
  34655. else {
  34656. var x = tmpIn[0] = data.get(dims[0], i);
  34657. var y = tmpIn[1] = data.get(dims[1], i);
  34658. // Also {Array.<number>}, not undefined to avoid if...else... statement
  34659. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  34660. }
  34661. if (isLargeRender) {
  34662. points[offset++] = point ? point[0] : NaN;
  34663. points[offset++] = point ? point[1] : NaN;
  34664. }
  34665. else {
  34666. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  34667. }
  34668. }
  34669. isLargeRender && data.setLayout('symbolPoints', points);
  34670. }
  34671. return dimLen && {progress: progress};
  34672. }
  34673. };
  34674. };
  34675. /*
  34676. * Licensed to the Apache Software Foundation (ASF) under one
  34677. * or more contributor license agreements. See the NOTICE file
  34678. * distributed with this work for additional information
  34679. * regarding copyright ownership. The ASF licenses this file
  34680. * to you under the Apache License, Version 2.0 (the
  34681. * "License"); you may not use this file except in compliance
  34682. * with the License. You may obtain a copy of the License at
  34683. *
  34684. * http://www.apache.org/licenses/LICENSE-2.0
  34685. *
  34686. * Unless required by applicable law or agreed to in writing,
  34687. * software distributed under the License is distributed on an
  34688. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34689. * KIND, either express or implied. See the License for the
  34690. * specific language governing permissions and limitations
  34691. * under the License.
  34692. */
  34693. var samplers = {
  34694. average: function (frame) {
  34695. var sum = 0;
  34696. var count = 0;
  34697. for (var i = 0; i < frame.length; i++) {
  34698. if (!isNaN(frame[i])) {
  34699. sum += frame[i];
  34700. count++;
  34701. }
  34702. }
  34703. // Return NaN if count is 0
  34704. return count === 0 ? NaN : sum / count;
  34705. },
  34706. sum: function (frame) {
  34707. var sum = 0;
  34708. for (var i = 0; i < frame.length; i++) {
  34709. // Ignore NaN
  34710. sum += frame[i] || 0;
  34711. }
  34712. return sum;
  34713. },
  34714. max: function (frame) {
  34715. var max = -Infinity;
  34716. for (var i = 0; i < frame.length; i++) {
  34717. frame[i] > max && (max = frame[i]);
  34718. }
  34719. // NaN will cause illegal axis extent.
  34720. return isFinite(max) ? max : NaN;
  34721. },
  34722. min: function (frame) {
  34723. var min = Infinity;
  34724. for (var i = 0; i < frame.length; i++) {
  34725. frame[i] < min && (min = frame[i]);
  34726. }
  34727. // NaN will cause illegal axis extent.
  34728. return isFinite(min) ? min : NaN;
  34729. },
  34730. // TODO
  34731. // Median
  34732. nearest: function (frame) {
  34733. return frame[0];
  34734. }
  34735. };
  34736. var indexSampler = function (frame, value) {
  34737. return Math.round(frame.length / 2);
  34738. };
  34739. var dataSample = function (seriesType) {
  34740. return {
  34741. seriesType: seriesType,
  34742. modifyOutputEnd: true,
  34743. reset: function (seriesModel, ecModel, api) {
  34744. var data = seriesModel.getData();
  34745. var sampling = seriesModel.get('sampling');
  34746. var coordSys = seriesModel.coordinateSystem;
  34747. // Only cartesian2d support down sampling
  34748. if (coordSys.type === 'cartesian2d' && sampling) {
  34749. var baseAxis = coordSys.getBaseAxis();
  34750. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34751. var extent = baseAxis.getExtent();
  34752. // Coordinste system has been resized
  34753. var size = Math.abs(extent[1] - extent[0]);
  34754. var rate = Math.round(data.count() / size);
  34755. if (rate > 1) {
  34756. var sampler;
  34757. if (typeof sampling === 'string') {
  34758. sampler = samplers[sampling];
  34759. }
  34760. else if (typeof sampling === 'function') {
  34761. sampler = sampling;
  34762. }
  34763. if (sampler) {
  34764. // Only support sample the first dim mapped from value axis.
  34765. seriesModel.setData(data.downSample(
  34766. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  34767. ));
  34768. }
  34769. }
  34770. }
  34771. }
  34772. };
  34773. };
  34774. /*
  34775. * Licensed to the Apache Software Foundation (ASF) under one
  34776. * or more contributor license agreements. See the NOTICE file
  34777. * distributed with this work for additional information
  34778. * regarding copyright ownership. The ASF licenses this file
  34779. * to you under the Apache License, Version 2.0 (the
  34780. * "License"); you may not use this file except in compliance
  34781. * with the License. You may obtain a copy of the License at
  34782. *
  34783. * http://www.apache.org/licenses/LICENSE-2.0
  34784. *
  34785. * Unless required by applicable law or agreed to in writing,
  34786. * software distributed under the License is distributed on an
  34787. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34788. * KIND, either express or implied. See the License for the
  34789. * specific language governing permissions and limitations
  34790. * under the License.
  34791. */
  34792. /**
  34793. * Cartesian coordinate system
  34794. * @module echarts/coord/Cartesian
  34795. *
  34796. */
  34797. function dimAxisMapper(dim) {
  34798. return this._axes[dim];
  34799. }
  34800. /**
  34801. * @alias module:echarts/coord/Cartesian
  34802. * @constructor
  34803. */
  34804. var Cartesian = function (name) {
  34805. this._axes = {};
  34806. this._dimList = [];
  34807. /**
  34808. * @type {string}
  34809. */
  34810. this.name = name || '';
  34811. };
  34812. Cartesian.prototype = {
  34813. constructor: Cartesian,
  34814. type: 'cartesian',
  34815. /**
  34816. * Get axis
  34817. * @param {number|string} dim
  34818. * @return {module:echarts/coord/Cartesian~Axis}
  34819. */
  34820. getAxis: function (dim) {
  34821. return this._axes[dim];
  34822. },
  34823. /**
  34824. * Get axes list
  34825. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  34826. */
  34827. getAxes: function () {
  34828. return map(this._dimList, dimAxisMapper, this);
  34829. },
  34830. /**
  34831. * Get axes list by given scale type
  34832. */
  34833. getAxesByScale: function (scaleType) {
  34834. scaleType = scaleType.toLowerCase();
  34835. return filter(
  34836. this.getAxes(),
  34837. function (axis) {
  34838. return axis.scale.type === scaleType;
  34839. }
  34840. );
  34841. },
  34842. /**
  34843. * Add axis
  34844. * @param {module:echarts/coord/Cartesian.Axis}
  34845. */
  34846. addAxis: function (axis) {
  34847. var dim = axis.dim;
  34848. this._axes[dim] = axis;
  34849. this._dimList.push(dim);
  34850. },
  34851. /**
  34852. * Convert data to coord in nd space
  34853. * @param {Array.<number>|Object.<string, number>} val
  34854. * @return {Array.<number>|Object.<string, number>}
  34855. */
  34856. dataToCoord: function (val) {
  34857. return this._dataCoordConvert(val, 'dataToCoord');
  34858. },
  34859. /**
  34860. * Convert coord in nd space to data
  34861. * @param {Array.<number>|Object.<string, number>} val
  34862. * @return {Array.<number>|Object.<string, number>}
  34863. */
  34864. coordToData: function (val) {
  34865. return this._dataCoordConvert(val, 'coordToData');
  34866. },
  34867. _dataCoordConvert: function (input, method) {
  34868. var dimList = this._dimList;
  34869. var output = input instanceof Array ? [] : {};
  34870. for (var i = 0; i < dimList.length; i++) {
  34871. var dim = dimList[i];
  34872. var axis = this._axes[dim];
  34873. output[dim] = axis[method](input[dim]);
  34874. }
  34875. return output;
  34876. }
  34877. };
  34878. /*
  34879. * Licensed to the Apache Software Foundation (ASF) under one
  34880. * or more contributor license agreements. See the NOTICE file
  34881. * distributed with this work for additional information
  34882. * regarding copyright ownership. The ASF licenses this file
  34883. * to you under the Apache License, Version 2.0 (the
  34884. * "License"); you may not use this file except in compliance
  34885. * with the License. You may obtain a copy of the License at
  34886. *
  34887. * http://www.apache.org/licenses/LICENSE-2.0
  34888. *
  34889. * Unless required by applicable law or agreed to in writing,
  34890. * software distributed under the License is distributed on an
  34891. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34892. * KIND, either express or implied. See the License for the
  34893. * specific language governing permissions and limitations
  34894. * under the License.
  34895. */
  34896. function Cartesian2D(name) {
  34897. Cartesian.call(this, name);
  34898. }
  34899. Cartesian2D.prototype = {
  34900. constructor: Cartesian2D,
  34901. type: 'cartesian2d',
  34902. /**
  34903. * @type {Array.<string>}
  34904. * @readOnly
  34905. */
  34906. dimensions: ['x', 'y'],
  34907. /**
  34908. * Base axis will be used on stacking.
  34909. *
  34910. * @return {module:echarts/coord/cartesian/Axis2D}
  34911. */
  34912. getBaseAxis: function () {
  34913. return this.getAxesByScale('ordinal')[0]
  34914. || this.getAxesByScale('time')[0]
  34915. || this.getAxis('x');
  34916. },
  34917. /**
  34918. * If contain point
  34919. * @param {Array.<number>} point
  34920. * @return {boolean}
  34921. */
  34922. containPoint: function (point) {
  34923. var axisX = this.getAxis('x');
  34924. var axisY = this.getAxis('y');
  34925. return axisX.contain(axisX.toLocalCoord(point[0]))
  34926. && axisY.contain(axisY.toLocalCoord(point[1]));
  34927. },
  34928. /**
  34929. * If contain data
  34930. * @param {Array.<number>} data
  34931. * @return {boolean}
  34932. */
  34933. containData: function (data) {
  34934. return this.getAxis('x').containData(data[0])
  34935. && this.getAxis('y').containData(data[1]);
  34936. },
  34937. /**
  34938. * @param {Array.<number>} data
  34939. * @param {Array.<number>} out
  34940. * @return {Array.<number>}
  34941. */
  34942. dataToPoint: function (data, reserved, out) {
  34943. var xAxis = this.getAxis('x');
  34944. var yAxis = this.getAxis('y');
  34945. out = out || [];
  34946. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  34947. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  34948. return out;
  34949. },
  34950. /**
  34951. * @param {Array.<number>} data
  34952. * @param {Array.<number>} out
  34953. * @return {Array.<number>}
  34954. */
  34955. clampData: function (data, out) {
  34956. var xScale = this.getAxis('x').scale;
  34957. var yScale = this.getAxis('y').scale;
  34958. var xAxisExtent = xScale.getExtent();
  34959. var yAxisExtent = yScale.getExtent();
  34960. var x = xScale.parse(data[0]);
  34961. var y = yScale.parse(data[1]);
  34962. out = out || [];
  34963. out[0] = Math.min(
  34964. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  34965. Math.max(xAxisExtent[0], xAxisExtent[1])
  34966. );
  34967. out[1] = Math.min(
  34968. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  34969. Math.max(yAxisExtent[0], yAxisExtent[1])
  34970. );
  34971. return out;
  34972. },
  34973. /**
  34974. * @param {Array.<number>} point
  34975. * @param {Array.<number>} out
  34976. * @return {Array.<number>}
  34977. */
  34978. pointToData: function (point, out) {
  34979. var xAxis = this.getAxis('x');
  34980. var yAxis = this.getAxis('y');
  34981. out = out || [];
  34982. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  34983. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  34984. return out;
  34985. },
  34986. /**
  34987. * Get other axis
  34988. * @param {module:echarts/coord/cartesian/Axis2D} axis
  34989. */
  34990. getOtherAxis: function (axis) {
  34991. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  34992. },
  34993. /**
  34994. * Get rect area of cartesian.
  34995. * Area will have a contain function to determine if a point is in the coordinate system.
  34996. * @return {BoundingRect}
  34997. */
  34998. getArea: function () {
  34999. var xExtent = this.getAxis('x').getGlobalExtent();
  35000. var yExtent = this.getAxis('y').getGlobalExtent();
  35001. var x = Math.min(xExtent[0], xExtent[1]);
  35002. var y = Math.min(yExtent[0], yExtent[1]);
  35003. var width = Math.max(xExtent[0], xExtent[1]) - x;
  35004. var height = Math.max(yExtent[0], yExtent[1]) - y;
  35005. var rect = new BoundingRect(x, y, width, height);
  35006. return rect;
  35007. }
  35008. };
  35009. inherits(Cartesian2D, Cartesian);
  35010. /*
  35011. * Licensed to the Apache Software Foundation (ASF) under one
  35012. * or more contributor license agreements. See the NOTICE file
  35013. * distributed with this work for additional information
  35014. * regarding copyright ownership. The ASF licenses this file
  35015. * to you under the Apache License, Version 2.0 (the
  35016. * "License"); you may not use this file except in compliance
  35017. * with the License. You may obtain a copy of the License at
  35018. *
  35019. * http://www.apache.org/licenses/LICENSE-2.0
  35020. *
  35021. * Unless required by applicable law or agreed to in writing,
  35022. * software distributed under the License is distributed on an
  35023. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35024. * KIND, either express or implied. See the License for the
  35025. * specific language governing permissions and limitations
  35026. * under the License.
  35027. */
  35028. /**
  35029. * Extend axis 2d
  35030. * @constructor module:echarts/coord/cartesian/Axis2D
  35031. * @extends {module:echarts/coord/cartesian/Axis}
  35032. * @param {string} dim
  35033. * @param {*} scale
  35034. * @param {Array.<number>} coordExtent
  35035. * @param {string} axisType
  35036. * @param {string} position
  35037. */
  35038. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  35039. Axis.call(this, dim, scale, coordExtent);
  35040. /**
  35041. * Axis type
  35042. * - 'category'
  35043. * - 'value'
  35044. * - 'time'
  35045. * - 'log'
  35046. * @type {string}
  35047. */
  35048. this.type = axisType || 'value';
  35049. /**
  35050. * Axis position
  35051. * - 'top'
  35052. * - 'bottom'
  35053. * - 'left'
  35054. * - 'right'
  35055. */
  35056. this.position = position || 'bottom';
  35057. };
  35058. Axis2D.prototype = {
  35059. constructor: Axis2D,
  35060. /**
  35061. * Index of axis, can be used as key
  35062. */
  35063. index: 0,
  35064. /**
  35065. * Implemented in <module:echarts/coord/cartesian/Grid>.
  35066. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  35067. * If not on zero of other axis, return null/undefined.
  35068. * If no axes, return an empty array.
  35069. */
  35070. getAxesOnZeroOf: null,
  35071. /**
  35072. * Axis model
  35073. * @param {module:echarts/coord/cartesian/AxisModel}
  35074. */
  35075. model: null,
  35076. isHorizontal: function () {
  35077. var position = this.position;
  35078. return position === 'top' || position === 'bottom';
  35079. },
  35080. /**
  35081. * Each item cooresponds to this.getExtent(), which
  35082. * means globalExtent[0] may greater than globalExtent[1],
  35083. * unless `asc` is input.
  35084. *
  35085. * @param {boolean} [asc]
  35086. * @return {Array.<number>}
  35087. */
  35088. getGlobalExtent: function (asc) {
  35089. var ret = this.getExtent();
  35090. ret[0] = this.toGlobalCoord(ret[0]);
  35091. ret[1] = this.toGlobalCoord(ret[1]);
  35092. asc && ret[0] > ret[1] && ret.reverse();
  35093. return ret;
  35094. },
  35095. getOtherAxis: function () {
  35096. this.grid.getOtherAxis();
  35097. },
  35098. /**
  35099. * @override
  35100. */
  35101. pointToData: function (point, clamp) {
  35102. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  35103. },
  35104. /**
  35105. * Transform global coord to local coord,
  35106. * i.e. var localCoord = axis.toLocalCoord(80);
  35107. * designate by module:echarts/coord/cartesian/Grid.
  35108. * @type {Function}
  35109. */
  35110. toLocalCoord: null,
  35111. /**
  35112. * Transform global coord to local coord,
  35113. * i.e. var globalCoord = axis.toLocalCoord(40);
  35114. * designate by module:echarts/coord/cartesian/Grid.
  35115. * @type {Function}
  35116. */
  35117. toGlobalCoord: null
  35118. };
  35119. inherits(Axis2D, Axis);
  35120. /*
  35121. * Licensed to the Apache Software Foundation (ASF) under one
  35122. * or more contributor license agreements. See the NOTICE file
  35123. * distributed with this work for additional information
  35124. * regarding copyright ownership. The ASF licenses this file
  35125. * to you under the Apache License, Version 2.0 (the
  35126. * "License"); you may not use this file except in compliance
  35127. * with the License. You may obtain a copy of the License at
  35128. *
  35129. * http://www.apache.org/licenses/LICENSE-2.0
  35130. *
  35131. * Unless required by applicable law or agreed to in writing,
  35132. * software distributed under the License is distributed on an
  35133. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35134. * KIND, either express or implied. See the License for the
  35135. * specific language governing permissions and limitations
  35136. * under the License.
  35137. */
  35138. var defaultOption = {
  35139. show: true,
  35140. zlevel: 0,
  35141. z: 0,
  35142. // Inverse the axis.
  35143. inverse: false,
  35144. // Axis name displayed.
  35145. name: '',
  35146. // 'start' | 'middle' | 'end'
  35147. nameLocation: 'end',
  35148. // By degree. By default auto rotate by nameLocation.
  35149. nameRotate: null,
  35150. nameTruncate: {
  35151. maxWidth: null,
  35152. ellipsis: '...',
  35153. placeholder: '.'
  35154. },
  35155. // Use global text style by default.
  35156. nameTextStyle: {},
  35157. // The gap between axisName and axisLine.
  35158. nameGap: 15,
  35159. // Default `false` to support tooltip.
  35160. silent: false,
  35161. // Default `false` to avoid legacy user event listener fail.
  35162. triggerEvent: false,
  35163. tooltip: {
  35164. show: false
  35165. },
  35166. axisPointer: {},
  35167. axisLine: {
  35168. show: true,
  35169. onZero: true,
  35170. onZeroAxisIndex: null,
  35171. lineStyle: {
  35172. color: '#333',
  35173. width: 1,
  35174. type: 'solid'
  35175. },
  35176. // The arrow at both ends the the axis.
  35177. symbol: ['none', 'none'],
  35178. symbolSize: [10, 15]
  35179. },
  35180. axisTick: {
  35181. show: true,
  35182. // Whether axisTick is inside the grid or outside the grid.
  35183. inside: false,
  35184. // The length of axisTick.
  35185. length: 5,
  35186. lineStyle: {
  35187. width: 1
  35188. }
  35189. },
  35190. axisLabel: {
  35191. show: true,
  35192. // Whether axisLabel is inside the grid or outside the grid.
  35193. inside: false,
  35194. rotate: 0,
  35195. // true | false | null/undefined (auto)
  35196. showMinLabel: null,
  35197. // true | false | null/undefined (auto)
  35198. showMaxLabel: null,
  35199. margin: 8,
  35200. // formatter: null,
  35201. fontSize: 12
  35202. },
  35203. splitLine: {
  35204. show: true,
  35205. lineStyle: {
  35206. color: ['#ccc'],
  35207. width: 1,
  35208. type: 'solid'
  35209. }
  35210. },
  35211. splitArea: {
  35212. show: false,
  35213. areaStyle: {
  35214. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  35215. }
  35216. }
  35217. };
  35218. var axisDefault = {};
  35219. axisDefault.categoryAxis = merge({
  35220. // The gap at both ends of the axis. For categoryAxis, boolean.
  35221. boundaryGap: true,
  35222. // Set false to faster category collection.
  35223. // Only usefull in the case like: category is
  35224. // ['2012-01-01', '2012-01-02', ...], where the input
  35225. // data has been ensured not duplicate and is large data.
  35226. // null means "auto":
  35227. // if axis.data provided, do not deduplication,
  35228. // else do deduplication.
  35229. deduplication: null,
  35230. // splitArea: {
  35231. // show: false
  35232. // },
  35233. splitLine: {
  35234. show: false
  35235. },
  35236. axisTick: {
  35237. // If tick is align with label when boundaryGap is true
  35238. alignWithLabel: false,
  35239. interval: 'auto'
  35240. },
  35241. axisLabel: {
  35242. interval: 'auto'
  35243. }
  35244. }, defaultOption);
  35245. axisDefault.valueAxis = merge({
  35246. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  35247. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  35248. boundaryGap: [0, 0],
  35249. // TODO
  35250. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  35251. // Min value of the axis. can be:
  35252. // + a number
  35253. // + 'dataMin': use the min value in data.
  35254. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  35255. // min: null,
  35256. // Max value of the axis. can be:
  35257. // + a number
  35258. // + 'dataMax': use the max value in data.
  35259. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  35260. // max: null,
  35261. // Readonly prop, specifies start value of the range when using data zoom.
  35262. // rangeStart: null
  35263. // Readonly prop, specifies end value of the range when using data zoom.
  35264. // rangeEnd: null
  35265. // Optional value can be:
  35266. // + `false`: always include value 0.
  35267. // + `true`: the extent do not consider value 0.
  35268. // scale: false,
  35269. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  35270. splitNumber: 5,
  35271. // Interval specifies the span of the ticks is mandatorily.
  35272. // interval: null
  35273. // Specify min interval when auto calculate tick interval.
  35274. // minInterval: null
  35275. // Specify max interval when auto calculate tick interval.
  35276. // maxInterval: null
  35277. minorTick: {
  35278. // Minor tick, not available for cateogry axis.
  35279. show: false,
  35280. // Split number of minor ticks. The value should be in range of (0, 100)
  35281. splitNumber: 5,
  35282. // Lenght of minor tick
  35283. length: 3,
  35284. // Same inside with axisTick
  35285. // Line style
  35286. lineStyle: {
  35287. // Default to be same with axisTick
  35288. }
  35289. },
  35290. minorSplitLine: {
  35291. show: false,
  35292. lineStyle: {
  35293. color: '#eee',
  35294. width: 1
  35295. }
  35296. }
  35297. }, defaultOption);
  35298. axisDefault.timeAxis = defaults({
  35299. scale: true,
  35300. min: 'dataMin',
  35301. max: 'dataMax'
  35302. }, axisDefault.valueAxis);
  35303. axisDefault.logAxis = defaults({
  35304. scale: true,
  35305. logBase: 10
  35306. }, axisDefault.valueAxis);
  35307. /*
  35308. * Licensed to the Apache Software Foundation (ASF) under one
  35309. * or more contributor license agreements. See the NOTICE file
  35310. * distributed with this work for additional information
  35311. * regarding copyright ownership. The ASF licenses this file
  35312. * to you under the Apache License, Version 2.0 (the
  35313. * "License"); you may not use this file except in compliance
  35314. * with the License. You may obtain a copy of the License at
  35315. *
  35316. * http://www.apache.org/licenses/LICENSE-2.0
  35317. *
  35318. * Unless required by applicable law or agreed to in writing,
  35319. * software distributed under the License is distributed on an
  35320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35321. * KIND, either express or implied. See the License for the
  35322. * specific language governing permissions and limitations
  35323. * under the License.
  35324. */
  35325. // FIXME axisType is fixed ?
  35326. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  35327. /**
  35328. * Generate sub axis model class
  35329. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  35330. * @param {module:echarts/model/Component} BaseAxisModelClass
  35331. * @param {Function} axisTypeDefaulter
  35332. * @param {Object} [extraDefaultOption]
  35333. */
  35334. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  35335. each$1(AXIS_TYPES, function (axisType) {
  35336. BaseAxisModelClass.extend({
  35337. /**
  35338. * @readOnly
  35339. */
  35340. type: axisName + 'Axis.' + axisType,
  35341. mergeDefaultAndTheme: function (option, ecModel) {
  35342. var layoutMode = this.layoutMode;
  35343. var inputPositionParams = layoutMode
  35344. ? getLayoutParams(option) : {};
  35345. var themeModel = ecModel.getTheme();
  35346. merge(option, themeModel.get(axisType + 'Axis'));
  35347. merge(option, this.getDefaultOption());
  35348. option.type = axisTypeDefaulter(axisName, option);
  35349. if (layoutMode) {
  35350. mergeLayoutParam(option, inputPositionParams, layoutMode);
  35351. }
  35352. },
  35353. /**
  35354. * @override
  35355. */
  35356. optionUpdated: function () {
  35357. var thisOption = this.option;
  35358. if (thisOption.type === 'category') {
  35359. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  35360. }
  35361. },
  35362. /**
  35363. * Should not be called before all of 'getInitailData' finished.
  35364. * Because categories are collected during initializing data.
  35365. */
  35366. getCategories: function (rawData) {
  35367. var option = this.option;
  35368. // FIXME
  35369. // warning if called before all of 'getInitailData' finished.
  35370. if (option.type === 'category') {
  35371. if (rawData) {
  35372. return option.data;
  35373. }
  35374. return this.__ordinalMeta.categories;
  35375. }
  35376. },
  35377. getOrdinalMeta: function () {
  35378. return this.__ordinalMeta;
  35379. },
  35380. defaultOption: mergeAll(
  35381. [
  35382. {},
  35383. axisDefault[axisType + 'Axis'],
  35384. extraDefaultOption
  35385. ],
  35386. true
  35387. )
  35388. });
  35389. });
  35390. ComponentModel.registerSubTypeDefaulter(
  35391. axisName + 'Axis',
  35392. curry(axisTypeDefaulter, axisName)
  35393. );
  35394. };
  35395. /*
  35396. * Licensed to the Apache Software Foundation (ASF) under one
  35397. * or more contributor license agreements. See the NOTICE file
  35398. * distributed with this work for additional information
  35399. * regarding copyright ownership. The ASF licenses this file
  35400. * to you under the Apache License, Version 2.0 (the
  35401. * "License"); you may not use this file except in compliance
  35402. * with the License. You may obtain a copy of the License at
  35403. *
  35404. * http://www.apache.org/licenses/LICENSE-2.0
  35405. *
  35406. * Unless required by applicable law or agreed to in writing,
  35407. * software distributed under the License is distributed on an
  35408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35409. * KIND, either express or implied. See the License for the
  35410. * specific language governing permissions and limitations
  35411. * under the License.
  35412. */
  35413. var AxisModel = ComponentModel.extend({
  35414. type: 'cartesian2dAxis',
  35415. /**
  35416. * @type {module:echarts/coord/cartesian/Axis2D}
  35417. */
  35418. axis: null,
  35419. /**
  35420. * @override
  35421. */
  35422. init: function () {
  35423. AxisModel.superApply(this, 'init', arguments);
  35424. this.resetRange();
  35425. },
  35426. /**
  35427. * @override
  35428. */
  35429. mergeOption: function () {
  35430. AxisModel.superApply(this, 'mergeOption', arguments);
  35431. this.resetRange();
  35432. },
  35433. /**
  35434. * @override
  35435. */
  35436. restoreData: function () {
  35437. AxisModel.superApply(this, 'restoreData', arguments);
  35438. this.resetRange();
  35439. },
  35440. /**
  35441. * @override
  35442. * @return {module:echarts/model/Component}
  35443. */
  35444. getCoordSysModel: function () {
  35445. return this.ecModel.queryComponents({
  35446. mainType: 'grid',
  35447. index: this.option.gridIndex,
  35448. id: this.option.gridId
  35449. })[0];
  35450. }
  35451. });
  35452. function getAxisType(axisDim, option) {
  35453. // Default axis with data is category axis
  35454. return option.type || (option.data ? 'category' : 'value');
  35455. }
  35456. merge(AxisModel.prototype, axisModelCommonMixin);
  35457. var extraOption = {
  35458. // gridIndex: 0,
  35459. // gridId: '',
  35460. // Offset is for multiple axis on the same position
  35461. offset: 0
  35462. };
  35463. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  35464. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  35465. /*
  35466. * Licensed to the Apache Software Foundation (ASF) under one
  35467. * or more contributor license agreements. See the NOTICE file
  35468. * distributed with this work for additional information
  35469. * regarding copyright ownership. The ASF licenses this file
  35470. * to you under the Apache License, Version 2.0 (the
  35471. * "License"); you may not use this file except in compliance
  35472. * with the License. You may obtain a copy of the License at
  35473. *
  35474. * http://www.apache.org/licenses/LICENSE-2.0
  35475. *
  35476. * Unless required by applicable law or agreed to in writing,
  35477. * software distributed under the License is distributed on an
  35478. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35479. * KIND, either express or implied. See the License for the
  35480. * specific language governing permissions and limitations
  35481. * under the License.
  35482. */
  35483. // Grid 是在有直角坐标系的时候必须要存在的
  35484. // 所以这里也要被 Cartesian2D 依赖
  35485. ComponentModel.extend({
  35486. type: 'grid',
  35487. dependencies: ['xAxis', 'yAxis'],
  35488. layoutMode: 'box',
  35489. /**
  35490. * @type {module:echarts/coord/cartesian/Grid}
  35491. */
  35492. coordinateSystem: null,
  35493. defaultOption: {
  35494. show: false,
  35495. zlevel: 0,
  35496. z: 0,
  35497. left: '10%',
  35498. top: 60,
  35499. right: '10%',
  35500. bottom: 60,
  35501. // If grid size contain label
  35502. containLabel: false,
  35503. // width: {totalWidth} - left - right,
  35504. // height: {totalHeight} - top - bottom,
  35505. backgroundColor: 'rgba(0,0,0,0)',
  35506. borderWidth: 1,
  35507. borderColor: '#ccc'
  35508. }
  35509. });
  35510. /*
  35511. * Licensed to the Apache Software Foundation (ASF) under one
  35512. * or more contributor license agreements. See the NOTICE file
  35513. * distributed with this work for additional information
  35514. * regarding copyright ownership. The ASF licenses this file
  35515. * to you under the Apache License, Version 2.0 (the
  35516. * "License"); you may not use this file except in compliance
  35517. * with the License. You may obtain a copy of the License at
  35518. *
  35519. * http://www.apache.org/licenses/LICENSE-2.0
  35520. *
  35521. * Unless required by applicable law or agreed to in writing,
  35522. * software distributed under the License is distributed on an
  35523. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35524. * KIND, either express or implied. See the License for the
  35525. * specific language governing permissions and limitations
  35526. * under the License.
  35527. */
  35528. /**
  35529. * Grid is a region which contains at most 4 cartesian systems
  35530. *
  35531. * TODO Default cartesian
  35532. */
  35533. // Depends on GridModel, AxisModel, which performs preprocess.
  35534. /**
  35535. * Check if the axis is used in the specified grid
  35536. * @inner
  35537. */
  35538. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  35539. return axisModel.getCoordSysModel() === gridModel;
  35540. }
  35541. function Grid(gridModel, ecModel, api) {
  35542. /**
  35543. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  35544. * @private
  35545. */
  35546. this._coordsMap = {};
  35547. /**
  35548. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  35549. * @private
  35550. */
  35551. this._coordsList = [];
  35552. /**
  35553. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  35554. * @private
  35555. */
  35556. this._axesMap = {};
  35557. /**
  35558. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  35559. * @private
  35560. */
  35561. this._axesList = [];
  35562. this._initCartesian(gridModel, ecModel, api);
  35563. this.model = gridModel;
  35564. }
  35565. var gridProto = Grid.prototype;
  35566. gridProto.type = 'grid';
  35567. gridProto.axisPointerEnabled = true;
  35568. gridProto.getRect = function () {
  35569. return this._rect;
  35570. };
  35571. gridProto.update = function (ecModel, api) {
  35572. var axesMap = this._axesMap;
  35573. this._updateScale(ecModel, this.model);
  35574. each$1(axesMap.x, function (xAxis) {
  35575. niceScaleExtent(xAxis.scale, xAxis.model);
  35576. });
  35577. each$1(axesMap.y, function (yAxis) {
  35578. niceScaleExtent(yAxis.scale, yAxis.model);
  35579. });
  35580. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  35581. var onZeroRecords = {};
  35582. each$1(axesMap.x, function (xAxis) {
  35583. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  35584. });
  35585. each$1(axesMap.y, function (yAxis) {
  35586. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  35587. });
  35588. // Resize again if containLabel is enabled
  35589. // FIXME It may cause getting wrong grid size in data processing stage
  35590. this.resize(this.model, api);
  35591. };
  35592. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  35593. axis.getAxesOnZeroOf = function () {
  35594. // TODO: onZero of multiple axes.
  35595. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  35596. };
  35597. // onZero can not be enabled in these two situations:
  35598. // 1. When any other axis is a category axis.
  35599. // 2. When no axis is cross 0 point.
  35600. var otherAxes = axesMap[otherAxisDim];
  35601. var otherAxisOnZeroOf;
  35602. var axisModel = axis.model;
  35603. var onZero = axisModel.get('axisLine.onZero');
  35604. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  35605. if (!onZero) {
  35606. return;
  35607. }
  35608. // If target axis is specified.
  35609. if (onZeroAxisIndex != null) {
  35610. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  35611. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  35612. }
  35613. }
  35614. else {
  35615. // Find the first available other axis.
  35616. for (var idx in otherAxes) {
  35617. if (otherAxes.hasOwnProperty(idx)
  35618. && canOnZeroToAxis(otherAxes[idx])
  35619. // Consider that two Y axes on one value axis,
  35620. // if both onZero, the two Y axes overlap.
  35621. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  35622. ) {
  35623. otherAxisOnZeroOf = otherAxes[idx];
  35624. break;
  35625. }
  35626. }
  35627. }
  35628. if (otherAxisOnZeroOf) {
  35629. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  35630. }
  35631. function getOnZeroRecordKey(axis) {
  35632. return axis.dim + '_' + axis.index;
  35633. }
  35634. }
  35635. function canOnZeroToAxis(axis) {
  35636. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  35637. }
  35638. /**
  35639. * Resize the grid
  35640. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35641. * @param {module:echarts/ExtensionAPI} api
  35642. */
  35643. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  35644. var gridRect = getLayoutRect(
  35645. gridModel.getBoxLayoutParams(), {
  35646. width: api.getWidth(),
  35647. height: api.getHeight()
  35648. });
  35649. this._rect = gridRect;
  35650. var axesList = this._axesList;
  35651. adjustAxes();
  35652. // Minus label size
  35653. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  35654. each$1(axesList, function (axis) {
  35655. if (!axis.model.get('axisLabel.inside')) {
  35656. var labelUnionRect = estimateLabelUnionRect(axis);
  35657. if (labelUnionRect) {
  35658. var dim = axis.isHorizontal() ? 'height' : 'width';
  35659. var margin = axis.model.get('axisLabel.margin');
  35660. gridRect[dim] -= labelUnionRect[dim] + margin;
  35661. if (axis.position === 'top') {
  35662. gridRect.y += labelUnionRect.height + margin;
  35663. }
  35664. else if (axis.position === 'left') {
  35665. gridRect.x += labelUnionRect.width + margin;
  35666. }
  35667. }
  35668. }
  35669. });
  35670. adjustAxes();
  35671. }
  35672. function adjustAxes() {
  35673. each$1(axesList, function (axis) {
  35674. var isHorizontal = axis.isHorizontal();
  35675. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  35676. var idx = axis.inverse ? 1 : 0;
  35677. axis.setExtent(extent[idx], extent[1 - idx]);
  35678. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  35679. });
  35680. }
  35681. };
  35682. /**
  35683. * @param {string} axisType
  35684. * @param {number} [axisIndex]
  35685. */
  35686. gridProto.getAxis = function (axisType, axisIndex) {
  35687. var axesMapOnDim = this._axesMap[axisType];
  35688. if (axesMapOnDim != null) {
  35689. if (axisIndex == null) {
  35690. // Find first axis
  35691. for (var name in axesMapOnDim) {
  35692. if (axesMapOnDim.hasOwnProperty(name)) {
  35693. return axesMapOnDim[name];
  35694. }
  35695. }
  35696. }
  35697. return axesMapOnDim[axisIndex];
  35698. }
  35699. };
  35700. /**
  35701. * @return {Array.<module:echarts/coord/Axis>}
  35702. */
  35703. gridProto.getAxes = function () {
  35704. return this._axesList.slice();
  35705. };
  35706. /**
  35707. * Usage:
  35708. * grid.getCartesian(xAxisIndex, yAxisIndex);
  35709. * grid.getCartesian(xAxisIndex);
  35710. * grid.getCartesian(null, yAxisIndex);
  35711. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  35712. *
  35713. * @param {number|Object} [xAxisIndex]
  35714. * @param {number} [yAxisIndex]
  35715. */
  35716. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  35717. if (xAxisIndex != null && yAxisIndex != null) {
  35718. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35719. return this._coordsMap[key];
  35720. }
  35721. if (isObject$1(xAxisIndex)) {
  35722. yAxisIndex = xAxisIndex.yAxisIndex;
  35723. xAxisIndex = xAxisIndex.xAxisIndex;
  35724. }
  35725. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  35726. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  35727. if (coordList[i].getAxis('x').index === xAxisIndex
  35728. || coordList[i].getAxis('y').index === yAxisIndex
  35729. ) {
  35730. return coordList[i];
  35731. }
  35732. }
  35733. };
  35734. gridProto.getCartesians = function () {
  35735. return this._coordsList.slice();
  35736. };
  35737. /**
  35738. * @implements
  35739. * see {module:echarts/CoodinateSystem}
  35740. */
  35741. gridProto.convertToPixel = function (ecModel, finder, value) {
  35742. var target = this._findConvertTarget(ecModel, finder);
  35743. return target.cartesian
  35744. ? target.cartesian.dataToPoint(value)
  35745. : target.axis
  35746. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  35747. : null;
  35748. };
  35749. /**
  35750. * @implements
  35751. * see {module:echarts/CoodinateSystem}
  35752. */
  35753. gridProto.convertFromPixel = function (ecModel, finder, value) {
  35754. var target = this._findConvertTarget(ecModel, finder);
  35755. return target.cartesian
  35756. ? target.cartesian.pointToData(value)
  35757. : target.axis
  35758. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  35759. : null;
  35760. };
  35761. /**
  35762. * @inner
  35763. */
  35764. gridProto._findConvertTarget = function (ecModel, finder) {
  35765. var seriesModel = finder.seriesModel;
  35766. var xAxisModel = finder.xAxisModel
  35767. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  35768. var yAxisModel = finder.yAxisModel
  35769. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  35770. var gridModel = finder.gridModel;
  35771. var coordsList = this._coordsList;
  35772. var cartesian;
  35773. var axis;
  35774. if (seriesModel) {
  35775. cartesian = seriesModel.coordinateSystem;
  35776. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  35777. }
  35778. else if (xAxisModel && yAxisModel) {
  35779. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  35780. }
  35781. else if (xAxisModel) {
  35782. axis = this.getAxis('x', xAxisModel.componentIndex);
  35783. }
  35784. else if (yAxisModel) {
  35785. axis = this.getAxis('y', yAxisModel.componentIndex);
  35786. }
  35787. // Lowest priority.
  35788. else if (gridModel) {
  35789. var grid = gridModel.coordinateSystem;
  35790. if (grid === this) {
  35791. cartesian = this._coordsList[0];
  35792. }
  35793. }
  35794. return {cartesian: cartesian, axis: axis};
  35795. };
  35796. /**
  35797. * @implements
  35798. * see {module:echarts/CoodinateSystem}
  35799. */
  35800. gridProto.containPoint = function (point) {
  35801. var coord = this._coordsList[0];
  35802. if (coord) {
  35803. return coord.containPoint(point);
  35804. }
  35805. };
  35806. /**
  35807. * Initialize cartesian coordinate systems
  35808. * @private
  35809. */
  35810. gridProto._initCartesian = function (gridModel, ecModel, api) {
  35811. var axisPositionUsed = {
  35812. left: false,
  35813. right: false,
  35814. top: false,
  35815. bottom: false
  35816. };
  35817. var axesMap = {
  35818. x: {},
  35819. y: {}
  35820. };
  35821. var axesCount = {
  35822. x: 0,
  35823. y: 0
  35824. };
  35825. /// Create axis
  35826. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  35827. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  35828. if (!axesCount.x || !axesCount.y) {
  35829. // Roll back when there no either x or y axis
  35830. this._axesMap = {};
  35831. this._axesList = [];
  35832. return;
  35833. }
  35834. this._axesMap = axesMap;
  35835. /// Create cartesian2d
  35836. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  35837. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  35838. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35839. var cartesian = new Cartesian2D(key);
  35840. cartesian.grid = this;
  35841. cartesian.model = gridModel;
  35842. this._coordsMap[key] = cartesian;
  35843. this._coordsList.push(cartesian);
  35844. cartesian.addAxis(xAxis);
  35845. cartesian.addAxis(yAxis);
  35846. }, this);
  35847. }, this);
  35848. function createAxisCreator(axisType) {
  35849. return function (axisModel, idx) {
  35850. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  35851. return;
  35852. }
  35853. var axisPosition = axisModel.get('position');
  35854. if (axisType === 'x') {
  35855. // Fix position
  35856. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  35857. // Default bottom of X
  35858. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  35859. }
  35860. }
  35861. else {
  35862. // Fix position
  35863. if (axisPosition !== 'left' && axisPosition !== 'right') {
  35864. // Default left of Y
  35865. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  35866. }
  35867. }
  35868. axisPositionUsed[axisPosition] = true;
  35869. var axis = new Axis2D(
  35870. axisType, createScaleByModel(axisModel),
  35871. [0, 0],
  35872. axisModel.get('type'),
  35873. axisPosition
  35874. );
  35875. var isCategory = axis.type === 'category';
  35876. axis.onBand = isCategory && axisModel.get('boundaryGap');
  35877. axis.inverse = axisModel.get('inverse');
  35878. // Inject axis into axisModel
  35879. axisModel.axis = axis;
  35880. // Inject axisModel into axis
  35881. axis.model = axisModel;
  35882. // Inject grid info axis
  35883. axis.grid = this;
  35884. // Index of axis, can be used as key
  35885. axis.index = idx;
  35886. this._axesList.push(axis);
  35887. axesMap[axisType][idx] = axis;
  35888. axesCount[axisType]++;
  35889. };
  35890. }
  35891. };
  35892. /**
  35893. * Update cartesian properties from series
  35894. * @param {module:echarts/model/Option} option
  35895. * @private
  35896. */
  35897. gridProto._updateScale = function (ecModel, gridModel) {
  35898. // Reset scale
  35899. each$1(this._axesList, function (axis) {
  35900. axis.scale.setExtent(Infinity, -Infinity);
  35901. });
  35902. ecModel.eachSeries(function (seriesModel) {
  35903. if (isCartesian2D(seriesModel)) {
  35904. var axesModels = findAxesModels(seriesModel, ecModel);
  35905. var xAxisModel = axesModels[0];
  35906. var yAxisModel = axesModels[1];
  35907. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  35908. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  35909. ) {
  35910. return;
  35911. }
  35912. var cartesian = this.getCartesian(
  35913. xAxisModel.componentIndex, yAxisModel.componentIndex
  35914. );
  35915. var data = seriesModel.getData();
  35916. var xAxis = cartesian.getAxis('x');
  35917. var yAxis = cartesian.getAxis('y');
  35918. if (data.type === 'list') {
  35919. unionExtent(data, xAxis, seriesModel);
  35920. unionExtent(data, yAxis, seriesModel);
  35921. }
  35922. }
  35923. }, this);
  35924. function unionExtent(data, axis, seriesModel) {
  35925. each$1(data.mapDimension(axis.dim, true), function (dim) {
  35926. axis.scale.unionExtentFromData(
  35927. // For example, the extent of the orginal dimension
  35928. // is [0.1, 0.5], the extent of the `stackResultDimension`
  35929. // is [7, 9], the final extent should not include [0.1, 0.5].
  35930. data, getStackedDimension(data, dim)
  35931. );
  35932. });
  35933. }
  35934. };
  35935. /**
  35936. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  35937. * @return {Object} {baseAxes: [], otherAxes: []}
  35938. */
  35939. gridProto.getTooltipAxes = function (dim) {
  35940. var baseAxes = [];
  35941. var otherAxes = [];
  35942. each$1(this.getCartesians(), function (cartesian) {
  35943. var baseAxis = (dim != null && dim !== 'auto')
  35944. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  35945. var otherAxis = cartesian.getOtherAxis(baseAxis);
  35946. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  35947. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  35948. });
  35949. return {baseAxes: baseAxes, otherAxes: otherAxes};
  35950. };
  35951. /**
  35952. * @inner
  35953. */
  35954. function updateAxisTransform(axis, coordBase) {
  35955. var axisExtent = axis.getExtent();
  35956. var axisExtentSum = axisExtent[0] + axisExtent[1];
  35957. // Fast transform
  35958. axis.toGlobalCoord = axis.dim === 'x'
  35959. ? function (coord) {
  35960. return coord + coordBase;
  35961. }
  35962. : function (coord) {
  35963. return axisExtentSum - coord + coordBase;
  35964. };
  35965. axis.toLocalCoord = axis.dim === 'x'
  35966. ? function (coord) {
  35967. return coord - coordBase;
  35968. }
  35969. : function (coord) {
  35970. return axisExtentSum - coord + coordBase;
  35971. };
  35972. }
  35973. var axesTypes = ['xAxis', 'yAxis'];
  35974. /**
  35975. * @inner
  35976. */
  35977. function findAxesModels(seriesModel, ecModel) {
  35978. return map(axesTypes, function (axisType) {
  35979. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  35980. if (__DEV__) {
  35981. if (!axisModel) {
  35982. throw new Error(axisType + ' "' + retrieve(
  35983. seriesModel.get(axisType + 'Index'),
  35984. seriesModel.get(axisType + 'Id'),
  35985. 0
  35986. ) + '" not found');
  35987. }
  35988. }
  35989. return axisModel;
  35990. });
  35991. }
  35992. /**
  35993. * @inner
  35994. */
  35995. function isCartesian2D(seriesModel) {
  35996. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  35997. }
  35998. Grid.create = function (ecModel, api) {
  35999. var grids = [];
  36000. ecModel.eachComponent('grid', function (gridModel, idx) {
  36001. var grid = new Grid(gridModel, ecModel, api);
  36002. grid.name = 'grid_' + idx;
  36003. // dataSampling requires axis extent, so resize
  36004. // should be performed in create stage.
  36005. grid.resize(gridModel, api, true);
  36006. gridModel.coordinateSystem = grid;
  36007. grids.push(grid);
  36008. });
  36009. // Inject the coordinateSystems into seriesModel
  36010. ecModel.eachSeries(function (seriesModel) {
  36011. if (!isCartesian2D(seriesModel)) {
  36012. return;
  36013. }
  36014. var axesModels = findAxesModels(seriesModel, ecModel);
  36015. var xAxisModel = axesModels[0];
  36016. var yAxisModel = axesModels[1];
  36017. var gridModel = xAxisModel.getCoordSysModel();
  36018. if (__DEV__) {
  36019. if (!gridModel) {
  36020. throw new Error(
  36021. 'Grid "' + retrieve(
  36022. xAxisModel.get('gridIndex'),
  36023. xAxisModel.get('gridId'),
  36024. 0
  36025. ) + '" not found'
  36026. );
  36027. }
  36028. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  36029. throw new Error('xAxis and yAxis must use the same grid');
  36030. }
  36031. }
  36032. var grid = gridModel.coordinateSystem;
  36033. seriesModel.coordinateSystem = grid.getCartesian(
  36034. xAxisModel.componentIndex, yAxisModel.componentIndex
  36035. );
  36036. });
  36037. return grids;
  36038. };
  36039. // For deciding which dimensions to use when creating list data
  36040. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  36041. CoordinateSystemManager.register('cartesian2d', Grid);
  36042. /*
  36043. * Licensed to the Apache Software Foundation (ASF) under one
  36044. * or more contributor license agreements. See the NOTICE file
  36045. * distributed with this work for additional information
  36046. * regarding copyright ownership. The ASF licenses this file
  36047. * to you under the Apache License, Version 2.0 (the
  36048. * "License"); you may not use this file except in compliance
  36049. * with the License. You may obtain a copy of the License at
  36050. *
  36051. * http://www.apache.org/licenses/LICENSE-2.0
  36052. *
  36053. * Unless required by applicable law or agreed to in writing,
  36054. * software distributed under the License is distributed on an
  36055. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36056. * KIND, either express or implied. See the License for the
  36057. * specific language governing permissions and limitations
  36058. * under the License.
  36059. */
  36060. var PI$2 = Math.PI;
  36061. /**
  36062. * A final axis is translated and rotated from a "standard axis".
  36063. * So opt.position and opt.rotation is required.
  36064. *
  36065. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  36066. * for example: (0, 0) ------------> (0, 50)
  36067. *
  36068. * nameDirection or tickDirection or labelDirection is 1 means tick
  36069. * or label is below the standard axis, whereas is -1 means above
  36070. * the standard axis. labelOffset means offset between label and axis,
  36071. * which is useful when 'onZero', where axisLabel is in the grid and
  36072. * label in outside grid.
  36073. *
  36074. * Tips: like always,
  36075. * positive rotation represents anticlockwise, and negative rotation
  36076. * represents clockwise.
  36077. * The direction of position coordinate is the same as the direction
  36078. * of screen coordinate.
  36079. *
  36080. * Do not need to consider axis 'inverse', which is auto processed by
  36081. * axis extent.
  36082. *
  36083. * @param {module:zrender/container/Group} group
  36084. * @param {Object} axisModel
  36085. * @param {Object} opt Standard axis parameters.
  36086. * @param {Array.<number>} opt.position [x, y]
  36087. * @param {number} opt.rotation by radian
  36088. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  36089. * @param {number} [opt.tickDirection=1] 1 or -1
  36090. * @param {number} [opt.labelDirection=1] 1 or -1
  36091. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  36092. * @param {string} [opt.axisLabelShow] default get from axisModel.
  36093. * @param {string} [opt.axisName] default get from axisModel.
  36094. * @param {number} [opt.axisNameAvailableWidth]
  36095. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  36096. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  36097. * @param {number} [opt.nameTruncateMaxWidth]
  36098. */
  36099. var AxisBuilder = function (axisModel, opt) {
  36100. /**
  36101. * @readOnly
  36102. */
  36103. this.opt = opt;
  36104. /**
  36105. * @readOnly
  36106. */
  36107. this.axisModel = axisModel;
  36108. // Default value
  36109. defaults(
  36110. opt,
  36111. {
  36112. labelOffset: 0,
  36113. nameDirection: 1,
  36114. tickDirection: 1,
  36115. labelDirection: 1,
  36116. silent: true
  36117. }
  36118. );
  36119. /**
  36120. * @readOnly
  36121. */
  36122. this.group = new Group();
  36123. // FIXME Not use a seperate text group?
  36124. var dumbGroup = new Group({
  36125. position: opt.position.slice(),
  36126. rotation: opt.rotation
  36127. });
  36128. // this.group.add(dumbGroup);
  36129. // this._dumbGroup = dumbGroup;
  36130. dumbGroup.updateTransform();
  36131. this._transform = dumbGroup.transform;
  36132. this._dumbGroup = dumbGroup;
  36133. };
  36134. AxisBuilder.prototype = {
  36135. constructor: AxisBuilder,
  36136. hasBuilder: function (name) {
  36137. return !!builders[name];
  36138. },
  36139. add: function (name) {
  36140. builders[name].call(this);
  36141. },
  36142. getGroup: function () {
  36143. return this.group;
  36144. }
  36145. };
  36146. var builders = {
  36147. /**
  36148. * @private
  36149. */
  36150. axisLine: function () {
  36151. var opt = this.opt;
  36152. var axisModel = this.axisModel;
  36153. if (!axisModel.get('axisLine.show')) {
  36154. return;
  36155. }
  36156. var extent = this.axisModel.axis.getExtent();
  36157. var matrix = this._transform;
  36158. var pt1 = [extent[0], 0];
  36159. var pt2 = [extent[1], 0];
  36160. if (matrix) {
  36161. applyTransform(pt1, pt1, matrix);
  36162. applyTransform(pt2, pt2, matrix);
  36163. }
  36164. var lineStyle = extend(
  36165. {
  36166. lineCap: 'round'
  36167. },
  36168. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  36169. );
  36170. this.group.add(new Line({
  36171. // Id for animation
  36172. anid: 'line',
  36173. subPixelOptimize: true,
  36174. shape: {
  36175. x1: pt1[0],
  36176. y1: pt1[1],
  36177. x2: pt2[0],
  36178. y2: pt2[1]
  36179. },
  36180. style: lineStyle,
  36181. strokeContainThreshold: opt.strokeContainThreshold || 5,
  36182. silent: true,
  36183. z2: 1
  36184. }));
  36185. var arrows = axisModel.get('axisLine.symbol');
  36186. var arrowSize = axisModel.get('axisLine.symbolSize');
  36187. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  36188. if (typeof arrowOffset === 'number') {
  36189. arrowOffset = [arrowOffset, arrowOffset];
  36190. }
  36191. if (arrows != null) {
  36192. if (typeof arrows === 'string') {
  36193. // Use the same arrow for start and end point
  36194. arrows = [arrows, arrows];
  36195. }
  36196. if (typeof arrowSize === 'string'
  36197. || typeof arrowSize === 'number'
  36198. ) {
  36199. // Use the same size for width and height
  36200. arrowSize = [arrowSize, arrowSize];
  36201. }
  36202. var symbolWidth = arrowSize[0];
  36203. var symbolHeight = arrowSize[1];
  36204. each$1([{
  36205. rotate: opt.rotation + Math.PI / 2,
  36206. offset: arrowOffset[0],
  36207. r: 0
  36208. }, {
  36209. rotate: opt.rotation - Math.PI / 2,
  36210. offset: arrowOffset[1],
  36211. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  36212. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  36213. }], function (point, index) {
  36214. if (arrows[index] !== 'none' && arrows[index] != null) {
  36215. var symbol = createSymbol(
  36216. arrows[index],
  36217. -symbolWidth / 2,
  36218. -symbolHeight / 2,
  36219. symbolWidth,
  36220. symbolHeight,
  36221. lineStyle.stroke,
  36222. true
  36223. );
  36224. // Calculate arrow position with offset
  36225. var r = point.r + point.offset;
  36226. var pos = [
  36227. pt1[0] + r * Math.cos(opt.rotation),
  36228. pt1[1] - r * Math.sin(opt.rotation)
  36229. ];
  36230. symbol.attr({
  36231. rotation: point.rotate,
  36232. position: pos,
  36233. silent: true,
  36234. z2: 11
  36235. });
  36236. this.group.add(symbol);
  36237. }
  36238. }, this);
  36239. }
  36240. },
  36241. /**
  36242. * @private
  36243. */
  36244. axisTickLabel: function () {
  36245. var axisModel = this.axisModel;
  36246. var opt = this.opt;
  36247. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  36248. var labelEls = buildAxisLabel(this, axisModel, opt);
  36249. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  36250. buildAxisMinorTicks(this, axisModel, opt);
  36251. },
  36252. /**
  36253. * @private
  36254. */
  36255. axisName: function () {
  36256. var opt = this.opt;
  36257. var axisModel = this.axisModel;
  36258. var name = retrieve(opt.axisName, axisModel.get('name'));
  36259. if (!name) {
  36260. return;
  36261. }
  36262. var nameLocation = axisModel.get('nameLocation');
  36263. var nameDirection = opt.nameDirection;
  36264. var textStyleModel = axisModel.getModel('nameTextStyle');
  36265. var gap = axisModel.get('nameGap') || 0;
  36266. var extent = this.axisModel.axis.getExtent();
  36267. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  36268. var pos = [
  36269. nameLocation === 'start'
  36270. ? extent[0] - gapSignal * gap
  36271. : nameLocation === 'end'
  36272. ? extent[1] + gapSignal * gap
  36273. : (extent[0] + extent[1]) / 2, // 'middle'
  36274. // Reuse labelOffset.
  36275. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  36276. ];
  36277. var labelLayout;
  36278. var nameRotation = axisModel.get('nameRotate');
  36279. if (nameRotation != null) {
  36280. nameRotation = nameRotation * PI$2 / 180; // To radian.
  36281. }
  36282. var axisNameAvailableWidth;
  36283. if (isNameLocationCenter(nameLocation)) {
  36284. labelLayout = innerTextLayout(
  36285. opt.rotation,
  36286. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  36287. nameDirection
  36288. );
  36289. }
  36290. else {
  36291. labelLayout = endTextLayout(
  36292. opt, nameLocation, nameRotation || 0, extent
  36293. );
  36294. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  36295. if (axisNameAvailableWidth != null) {
  36296. axisNameAvailableWidth = Math.abs(
  36297. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  36298. );
  36299. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  36300. }
  36301. }
  36302. var textFont = textStyleModel.getFont();
  36303. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  36304. var ellipsis = truncateOpt.ellipsis;
  36305. var maxWidth = retrieve(
  36306. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  36307. );
  36308. // FIXME
  36309. // truncate rich text? (consider performance)
  36310. var truncatedText = (ellipsis != null && maxWidth != null)
  36311. ? truncateText$1(
  36312. name, maxWidth, textFont, ellipsis,
  36313. {minChar: 2, placeholder: truncateOpt.placeholder}
  36314. )
  36315. : name;
  36316. var tooltipOpt = axisModel.get('tooltip', true);
  36317. var mainType = axisModel.mainType;
  36318. var formatterParams = {
  36319. componentType: mainType,
  36320. name: name,
  36321. $vars: ['name']
  36322. };
  36323. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  36324. var textEl = new Text({
  36325. // Id for animation
  36326. anid: 'name',
  36327. __fullText: name,
  36328. __truncatedText: truncatedText,
  36329. position: pos,
  36330. rotation: labelLayout.rotation,
  36331. silent: isLabelSilent(axisModel),
  36332. z2: 1,
  36333. tooltip: (tooltipOpt && tooltipOpt.show)
  36334. ? extend({
  36335. content: name,
  36336. formatter: function () {
  36337. return name;
  36338. },
  36339. formatterParams: formatterParams
  36340. }, tooltipOpt)
  36341. : null
  36342. });
  36343. setTextStyle(textEl.style, textStyleModel, {
  36344. text: truncatedText,
  36345. textFont: textFont,
  36346. textFill: textStyleModel.getTextColor()
  36347. || axisModel.get('axisLine.lineStyle.color'),
  36348. textAlign: textStyleModel.get('align')
  36349. || labelLayout.textAlign,
  36350. textVerticalAlign: textStyleModel.get('verticalAlign')
  36351. || labelLayout.textVerticalAlign
  36352. });
  36353. if (axisModel.get('triggerEvent')) {
  36354. textEl.eventData = makeAxisEventDataBase(axisModel);
  36355. textEl.eventData.targetType = 'axisName';
  36356. textEl.eventData.name = name;
  36357. }
  36358. // FIXME
  36359. this._dumbGroup.add(textEl);
  36360. textEl.updateTransform();
  36361. this.group.add(textEl);
  36362. textEl.decomposeTransform();
  36363. }
  36364. };
  36365. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  36366. var eventData = {
  36367. componentType: axisModel.mainType,
  36368. componentIndex: axisModel.componentIndex
  36369. };
  36370. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  36371. return eventData;
  36372. };
  36373. /**
  36374. * @public
  36375. * @static
  36376. * @param {Object} opt
  36377. * @param {number} axisRotation in radian
  36378. * @param {number} textRotation in radian
  36379. * @param {number} direction
  36380. * @return {Object} {
  36381. * rotation, // according to axis
  36382. * textAlign,
  36383. * textVerticalAlign
  36384. * }
  36385. */
  36386. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  36387. var rotationDiff = remRadian(textRotation - axisRotation);
  36388. var textAlign;
  36389. var textVerticalAlign;
  36390. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  36391. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  36392. textAlign = 'center';
  36393. }
  36394. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  36395. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  36396. textAlign = 'center';
  36397. }
  36398. else {
  36399. textVerticalAlign = 'middle';
  36400. if (rotationDiff > 0 && rotationDiff < PI$2) {
  36401. textAlign = direction > 0 ? 'right' : 'left';
  36402. }
  36403. else {
  36404. textAlign = direction > 0 ? 'left' : 'right';
  36405. }
  36406. }
  36407. return {
  36408. rotation: rotationDiff,
  36409. textAlign: textAlign,
  36410. textVerticalAlign: textVerticalAlign
  36411. };
  36412. };
  36413. function endTextLayout(opt, textPosition, textRotate, extent) {
  36414. var rotationDiff = remRadian(textRotate - opt.rotation);
  36415. var textAlign;
  36416. var textVerticalAlign;
  36417. var inverse = extent[0] > extent[1];
  36418. var onLeft = (textPosition === 'start' && !inverse)
  36419. || (textPosition !== 'start' && inverse);
  36420. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  36421. textVerticalAlign = onLeft ? 'bottom' : 'top';
  36422. textAlign = 'center';
  36423. }
  36424. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  36425. textVerticalAlign = onLeft ? 'top' : 'bottom';
  36426. textAlign = 'center';
  36427. }
  36428. else {
  36429. textVerticalAlign = 'middle';
  36430. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  36431. textAlign = onLeft ? 'left' : 'right';
  36432. }
  36433. else {
  36434. textAlign = onLeft ? 'right' : 'left';
  36435. }
  36436. }
  36437. return {
  36438. rotation: rotationDiff,
  36439. textAlign: textAlign,
  36440. textVerticalAlign: textVerticalAlign
  36441. };
  36442. }
  36443. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  36444. var tooltipOpt = axisModel.get('tooltip');
  36445. return axisModel.get('silent')
  36446. // Consider mouse cursor, add these restrictions.
  36447. || !(
  36448. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  36449. );
  36450. };
  36451. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  36452. if (shouldShowAllLabels(axisModel.axis)) {
  36453. return;
  36454. }
  36455. // If min or max are user set, we need to check
  36456. // If the tick on min(max) are overlap on their neighbour tick
  36457. // If they are overlapped, we need to hide the min(max) tick label
  36458. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  36459. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  36460. // FIXME
  36461. // Have not consider onBand yet, where tick els is more than label els.
  36462. labelEls = labelEls || [];
  36463. tickEls = tickEls || [];
  36464. var firstLabel = labelEls[0];
  36465. var nextLabel = labelEls[1];
  36466. var lastLabel = labelEls[labelEls.length - 1];
  36467. var prevLabel = labelEls[labelEls.length - 2];
  36468. var firstTick = tickEls[0];
  36469. var nextTick = tickEls[1];
  36470. var lastTick = tickEls[tickEls.length - 1];
  36471. var prevTick = tickEls[tickEls.length - 2];
  36472. if (showMinLabel === false) {
  36473. ignoreEl(firstLabel);
  36474. ignoreEl(firstTick);
  36475. }
  36476. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  36477. if (showMinLabel) {
  36478. ignoreEl(nextLabel);
  36479. ignoreEl(nextTick);
  36480. }
  36481. else {
  36482. ignoreEl(firstLabel);
  36483. ignoreEl(firstTick);
  36484. }
  36485. }
  36486. if (showMaxLabel === false) {
  36487. ignoreEl(lastLabel);
  36488. ignoreEl(lastTick);
  36489. }
  36490. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  36491. if (showMaxLabel) {
  36492. ignoreEl(prevLabel);
  36493. ignoreEl(prevTick);
  36494. }
  36495. else {
  36496. ignoreEl(lastLabel);
  36497. ignoreEl(lastTick);
  36498. }
  36499. }
  36500. }
  36501. function ignoreEl(el) {
  36502. el && (el.ignore = true);
  36503. }
  36504. function isTwoLabelOverlapped(current, next, labelLayout) {
  36505. // current and next has the same rotation.
  36506. var firstRect = current && current.getBoundingRect().clone();
  36507. var nextRect = next && next.getBoundingRect().clone();
  36508. if (!firstRect || !nextRect) {
  36509. return;
  36510. }
  36511. // When checking intersect of two rotated labels, we use mRotationBack
  36512. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  36513. var mRotationBack = identity([]);
  36514. rotate(mRotationBack, mRotationBack, -current.rotation);
  36515. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  36516. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  36517. return firstRect.intersect(nextRect);
  36518. }
  36519. function isNameLocationCenter(nameLocation) {
  36520. return nameLocation === 'middle' || nameLocation === 'center';
  36521. }
  36522. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  36523. var tickEls = [];
  36524. var pt1 = [];
  36525. var pt2 = [];
  36526. for (var i = 0; i < ticksCoords.length; i++) {
  36527. var tickCoord = ticksCoords[i].coord;
  36528. pt1[0] = tickCoord;
  36529. pt1[1] = 0;
  36530. pt2[0] = tickCoord;
  36531. pt2[1] = tickEndCoord;
  36532. if (tickTransform) {
  36533. applyTransform(pt1, pt1, tickTransform);
  36534. applyTransform(pt2, pt2, tickTransform);
  36535. }
  36536. // Tick line, Not use group transform to have better line draw
  36537. var tickEl = new Line({
  36538. // Id for animation
  36539. anid: aniid + '_' + ticksCoords[i].tickValue,
  36540. subPixelOptimize: true,
  36541. shape: {
  36542. x1: pt1[0],
  36543. y1: pt1[1],
  36544. x2: pt2[0],
  36545. y2: pt2[1]
  36546. },
  36547. style: tickLineStyle,
  36548. z2: 2,
  36549. silent: true
  36550. });
  36551. tickEls.push(tickEl);
  36552. }
  36553. return tickEls;
  36554. }
  36555. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  36556. var axis = axisModel.axis;
  36557. var tickModel = axisModel.getModel('axisTick');
  36558. if (!tickModel.get('show') || axis.scale.isBlank()) {
  36559. return;
  36560. }
  36561. var lineStyleModel = tickModel.getModel('lineStyle');
  36562. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  36563. var ticksCoords = axis.getTicksCoords();
  36564. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  36565. lineStyleModel.getLineStyle(),
  36566. {
  36567. stroke: axisModel.get('axisLine.lineStyle.color')
  36568. }
  36569. ), 'ticks');
  36570. for (var i = 0; i < ticksEls.length; i++) {
  36571. axisBuilder.group.add(ticksEls[i]);
  36572. }
  36573. return ticksEls;
  36574. }
  36575. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  36576. var axis = axisModel.axis;
  36577. var minorTickModel = axisModel.getModel('minorTick');
  36578. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  36579. return;
  36580. }
  36581. var minorTicksCoords = axis.getMinorTicksCoords();
  36582. if (!minorTicksCoords.length) {
  36583. return;
  36584. }
  36585. var lineStyleModel = minorTickModel.getModel('lineStyle');
  36586. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  36587. var minorTickLineStyle = defaults(
  36588. lineStyleModel.getLineStyle(),
  36589. defaults(
  36590. axisModel.getModel('axisTick').getLineStyle(),
  36591. {
  36592. stroke: axisModel.get('axisLine.lineStyle.color')
  36593. }
  36594. )
  36595. );
  36596. for (var i = 0; i < minorTicksCoords.length; i++) {
  36597. var minorTicksEls = createTicks(
  36598. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  36599. );
  36600. for (var k = 0; k < minorTicksEls.length; k++) {
  36601. axisBuilder.group.add(minorTicksEls[k]);
  36602. }
  36603. }
  36604. }
  36605. function buildAxisLabel(axisBuilder, axisModel, opt) {
  36606. var axis = axisModel.axis;
  36607. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  36608. if (!show || axis.scale.isBlank()) {
  36609. return;
  36610. }
  36611. var labelModel = axisModel.getModel('axisLabel');
  36612. var labelMargin = labelModel.get('margin');
  36613. var labels = axis.getViewLabels();
  36614. // Special label rotate.
  36615. var labelRotation = (
  36616. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  36617. ) * PI$2 / 180;
  36618. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  36619. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  36620. var labelEls = [];
  36621. var silent = isLabelSilent(axisModel);
  36622. var triggerEvent = axisModel.get('triggerEvent');
  36623. each$1(labels, function (labelItem, index) {
  36624. var tickValue = labelItem.tickValue;
  36625. var formattedLabel = labelItem.formattedLabel;
  36626. var rawLabel = labelItem.rawLabel;
  36627. var itemLabelModel = labelModel;
  36628. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  36629. itemLabelModel = new Model(
  36630. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  36631. );
  36632. }
  36633. var textColor = itemLabelModel.getTextColor()
  36634. || axisModel.get('axisLine.lineStyle.color');
  36635. var tickCoord = axis.dataToCoord(tickValue);
  36636. var pos = [
  36637. tickCoord,
  36638. opt.labelOffset + opt.labelDirection * labelMargin
  36639. ];
  36640. var textEl = new Text({
  36641. // Id for animation
  36642. anid: 'label_' + tickValue,
  36643. position: pos,
  36644. rotation: labelLayout.rotation,
  36645. silent: silent,
  36646. z2: 10
  36647. });
  36648. setTextStyle(textEl.style, itemLabelModel, {
  36649. text: formattedLabel,
  36650. textAlign: itemLabelModel.getShallow('align', true)
  36651. || labelLayout.textAlign,
  36652. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  36653. || itemLabelModel.getShallow('baseline', true)
  36654. || labelLayout.textVerticalAlign,
  36655. textFill: typeof textColor === 'function'
  36656. ? textColor(
  36657. // (1) In category axis with data zoom, tick is not the original
  36658. // index of axis.data. So tick should not be exposed to user
  36659. // in category axis.
  36660. // (2) Compatible with previous version, which always use formatted label as
  36661. // input. But in interval scale the formatted label is like '223,445', which
  36662. // maked user repalce ','. So we modify it to return original val but remain
  36663. // it as 'string' to avoid error in replacing.
  36664. axis.type === 'category'
  36665. ? rawLabel
  36666. : axis.type === 'value'
  36667. ? tickValue + ''
  36668. : tickValue,
  36669. index
  36670. )
  36671. : textColor
  36672. });
  36673. // Pack data for mouse event
  36674. if (triggerEvent) {
  36675. textEl.eventData = makeAxisEventDataBase(axisModel);
  36676. textEl.eventData.targetType = 'axisLabel';
  36677. textEl.eventData.value = rawLabel;
  36678. }
  36679. // FIXME
  36680. axisBuilder._dumbGroup.add(textEl);
  36681. textEl.updateTransform();
  36682. labelEls.push(textEl);
  36683. axisBuilder.group.add(textEl);
  36684. textEl.decomposeTransform();
  36685. });
  36686. return labelEls;
  36687. }
  36688. /*
  36689. * Licensed to the Apache Software Foundation (ASF) under one
  36690. * or more contributor license agreements. See the NOTICE file
  36691. * distributed with this work for additional information
  36692. * regarding copyright ownership. The ASF licenses this file
  36693. * to you under the Apache License, Version 2.0 (the
  36694. * "License"); you may not use this file except in compliance
  36695. * with the License. You may obtain a copy of the License at
  36696. *
  36697. * http://www.apache.org/licenses/LICENSE-2.0
  36698. *
  36699. * Unless required by applicable law or agreed to in writing,
  36700. * software distributed under the License is distributed on an
  36701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36702. * KIND, either express or implied. See the License for the
  36703. * specific language governing permissions and limitations
  36704. * under the License.
  36705. */
  36706. var each$6 = each$1;
  36707. var curry$1 = curry;
  36708. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  36709. // allAxesInfo should be updated when setOption performed.
  36710. function collect(ecModel, api) {
  36711. var result = {
  36712. /**
  36713. * key: makeKey(axis.model)
  36714. * value: {
  36715. * axis,
  36716. * coordSys,
  36717. * axisPointerModel,
  36718. * triggerTooltip,
  36719. * involveSeries,
  36720. * snap,
  36721. * seriesModels,
  36722. * seriesDataCount
  36723. * }
  36724. */
  36725. axesInfo: {},
  36726. seriesInvolved: false,
  36727. /**
  36728. * key: makeKey(coordSys.model)
  36729. * value: Object: key makeKey(axis.model), value: axisInfo
  36730. */
  36731. coordSysAxesInfo: {},
  36732. coordSysMap: {}
  36733. };
  36734. collectAxesInfo(result, ecModel, api);
  36735. // Check seriesInvolved for performance, in case too many series in some chart.
  36736. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  36737. return result;
  36738. }
  36739. function collectAxesInfo(result, ecModel, api) {
  36740. var globalTooltipModel = ecModel.getComponent('tooltip');
  36741. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  36742. // links can only be set on global.
  36743. var linksOption = globalAxisPointerModel.get('link', true) || [];
  36744. var linkGroups = [];
  36745. // Collect axes info.
  36746. each$6(api.getCoordinateSystems(), function (coordSys) {
  36747. // Some coordinate system do not support axes, like geo.
  36748. if (!coordSys.axisPointerEnabled) {
  36749. return;
  36750. }
  36751. var coordSysKey = makeKey(coordSys.model);
  36752. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  36753. result.coordSysMap[coordSysKey] = coordSys;
  36754. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  36755. // for user. So we enable seting tooltip on coordSys model.
  36756. var coordSysModel = coordSys.model;
  36757. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  36758. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  36759. // If axis tooltip used, choose tooltip axis for each coordSys.
  36760. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  36761. if (coordSys.getTooltipAxes
  36762. && globalTooltipModel
  36763. // If tooltip.showContent is set as false, tooltip will not
  36764. // show but axisPointer will show as normal.
  36765. && baseTooltipModel.get('show')
  36766. ) {
  36767. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  36768. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  36769. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  36770. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  36771. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  36772. if (triggerAxis || cross) {
  36773. each$6(tooltipAxes.baseAxes, curry$1(
  36774. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  36775. ));
  36776. }
  36777. if (cross) {
  36778. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  36779. }
  36780. }
  36781. // fromTooltip: true | false | 'cross'
  36782. // triggerTooltip: true | false | null
  36783. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  36784. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  36785. var axisPointerShow = axisPointerModel.get('show');
  36786. if (!axisPointerShow || (
  36787. axisPointerShow === 'auto'
  36788. && !fromTooltip
  36789. && !isHandleTrigger(axisPointerModel)
  36790. )) {
  36791. return;
  36792. }
  36793. if (triggerTooltip == null) {
  36794. triggerTooltip = axisPointerModel.get('triggerTooltip');
  36795. }
  36796. axisPointerModel = fromTooltip
  36797. ? makeAxisPointerModel(
  36798. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  36799. fromTooltip, triggerTooltip
  36800. )
  36801. : axisPointerModel;
  36802. var snap = axisPointerModel.get('snap');
  36803. var key = makeKey(axis.model);
  36804. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  36805. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  36806. var axisInfo = result.axesInfo[key] = {
  36807. key: key,
  36808. axis: axis,
  36809. coordSys: coordSys,
  36810. axisPointerModel: axisPointerModel,
  36811. triggerTooltip: triggerTooltip,
  36812. involveSeries: involveSeries,
  36813. snap: snap,
  36814. useHandle: isHandleTrigger(axisPointerModel),
  36815. seriesModels: []
  36816. };
  36817. axesInfoInCoordSys[key] = axisInfo;
  36818. result.seriesInvolved |= involveSeries;
  36819. var groupIndex = getLinkGroupIndex(linksOption, axis);
  36820. if (groupIndex != null) {
  36821. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  36822. linkGroup.axesInfo[key] = axisInfo;
  36823. linkGroup.mapper = linksOption[groupIndex].mapper;
  36824. axisInfo.linkGroup = linkGroup;
  36825. }
  36826. }
  36827. });
  36828. }
  36829. function makeAxisPointerModel(
  36830. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  36831. ) {
  36832. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  36833. var volatileOption = {};
  36834. each$6(
  36835. [
  36836. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  36837. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  36838. ],
  36839. function (field) {
  36840. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  36841. }
  36842. );
  36843. // category axis do not auto snap, otherwise some tick that do not
  36844. // has value can not be hovered. value/time/log axis default snap if
  36845. // triggered from tooltip and trigger tooltip.
  36846. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  36847. // Compatibel with previous behavior, tooltip axis do not show label by default.
  36848. // Only these properties can be overrided from tooltip to axisPointer.
  36849. if (tooltipAxisPointerModel.get('type') === 'cross') {
  36850. volatileOption.type = 'line';
  36851. }
  36852. var labelOption = volatileOption.label || (volatileOption.label = {});
  36853. // Follow the convention, do not show label when triggered by tooltip by default.
  36854. labelOption.show == null && (labelOption.show = false);
  36855. if (fromTooltip === 'cross') {
  36856. // When 'cross', both axes show labels.
  36857. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  36858. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  36859. // If triggerTooltip, this is a base axis, which should better not use cross style
  36860. // (cross style is dashed by default)
  36861. if (!triggerTooltip) {
  36862. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  36863. crossStyle && defaults(labelOption, crossStyle.textStyle);
  36864. }
  36865. }
  36866. return axis.model.getModel(
  36867. 'axisPointer',
  36868. new Model(volatileOption, globalAxisPointerModel, ecModel)
  36869. );
  36870. }
  36871. function collectSeriesInfo(result, ecModel) {
  36872. // Prepare data for axis trigger
  36873. ecModel.eachSeries(function (seriesModel) {
  36874. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  36875. var coordSys = seriesModel.coordinateSystem;
  36876. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  36877. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  36878. if (!coordSys
  36879. || seriesTooltipTrigger === 'none'
  36880. || seriesTooltipTrigger === false
  36881. || seriesTooltipTrigger === 'item'
  36882. || seriesTooltipShow === false
  36883. || seriesModel.get('axisPointer.show', true) === false
  36884. ) {
  36885. return;
  36886. }
  36887. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  36888. var axis = axisInfo.axis;
  36889. if (coordSys.getAxis(axis.dim) === axis) {
  36890. axisInfo.seriesModels.push(seriesModel);
  36891. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  36892. axisInfo.seriesDataCount += seriesModel.getData().count();
  36893. }
  36894. });
  36895. }, this);
  36896. }
  36897. /**
  36898. * For example:
  36899. * {
  36900. * axisPointer: {
  36901. * links: [{
  36902. * xAxisIndex: [2, 4],
  36903. * yAxisIndex: 'all'
  36904. * }, {
  36905. * xAxisId: ['a5', 'a7'],
  36906. * xAxisName: 'xxx'
  36907. * }]
  36908. * }
  36909. * }
  36910. */
  36911. function getLinkGroupIndex(linksOption, axis) {
  36912. var axisModel = axis.model;
  36913. var dim = axis.dim;
  36914. for (var i = 0; i < linksOption.length; i++) {
  36915. var linkOption = linksOption[i] || {};
  36916. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  36917. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  36918. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  36919. ) {
  36920. return i;
  36921. }
  36922. }
  36923. }
  36924. function checkPropInLink(linkPropValue, axisPropValue) {
  36925. return linkPropValue === 'all'
  36926. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  36927. || linkPropValue === axisPropValue;
  36928. }
  36929. function fixValue(axisModel) {
  36930. var axisInfo = getAxisInfo(axisModel);
  36931. if (!axisInfo) {
  36932. return;
  36933. }
  36934. var axisPointerModel = axisInfo.axisPointerModel;
  36935. var scale = axisInfo.axis.scale;
  36936. var option = axisPointerModel.option;
  36937. var status = axisPointerModel.get('status');
  36938. var value = axisPointerModel.get('value');
  36939. // Parse init value for category and time axis.
  36940. if (value != null) {
  36941. value = scale.parse(value);
  36942. }
  36943. var useHandle = isHandleTrigger(axisPointerModel);
  36944. // If `handle` used, `axisPointer` will always be displayed, so value
  36945. // and status should be initialized.
  36946. if (status == null) {
  36947. option.status = useHandle ? 'show' : 'hide';
  36948. }
  36949. var extent = scale.getExtent().slice();
  36950. extent[0] > extent[1] && extent.reverse();
  36951. if (// Pick a value on axis when initializing.
  36952. value == null
  36953. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  36954. // where we should re-pick a value to keep `handle` displaying normally.
  36955. || value > extent[1]
  36956. ) {
  36957. // Make handle displayed on the end of the axis when init, which looks better.
  36958. value = extent[1];
  36959. }
  36960. if (value < extent[0]) {
  36961. value = extent[0];
  36962. }
  36963. option.value = value;
  36964. if (useHandle) {
  36965. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  36966. }
  36967. }
  36968. function getAxisInfo(axisModel) {
  36969. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  36970. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  36971. }
  36972. function getAxisPointerModel(axisModel) {
  36973. var axisInfo = getAxisInfo(axisModel);
  36974. return axisInfo && axisInfo.axisPointerModel;
  36975. }
  36976. function isHandleTrigger(axisPointerModel) {
  36977. return !!axisPointerModel.get('handle.show');
  36978. }
  36979. /**
  36980. * @param {module:echarts/model/Model} model
  36981. * @return {string} unique key
  36982. */
  36983. function makeKey(model) {
  36984. return model.type + '||' + model.id;
  36985. }
  36986. /*
  36987. * Licensed to the Apache Software Foundation (ASF) under one
  36988. * or more contributor license agreements. See the NOTICE file
  36989. * distributed with this work for additional information
  36990. * regarding copyright ownership. The ASF licenses this file
  36991. * to you under the Apache License, Version 2.0 (the
  36992. * "License"); you may not use this file except in compliance
  36993. * with the License. You may obtain a copy of the License at
  36994. *
  36995. * http://www.apache.org/licenses/LICENSE-2.0
  36996. *
  36997. * Unless required by applicable law or agreed to in writing,
  36998. * software distributed under the License is distributed on an
  36999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37000. * KIND, either express or implied. See the License for the
  37001. * specific language governing permissions and limitations
  37002. * under the License.
  37003. */
  37004. /**
  37005. * Base class of AxisView.
  37006. */
  37007. var AxisView = extendComponentView({
  37008. type: 'axis',
  37009. /**
  37010. * @private
  37011. */
  37012. _axisPointer: null,
  37013. /**
  37014. * @protected
  37015. * @type {string}
  37016. */
  37017. axisPointerClass: null,
  37018. /**
  37019. * @override
  37020. */
  37021. render: function (axisModel, ecModel, api, payload) {
  37022. // FIXME
  37023. // This process should proformed after coordinate systems updated
  37024. // (axis scale updated), and should be performed each time update.
  37025. // So put it here temporarily, although it is not appropriate to
  37026. // put a model-writing procedure in `view`.
  37027. this.axisPointerClass && fixValue(axisModel);
  37028. AxisView.superApply(this, 'render', arguments);
  37029. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  37030. },
  37031. /**
  37032. * Action handler.
  37033. * @public
  37034. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37035. * @param {module:echarts/model/Global} ecModel
  37036. * @param {module:echarts/ExtensionAPI} api
  37037. * @param {Object} payload
  37038. */
  37039. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  37040. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  37041. },
  37042. /**
  37043. * @override
  37044. */
  37045. remove: function (ecModel, api) {
  37046. var axisPointer = this._axisPointer;
  37047. axisPointer && axisPointer.remove(api);
  37048. AxisView.superApply(this, 'remove', arguments);
  37049. },
  37050. /**
  37051. * @override
  37052. */
  37053. dispose: function (ecModel, api) {
  37054. disposeAxisPointer(this, api);
  37055. AxisView.superApply(this, 'dispose', arguments);
  37056. }
  37057. });
  37058. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  37059. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  37060. if (!Clazz) {
  37061. return;
  37062. }
  37063. var axisPointerModel = getAxisPointerModel(axisModel);
  37064. axisPointerModel
  37065. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  37066. .render(axisModel, axisPointerModel, api, forceRender)
  37067. : disposeAxisPointer(axisView, api);
  37068. }
  37069. function disposeAxisPointer(axisView, ecModel, api) {
  37070. var axisPointer = axisView._axisPointer;
  37071. axisPointer && axisPointer.dispose(ecModel, api);
  37072. axisView._axisPointer = null;
  37073. }
  37074. var axisPointerClazz = [];
  37075. AxisView.registerAxisPointerClass = function (type, clazz) {
  37076. if (__DEV__) {
  37077. if (axisPointerClazz[type]) {
  37078. throw new Error('axisPointer ' + type + ' exists');
  37079. }
  37080. }
  37081. axisPointerClazz[type] = clazz;
  37082. };
  37083. AxisView.getAxisPointerClass = function (type) {
  37084. return type && axisPointerClazz[type];
  37085. };
  37086. /*
  37087. * Licensed to the Apache Software Foundation (ASF) under one
  37088. * or more contributor license agreements. See the NOTICE file
  37089. * distributed with this work for additional information
  37090. * regarding copyright ownership. The ASF licenses this file
  37091. * to you under the Apache License, Version 2.0 (the
  37092. * "License"); you may not use this file except in compliance
  37093. * with the License. You may obtain a copy of the License at
  37094. *
  37095. * http://www.apache.org/licenses/LICENSE-2.0
  37096. *
  37097. * Unless required by applicable law or agreed to in writing,
  37098. * software distributed under the License is distributed on an
  37099. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37100. * KIND, either express or implied. See the License for the
  37101. * specific language governing permissions and limitations
  37102. * under the License.
  37103. */
  37104. /**
  37105. * Can only be called after coordinate system creation stage.
  37106. * (Can be called before coordinate system update stage).
  37107. *
  37108. * @param {Object} opt {labelInside}
  37109. * @return {Object} {
  37110. * position, rotation, labelDirection, labelOffset,
  37111. * tickDirection, labelRotate, z2
  37112. * }
  37113. */
  37114. function layout$1(gridModel, axisModel, opt) {
  37115. opt = opt || {};
  37116. var grid = gridModel.coordinateSystem;
  37117. var axis = axisModel.axis;
  37118. var layout = {};
  37119. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  37120. var rawAxisPosition = axis.position;
  37121. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  37122. var axisDim = axis.dim;
  37123. var rect = grid.getRect();
  37124. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  37125. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  37126. var axisOffset = axisModel.get('offset') || 0;
  37127. var posBound = axisDim === 'x'
  37128. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  37129. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  37130. if (otherAxisOnZeroOf) {
  37131. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  37132. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  37133. }
  37134. // Axis position
  37135. layout.position = [
  37136. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  37137. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  37138. ];
  37139. // Axis rotation
  37140. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  37141. // Tick and label direction, x y is axisDim
  37142. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  37143. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  37144. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  37145. if (axisModel.get('axisTick.inside')) {
  37146. layout.tickDirection = -layout.tickDirection;
  37147. }
  37148. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  37149. layout.labelDirection = -layout.labelDirection;
  37150. }
  37151. // Special label rotation
  37152. var labelRotate = axisModel.get('axisLabel.rotate');
  37153. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  37154. // Over splitLine and splitArea
  37155. layout.z2 = 1;
  37156. return layout;
  37157. }
  37158. /*
  37159. * Licensed to the Apache Software Foundation (ASF) under one
  37160. * or more contributor license agreements. See the NOTICE file
  37161. * distributed with this work for additional information
  37162. * regarding copyright ownership. The ASF licenses this file
  37163. * to you under the Apache License, Version 2.0 (the
  37164. * "License"); you may not use this file except in compliance
  37165. * with the License. You may obtain a copy of the License at
  37166. *
  37167. * http://www.apache.org/licenses/LICENSE-2.0
  37168. *
  37169. * Unless required by applicable law or agreed to in writing,
  37170. * software distributed under the License is distributed on an
  37171. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37172. * KIND, either express or implied. See the License for the
  37173. * specific language governing permissions and limitations
  37174. * under the License.
  37175. */
  37176. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  37177. var axis = axisModel.axis;
  37178. if (axis.scale.isBlank()) {
  37179. return;
  37180. }
  37181. var splitAreaModel = axisModel.getModel('splitArea');
  37182. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  37183. var areaColors = areaStyleModel.get('color');
  37184. var gridRect = gridModel.coordinateSystem.getRect();
  37185. var ticksCoords = axis.getTicksCoords({
  37186. tickModel: splitAreaModel,
  37187. clamp: true
  37188. });
  37189. if (!ticksCoords.length) {
  37190. return;
  37191. }
  37192. // For Making appropriate splitArea animation, the color and anid
  37193. // should be corresponding to previous one if possible.
  37194. var areaColorsLen = areaColors.length;
  37195. var lastSplitAreaColors = axisView.__splitAreaColors;
  37196. var newSplitAreaColors = createHashMap();
  37197. var colorIndex = 0;
  37198. if (lastSplitAreaColors) {
  37199. for (var i = 0; i < ticksCoords.length; i++) {
  37200. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  37201. if (cIndex != null) {
  37202. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  37203. break;
  37204. }
  37205. }
  37206. }
  37207. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  37208. var areaStyle = areaStyleModel.getAreaStyle();
  37209. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  37210. for (var i = 1; i < ticksCoords.length; i++) {
  37211. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37212. var x;
  37213. var y;
  37214. var width;
  37215. var height;
  37216. if (axis.isHorizontal()) {
  37217. x = prev;
  37218. y = gridRect.y;
  37219. width = tickCoord - x;
  37220. height = gridRect.height;
  37221. prev = x + width;
  37222. }
  37223. else {
  37224. x = gridRect.x;
  37225. y = prev;
  37226. width = gridRect.width;
  37227. height = tickCoord - y;
  37228. prev = y + height;
  37229. }
  37230. var tickValue = ticksCoords[i - 1].tickValue;
  37231. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  37232. axisGroup.add(new Rect({
  37233. anid: tickValue != null ? 'area_' + tickValue : null,
  37234. shape: {
  37235. x: x,
  37236. y: y,
  37237. width: width,
  37238. height: height
  37239. },
  37240. style: defaults({
  37241. fill: areaColors[colorIndex]
  37242. }, areaStyle),
  37243. silent: true
  37244. }));
  37245. colorIndex = (colorIndex + 1) % areaColorsLen;
  37246. }
  37247. axisView.__splitAreaColors = newSplitAreaColors;
  37248. }
  37249. function rectCoordAxisHandleRemove(axisView) {
  37250. axisView.__splitAreaColors = null;
  37251. }
  37252. /*
  37253. * Licensed to the Apache Software Foundation (ASF) under one
  37254. * or more contributor license agreements. See the NOTICE file
  37255. * distributed with this work for additional information
  37256. * regarding copyright ownership. The ASF licenses this file
  37257. * to you under the Apache License, Version 2.0 (the
  37258. * "License"); you may not use this file except in compliance
  37259. * with the License. You may obtain a copy of the License at
  37260. *
  37261. * http://www.apache.org/licenses/LICENSE-2.0
  37262. *
  37263. * Unless required by applicable law or agreed to in writing,
  37264. * software distributed under the License is distributed on an
  37265. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37266. * KIND, either express or implied. See the License for the
  37267. * specific language governing permissions and limitations
  37268. * under the License.
  37269. */
  37270. var axisBuilderAttrs = [
  37271. 'axisLine', 'axisTickLabel', 'axisName'
  37272. ];
  37273. var selfBuilderAttrs = [
  37274. 'splitArea', 'splitLine', 'minorSplitLine'
  37275. ];
  37276. var CartesianAxisView = AxisView.extend({
  37277. type: 'cartesianAxis',
  37278. axisPointerClass: 'CartesianAxisPointer',
  37279. /**
  37280. * @override
  37281. */
  37282. render: function (axisModel, ecModel, api, payload) {
  37283. this.group.removeAll();
  37284. var oldAxisGroup = this._axisGroup;
  37285. this._axisGroup = new Group();
  37286. this.group.add(this._axisGroup);
  37287. if (!axisModel.get('show')) {
  37288. return;
  37289. }
  37290. var gridModel = axisModel.getCoordSysModel();
  37291. var layout = layout$1(gridModel, axisModel);
  37292. var axisBuilder = new AxisBuilder(axisModel, layout);
  37293. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  37294. this._axisGroup.add(axisBuilder.getGroup());
  37295. each$1(selfBuilderAttrs, function (name) {
  37296. if (axisModel.get(name + '.show')) {
  37297. this['_' + name](axisModel, gridModel);
  37298. }
  37299. }, this);
  37300. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  37301. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  37302. },
  37303. remove: function () {
  37304. rectCoordAxisHandleRemove(this);
  37305. },
  37306. /**
  37307. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37308. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37309. * @private
  37310. */
  37311. _splitLine: function (axisModel, gridModel) {
  37312. var axis = axisModel.axis;
  37313. if (axis.scale.isBlank()) {
  37314. return;
  37315. }
  37316. var splitLineModel = axisModel.getModel('splitLine');
  37317. var lineStyleModel = splitLineModel.getModel('lineStyle');
  37318. var lineColors = lineStyleModel.get('color');
  37319. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  37320. var gridRect = gridModel.coordinateSystem.getRect();
  37321. var isHorizontal = axis.isHorizontal();
  37322. var lineCount = 0;
  37323. var ticksCoords = axis.getTicksCoords({
  37324. tickModel: splitLineModel
  37325. });
  37326. var p1 = [];
  37327. var p2 = [];
  37328. var lineStyle = lineStyleModel.getLineStyle();
  37329. for (var i = 0; i < ticksCoords.length; i++) {
  37330. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37331. if (isHorizontal) {
  37332. p1[0] = tickCoord;
  37333. p1[1] = gridRect.y;
  37334. p2[0] = tickCoord;
  37335. p2[1] = gridRect.y + gridRect.height;
  37336. }
  37337. else {
  37338. p1[0] = gridRect.x;
  37339. p1[1] = tickCoord;
  37340. p2[0] = gridRect.x + gridRect.width;
  37341. p2[1] = tickCoord;
  37342. }
  37343. var colorIndex = (lineCount++) % lineColors.length;
  37344. var tickValue = ticksCoords[i].tickValue;
  37345. this._axisGroup.add(new Line({
  37346. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  37347. subPixelOptimize: true,
  37348. shape: {
  37349. x1: p1[0],
  37350. y1: p1[1],
  37351. x2: p2[0],
  37352. y2: p2[1]
  37353. },
  37354. style: defaults({
  37355. stroke: lineColors[colorIndex]
  37356. }, lineStyle),
  37357. silent: true
  37358. }));
  37359. }
  37360. },
  37361. /**
  37362. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37363. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37364. * @private
  37365. */
  37366. _minorSplitLine: function (axisModel, gridModel) {
  37367. var axis = axisModel.axis;
  37368. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  37369. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  37370. var gridRect = gridModel.coordinateSystem.getRect();
  37371. var isHorizontal = axis.isHorizontal();
  37372. var minorTicksCoords = axis.getMinorTicksCoords();
  37373. if (!minorTicksCoords.length) {
  37374. return;
  37375. }
  37376. var p1 = [];
  37377. var p2 = [];
  37378. var lineStyle = lineStyleModel.getLineStyle();
  37379. for (var i = 0; i < minorTicksCoords.length; i++) {
  37380. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  37381. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  37382. if (isHorizontal) {
  37383. p1[0] = tickCoord;
  37384. p1[1] = gridRect.y;
  37385. p2[0] = tickCoord;
  37386. p2[1] = gridRect.y + gridRect.height;
  37387. }
  37388. else {
  37389. p1[0] = gridRect.x;
  37390. p1[1] = tickCoord;
  37391. p2[0] = gridRect.x + gridRect.width;
  37392. p2[1] = tickCoord;
  37393. }
  37394. this._axisGroup.add(new Line({
  37395. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  37396. subPixelOptimize: true,
  37397. shape: {
  37398. x1: p1[0],
  37399. y1: p1[1],
  37400. x2: p2[0],
  37401. y2: p2[1]
  37402. },
  37403. style: lineStyle,
  37404. silent: true
  37405. }));
  37406. }
  37407. }
  37408. },
  37409. /**
  37410. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37411. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37412. * @private
  37413. */
  37414. _splitArea: function (axisModel, gridModel) {
  37415. rectCoordAxisBuildSplitArea(this, this._axisGroup, axisModel, gridModel);
  37416. }
  37417. });
  37418. CartesianAxisView.extend({
  37419. type: 'xAxis'
  37420. });
  37421. CartesianAxisView.extend({
  37422. type: 'yAxis'
  37423. });
  37424. /*
  37425. * Licensed to the Apache Software Foundation (ASF) under one
  37426. * or more contributor license agreements. See the NOTICE file
  37427. * distributed with this work for additional information
  37428. * regarding copyright ownership. The ASF licenses this file
  37429. * to you under the Apache License, Version 2.0 (the
  37430. * "License"); you may not use this file except in compliance
  37431. * with the License. You may obtain a copy of the License at
  37432. *
  37433. * http://www.apache.org/licenses/LICENSE-2.0
  37434. *
  37435. * Unless required by applicable law or agreed to in writing,
  37436. * software distributed under the License is distributed on an
  37437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37438. * KIND, either express or implied. See the License for the
  37439. * specific language governing permissions and limitations
  37440. * under the License.
  37441. */
  37442. /*
  37443. * Licensed to the Apache Software Foundation (ASF) under one
  37444. * or more contributor license agreements. See the NOTICE file
  37445. * distributed with this work for additional information
  37446. * regarding copyright ownership. The ASF licenses this file
  37447. * to you under the Apache License, Version 2.0 (the
  37448. * "License"); you may not use this file except in compliance
  37449. * with the License. You may obtain a copy of the License at
  37450. *
  37451. * http://www.apache.org/licenses/LICENSE-2.0
  37452. *
  37453. * Unless required by applicable law or agreed to in writing,
  37454. * software distributed under the License is distributed on an
  37455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37456. * KIND, either express or implied. See the License for the
  37457. * specific language governing permissions and limitations
  37458. * under the License.
  37459. */
  37460. // Grid view
  37461. extendComponentView({
  37462. type: 'grid',
  37463. render: function (gridModel, ecModel) {
  37464. this.group.removeAll();
  37465. if (gridModel.get('show')) {
  37466. this.group.add(new Rect({
  37467. shape: gridModel.coordinateSystem.getRect(),
  37468. style: defaults({
  37469. fill: gridModel.get('backgroundColor')
  37470. }, gridModel.getItemStyle()),
  37471. silent: true,
  37472. z2: -1
  37473. }));
  37474. }
  37475. }
  37476. });
  37477. registerPreprocessor(function (option) {
  37478. // Only create grid when need
  37479. if (option.xAxis && option.yAxis && !option.grid) {
  37480. option.grid = {};
  37481. }
  37482. });
  37483. /*
  37484. * Licensed to the Apache Software Foundation (ASF) under one
  37485. * or more contributor license agreements. See the NOTICE file
  37486. * distributed with this work for additional information
  37487. * regarding copyright ownership. The ASF licenses this file
  37488. * to you under the Apache License, Version 2.0 (the
  37489. * "License"); you may not use this file except in compliance
  37490. * with the License. You may obtain a copy of the License at
  37491. *
  37492. * http://www.apache.org/licenses/LICENSE-2.0
  37493. *
  37494. * Unless required by applicable law or agreed to in writing,
  37495. * software distributed under the License is distributed on an
  37496. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37497. * KIND, either express or implied. See the License for the
  37498. * specific language governing permissions and limitations
  37499. * under the License.
  37500. */
  37501. // In case developer forget to include grid component
  37502. registerVisual(visualSymbol('line', 'circle', 'line'));
  37503. registerLayout(pointsLayout('line'));
  37504. // Down sample after filter
  37505. registerProcessor(
  37506. PRIORITY.PROCESSOR.STATISTIC,
  37507. dataSample('line')
  37508. );
  37509. /*
  37510. * Licensed to the Apache Software Foundation (ASF) under one
  37511. * or more contributor license agreements. See the NOTICE file
  37512. * distributed with this work for additional information
  37513. * regarding copyright ownership. The ASF licenses this file
  37514. * to you under the Apache License, Version 2.0 (the
  37515. * "License"); you may not use this file except in compliance
  37516. * with the License. You may obtain a copy of the License at
  37517. *
  37518. * http://www.apache.org/licenses/LICENSE-2.0
  37519. *
  37520. * Unless required by applicable law or agreed to in writing,
  37521. * software distributed under the License is distributed on an
  37522. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37523. * KIND, either express or implied. See the License for the
  37524. * specific language governing permissions and limitations
  37525. * under the License.
  37526. */
  37527. var BaseBarSeries = SeriesModel.extend({
  37528. type: 'series.__base_bar__',
  37529. getInitialData: function (option, ecModel) {
  37530. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  37531. },
  37532. getMarkerPosition: function (value) {
  37533. var coordSys = this.coordinateSystem;
  37534. if (coordSys) {
  37535. // PENDING if clamp ?
  37536. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  37537. var data = this.getData();
  37538. var offset = data.getLayout('offset');
  37539. var size = data.getLayout('size');
  37540. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  37541. pt[offsetIndex] += offset + size / 2;
  37542. return pt;
  37543. }
  37544. return [NaN, NaN];
  37545. },
  37546. defaultOption: {
  37547. zlevel: 0, // 一级层叠
  37548. z: 2, // 二级层叠
  37549. coordinateSystem: 'cartesian2d',
  37550. legendHoverLink: true,
  37551. // stack: null
  37552. // Cartesian coordinate system
  37553. // xAxisIndex: 0,
  37554. // yAxisIndex: 0,
  37555. // 最小高度改为0
  37556. barMinHeight: 0,
  37557. // 最小角度为0,仅对极坐标系下的柱状图有效
  37558. barMinAngle: 0,
  37559. // cursor: null,
  37560. large: false,
  37561. largeThreshold: 400,
  37562. progressive: 3e3,
  37563. progressiveChunkMode: 'mod',
  37564. // barMaxWidth: null,
  37565. // In cartesian, the default value is 1. Otherwise null.
  37566. // barMinWidth: null,
  37567. // 默认自适应
  37568. // barWidth: null,
  37569. // 柱间距离,默认为柱形宽度的30%,可设固定值
  37570. // barGap: '30%',
  37571. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  37572. // barCategoryGap: '20%',
  37573. // label: {
  37574. // show: false
  37575. // },
  37576. itemStyle: {},
  37577. emphasis: {}
  37578. }
  37579. });
  37580. /*
  37581. * Licensed to the Apache Software Foundation (ASF) under one
  37582. * or more contributor license agreements. See the NOTICE file
  37583. * distributed with this work for additional information
  37584. * regarding copyright ownership. The ASF licenses this file
  37585. * to you under the Apache License, Version 2.0 (the
  37586. * "License"); you may not use this file except in compliance
  37587. * with the License. You may obtain a copy of the License at
  37588. *
  37589. * http://www.apache.org/licenses/LICENSE-2.0
  37590. *
  37591. * Unless required by applicable law or agreed to in writing,
  37592. * software distributed under the License is distributed on an
  37593. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37594. * KIND, either express or implied. See the License for the
  37595. * specific language governing permissions and limitations
  37596. * under the License.
  37597. */
  37598. BaseBarSeries.extend({
  37599. type: 'series.bar',
  37600. dependencies: ['grid', 'polar'],
  37601. brushSelector: 'rect',
  37602. /**
  37603. * @override
  37604. */
  37605. getProgressive: function () {
  37606. // Do not support progressive in normal mode.
  37607. return this.get('large')
  37608. ? this.get('progressive')
  37609. : false;
  37610. },
  37611. /**
  37612. * @override
  37613. */
  37614. getProgressiveThreshold: function () {
  37615. // Do not support progressive in normal mode.
  37616. var progressiveThreshold = this.get('progressiveThreshold');
  37617. var largeThreshold = this.get('largeThreshold');
  37618. if (largeThreshold > progressiveThreshold) {
  37619. progressiveThreshold = largeThreshold;
  37620. }
  37621. return progressiveThreshold;
  37622. },
  37623. defaultOption: {
  37624. // If clipped
  37625. // Only available on cartesian2d
  37626. clip: true,
  37627. // If use caps on two sides of bars
  37628. // Only available on tangential polar bar
  37629. roundCap: false,
  37630. showBackground: false,
  37631. backgroundStyle: {
  37632. color: 'rgba(180, 180, 180, 0.2)',
  37633. borderColor: null,
  37634. borderWidth: 0,
  37635. borderType: 'solid',
  37636. borderRadius: 0,
  37637. shadowBlur: 0,
  37638. shadowColor: null,
  37639. shadowOffsetX: 0,
  37640. shadowOffsetY: 0,
  37641. opacity: 1
  37642. }
  37643. }
  37644. });
  37645. /*
  37646. * Licensed to the Apache Software Foundation (ASF) under one
  37647. * or more contributor license agreements. See the NOTICE file
  37648. * distributed with this work for additional information
  37649. * regarding copyright ownership. The ASF licenses this file
  37650. * to you under the Apache License, Version 2.0 (the
  37651. * "License"); you may not use this file except in compliance
  37652. * with the License. You may obtain a copy of the License at
  37653. *
  37654. * http://www.apache.org/licenses/LICENSE-2.0
  37655. *
  37656. * Unless required by applicable law or agreed to in writing,
  37657. * software distributed under the License is distributed on an
  37658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37659. * KIND, either express or implied. See the License for the
  37660. * specific language governing permissions and limitations
  37661. * under the License.
  37662. */
  37663. function setLabel(
  37664. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  37665. ) {
  37666. var labelModel = itemModel.getModel('label');
  37667. var hoverLabelModel = itemModel.getModel('emphasis.label');
  37668. setLabelStyle(
  37669. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  37670. {
  37671. labelFetcher: seriesModel,
  37672. labelDataIndex: dataIndex,
  37673. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37674. isRectText: true,
  37675. autoColor: color
  37676. }
  37677. );
  37678. fixPosition(normalStyle);
  37679. fixPosition(hoverStyle);
  37680. }
  37681. function fixPosition(style, labelPositionOutside) {
  37682. if (style.textPosition === 'outside') {
  37683. style.textPosition = labelPositionOutside;
  37684. }
  37685. }
  37686. /*
  37687. * Licensed to the Apache Software Foundation (ASF) under one
  37688. * or more contributor license agreements. See the NOTICE file
  37689. * distributed with this work for additional information
  37690. * regarding copyright ownership. The ASF licenses this file
  37691. * to you under the Apache License, Version 2.0 (the
  37692. * "License"); you may not use this file except in compliance
  37693. * with the License. You may obtain a copy of the License at
  37694. *
  37695. * http://www.apache.org/licenses/LICENSE-2.0
  37696. *
  37697. * Unless required by applicable law or agreed to in writing,
  37698. * software distributed under the License is distributed on an
  37699. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37700. * KIND, either express or implied. See the License for the
  37701. * specific language governing permissions and limitations
  37702. * under the License.
  37703. */
  37704. var getBarItemStyle = makeStyleMapper(
  37705. [
  37706. ['fill', 'color'],
  37707. ['stroke', 'borderColor'],
  37708. ['lineWidth', 'borderWidth'],
  37709. // Compatitable with 2
  37710. ['stroke', 'barBorderColor'],
  37711. ['lineWidth', 'barBorderWidth'],
  37712. ['opacity'],
  37713. ['shadowBlur'],
  37714. ['shadowOffsetX'],
  37715. ['shadowOffsetY'],
  37716. ['shadowColor']
  37717. ]
  37718. );
  37719. var barItemStyle = {
  37720. getBarItemStyle: function (excludes) {
  37721. var style = getBarItemStyle(this, excludes);
  37722. if (this.getBorderLineDash) {
  37723. var lineDash = this.getBorderLineDash();
  37724. lineDash && (style.lineDash = lineDash);
  37725. }
  37726. return style;
  37727. }
  37728. };
  37729. /*
  37730. * Licensed to the Apache Software Foundation (ASF) under one
  37731. * or more contributor license agreements. See the NOTICE file
  37732. * distributed with this work for additional information
  37733. * regarding copyright ownership. The ASF licenses this file
  37734. * to you under the Apache License, Version 2.0 (the
  37735. * "License"); you may not use this file except in compliance
  37736. * with the License. You may obtain a copy of the License at
  37737. *
  37738. * http://www.apache.org/licenses/LICENSE-2.0
  37739. *
  37740. * Unless required by applicable law or agreed to in writing,
  37741. * software distributed under the License is distributed on an
  37742. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37743. * KIND, either express or implied. See the License for the
  37744. * specific language governing permissions and limitations
  37745. * under the License.
  37746. */
  37747. /**
  37748. * Sausage: similar to sector, but have half circle on both sides
  37749. * @public
  37750. */
  37751. var Sausage = extendShape({
  37752. type: 'sausage',
  37753. shape: {
  37754. cx: 0,
  37755. cy: 0,
  37756. r0: 0,
  37757. r: 0,
  37758. startAngle: 0,
  37759. endAngle: Math.PI * 2,
  37760. clockwise: true
  37761. },
  37762. buildPath: function (ctx, shape) {
  37763. var x = shape.cx;
  37764. var y = shape.cy;
  37765. var r0 = Math.max(shape.r0 || 0, 0);
  37766. var r = Math.max(shape.r, 0);
  37767. var dr = (r - r0) * 0.5;
  37768. var rCenter = r0 + dr;
  37769. var startAngle = shape.startAngle;
  37770. var endAngle = shape.endAngle;
  37771. var clockwise = shape.clockwise;
  37772. var unitStartX = Math.cos(startAngle);
  37773. var unitStartY = Math.sin(startAngle);
  37774. var unitEndX = Math.cos(endAngle);
  37775. var unitEndY = Math.sin(endAngle);
  37776. var lessThanCircle = clockwise
  37777. ? endAngle - startAngle < Math.PI * 2
  37778. : startAngle - endAngle < Math.PI * 2;
  37779. if (lessThanCircle) {
  37780. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  37781. ctx.arc(
  37782. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  37783. -Math.PI + startAngle, startAngle, !clockwise
  37784. );
  37785. }
  37786. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  37787. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  37788. ctx.arc(
  37789. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  37790. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  37791. );
  37792. if (r0 !== 0) {
  37793. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  37794. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  37795. }
  37796. ctx.closePath();
  37797. }
  37798. });
  37799. /*
  37800. * Licensed to the Apache Software Foundation (ASF) under one
  37801. * or more contributor license agreements. See the NOTICE file
  37802. * distributed with this work for additional information
  37803. * regarding copyright ownership. The ASF licenses this file
  37804. * to you under the Apache License, Version 2.0 (the
  37805. * "License"); you may not use this file except in compliance
  37806. * with the License. You may obtain a copy of the License at
  37807. *
  37808. * http://www.apache.org/licenses/LICENSE-2.0
  37809. *
  37810. * Unless required by applicable law or agreed to in writing,
  37811. * software distributed under the License is distributed on an
  37812. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37813. * KIND, either express or implied. See the License for the
  37814. * specific language governing permissions and limitations
  37815. * under the License.
  37816. */
  37817. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  37818. var _eventPos = [0, 0];
  37819. // FIXME
  37820. // Just for compatible with ec2.
  37821. extend(Model.prototype, barItemStyle);
  37822. function getClipArea(coord, data) {
  37823. var coordSysClipArea = coord.getArea && coord.getArea();
  37824. if (coord.type === 'cartesian2d') {
  37825. var baseAxis = coord.getBaseAxis();
  37826. // When boundaryGap is false or using time axis. bar may exceed the grid.
  37827. // We should not clip this part.
  37828. // See test/bar2.html
  37829. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  37830. var expandWidth = data.getLayout('bandWidth');
  37831. if (baseAxis.isHorizontal()) {
  37832. coordSysClipArea.x -= expandWidth;
  37833. coordSysClipArea.width += expandWidth * 2;
  37834. }
  37835. else {
  37836. coordSysClipArea.y -= expandWidth;
  37837. coordSysClipArea.height += expandWidth * 2;
  37838. }
  37839. }
  37840. }
  37841. return coordSysClipArea;
  37842. }
  37843. extendChartView({
  37844. type: 'bar',
  37845. render: function (seriesModel, ecModel, api) {
  37846. this._updateDrawMode(seriesModel);
  37847. var coordinateSystemType = seriesModel.get('coordinateSystem');
  37848. if (coordinateSystemType === 'cartesian2d'
  37849. || coordinateSystemType === 'polar'
  37850. ) {
  37851. this._isLargeDraw
  37852. ? this._renderLarge(seriesModel, ecModel, api)
  37853. : this._renderNormal(seriesModel, ecModel, api);
  37854. }
  37855. else if (__DEV__) {
  37856. console.warn('Only cartesian2d and polar supported for bar.');
  37857. }
  37858. return this.group;
  37859. },
  37860. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37861. this._clear();
  37862. this._updateDrawMode(seriesModel);
  37863. },
  37864. incrementalRender: function (params, seriesModel, ecModel, api) {
  37865. // Do not support progressive in normal mode.
  37866. this._incrementalRenderLarge(params, seriesModel);
  37867. },
  37868. _updateDrawMode: function (seriesModel) {
  37869. var isLargeDraw = seriesModel.pipelineContext.large;
  37870. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  37871. this._isLargeDraw = isLargeDraw;
  37872. this._clear();
  37873. }
  37874. },
  37875. _renderNormal: function (seriesModel, ecModel, api) {
  37876. var group = this.group;
  37877. var data = seriesModel.getData();
  37878. var oldData = this._data;
  37879. var coord = seriesModel.coordinateSystem;
  37880. var baseAxis = coord.getBaseAxis();
  37881. var isHorizontalOrRadial;
  37882. if (coord.type === 'cartesian2d') {
  37883. isHorizontalOrRadial = baseAxis.isHorizontal();
  37884. }
  37885. else if (coord.type === 'polar') {
  37886. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37887. }
  37888. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  37889. var needsClip = seriesModel.get('clip', true);
  37890. var coordSysClipArea = getClipArea(coord, data);
  37891. // If there is clipPath created in large mode. Remove it.
  37892. group.removeClipPath();
  37893. // We don't use clipPath in normal mode because we needs a perfect animation
  37894. // And don't want the label are clipped.
  37895. var roundCap = seriesModel.get('roundCap', true);
  37896. var drawBackground = seriesModel.get('showBackground', true);
  37897. var backgroundModel = seriesModel.getModel('backgroundStyle');
  37898. var barBorderRadius = backgroundModel.get('barBorderRadius') || 0;
  37899. var bgEls = [];
  37900. var oldBgEls = this._backgroundEls || [];
  37901. var createBackground = function (dataIndex) {
  37902. var bgLayout = getLayout[coord.type](data, dataIndex);
  37903. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  37904. bgEl.useStyle(backgroundModel.getBarItemStyle());
  37905. // Only cartesian2d support borderRadius.
  37906. if (coord.type === 'cartesian2d') {
  37907. bgEl.setShape('r', barBorderRadius);
  37908. }
  37909. bgEls[dataIndex] = bgEl;
  37910. return bgEl;
  37911. };
  37912. data.diff(oldData)
  37913. .add(function (dataIndex) {
  37914. var itemModel = data.getItemModel(dataIndex);
  37915. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  37916. if (drawBackground) {
  37917. createBackground(dataIndex);
  37918. }
  37919. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  37920. if (!data.hasValue(dataIndex)) {
  37921. return;
  37922. }
  37923. if (needsClip) {
  37924. // Clip will modify the layout params.
  37925. // And return a boolean to determine if the shape are fully clipped.
  37926. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37927. if (isClipped) {
  37928. group.remove(el);
  37929. return;
  37930. }
  37931. }
  37932. var el = elementCreator[coord.type](
  37933. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  37934. );
  37935. data.setItemGraphicEl(dataIndex, el);
  37936. group.add(el);
  37937. updateStyle(
  37938. el, data, dataIndex, itemModel, layout,
  37939. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37940. );
  37941. })
  37942. .update(function (newIndex, oldIndex) {
  37943. var itemModel = data.getItemModel(newIndex);
  37944. var layout = getLayout[coord.type](data, newIndex, itemModel);
  37945. if (drawBackground) {
  37946. var bgEl;
  37947. if (oldBgEls.length === 0) {
  37948. bgEl = createBackground(oldIndex);
  37949. }
  37950. else {
  37951. bgEl = oldBgEls[oldIndex];
  37952. bgEl.useStyle(backgroundModel.getBarItemStyle());
  37953. // Only cartesian2d support borderRadius.
  37954. if (coord.type === 'cartesian2d') {
  37955. bgEl.setShape('r', barBorderRadius);
  37956. }
  37957. bgEls[newIndex] = bgEl;
  37958. }
  37959. var bgLayout = getLayout[coord.type](data, newIndex);
  37960. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  37961. updateProps(bgEl, { shape: shape }, animationModel, newIndex);
  37962. }
  37963. var el = oldData.getItemGraphicEl(oldIndex);
  37964. if (!data.hasValue(newIndex)) {
  37965. group.remove(el);
  37966. return;
  37967. }
  37968. if (needsClip) {
  37969. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37970. if (isClipped) {
  37971. group.remove(el);
  37972. return;
  37973. }
  37974. }
  37975. if (el) {
  37976. updateProps(el, {shape: layout}, animationModel, newIndex);
  37977. }
  37978. else {
  37979. el = elementCreator[coord.type](
  37980. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  37981. );
  37982. }
  37983. data.setItemGraphicEl(newIndex, el);
  37984. // Add back
  37985. group.add(el);
  37986. updateStyle(
  37987. el, data, newIndex, itemModel, layout,
  37988. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37989. );
  37990. })
  37991. .remove(function (dataIndex) {
  37992. var el = oldData.getItemGraphicEl(dataIndex);
  37993. if (coord.type === 'cartesian2d') {
  37994. el && removeRect(dataIndex, animationModel, el);
  37995. }
  37996. else {
  37997. el && removeSector(dataIndex, animationModel, el);
  37998. }
  37999. })
  38000. .execute();
  38001. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  38002. bgGroup.removeAll();
  38003. for (var i = 0; i < bgEls.length; ++i) {
  38004. bgGroup.add(bgEls[i]);
  38005. }
  38006. group.add(bgGroup);
  38007. this._backgroundEls = bgEls;
  38008. this._data = data;
  38009. },
  38010. _renderLarge: function (seriesModel, ecModel, api) {
  38011. this._clear();
  38012. createLarge(seriesModel, this.group);
  38013. // Use clipPath in large mode.
  38014. var clipPath = seriesModel.get('clip', true)
  38015. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  38016. : null;
  38017. if (clipPath) {
  38018. this.group.setClipPath(clipPath);
  38019. }
  38020. else {
  38021. this.group.removeClipPath();
  38022. }
  38023. },
  38024. _incrementalRenderLarge: function (params, seriesModel) {
  38025. this._removeBackground();
  38026. createLarge(seriesModel, this.group, true);
  38027. },
  38028. dispose: noop,
  38029. remove: function (ecModel) {
  38030. this._clear(ecModel);
  38031. },
  38032. _clear: function (ecModel) {
  38033. var group = this.group;
  38034. var data = this._data;
  38035. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  38036. this._removeBackground();
  38037. this._backgroundEls = [];
  38038. data.eachItemGraphicEl(function (el) {
  38039. if (el.type === 'sector') {
  38040. removeSector(el.dataIndex, ecModel, el);
  38041. }
  38042. else {
  38043. removeRect(el.dataIndex, ecModel, el);
  38044. }
  38045. });
  38046. }
  38047. else {
  38048. group.removeAll();
  38049. }
  38050. this._data = null;
  38051. },
  38052. _removeBackground: function () {
  38053. this.group.remove(this._backgroundGroup);
  38054. this._backgroundGroup = null;
  38055. }
  38056. });
  38057. var mathMax$4 = Math.max;
  38058. var mathMin$4 = Math.min;
  38059. var clip = {
  38060. cartesian2d: function (coordSysBoundingRect, layout) {
  38061. var signWidth = layout.width < 0 ? -1 : 1;
  38062. var signHeight = layout.height < 0 ? -1 : 1;
  38063. // Needs positive width and height
  38064. if (signWidth < 0) {
  38065. layout.x += layout.width;
  38066. layout.width = -layout.width;
  38067. }
  38068. if (signHeight < 0) {
  38069. layout.y += layout.height;
  38070. layout.height = -layout.height;
  38071. }
  38072. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  38073. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  38074. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  38075. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  38076. layout.x = x;
  38077. layout.y = y;
  38078. layout.width = x2 - x;
  38079. layout.height = y2 - y;
  38080. var clipped = layout.width < 0 || layout.height < 0;
  38081. // Reverse back
  38082. if (signWidth < 0) {
  38083. layout.x += layout.width;
  38084. layout.width = -layout.width;
  38085. }
  38086. if (signHeight < 0) {
  38087. layout.y += layout.height;
  38088. layout.height = -layout.height;
  38089. }
  38090. return clipped;
  38091. },
  38092. polar: function (coordSysClipArea, layout) {
  38093. var signR = layout.r0 <= layout.r ? 1 : -1;
  38094. // Make sure r is larger than r0
  38095. if (signR < 0) {
  38096. var r = layout.r;
  38097. layout.r = layout.r0;
  38098. layout.r0 = r;
  38099. }
  38100. var r = mathMin$4(layout.r, coordSysClipArea.r);
  38101. var r0 = mathMax$4(layout.r0, coordSysClipArea.r0);
  38102. layout.r = r;
  38103. layout.r0 = r0;
  38104. var clipped = r - r0 < 0;
  38105. // Reverse back
  38106. if (signR < 0) {
  38107. var r = layout.r;
  38108. layout.r = layout.r0;
  38109. layout.r0 = r;
  38110. }
  38111. return clipped;
  38112. }
  38113. };
  38114. var elementCreator = {
  38115. cartesian2d: function (
  38116. dataIndex, layout, isHorizontal,
  38117. animationModel, isUpdate
  38118. ) {
  38119. var rect = new Rect({
  38120. shape: extend({}, layout),
  38121. z2: 1
  38122. });
  38123. rect.name = 'item';
  38124. // Animation
  38125. if (animationModel) {
  38126. var rectShape = rect.shape;
  38127. var animateProperty = isHorizontal ? 'height' : 'width';
  38128. var animateTarget = {};
  38129. rectShape[animateProperty] = 0;
  38130. animateTarget[animateProperty] = layout[animateProperty];
  38131. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  38132. shape: animateTarget
  38133. }, animationModel, dataIndex);
  38134. }
  38135. return rect;
  38136. },
  38137. polar: function (
  38138. dataIndex, layout, isRadial,
  38139. animationModel, isUpdate, roundCap
  38140. ) {
  38141. // Keep the same logic with bar in catesion: use end value to control
  38142. // direction. Notice that if clockwise is true (by default), the sector
  38143. // will always draw clockwisely, no matter whether endAngle is greater
  38144. // or less than startAngle.
  38145. var clockwise = layout.startAngle < layout.endAngle;
  38146. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  38147. var sector = new ShapeClass({
  38148. shape: defaults({clockwise: clockwise}, layout),
  38149. z2: 1
  38150. });
  38151. sector.name = 'item';
  38152. // Animation
  38153. if (animationModel) {
  38154. var sectorShape = sector.shape;
  38155. var animateProperty = isRadial ? 'r' : 'endAngle';
  38156. var animateTarget = {};
  38157. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  38158. animateTarget[animateProperty] = layout[animateProperty];
  38159. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  38160. shape: animateTarget
  38161. }, animationModel, dataIndex);
  38162. }
  38163. return sector;
  38164. }
  38165. };
  38166. function removeRect(dataIndex, animationModel, el) {
  38167. // Not show text when animating
  38168. el.style.text = null;
  38169. updateProps(el, {
  38170. shape: {
  38171. width: 0
  38172. }
  38173. }, animationModel, dataIndex, function () {
  38174. el.parent && el.parent.remove(el);
  38175. });
  38176. }
  38177. function removeSector(dataIndex, animationModel, el) {
  38178. // Not show text when animating
  38179. el.style.text = null;
  38180. updateProps(el, {
  38181. shape: {
  38182. r: el.shape.r0
  38183. }
  38184. }, animationModel, dataIndex, function () {
  38185. el.parent && el.parent.remove(el);
  38186. });
  38187. }
  38188. var getLayout = {
  38189. // itemModel is only used to get borderWidth, which is not needed
  38190. // when calculating bar background layout.
  38191. cartesian2d: function (data, dataIndex, itemModel) {
  38192. var layout = data.getItemLayout(dataIndex);
  38193. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0;
  38194. // fix layout with lineWidth
  38195. var signX = layout.width > 0 ? 1 : -1;
  38196. var signY = layout.height > 0 ? 1 : -1;
  38197. return {
  38198. x: layout.x + signX * fixedLineWidth / 2,
  38199. y: layout.y + signY * fixedLineWidth / 2,
  38200. width: layout.width - signX * fixedLineWidth,
  38201. height: layout.height - signY * fixedLineWidth
  38202. };
  38203. },
  38204. polar: function (data, dataIndex, itemModel) {
  38205. var layout = data.getItemLayout(dataIndex);
  38206. return {
  38207. cx: layout.cx,
  38208. cy: layout.cy,
  38209. r0: layout.r0,
  38210. r: layout.r,
  38211. startAngle: layout.startAngle,
  38212. endAngle: layout.endAngle
  38213. };
  38214. }
  38215. };
  38216. function isZeroOnPolar(layout) {
  38217. return layout.startAngle != null
  38218. && layout.endAngle != null
  38219. && layout.startAngle === layout.endAngle;
  38220. }
  38221. function updateStyle(
  38222. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  38223. ) {
  38224. var color = data.getItemVisual(dataIndex, 'color');
  38225. var opacity = data.getItemVisual(dataIndex, 'opacity');
  38226. var stroke = data.getVisual('borderColor');
  38227. var itemStyleModel = itemModel.getModel('itemStyle');
  38228. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  38229. if (!isPolar) {
  38230. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  38231. }
  38232. el.useStyle(defaults(
  38233. {
  38234. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  38235. fill: isZeroOnPolar(layout) ? 'none' : color,
  38236. opacity: opacity
  38237. },
  38238. itemStyleModel.getBarItemStyle()
  38239. ));
  38240. var cursorStyle = itemModel.getShallow('cursor');
  38241. cursorStyle && el.attr('cursor', cursorStyle);
  38242. var labelPositionOutside = isHorizontal
  38243. ? (layout.height > 0 ? 'bottom' : 'top')
  38244. : (layout.width > 0 ? 'left' : 'right');
  38245. if (!isPolar) {
  38246. setLabel(
  38247. el.style, hoverStyle, itemModel, color,
  38248. seriesModel, dataIndex, labelPositionOutside
  38249. );
  38250. }
  38251. if (isZeroOnPolar(layout)) {
  38252. hoverStyle.fill = hoverStyle.stroke = 'none';
  38253. }
  38254. setHoverStyle(el, hoverStyle);
  38255. }
  38256. // In case width or height are too small.
  38257. function getLineWidth(itemModel, rawLayout) {
  38258. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  38259. // width or height may be NaN for empty data
  38260. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  38261. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  38262. return Math.min(lineWidth, width, height);
  38263. }
  38264. var LargePath = Path.extend({
  38265. type: 'largeBar',
  38266. shape: {points: []},
  38267. buildPath: function (ctx, shape) {
  38268. // Drawing lines is more efficient than drawing
  38269. // a whole line or drawing rects.
  38270. var points = shape.points;
  38271. var startPoint = this.__startPoint;
  38272. var baseDimIdx = this.__baseDimIdx;
  38273. for (var i = 0; i < points.length; i += 2) {
  38274. startPoint[baseDimIdx] = points[i + baseDimIdx];
  38275. ctx.moveTo(startPoint[0], startPoint[1]);
  38276. ctx.lineTo(points[i], points[i + 1]);
  38277. }
  38278. }
  38279. });
  38280. function createLarge(seriesModel, group, incremental) {
  38281. // TODO support polar
  38282. var data = seriesModel.getData();
  38283. var startPoint = [];
  38284. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  38285. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  38286. var largeDataIndices = data.getLayout('largeDataIndices');
  38287. var barWidth = data.getLayout('barWidth');
  38288. var backgroundModel = seriesModel.getModel('backgroundStyle');
  38289. var drawBackground = seriesModel.get('showBackground', true);
  38290. if (drawBackground) {
  38291. var points = data.getLayout('largeBackgroundPoints');
  38292. var backgroundStartPoint = [];
  38293. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  38294. var bgEl = new LargePath({
  38295. shape: {points: points},
  38296. incremental: !!incremental,
  38297. __startPoint: backgroundStartPoint,
  38298. __baseDimIdx: baseDimIdx,
  38299. __largeDataIndices: largeDataIndices,
  38300. __barWidth: barWidth,
  38301. silent: true,
  38302. z2: 0
  38303. });
  38304. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  38305. group.add(bgEl);
  38306. }
  38307. var el = new LargePath({
  38308. shape: {points: data.getLayout('largePoints')},
  38309. incremental: !!incremental,
  38310. __startPoint: startPoint,
  38311. __baseDimIdx: baseDimIdx,
  38312. __largeDataIndices: largeDataIndices,
  38313. __barWidth: barWidth
  38314. });
  38315. group.add(el);
  38316. setLargeStyle(el, seriesModel, data);
  38317. // Enable tooltip and user mouse/touch event handlers.
  38318. el.seriesIndex = seriesModel.seriesIndex;
  38319. if (!seriesModel.get('silent')) {
  38320. el.on('mousedown', largePathUpdateDataIndex);
  38321. el.on('mousemove', largePathUpdateDataIndex);
  38322. }
  38323. }
  38324. // Use throttle to avoid frequently traverse to find dataIndex.
  38325. var largePathUpdateDataIndex = throttle(function (event) {
  38326. var largePath = this;
  38327. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  38328. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  38329. }, 30, false);
  38330. function largePathFindDataIndex(largePath, x, y) {
  38331. var baseDimIdx = largePath.__baseDimIdx;
  38332. var valueDimIdx = 1 - baseDimIdx;
  38333. var points = largePath.shape.points;
  38334. var largeDataIndices = largePath.__largeDataIndices;
  38335. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  38336. var startValueVal = largePath.__startPoint[valueDimIdx];
  38337. _eventPos[0] = x;
  38338. _eventPos[1] = y;
  38339. var pointerBaseVal = _eventPos[baseDimIdx];
  38340. var pointerValueVal = _eventPos[1 - baseDimIdx];
  38341. var baseLowerBound = pointerBaseVal - barWidthHalf;
  38342. var baseUpperBound = pointerBaseVal + barWidthHalf;
  38343. for (var i = 0, len = points.length / 2; i < len; i++) {
  38344. var ii = i * 2;
  38345. var barBaseVal = points[ii + baseDimIdx];
  38346. var barValueVal = points[ii + valueDimIdx];
  38347. if (
  38348. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  38349. && (
  38350. startValueVal <= barValueVal
  38351. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  38352. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  38353. )
  38354. ) {
  38355. return largeDataIndices[i];
  38356. }
  38357. }
  38358. return -1;
  38359. }
  38360. function setLargeStyle(el, seriesModel, data) {
  38361. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  38362. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  38363. el.useStyle(itemStyle);
  38364. el.style.fill = null;
  38365. el.style.stroke = borderColor;
  38366. el.style.lineWidth = data.getLayout('barWidth');
  38367. }
  38368. function setLargeBackgroundStyle(el, backgroundModel, data) {
  38369. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  38370. var itemStyle = backgroundModel.getItemStyle(['color', 'borderColor']);
  38371. el.useStyle(itemStyle);
  38372. el.style.fill = null;
  38373. el.style.stroke = borderColor;
  38374. el.style.lineWidth = data.getLayout('barWidth');
  38375. }
  38376. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  38377. var coordLayout;
  38378. var isPolar = coord.type === 'polar';
  38379. if (isPolar) {
  38380. coordLayout = coord.getArea();
  38381. }
  38382. else {
  38383. coordLayout = coord.grid.getRect();
  38384. }
  38385. if (isPolar) {
  38386. return {
  38387. cx: coordLayout.cx,
  38388. cy: coordLayout.cy,
  38389. r0: isHorizontalOrRadial ? coordLayout.r0 : layout.r0,
  38390. r: isHorizontalOrRadial ? coordLayout.r : layout.r,
  38391. startAngle: isHorizontalOrRadial ? layout.startAngle : 0,
  38392. endAngle: isHorizontalOrRadial ? layout.endAngle : Math.PI * 2
  38393. };
  38394. }
  38395. else {
  38396. return {
  38397. x: isHorizontalOrRadial ? layout.x : coordLayout.x,
  38398. y: isHorizontalOrRadial ? coordLayout.y : layout.y,
  38399. width: isHorizontalOrRadial ? layout.width : coordLayout.width,
  38400. height: isHorizontalOrRadial ? coordLayout.height : layout.height
  38401. };
  38402. }
  38403. }
  38404. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  38405. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  38406. return new ElementClz({
  38407. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  38408. silent: true,
  38409. z2: 0
  38410. });
  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. // In case developer forget to include grid component
  38431. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  38432. // Use higher prority to avoid to be blocked by other overall layout, which do not
  38433. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  38434. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  38435. registerVisual({
  38436. seriesType: 'bar',
  38437. reset: function (seriesModel) {
  38438. // Visual coding for legend
  38439. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  38440. }
  38441. });
  38442. /*
  38443. * Licensed to the Apache Software Foundation (ASF) under one
  38444. * or more contributor license agreements. See the NOTICE file
  38445. * distributed with this work for additional information
  38446. * regarding copyright ownership. The ASF licenses this file
  38447. * to you under the Apache License, Version 2.0 (the
  38448. * "License"); you may not use this file except in compliance
  38449. * with the License. You may obtain a copy of the License at
  38450. *
  38451. * http://www.apache.org/licenses/LICENSE-2.0
  38452. *
  38453. * Unless required by applicable law or agreed to in writing,
  38454. * software distributed under the License is distributed on an
  38455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38456. * KIND, either express or implied. See the License for the
  38457. * specific language governing permissions and limitations
  38458. * under the License.
  38459. */
  38460. /**
  38461. * [Usage]:
  38462. * (1)
  38463. * createListSimply(seriesModel, ['value']);
  38464. * (2)
  38465. * createListSimply(seriesModel, {
  38466. * coordDimensions: ['value'],
  38467. * dimensionsCount: 5
  38468. * });
  38469. *
  38470. * @param {module:echarts/model/Series} seriesModel
  38471. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  38472. * The options in opt, see `echarts/data/helper/createDimensions`
  38473. * @param {Array.<string>} [nameList]
  38474. * @return {module:echarts/data/List}
  38475. */
  38476. var createListSimply = function (seriesModel, opt, nameList) {
  38477. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  38478. var source = seriesModel.getSource();
  38479. var dimensionsInfo = createDimensions(source, opt);
  38480. var list = new List(dimensionsInfo, seriesModel);
  38481. list.initData(source, nameList);
  38482. return list;
  38483. };
  38484. /*
  38485. * Licensed to the Apache Software Foundation (ASF) under one
  38486. * or more contributor license agreements. See the NOTICE file
  38487. * distributed with this work for additional information
  38488. * regarding copyright ownership. The ASF licenses this file
  38489. * to you under the Apache License, Version 2.0 (the
  38490. * "License"); you may not use this file except in compliance
  38491. * with the License. You may obtain a copy of the License at
  38492. *
  38493. * http://www.apache.org/licenses/LICENSE-2.0
  38494. *
  38495. * Unless required by applicable law or agreed to in writing,
  38496. * software distributed under the License is distributed on an
  38497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38498. * KIND, either express or implied. See the License for the
  38499. * specific language governing permissions and limitations
  38500. * under the License.
  38501. */
  38502. /**
  38503. * Data selectable mixin for chart series.
  38504. * To eanble data select, option of series must have `selectedMode`.
  38505. * And each data item will use `selected` to toggle itself selected status
  38506. */
  38507. var dataSelectableMixin = {
  38508. /**
  38509. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  38510. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  38511. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  38512. */
  38513. updateSelectedMap: function (targetList) {
  38514. this._targetList = isArray(targetList) ? targetList.slice() : [];
  38515. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  38516. targetMap.set(target.name, target);
  38517. return targetMap;
  38518. }, createHashMap());
  38519. },
  38520. /**
  38521. * Either name or id should be passed as input here.
  38522. * If both of them are defined, id is used.
  38523. *
  38524. * @param {string|undefined} name name of data
  38525. * @param {number|undefined} id dataIndex of data
  38526. */
  38527. // PENGING If selectedMode is null ?
  38528. select: function (name, id) {
  38529. var target = id != null
  38530. ? this._targetList[id]
  38531. : this._selectTargetMap.get(name);
  38532. var selectedMode = this.get('selectedMode');
  38533. if (selectedMode === 'single') {
  38534. this._selectTargetMap.each(function (target) {
  38535. target.selected = false;
  38536. });
  38537. }
  38538. target && (target.selected = true);
  38539. },
  38540. /**
  38541. * Either name or id should be passed as input here.
  38542. * If both of them are defined, id is used.
  38543. *
  38544. * @param {string|undefined} name name of data
  38545. * @param {number|undefined} id dataIndex of data
  38546. */
  38547. unSelect: function (name, id) {
  38548. var target = id != null
  38549. ? this._targetList[id]
  38550. : this._selectTargetMap.get(name);
  38551. // var selectedMode = this.get('selectedMode');
  38552. // selectedMode !== 'single' && target && (target.selected = false);
  38553. target && (target.selected = false);
  38554. },
  38555. /**
  38556. * Either name or id should be passed as input here.
  38557. * If both of them are defined, id is used.
  38558. *
  38559. * @param {string|undefined} name name of data
  38560. * @param {number|undefined} id dataIndex of data
  38561. */
  38562. toggleSelected: function (name, id) {
  38563. var target = id != null
  38564. ? this._targetList[id]
  38565. : this._selectTargetMap.get(name);
  38566. if (target != null) {
  38567. this[target.selected ? 'unSelect' : 'select'](name, id);
  38568. return target.selected;
  38569. }
  38570. },
  38571. /**
  38572. * Either name or id should be passed as input here.
  38573. * If both of them are defined, id is used.
  38574. *
  38575. * @param {string|undefined} name name of data
  38576. * @param {number|undefined} id dataIndex of data
  38577. */
  38578. isSelected: function (name, id) {
  38579. var target = id != null
  38580. ? this._targetList[id]
  38581. : this._selectTargetMap.get(name);
  38582. return target && target.selected;
  38583. }
  38584. };
  38585. /*
  38586. * Licensed to the Apache Software Foundation (ASF) under one
  38587. * or more contributor license agreements. See the NOTICE file
  38588. * distributed with this work for additional information
  38589. * regarding copyright ownership. The ASF licenses this file
  38590. * to you under the Apache License, Version 2.0 (the
  38591. * "License"); you may not use this file except in compliance
  38592. * with the License. You may obtain a copy of the License at
  38593. *
  38594. * http://www.apache.org/licenses/LICENSE-2.0
  38595. *
  38596. * Unless required by applicable law or agreed to in writing,
  38597. * software distributed under the License is distributed on an
  38598. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38599. * KIND, either express or implied. See the License for the
  38600. * specific language governing permissions and limitations
  38601. * under the License.
  38602. */
  38603. /**
  38604. * LegendVisualProvider is an bridge that pick encoded color from data and
  38605. * provide to the legend component.
  38606. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  38607. * @param {Function} getRawData Function to get raw data before filtered.
  38608. */
  38609. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  38610. this.getAllNames = function () {
  38611. var rawData = getRawData();
  38612. // We find the name from the raw data. In case it's filtered by the legend component.
  38613. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38614. return rawData.mapArray(rawData.getName);
  38615. };
  38616. this.containName = function (name) {
  38617. var rawData = getRawData();
  38618. return rawData.indexOfName(name) >= 0;
  38619. };
  38620. this.indexOfName = function (name) {
  38621. // Only get data when necessary.
  38622. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38623. // Invoking Series#getData immediately will throw an error.
  38624. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38625. return dataWithEncodedVisual.indexOfName(name);
  38626. };
  38627. this.getItemVisual = function (dataIndex, key) {
  38628. // Get encoded visual properties from final filtered data.
  38629. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38630. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38631. };
  38632. }
  38633. /*
  38634. * Licensed to the Apache Software Foundation (ASF) under one
  38635. * or more contributor license agreements. See the NOTICE file
  38636. * distributed with this work for additional information
  38637. * regarding copyright ownership. The ASF licenses this file
  38638. * to you under the Apache License, Version 2.0 (the
  38639. * "License"); you may not use this file except in compliance
  38640. * with the License. You may obtain a copy of the License at
  38641. *
  38642. * http://www.apache.org/licenses/LICENSE-2.0
  38643. *
  38644. * Unless required by applicable law or agreed to in writing,
  38645. * software distributed under the License is distributed on an
  38646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38647. * KIND, either express or implied. See the License for the
  38648. * specific language governing permissions and limitations
  38649. * under the License.
  38650. */
  38651. var PieSeries = extendSeriesModel({
  38652. type: 'series.pie',
  38653. // Overwrite
  38654. init: function (option) {
  38655. PieSeries.superApply(this, 'init', arguments);
  38656. // Enable legend selection for each data item
  38657. // Use a function instead of direct access because data reference may changed
  38658. this.legendVisualProvider = new LegendVisualProvider(
  38659. bind(this.getData, this), bind(this.getRawData, this)
  38660. );
  38661. this.updateSelectedMap(this._createSelectableList());
  38662. this._defaultLabelLine(option);
  38663. },
  38664. // Overwrite
  38665. mergeOption: function (newOption) {
  38666. PieSeries.superCall(this, 'mergeOption', newOption);
  38667. this.updateSelectedMap(this._createSelectableList());
  38668. },
  38669. getInitialData: function (option, ecModel) {
  38670. return createListSimply(this, {
  38671. coordDimensions: ['value'],
  38672. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38673. });
  38674. },
  38675. _createSelectableList: function () {
  38676. var data = this.getRawData();
  38677. var valueDim = data.mapDimension('value');
  38678. var targetList = [];
  38679. for (var i = 0, len = data.count(); i < len; i++) {
  38680. targetList.push({
  38681. name: data.getName(i),
  38682. value: data.get(valueDim, i),
  38683. selected: retrieveRawAttr(data, i, 'selected')
  38684. });
  38685. }
  38686. return targetList;
  38687. },
  38688. // Overwrite
  38689. getDataParams: function (dataIndex) {
  38690. var data = this.getData();
  38691. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  38692. // FIXME toFixed?
  38693. var valueList = [];
  38694. data.each(data.mapDimension('value'), function (value) {
  38695. valueList.push(value);
  38696. });
  38697. params.percent = getPercentWithPrecision(
  38698. valueList,
  38699. dataIndex,
  38700. data.hostModel.get('percentPrecision')
  38701. );
  38702. params.$vars.push('percent');
  38703. return params;
  38704. },
  38705. _defaultLabelLine: function (option) {
  38706. // Extend labelLine emphasis
  38707. defaultEmphasis(option, 'labelLine', ['show']);
  38708. var labelLineNormalOpt = option.labelLine;
  38709. var labelLineEmphasisOpt = option.emphasis.labelLine;
  38710. // Not show label line if `label.normal.show = false`
  38711. labelLineNormalOpt.show = labelLineNormalOpt.show
  38712. && option.label.show;
  38713. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  38714. && option.emphasis.label.show;
  38715. },
  38716. defaultOption: {
  38717. zlevel: 0,
  38718. z: 2,
  38719. legendHoverLink: true,
  38720. hoverAnimation: true,
  38721. // 默认全局居中
  38722. center: ['50%', '50%'],
  38723. radius: [0, '75%'],
  38724. // 默认顺时针
  38725. clockwise: true,
  38726. startAngle: 90,
  38727. // 最小角度改为0
  38728. minAngle: 0,
  38729. // If the angle of a sector less than `minShowLabelAngle`,
  38730. // the label will not be displayed.
  38731. minShowLabelAngle: 0,
  38732. // 选中时扇区偏移量
  38733. selectedOffset: 10,
  38734. // 高亮扇区偏移量
  38735. hoverOffset: 10,
  38736. // If use strategy to avoid label overlapping
  38737. avoidLabelOverlap: true,
  38738. // 选择模式,默认关闭,可选single,multiple
  38739. // selectedMode: false,
  38740. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38741. // roseType: null,
  38742. percentPrecision: 2,
  38743. // If still show when all data zero.
  38744. stillShowZeroSum: true,
  38745. // cursor: null,
  38746. left: 0,
  38747. top: 0,
  38748. right: 0,
  38749. bottom: 0,
  38750. width: null,
  38751. height: null,
  38752. label: {
  38753. // If rotate around circle
  38754. rotate: false,
  38755. show: true,
  38756. // 'outer', 'inside', 'center'
  38757. position: 'outer',
  38758. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38759. alignTo: 'none',
  38760. // Closest distance between label and chart edge.
  38761. // Works only position is 'outer' and alignTo is 'edge'.
  38762. margin: '25%',
  38763. // Works only position is 'outer' and alignTo is not 'edge'.
  38764. bleedMargin: 10,
  38765. // Distance between text and label line.
  38766. distanceToLabelLine: 5
  38767. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38768. // 默认使用全局文本样式,详见TEXTSTYLE
  38769. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38770. },
  38771. // Enabled when label.normal.position is 'outer'
  38772. labelLine: {
  38773. show: true,
  38774. // 引导线两段中的第一段长度
  38775. length: 15,
  38776. // 引导线两段中的第二段长度
  38777. length2: 15,
  38778. smooth: false,
  38779. lineStyle: {
  38780. // color: 各异,
  38781. width: 1,
  38782. type: 'solid'
  38783. }
  38784. },
  38785. itemStyle: {
  38786. borderWidth: 1
  38787. },
  38788. // Animation type. Valid values: expansion, scale
  38789. animationType: 'expansion',
  38790. // Animation type when update. Valid values: transition, expansion
  38791. animationTypeUpdate: 'transition',
  38792. animationEasing: 'cubicOut'
  38793. }
  38794. });
  38795. mixin(PieSeries, dataSelectableMixin);
  38796. /*
  38797. * Licensed to the Apache Software Foundation (ASF) under one
  38798. * or more contributor license agreements. See the NOTICE file
  38799. * distributed with this work for additional information
  38800. * regarding copyright ownership. The ASF licenses this file
  38801. * to you under the Apache License, Version 2.0 (the
  38802. * "License"); you may not use this file except in compliance
  38803. * with the License. You may obtain a copy of the License at
  38804. *
  38805. * http://www.apache.org/licenses/LICENSE-2.0
  38806. *
  38807. * Unless required by applicable law or agreed to in writing,
  38808. * software distributed under the License is distributed on an
  38809. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38810. * KIND, either express or implied. See the License for the
  38811. * specific language governing permissions and limitations
  38812. * under the License.
  38813. */
  38814. /**
  38815. * @param {module:echarts/model/Series} seriesModel
  38816. * @param {boolean} hasAnimation
  38817. * @inner
  38818. */
  38819. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  38820. var data = seriesModel.getData();
  38821. var dataIndex = this.dataIndex;
  38822. var name = data.getName(dataIndex);
  38823. var selectedOffset = seriesModel.get('selectedOffset');
  38824. api.dispatchAction({
  38825. type: 'pieToggleSelect',
  38826. from: uid,
  38827. name: name,
  38828. seriesId: seriesModel.id
  38829. });
  38830. data.each(function (idx) {
  38831. toggleItemSelected(
  38832. data.getItemGraphicEl(idx),
  38833. data.getItemLayout(idx),
  38834. seriesModel.isSelected(data.getName(idx)),
  38835. selectedOffset,
  38836. hasAnimation
  38837. );
  38838. });
  38839. }
  38840. /**
  38841. * @param {module:zrender/graphic/Sector} el
  38842. * @param {Object} layout
  38843. * @param {boolean} isSelected
  38844. * @param {number} selectedOffset
  38845. * @param {boolean} hasAnimation
  38846. * @inner
  38847. */
  38848. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  38849. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38850. var dx = Math.cos(midAngle);
  38851. var dy = Math.sin(midAngle);
  38852. var offset = isSelected ? selectedOffset : 0;
  38853. var position = [dx * offset, dy * offset];
  38854. hasAnimation
  38855. // animateTo will stop revious animation like update transition
  38856. ? el.animate()
  38857. .when(200, {
  38858. position: position
  38859. })
  38860. .start('bounceOut')
  38861. : el.attr('position', position);
  38862. }
  38863. /**
  38864. * Piece of pie including Sector, Label, LabelLine
  38865. * @constructor
  38866. * @extends {module:zrender/graphic/Group}
  38867. */
  38868. function PiePiece(data, idx) {
  38869. Group.call(this);
  38870. var sector = new Sector({
  38871. z2: 2
  38872. });
  38873. var polyline = new Polyline();
  38874. var text = new Text();
  38875. this.add(sector);
  38876. this.add(polyline);
  38877. this.add(text);
  38878. this.updateData(data, idx, true);
  38879. }
  38880. var piePieceProto = PiePiece.prototype;
  38881. piePieceProto.updateData = function (data, idx, firstCreate) {
  38882. var sector = this.childAt(0);
  38883. var labelLine = this.childAt(1);
  38884. var labelText = this.childAt(2);
  38885. var seriesModel = data.hostModel;
  38886. var itemModel = data.getItemModel(idx);
  38887. var layout = data.getItemLayout(idx);
  38888. var sectorShape = extend({}, layout);
  38889. sectorShape.label = null;
  38890. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  38891. if (firstCreate) {
  38892. sector.setShape(sectorShape);
  38893. var animationType = seriesModel.getShallow('animationType');
  38894. if (animationType === 'scale') {
  38895. sector.shape.r = layout.r0;
  38896. initProps(sector, {
  38897. shape: {
  38898. r: layout.r
  38899. }
  38900. }, seriesModel, idx);
  38901. }
  38902. // Expansion
  38903. else {
  38904. sector.shape.endAngle = layout.startAngle;
  38905. updateProps(sector, {
  38906. shape: {
  38907. endAngle: layout.endAngle
  38908. }
  38909. }, seriesModel, idx);
  38910. }
  38911. }
  38912. else {
  38913. if (animationTypeUpdate === 'expansion') {
  38914. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  38915. sector.setShape(sectorShape);
  38916. }
  38917. else {
  38918. // Transition animation from the old shape
  38919. updateProps(sector, {
  38920. shape: sectorShape
  38921. }, seriesModel, idx);
  38922. }
  38923. }
  38924. // Update common style
  38925. var visualColor = data.getItemVisual(idx, 'color');
  38926. sector.useStyle(
  38927. defaults(
  38928. {
  38929. lineJoin: 'bevel',
  38930. fill: visualColor
  38931. },
  38932. itemModel.getModel('itemStyle').getItemStyle()
  38933. )
  38934. );
  38935. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38936. var cursorStyle = itemModel.getShallow('cursor');
  38937. cursorStyle && sector.attr('cursor', cursorStyle);
  38938. // Toggle selected
  38939. toggleItemSelected(
  38940. this,
  38941. data.getItemLayout(idx),
  38942. seriesModel.isSelected(data.getName(idx)),
  38943. seriesModel.get('selectedOffset'),
  38944. seriesModel.get('animation')
  38945. );
  38946. // Label and text animation should be applied only for transition type animation when update
  38947. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  38948. this._updateLabel(data, idx, withAnimation);
  38949. this.highDownOnUpdate = !seriesModel.get('silent')
  38950. ? function (fromState, toState) {
  38951. var hasAnimation = seriesModel.isAnimationEnabled() && itemModel.get('hoverAnimation');
  38952. if (toState === 'emphasis') {
  38953. labelLine.ignore = labelLine.hoverIgnore;
  38954. labelText.ignore = labelText.hoverIgnore;
  38955. // Sector may has animation of updating data. Force to move to the last frame
  38956. // Or it may stopped on the wrong shape
  38957. if (hasAnimation) {
  38958. sector.stopAnimation(true);
  38959. sector.animateTo({
  38960. shape: {
  38961. r: layout.r + seriesModel.get('hoverOffset')
  38962. }
  38963. }, 300, 'elasticOut');
  38964. }
  38965. }
  38966. else {
  38967. labelLine.ignore = labelLine.normalIgnore;
  38968. labelText.ignore = labelText.normalIgnore;
  38969. if (hasAnimation) {
  38970. sector.stopAnimation(true);
  38971. sector.animateTo({
  38972. shape: {
  38973. r: layout.r
  38974. }
  38975. }, 300, 'elasticOut');
  38976. }
  38977. }
  38978. }
  38979. : null;
  38980. setHoverStyle(this);
  38981. };
  38982. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  38983. var labelLine = this.childAt(1);
  38984. var labelText = this.childAt(2);
  38985. var seriesModel = data.hostModel;
  38986. var itemModel = data.getItemModel(idx);
  38987. var layout = data.getItemLayout(idx);
  38988. var labelLayout = layout.label;
  38989. var visualColor = data.getItemVisual(idx, 'color');
  38990. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  38991. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  38992. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  38993. return;
  38994. }
  38995. var targetLineShape = {
  38996. points: labelLayout.linePoints || [
  38997. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  38998. ]
  38999. };
  39000. var targetTextStyle = {
  39001. x: labelLayout.x,
  39002. y: labelLayout.y
  39003. };
  39004. if (withAnimation) {
  39005. updateProps(labelLine, {
  39006. shape: targetLineShape
  39007. }, seriesModel, idx);
  39008. updateProps(labelText, {
  39009. style: targetTextStyle
  39010. }, seriesModel, idx);
  39011. }
  39012. else {
  39013. labelLine.attr({
  39014. shape: targetLineShape
  39015. });
  39016. labelText.attr({
  39017. style: targetTextStyle
  39018. });
  39019. }
  39020. labelText.attr({
  39021. rotation: labelLayout.rotation,
  39022. origin: [labelLayout.x, labelLayout.y],
  39023. z2: 10
  39024. });
  39025. var labelModel = itemModel.getModel('label');
  39026. var labelHoverModel = itemModel.getModel('emphasis.label');
  39027. var labelLineModel = itemModel.getModel('labelLine');
  39028. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  39029. var visualColor = data.getItemVisual(idx, 'color');
  39030. setLabelStyle(
  39031. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  39032. {
  39033. labelFetcher: data.hostModel,
  39034. labelDataIndex: idx,
  39035. defaultText: labelLayout.text,
  39036. autoColor: visualColor,
  39037. useInsideStyle: !!labelLayout.inside
  39038. },
  39039. {
  39040. textAlign: labelLayout.textAlign,
  39041. textVerticalAlign: labelLayout.verticalAlign,
  39042. opacity: data.getItemVisual(idx, 'opacity')
  39043. }
  39044. );
  39045. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  39046. labelText.hoverIgnore = !labelHoverModel.get('show');
  39047. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  39048. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  39049. // Default use item visual color
  39050. labelLine.setStyle({
  39051. stroke: visualColor,
  39052. opacity: data.getItemVisual(idx, 'opacity')
  39053. });
  39054. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  39055. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  39056. var smooth = labelLineModel.get('smooth');
  39057. if (smooth && smooth === true) {
  39058. smooth = 0.4;
  39059. }
  39060. labelLine.setShape({
  39061. smooth: smooth
  39062. });
  39063. };
  39064. inherits(PiePiece, Group);
  39065. // Pie view
  39066. var PieView = Chart.extend({
  39067. type: 'pie',
  39068. init: function () {
  39069. var sectorGroup = new Group();
  39070. this._sectorGroup = sectorGroup;
  39071. },
  39072. render: function (seriesModel, ecModel, api, payload) {
  39073. if (payload && (payload.from === this.uid)) {
  39074. return;
  39075. }
  39076. var data = seriesModel.getData();
  39077. var oldData = this._data;
  39078. var group = this.group;
  39079. var hasAnimation = ecModel.get('animation');
  39080. var isFirstRender = !oldData;
  39081. var animationType = seriesModel.get('animationType');
  39082. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  39083. var onSectorClick = curry(
  39084. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  39085. );
  39086. var selectedMode = seriesModel.get('selectedMode');
  39087. data.diff(oldData)
  39088. .add(function (idx) {
  39089. var piePiece = new PiePiece(data, idx);
  39090. // Default expansion animation
  39091. if (isFirstRender && animationType !== 'scale') {
  39092. piePiece.eachChild(function (child) {
  39093. child.stopAnimation(true);
  39094. });
  39095. }
  39096. selectedMode && piePiece.on('click', onSectorClick);
  39097. data.setItemGraphicEl(idx, piePiece);
  39098. group.add(piePiece);
  39099. })
  39100. .update(function (newIdx, oldIdx) {
  39101. var piePiece = oldData.getItemGraphicEl(oldIdx);
  39102. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  39103. piePiece.eachChild(function (child) {
  39104. child.stopAnimation(true);
  39105. });
  39106. }
  39107. piePiece.updateData(data, newIdx);
  39108. piePiece.off('click');
  39109. selectedMode && piePiece.on('click', onSectorClick);
  39110. group.add(piePiece);
  39111. data.setItemGraphicEl(newIdx, piePiece);
  39112. })
  39113. .remove(function (idx) {
  39114. var piePiece = oldData.getItemGraphicEl(idx);
  39115. group.remove(piePiece);
  39116. })
  39117. .execute();
  39118. if (
  39119. hasAnimation && data.count() > 0
  39120. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  39121. ) {
  39122. var shape = data.getItemLayout(0);
  39123. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  39124. shape = data.getItemLayout(s);
  39125. }
  39126. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  39127. var removeClipPath = bind(group.removeClipPath, group);
  39128. group.setClipPath(this._createClipPath(
  39129. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  39130. ));
  39131. }
  39132. else {
  39133. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  39134. group.removeClipPath();
  39135. }
  39136. this._data = data;
  39137. },
  39138. dispose: function () {},
  39139. _createClipPath: function (
  39140. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  39141. ) {
  39142. var clipPath = new Sector({
  39143. shape: {
  39144. cx: cx,
  39145. cy: cy,
  39146. r0: 0,
  39147. r: r,
  39148. startAngle: startAngle,
  39149. endAngle: startAngle,
  39150. clockwise: clockwise
  39151. }
  39152. });
  39153. var initOrUpdate = isFirstRender ? initProps : updateProps;
  39154. initOrUpdate(clipPath, {
  39155. shape: {
  39156. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  39157. }
  39158. }, seriesModel, cb);
  39159. return clipPath;
  39160. },
  39161. /**
  39162. * @implement
  39163. */
  39164. containPoint: function (point, seriesModel) {
  39165. var data = seriesModel.getData();
  39166. var itemLayout = data.getItemLayout(0);
  39167. if (itemLayout) {
  39168. var dx = point[0] - itemLayout.cx;
  39169. var dy = point[1] - itemLayout.cy;
  39170. var radius = Math.sqrt(dx * dx + dy * dy);
  39171. return radius <= itemLayout.r && radius >= itemLayout.r0;
  39172. }
  39173. }
  39174. });
  39175. /*
  39176. * Licensed to the Apache Software Foundation (ASF) under one
  39177. * or more contributor license agreements. See the NOTICE file
  39178. * distributed with this work for additional information
  39179. * regarding copyright ownership. The ASF licenses this file
  39180. * to you under the Apache License, Version 2.0 (the
  39181. * "License"); you may not use this file except in compliance
  39182. * with the License. You may obtain a copy of the License at
  39183. *
  39184. * http://www.apache.org/licenses/LICENSE-2.0
  39185. *
  39186. * Unless required by applicable law or agreed to in writing,
  39187. * software distributed under the License is distributed on an
  39188. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39189. * KIND, either express or implied. See the License for the
  39190. * specific language governing permissions and limitations
  39191. * under the License.
  39192. */
  39193. var createDataSelectAction = function (seriesType, actionInfos) {
  39194. each$1(actionInfos, function (actionInfo) {
  39195. actionInfo.update = 'updateView';
  39196. /**
  39197. * @payload
  39198. * @property {string} seriesName
  39199. * @property {string} name
  39200. */
  39201. registerAction(actionInfo, function (payload, ecModel) {
  39202. var selected = {};
  39203. ecModel.eachComponent(
  39204. {mainType: 'series', subType: seriesType, query: payload},
  39205. function (seriesModel) {
  39206. if (seriesModel[actionInfo.method]) {
  39207. seriesModel[actionInfo.method](
  39208. payload.name,
  39209. payload.dataIndex
  39210. );
  39211. }
  39212. var data = seriesModel.getData();
  39213. // Create selected map
  39214. data.each(function (idx) {
  39215. var name = data.getName(idx);
  39216. selected[name] = seriesModel.isSelected(name)
  39217. || false;
  39218. });
  39219. }
  39220. );
  39221. return {
  39222. name: payload.name,
  39223. selected: selected,
  39224. seriesId: payload.seriesId
  39225. };
  39226. });
  39227. });
  39228. };
  39229. /*
  39230. * Licensed to the Apache Software Foundation (ASF) under one
  39231. * or more contributor license agreements. See the NOTICE file
  39232. * distributed with this work for additional information
  39233. * regarding copyright ownership. The ASF licenses this file
  39234. * to you under the Apache License, Version 2.0 (the
  39235. * "License"); you may not use this file except in compliance
  39236. * with the License. You may obtain a copy of the License at
  39237. *
  39238. * http://www.apache.org/licenses/LICENSE-2.0
  39239. *
  39240. * Unless required by applicable law or agreed to in writing,
  39241. * software distributed under the License is distributed on an
  39242. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39243. * KIND, either express or implied. See the License for the
  39244. * specific language governing permissions and limitations
  39245. * under the License.
  39246. */
  39247. // Pick color from palette for each data item.
  39248. // Applicable for charts that require applying color palette
  39249. // in data level (like pie, funnel, chord).
  39250. var dataColor = function (seriesType) {
  39251. return {
  39252. getTargetSeries: function (ecModel) {
  39253. // Pie and funnel may use diferrent scope
  39254. var paletteScope = {};
  39255. var seiresModelMap = createHashMap();
  39256. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39257. seriesModel.__paletteScope = paletteScope;
  39258. seiresModelMap.set(seriesModel.uid, seriesModel);
  39259. });
  39260. return seiresModelMap;
  39261. },
  39262. reset: function (seriesModel, ecModel) {
  39263. var dataAll = seriesModel.getRawData();
  39264. var idxMap = {};
  39265. var data = seriesModel.getData();
  39266. data.each(function (idx) {
  39267. var rawIdx = data.getRawIndex(idx);
  39268. idxMap[rawIdx] = idx;
  39269. });
  39270. dataAll.each(function (rawIdx) {
  39271. var filteredIdx = idxMap[rawIdx];
  39272. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  39273. var singleDataColor = filteredIdx != null
  39274. && data.getItemVisual(filteredIdx, 'color', true);
  39275. var singleDataBorderColor = filteredIdx != null
  39276. && data.getItemVisual(filteredIdx, 'borderColor', true);
  39277. var itemModel;
  39278. if (!singleDataColor || !singleDataBorderColor) {
  39279. // FIXME Performance
  39280. itemModel = dataAll.getItemModel(rawIdx);
  39281. }
  39282. if (!singleDataColor) {
  39283. var color = itemModel.get('itemStyle.color')
  39284. || seriesModel.getColorFromPalette(
  39285. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  39286. dataAll.count()
  39287. );
  39288. // Data is not filtered
  39289. if (filteredIdx != null) {
  39290. data.setItemVisual(filteredIdx, 'color', color);
  39291. }
  39292. }
  39293. if (!singleDataBorderColor) {
  39294. var borderColor = itemModel.get('itemStyle.borderColor');
  39295. // Data is not filtered
  39296. if (filteredIdx != null) {
  39297. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  39298. }
  39299. }
  39300. });
  39301. }
  39302. };
  39303. };
  39304. /*
  39305. * Licensed to the Apache Software Foundation (ASF) under one
  39306. * or more contributor license agreements. See the NOTICE file
  39307. * distributed with this work for additional information
  39308. * regarding copyright ownership. The ASF licenses this file
  39309. * to you under the Apache License, Version 2.0 (the
  39310. * "License"); you may not use this file except in compliance
  39311. * with the License. You may obtain a copy of the License at
  39312. *
  39313. * http://www.apache.org/licenses/LICENSE-2.0
  39314. *
  39315. * Unless required by applicable law or agreed to in writing,
  39316. * software distributed under the License is distributed on an
  39317. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39318. * KIND, either express or implied. See the License for the
  39319. * specific language governing permissions and limitations
  39320. * under the License.
  39321. */
  39322. // FIXME emphasis label position is not same with normal label position
  39323. var RADIAN$1 = Math.PI / 180;
  39324. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  39325. list.sort(function (a, b) {
  39326. return a.y - b.y;
  39327. });
  39328. function shiftDown(start, end, delta, dir) {
  39329. for (var j = start; j < end; j++) {
  39330. if (list[j].y + delta > viewTop + viewHeight) {
  39331. break;
  39332. }
  39333. list[j].y += delta;
  39334. if (j > start
  39335. && j + 1 < end
  39336. && list[j + 1].y > list[j].y + list[j].height
  39337. ) {
  39338. shiftUp(j, delta / 2);
  39339. return;
  39340. }
  39341. }
  39342. shiftUp(end - 1, delta / 2);
  39343. }
  39344. function shiftUp(end, delta) {
  39345. for (var j = end; j >= 0; j--) {
  39346. if (list[j].y - delta < viewTop) {
  39347. break;
  39348. }
  39349. list[j].y -= delta;
  39350. if (j > 0
  39351. && list[j].y > list[j - 1].y + list[j - 1].height
  39352. ) {
  39353. break;
  39354. }
  39355. }
  39356. }
  39357. function changeX(list, isDownList, cx, cy, r, dir) {
  39358. var lastDeltaX = dir > 0
  39359. ? isDownList // right-side
  39360. ? Number.MAX_VALUE // down
  39361. : 0 // up
  39362. : isDownList // left-side
  39363. ? Number.MAX_VALUE // down
  39364. : 0; // up
  39365. for (var i = 0, l = list.length; i < l; i++) {
  39366. if (list[i].labelAlignTo !== 'none') {
  39367. continue;
  39368. }
  39369. var deltaY = Math.abs(list[i].y - cy);
  39370. var length = list[i].len;
  39371. var length2 = list[i].len2;
  39372. var deltaX = (deltaY < r + length)
  39373. ? Math.sqrt(
  39374. (r + length + length2) * (r + length + length2)
  39375. - deltaY * deltaY
  39376. )
  39377. : Math.abs(list[i].x - cx);
  39378. if (isDownList && deltaX >= lastDeltaX) {
  39379. // right-down, left-down
  39380. deltaX = lastDeltaX - 10;
  39381. }
  39382. if (!isDownList && deltaX <= lastDeltaX) {
  39383. // right-up, left-up
  39384. deltaX = lastDeltaX + 10;
  39385. }
  39386. list[i].x = cx + deltaX * dir;
  39387. lastDeltaX = deltaX;
  39388. }
  39389. }
  39390. var lastY = 0;
  39391. var delta;
  39392. var len = list.length;
  39393. var upList = [];
  39394. var downList = [];
  39395. for (var i = 0; i < len; i++) {
  39396. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  39397. var dx = list[i].x - farthestX;
  39398. list[i].linePoints[1][0] += dx;
  39399. list[i].x = farthestX;
  39400. }
  39401. delta = list[i].y - lastY;
  39402. if (delta < 0) {
  39403. shiftDown(i, len, -delta, dir);
  39404. }
  39405. lastY = list[i].y + list[i].height;
  39406. }
  39407. if (viewHeight - lastY < 0) {
  39408. shiftUp(len - 1, lastY - viewHeight);
  39409. }
  39410. for (var i = 0; i < len; i++) {
  39411. if (list[i].y >= cy) {
  39412. downList.push(list[i]);
  39413. }
  39414. else {
  39415. upList.push(list[i]);
  39416. }
  39417. }
  39418. changeX(upList, false, cx, cy, r, dir);
  39419. changeX(downList, true, cx, cy, r, dir);
  39420. }
  39421. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39422. var leftList = [];
  39423. var rightList = [];
  39424. var leftmostX = Number.MAX_VALUE;
  39425. var rightmostX = -Number.MAX_VALUE;
  39426. for (var i = 0; i < labelLayoutList.length; i++) {
  39427. if (isPositionCenter(labelLayoutList[i])) {
  39428. continue;
  39429. }
  39430. if (labelLayoutList[i].x < cx) {
  39431. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  39432. leftList.push(labelLayoutList[i]);
  39433. }
  39434. else {
  39435. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  39436. rightList.push(labelLayoutList[i]);
  39437. }
  39438. }
  39439. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  39440. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  39441. for (var i = 0; i < labelLayoutList.length; i++) {
  39442. var layout = labelLayoutList[i];
  39443. if (isPositionCenter(layout)) {
  39444. continue;
  39445. }
  39446. var linePoints = layout.linePoints;
  39447. if (linePoints) {
  39448. var isAlignToEdge = layout.labelAlignTo === 'edge';
  39449. var realTextWidth = layout.textRect.width;
  39450. var targetTextWidth;
  39451. if (isAlignToEdge) {
  39452. if (layout.x < cx) {
  39453. targetTextWidth = linePoints[2][0] - layout.labelDistance
  39454. - viewLeft - layout.labelMargin;
  39455. }
  39456. else {
  39457. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  39458. - linePoints[2][0] - layout.labelDistance;
  39459. }
  39460. }
  39461. else {
  39462. if (layout.x < cx) {
  39463. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  39464. }
  39465. else {
  39466. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  39467. }
  39468. }
  39469. if (targetTextWidth < layout.textRect.width) {
  39470. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  39471. if (layout.labelAlignTo === 'edge') {
  39472. realTextWidth = getWidth(layout.text, layout.font);
  39473. }
  39474. }
  39475. var dist = linePoints[1][0] - linePoints[2][0];
  39476. if (isAlignToEdge) {
  39477. if (layout.x < cx) {
  39478. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  39479. }
  39480. else {
  39481. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  39482. - realTextWidth - layout.labelDistance;
  39483. }
  39484. }
  39485. else {
  39486. if (layout.x < cx) {
  39487. linePoints[2][0] = layout.x + layout.labelDistance;
  39488. }
  39489. else {
  39490. linePoints[2][0] = layout.x - layout.labelDistance;
  39491. }
  39492. linePoints[1][0] = linePoints[2][0] + dist;
  39493. }
  39494. linePoints[1][1] = linePoints[2][1] = layout.y;
  39495. }
  39496. }
  39497. }
  39498. function isPositionCenter(layout) {
  39499. // Not change x for center label
  39500. return layout.position === 'center';
  39501. }
  39502. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39503. var data = seriesModel.getData();
  39504. var labelLayoutList = [];
  39505. var cx;
  39506. var cy;
  39507. var hasLabelRotate = false;
  39508. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  39509. data.each(function (idx) {
  39510. var layout = data.getItemLayout(idx);
  39511. var itemModel = data.getItemModel(idx);
  39512. var labelModel = itemModel.getModel('label');
  39513. // Use position in normal or emphasis
  39514. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  39515. var labelDistance = labelModel.get('distanceToLabelLine');
  39516. var labelAlignTo = labelModel.get('alignTo');
  39517. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  39518. var bleedMargin = labelModel.get('bleedMargin');
  39519. var font = labelModel.getFont();
  39520. var labelLineModel = itemModel.getModel('labelLine');
  39521. var labelLineLen = labelLineModel.get('length');
  39522. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  39523. var labelLineLen2 = labelLineModel.get('length2');
  39524. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  39525. if (layout.angle < minShowLabelRadian) {
  39526. return;
  39527. }
  39528. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  39529. var dx = Math.cos(midAngle);
  39530. var dy = Math.sin(midAngle);
  39531. var textX;
  39532. var textY;
  39533. var linePoints;
  39534. var textAlign;
  39535. cx = layout.cx;
  39536. cy = layout.cy;
  39537. var text = seriesModel.getFormattedLabel(idx, 'normal')
  39538. || data.getName(idx);
  39539. var textRect = getBoundingRect(
  39540. text, font, textAlign, 'top'
  39541. );
  39542. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  39543. if (labelPosition === 'center') {
  39544. textX = layout.cx;
  39545. textY = layout.cy;
  39546. textAlign = 'center';
  39547. }
  39548. else {
  39549. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  39550. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  39551. textX = x1 + dx * 3;
  39552. textY = y1 + dy * 3;
  39553. if (!isLabelInside) {
  39554. // For roseType
  39555. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  39556. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  39557. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  39558. var y3 = y2;
  39559. if (labelAlignTo === 'edge') {
  39560. // Adjust textX because text align of edge is opposite
  39561. textX = dx < 0
  39562. ? viewLeft + labelMargin
  39563. : viewLeft + viewWidth - labelMargin;
  39564. }
  39565. else {
  39566. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  39567. }
  39568. textY = y3;
  39569. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  39570. }
  39571. textAlign = isLabelInside
  39572. ? 'center'
  39573. : (labelAlignTo === 'edge'
  39574. ? (dx > 0 ? 'right' : 'left')
  39575. : (dx > 0 ? 'left' : 'right'));
  39576. }
  39577. var labelRotate;
  39578. var rotate = labelModel.get('rotate');
  39579. if (typeof rotate === 'number') {
  39580. labelRotate = rotate * (Math.PI / 180);
  39581. }
  39582. else {
  39583. labelRotate = rotate
  39584. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  39585. : 0;
  39586. }
  39587. hasLabelRotate = !!labelRotate;
  39588. layout.label = {
  39589. x: textX,
  39590. y: textY,
  39591. position: labelPosition,
  39592. height: textRect.height,
  39593. len: labelLineLen,
  39594. len2: labelLineLen2,
  39595. linePoints: linePoints,
  39596. textAlign: textAlign,
  39597. verticalAlign: 'middle',
  39598. rotation: labelRotate,
  39599. inside: isLabelInside,
  39600. labelDistance: labelDistance,
  39601. labelAlignTo: labelAlignTo,
  39602. labelMargin: labelMargin,
  39603. bleedMargin: bleedMargin,
  39604. textRect: textRect,
  39605. text: text,
  39606. font: font
  39607. };
  39608. // Not layout the inside label
  39609. if (!isLabelInside) {
  39610. labelLayoutList.push(layout.label);
  39611. }
  39612. });
  39613. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  39614. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  39615. }
  39616. };
  39617. /*
  39618. * Licensed to the Apache Software Foundation (ASF) under one
  39619. * or more contributor license agreements. See the NOTICE file
  39620. * distributed with this work for additional information
  39621. * regarding copyright ownership. The ASF licenses this file
  39622. * to you under the Apache License, Version 2.0 (the
  39623. * "License"); you may not use this file except in compliance
  39624. * with the License. You may obtain a copy of the License at
  39625. *
  39626. * http://www.apache.org/licenses/LICENSE-2.0
  39627. *
  39628. * Unless required by applicable law or agreed to in writing,
  39629. * software distributed under the License is distributed on an
  39630. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39631. * KIND, either express or implied. See the License for the
  39632. * specific language governing permissions and limitations
  39633. * under the License.
  39634. */
  39635. var PI2$4 = Math.PI * 2;
  39636. var RADIAN = Math.PI / 180;
  39637. function getViewRect(seriesModel, api) {
  39638. return getLayoutRect(
  39639. seriesModel.getBoxLayoutParams(), {
  39640. width: api.getWidth(),
  39641. height: api.getHeight()
  39642. }
  39643. );
  39644. }
  39645. var pieLayout = function (seriesType, ecModel, api, payload) {
  39646. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39647. var data = seriesModel.getData();
  39648. var valueDim = data.mapDimension('value');
  39649. var viewRect = getViewRect(seriesModel, api);
  39650. var center = seriesModel.get('center');
  39651. var radius = seriesModel.get('radius');
  39652. if (!isArray(radius)) {
  39653. radius = [0, radius];
  39654. }
  39655. if (!isArray(center)) {
  39656. center = [center, center];
  39657. }
  39658. var width = parsePercent$1(viewRect.width, api.getWidth());
  39659. var height = parsePercent$1(viewRect.height, api.getHeight());
  39660. var size = Math.min(width, height);
  39661. var cx = parsePercent$1(center[0], width) + viewRect.x;
  39662. var cy = parsePercent$1(center[1], height) + viewRect.y;
  39663. var r0 = parsePercent$1(radius[0], size / 2);
  39664. var r = parsePercent$1(radius[1], size / 2);
  39665. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  39666. var minAngle = seriesModel.get('minAngle') * RADIAN;
  39667. var validDataCount = 0;
  39668. data.each(valueDim, function (value) {
  39669. !isNaN(value) && validDataCount++;
  39670. });
  39671. var sum = data.getSum(valueDim);
  39672. // Sum may be 0
  39673. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  39674. var clockwise = seriesModel.get('clockwise');
  39675. var roseType = seriesModel.get('roseType');
  39676. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  39677. // [0...max]
  39678. var extent = data.getDataExtent(valueDim);
  39679. extent[0] = 0;
  39680. // In the case some sector angle is smaller than minAngle
  39681. var restAngle = PI2$4;
  39682. var valueSumLargerThanMinAngle = 0;
  39683. var currentAngle = startAngle;
  39684. var dir = clockwise ? 1 : -1;
  39685. data.each(valueDim, function (value, idx) {
  39686. var angle;
  39687. if (isNaN(value)) {
  39688. data.setItemLayout(idx, {
  39689. angle: NaN,
  39690. startAngle: NaN,
  39691. endAngle: NaN,
  39692. clockwise: clockwise,
  39693. cx: cx,
  39694. cy: cy,
  39695. r0: r0,
  39696. r: roseType
  39697. ? NaN
  39698. : r,
  39699. viewRect: viewRect
  39700. });
  39701. return;
  39702. }
  39703. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  39704. if (roseType !== 'area') {
  39705. angle = (sum === 0 && stillShowZeroSum)
  39706. ? unitRadian : (value * unitRadian);
  39707. }
  39708. else {
  39709. angle = PI2$4 / validDataCount;
  39710. }
  39711. if (angle < minAngle) {
  39712. angle = minAngle;
  39713. restAngle -= minAngle;
  39714. }
  39715. else {
  39716. valueSumLargerThanMinAngle += value;
  39717. }
  39718. var endAngle = currentAngle + dir * angle;
  39719. data.setItemLayout(idx, {
  39720. angle: angle,
  39721. startAngle: currentAngle,
  39722. endAngle: endAngle,
  39723. clockwise: clockwise,
  39724. cx: cx,
  39725. cy: cy,
  39726. r0: r0,
  39727. r: roseType
  39728. ? linearMap(value, extent, [r0, r])
  39729. : r,
  39730. viewRect: viewRect
  39731. });
  39732. currentAngle = endAngle;
  39733. });
  39734. // Some sector is constrained by minAngle
  39735. // Rest sectors needs recalculate angle
  39736. if (restAngle < PI2$4 && validDataCount) {
  39737. // Average the angle if rest angle is not enough after all angles is
  39738. // Constrained by minAngle
  39739. if (restAngle <= 1e-3) {
  39740. var angle = PI2$4 / validDataCount;
  39741. data.each(valueDim, function (value, idx) {
  39742. if (!isNaN(value)) {
  39743. var layout = data.getItemLayout(idx);
  39744. layout.angle = angle;
  39745. layout.startAngle = startAngle + dir * idx * angle;
  39746. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  39747. }
  39748. });
  39749. }
  39750. else {
  39751. unitRadian = restAngle / valueSumLargerThanMinAngle;
  39752. currentAngle = startAngle;
  39753. data.each(valueDim, function (value, idx) {
  39754. if (!isNaN(value)) {
  39755. var layout = data.getItemLayout(idx);
  39756. var angle = layout.angle === minAngle
  39757. ? minAngle : value * unitRadian;
  39758. layout.startAngle = currentAngle;
  39759. layout.endAngle = currentAngle + dir * angle;
  39760. currentAngle += dir * angle;
  39761. }
  39762. });
  39763. }
  39764. }
  39765. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  39766. });
  39767. };
  39768. /*
  39769. * Licensed to the Apache Software Foundation (ASF) under one
  39770. * or more contributor license agreements. See the NOTICE file
  39771. * distributed with this work for additional information
  39772. * regarding copyright ownership. The ASF licenses this file
  39773. * to you under the Apache License, Version 2.0 (the
  39774. * "License"); you may not use this file except in compliance
  39775. * with the License. You may obtain a copy of the License at
  39776. *
  39777. * http://www.apache.org/licenses/LICENSE-2.0
  39778. *
  39779. * Unless required by applicable law or agreed to in writing,
  39780. * software distributed under the License is distributed on an
  39781. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39782. * KIND, either express or implied. See the License for the
  39783. * specific language governing permissions and limitations
  39784. * under the License.
  39785. */
  39786. var dataFilter = function (seriesType) {
  39787. return {
  39788. seriesType: seriesType,
  39789. reset: function (seriesModel, ecModel) {
  39790. var legendModels = ecModel.findComponents({
  39791. mainType: 'legend'
  39792. });
  39793. if (!legendModels || !legendModels.length) {
  39794. return;
  39795. }
  39796. var data = seriesModel.getData();
  39797. data.filterSelf(function (idx) {
  39798. var name = data.getName(idx);
  39799. // If in any legend component the status is not selected.
  39800. for (var i = 0; i < legendModels.length; i++) {
  39801. if (!legendModels[i].isSelected(name)) {
  39802. return false;
  39803. }
  39804. }
  39805. return true;
  39806. });
  39807. }
  39808. };
  39809. };
  39810. /*
  39811. * Licensed to the Apache Software Foundation (ASF) under one
  39812. * or more contributor license agreements. See the NOTICE file
  39813. * distributed with this work for additional information
  39814. * regarding copyright ownership. The ASF licenses this file
  39815. * to you under the Apache License, Version 2.0 (the
  39816. * "License"); you may not use this file except in compliance
  39817. * with the License. You may obtain a copy of the License at
  39818. *
  39819. * http://www.apache.org/licenses/LICENSE-2.0
  39820. *
  39821. * Unless required by applicable law or agreed to in writing,
  39822. * software distributed under the License is distributed on an
  39823. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39824. * KIND, either express or implied. See the License for the
  39825. * specific language governing permissions and limitations
  39826. * under the License.
  39827. */
  39828. createDataSelectAction('pie', [{
  39829. type: 'pieToggleSelect',
  39830. event: 'pieselectchanged',
  39831. method: 'toggleSelected'
  39832. }, {
  39833. type: 'pieSelect',
  39834. event: 'pieselected',
  39835. method: 'select'
  39836. }, {
  39837. type: 'pieUnSelect',
  39838. event: 'pieunselected',
  39839. method: 'unSelect'
  39840. }]);
  39841. registerVisual(dataColor('pie'));
  39842. registerLayout(curry(pieLayout, 'pie'));
  39843. registerProcessor(dataFilter('pie'));
  39844. /*
  39845. * Licensed to the Apache Software Foundation (ASF) under one
  39846. * or more contributor license agreements. See the NOTICE file
  39847. * distributed with this work for additional information
  39848. * regarding copyright ownership. The ASF licenses this file
  39849. * to you under the Apache License, Version 2.0 (the
  39850. * "License"); you may not use this file except in compliance
  39851. * with the License. You may obtain a copy of the License at
  39852. *
  39853. * http://www.apache.org/licenses/LICENSE-2.0
  39854. *
  39855. * Unless required by applicable law or agreed to in writing,
  39856. * software distributed under the License is distributed on an
  39857. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39858. * KIND, either express or implied. See the License for the
  39859. * specific language governing permissions and limitations
  39860. * under the License.
  39861. */
  39862. SeriesModel.extend({
  39863. type: 'series.scatter',
  39864. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  39865. getInitialData: function (option, ecModel) {
  39866. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  39867. },
  39868. brushSelector: 'point',
  39869. getProgressive: function () {
  39870. var progressive = this.option.progressive;
  39871. if (progressive == null) {
  39872. // PENDING
  39873. return this.option.large ? 5e3 : this.get('progressive');
  39874. }
  39875. return progressive;
  39876. },
  39877. getProgressiveThreshold: function () {
  39878. var progressiveThreshold = this.option.progressiveThreshold;
  39879. if (progressiveThreshold == null) {
  39880. // PENDING
  39881. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  39882. }
  39883. return progressiveThreshold;
  39884. },
  39885. defaultOption: {
  39886. coordinateSystem: 'cartesian2d',
  39887. zlevel: 0,
  39888. z: 2,
  39889. legendHoverLink: true,
  39890. hoverAnimation: true,
  39891. // Cartesian coordinate system
  39892. // xAxisIndex: 0,
  39893. // yAxisIndex: 0,
  39894. // Polar coordinate system
  39895. // polarIndex: 0,
  39896. // Geo coordinate system
  39897. // geoIndex: 0,
  39898. // symbol: null, // 图形类型
  39899. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  39900. // symbolRotate: null, // 图形旋转控制
  39901. large: false,
  39902. // Available when large is true
  39903. largeThreshold: 2000,
  39904. // cursor: null,
  39905. // label: {
  39906. // show: false
  39907. // distance: 5,
  39908. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  39909. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  39910. // 'inside'|'left'|'right'|'top'|'bottom'
  39911. // 默认使用全局文本样式,详见TEXTSTYLE
  39912. // },
  39913. itemStyle: {
  39914. opacity: 0.8
  39915. // color: 各异
  39916. },
  39917. // If clip the overflow graphics
  39918. // Works on cartesian / polar series
  39919. clip: true
  39920. // progressive: null
  39921. }
  39922. });
  39923. /*
  39924. * Licensed to the Apache Software Foundation (ASF) under one
  39925. * or more contributor license agreements. See the NOTICE file
  39926. * distributed with this work for additional information
  39927. * regarding copyright ownership. The ASF licenses this file
  39928. * to you under the Apache License, Version 2.0 (the
  39929. * "License"); you may not use this file except in compliance
  39930. * with the License. You may obtain a copy of the License at
  39931. *
  39932. * http://www.apache.org/licenses/LICENSE-2.0
  39933. *
  39934. * Unless required by applicable law or agreed to in writing,
  39935. * software distributed under the License is distributed on an
  39936. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39937. * KIND, either express or implied. See the License for the
  39938. * specific language governing permissions and limitations
  39939. * under the License.
  39940. */
  39941. /* global Float32Array */
  39942. // TODO Batch by color
  39943. var BOOST_SIZE_THRESHOLD = 4;
  39944. var LargeSymbolPath = extendShape({
  39945. shape: {
  39946. points: null
  39947. },
  39948. symbolProxy: null,
  39949. softClipShape: null,
  39950. buildPath: function (path, shape) {
  39951. var points = shape.points;
  39952. var size = shape.size;
  39953. var symbolProxy = this.symbolProxy;
  39954. var symbolProxyShape = symbolProxy.shape;
  39955. var ctx = path.getContext ? path.getContext() : path;
  39956. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  39957. // Do draw in afterBrush.
  39958. if (canBoost) {
  39959. return;
  39960. }
  39961. for (var i = 0; i < points.length;) {
  39962. var x = points[i++];
  39963. var y = points[i++];
  39964. if (isNaN(x) || isNaN(y)) {
  39965. continue;
  39966. }
  39967. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39968. continue;
  39969. }
  39970. symbolProxyShape.x = x - size[0] / 2;
  39971. symbolProxyShape.y = y - size[1] / 2;
  39972. symbolProxyShape.width = size[0];
  39973. symbolProxyShape.height = size[1];
  39974. symbolProxy.buildPath(path, symbolProxyShape, true);
  39975. }
  39976. },
  39977. afterBrush: function (ctx) {
  39978. var shape = this.shape;
  39979. var points = shape.points;
  39980. var size = shape.size;
  39981. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  39982. if (!canBoost) {
  39983. return;
  39984. }
  39985. this.setTransform(ctx);
  39986. // PENDING If style or other canvas status changed?
  39987. for (var i = 0; i < points.length;) {
  39988. var x = points[i++];
  39989. var y = points[i++];
  39990. if (isNaN(x) || isNaN(y)) {
  39991. continue;
  39992. }
  39993. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39994. continue;
  39995. }
  39996. // fillRect is faster than building a rect path and draw.
  39997. // And it support light globalCompositeOperation.
  39998. ctx.fillRect(
  39999. x - size[0] / 2, y - size[1] / 2,
  40000. size[0], size[1]
  40001. );
  40002. }
  40003. this.restoreTransform(ctx);
  40004. },
  40005. findDataIndex: function (x, y) {
  40006. // TODO ???
  40007. // Consider transform
  40008. var shape = this.shape;
  40009. var points = shape.points;
  40010. var size = shape.size;
  40011. var w = Math.max(size[0], 4);
  40012. var h = Math.max(size[1], 4);
  40013. // Not consider transform
  40014. // Treat each element as a rect
  40015. // top down traverse
  40016. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  40017. var i = idx * 2;
  40018. var x0 = points[i] - w / 2;
  40019. var y0 = points[i + 1] - h / 2;
  40020. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  40021. return idx;
  40022. }
  40023. }
  40024. return -1;
  40025. }
  40026. });
  40027. function LargeSymbolDraw() {
  40028. this.group = new Group();
  40029. }
  40030. var largeSymbolProto = LargeSymbolDraw.prototype;
  40031. largeSymbolProto.isPersistent = function () {
  40032. return !this._incremental;
  40033. };
  40034. /**
  40035. * Update symbols draw by new data
  40036. * @param {module:echarts/data/List} data
  40037. * @param {Object} opt
  40038. * @param {Object} [opt.clipShape]
  40039. */
  40040. largeSymbolProto.updateData = function (data, opt) {
  40041. this.group.removeAll();
  40042. var symbolEl = new LargeSymbolPath({
  40043. rectHover: true,
  40044. cursor: 'default'
  40045. });
  40046. symbolEl.setShape({
  40047. points: data.getLayout('symbolPoints')
  40048. });
  40049. this._setCommon(symbolEl, data, false, opt);
  40050. this.group.add(symbolEl);
  40051. this._incremental = null;
  40052. };
  40053. largeSymbolProto.updateLayout = function (data) {
  40054. if (this._incremental) {
  40055. return;
  40056. }
  40057. var points = data.getLayout('symbolPoints');
  40058. this.group.eachChild(function (child) {
  40059. if (child.startIndex != null) {
  40060. var len = (child.endIndex - child.startIndex) * 2;
  40061. var byteOffset = child.startIndex * 4 * 2;
  40062. points = new Float32Array(points.buffer, byteOffset, len);
  40063. }
  40064. child.setShape('points', points);
  40065. });
  40066. };
  40067. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  40068. this.group.removeAll();
  40069. this._clearIncremental();
  40070. // Only use incremental displayables when data amount is larger than 2 million.
  40071. // PENDING Incremental data?
  40072. if (data.count() > 2e6) {
  40073. if (!this._incremental) {
  40074. this._incremental = new IncrementalDisplayble({
  40075. silent: true
  40076. });
  40077. }
  40078. this.group.add(this._incremental);
  40079. }
  40080. else {
  40081. this._incremental = null;
  40082. }
  40083. };
  40084. largeSymbolProto.incrementalUpdate = function (taskParams, data, opt) {
  40085. var symbolEl;
  40086. if (this._incremental) {
  40087. symbolEl = new LargeSymbolPath();
  40088. this._incremental.addDisplayable(symbolEl, true);
  40089. }
  40090. else {
  40091. symbolEl = new LargeSymbolPath({
  40092. rectHover: true,
  40093. cursor: 'default',
  40094. startIndex: taskParams.start,
  40095. endIndex: taskParams.end
  40096. });
  40097. symbolEl.incremental = true;
  40098. this.group.add(symbolEl);
  40099. }
  40100. symbolEl.setShape({
  40101. points: data.getLayout('symbolPoints')
  40102. });
  40103. this._setCommon(symbolEl, data, !!this._incremental, opt);
  40104. };
  40105. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental, opt) {
  40106. var hostModel = data.hostModel;
  40107. opt = opt || {};
  40108. // TODO
  40109. // if (data.hasItemVisual.symbolSize) {
  40110. // // TODO typed array?
  40111. // symbolEl.setShape('sizes', data.mapArray(
  40112. // function (idx) {
  40113. // var size = data.getItemVisual(idx, 'symbolSize');
  40114. // return (size instanceof Array) ? size : [size, size];
  40115. // }
  40116. // ));
  40117. // }
  40118. // else {
  40119. var size = data.getVisual('symbolSize');
  40120. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  40121. // }
  40122. symbolEl.softClipShape = opt.clipShape || null;
  40123. // Create symbolProxy to build path for each data
  40124. symbolEl.symbolProxy = createSymbol(
  40125. data.getVisual('symbol'), 0, 0, 0, 0
  40126. );
  40127. // Use symbolProxy setColor method
  40128. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  40129. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  40130. symbolEl.useStyle(
  40131. // Draw shadow when doing fillRect is extremely slow.
  40132. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  40133. );
  40134. var visualColor = data.getVisual('color');
  40135. if (visualColor) {
  40136. symbolEl.setColor(visualColor);
  40137. }
  40138. if (!isIncremental) {
  40139. // Enable tooltip
  40140. // PENDING May have performance issue when path is extremely large
  40141. symbolEl.seriesIndex = hostModel.seriesIndex;
  40142. symbolEl.on('mousemove', function (e) {
  40143. symbolEl.dataIndex = null;
  40144. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  40145. if (dataIndex >= 0) {
  40146. // Provide dataIndex for tooltip
  40147. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  40148. }
  40149. });
  40150. }
  40151. };
  40152. largeSymbolProto.remove = function () {
  40153. this._clearIncremental();
  40154. this._incremental = null;
  40155. this.group.removeAll();
  40156. };
  40157. largeSymbolProto._clearIncremental = function () {
  40158. var incremental = this._incremental;
  40159. if (incremental) {
  40160. incremental.clearDisplaybles();
  40161. }
  40162. };
  40163. /*
  40164. * Licensed to the Apache Software Foundation (ASF) under one
  40165. * or more contributor license agreements. See the NOTICE file
  40166. * distributed with this work for additional information
  40167. * regarding copyright ownership. The ASF licenses this file
  40168. * to you under the Apache License, Version 2.0 (the
  40169. * "License"); you may not use this file except in compliance
  40170. * with the License. You may obtain a copy of the License at
  40171. *
  40172. * http://www.apache.org/licenses/LICENSE-2.0
  40173. *
  40174. * Unless required by applicable law or agreed to in writing,
  40175. * software distributed under the License is distributed on an
  40176. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40177. * KIND, either express or implied. See the License for the
  40178. * specific language governing permissions and limitations
  40179. * under the License.
  40180. */
  40181. extendChartView({
  40182. type: 'scatter',
  40183. render: function (seriesModel, ecModel, api) {
  40184. var data = seriesModel.getData();
  40185. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40186. symbolDraw.updateData(data, {
  40187. // TODO
  40188. // If this parameter should be a shape or a bounding volume
  40189. // shape will be more general.
  40190. // But bounding volume like bounding rect will be much faster in the contain calculation
  40191. clipShape: this._getClipShape(seriesModel)
  40192. });
  40193. this._finished = true;
  40194. },
  40195. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  40196. var data = seriesModel.getData();
  40197. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40198. symbolDraw.incrementalPrepareUpdate(data);
  40199. this._finished = false;
  40200. },
  40201. incrementalRender: function (taskParams, seriesModel, ecModel) {
  40202. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  40203. clipShape: this._getClipShape(seriesModel)
  40204. });
  40205. this._finished = taskParams.end === seriesModel.getData().count();
  40206. },
  40207. updateTransform: function (seriesModel, ecModel, api) {
  40208. var data = seriesModel.getData();
  40209. // Must mark group dirty and make sure the incremental layer will be cleared
  40210. // PENDING
  40211. this.group.dirty();
  40212. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  40213. return {
  40214. update: true
  40215. };
  40216. }
  40217. else {
  40218. var res = pointsLayout().reset(seriesModel);
  40219. if (res.progress) {
  40220. res.progress({ start: 0, end: data.count() }, data);
  40221. }
  40222. this._symbolDraw.updateLayout(data);
  40223. }
  40224. },
  40225. _getClipShape: function (seriesModel) {
  40226. var coordSys = seriesModel.coordinateSystem;
  40227. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  40228. return seriesModel.get('clip', true) ? clipArea : null;
  40229. },
  40230. _updateSymbolDraw: function (data, seriesModel) {
  40231. var symbolDraw = this._symbolDraw;
  40232. var pipelineContext = seriesModel.pipelineContext;
  40233. var isLargeDraw = pipelineContext.large;
  40234. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  40235. symbolDraw && symbolDraw.remove();
  40236. symbolDraw = this._symbolDraw = isLargeDraw
  40237. ? new LargeSymbolDraw()
  40238. : new SymbolDraw();
  40239. this._isLargeDraw = isLargeDraw;
  40240. this.group.removeAll();
  40241. }
  40242. this.group.add(symbolDraw.group);
  40243. return symbolDraw;
  40244. },
  40245. remove: function (ecModel, api) {
  40246. this._symbolDraw && this._symbolDraw.remove(true);
  40247. this._symbolDraw = null;
  40248. },
  40249. dispose: function () {}
  40250. });
  40251. /*
  40252. * Licensed to the Apache Software Foundation (ASF) under one
  40253. * or more contributor license agreements. See the NOTICE file
  40254. * distributed with this work for additional information
  40255. * regarding copyright ownership. The ASF licenses this file
  40256. * to you under the Apache License, Version 2.0 (the
  40257. * "License"); you may not use this file except in compliance
  40258. * with the License. You may obtain a copy of the License at
  40259. *
  40260. * http://www.apache.org/licenses/LICENSE-2.0
  40261. *
  40262. * Unless required by applicable law or agreed to in writing,
  40263. * software distributed under the License is distributed on an
  40264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40265. * KIND, either express or implied. See the License for the
  40266. * specific language governing permissions and limitations
  40267. * under the License.
  40268. */
  40269. // import * as zrUtil from 'zrender/src/core/util';
  40270. // In case developer forget to include grid component
  40271. registerVisual(visualSymbol('scatter', 'circle'));
  40272. registerLayout(pointsLayout('scatter'));
  40273. // echarts.registerProcessor(function (ecModel, api) {
  40274. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  40275. // var data = seriesModel.getData();
  40276. // var coordSys = seriesModel.coordinateSystem;
  40277. // if (coordSys.type !== 'geo') {
  40278. // return;
  40279. // }
  40280. // var startPt = coordSys.pointToData([0, 0]);
  40281. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  40282. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  40283. // return data.mapDimension(dim);
  40284. // });
  40285. // var range = {};
  40286. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  40287. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  40288. // data.selectRange(range);
  40289. // });
  40290. // });
  40291. /*
  40292. * Licensed to the Apache Software Foundation (ASF) under one
  40293. * or more contributor license agreements. See the NOTICE file
  40294. * distributed with this work for additional information
  40295. * regarding copyright ownership. The ASF licenses this file
  40296. * to you under the Apache License, Version 2.0 (the
  40297. * "License"); you may not use this file except in compliance
  40298. * with the License. You may obtain a copy of the License at
  40299. *
  40300. * http://www.apache.org/licenses/LICENSE-2.0
  40301. *
  40302. * Unless required by applicable law or agreed to in writing,
  40303. * software distributed under the License is distributed on an
  40304. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40305. * KIND, either express or implied. See the License for the
  40306. * specific language governing permissions and limitations
  40307. * under the License.
  40308. */
  40309. var _nonShapeGraphicElements = {
  40310. // Reserved but not supported in graphic component.
  40311. path: null,
  40312. compoundPath: null,
  40313. // Supported in graphic component.
  40314. group: Group,
  40315. image: ZImage,
  40316. text: Text
  40317. };
  40318. // -------------
  40319. // Preprocessor
  40320. // -------------
  40321. registerPreprocessor(function (option) {
  40322. var graphicOption = option.graphic;
  40323. // Convert
  40324. // {graphic: [{left: 10, type: 'circle'}, ...]}
  40325. // or
  40326. // {graphic: {left: 10, type: 'circle'}}
  40327. // to
  40328. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  40329. if (isArray(graphicOption)) {
  40330. if (!graphicOption[0] || !graphicOption[0].elements) {
  40331. option.graphic = [{elements: graphicOption}];
  40332. }
  40333. else {
  40334. // Only one graphic instance can be instantiated. (We dont
  40335. // want that too many views are created in echarts._viewMap)
  40336. option.graphic = [option.graphic[0]];
  40337. }
  40338. }
  40339. else if (graphicOption && !graphicOption.elements) {
  40340. option.graphic = [{elements: [graphicOption]}];
  40341. }
  40342. });
  40343. // ------
  40344. // Model
  40345. // ------
  40346. var GraphicModel = extendComponentModel({
  40347. type: 'graphic',
  40348. defaultOption: {
  40349. // Extra properties for each elements:
  40350. //
  40351. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  40352. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  40353. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  40354. // This mechanism is useful when you want to position a group/element
  40355. // against the right side or the center of this container.
  40356. //
  40357. // width/height: (can only be pixel value, default 0)
  40358. // Only be used to specify contianer(group) size, if needed. And
  40359. // can not be percentage value (like '33%'). See the reason in the
  40360. // layout algorithm below.
  40361. //
  40362. // bounding: (enum: 'all' (default) | 'raw')
  40363. // Specify how to calculate boundingRect when locating.
  40364. // 'all': Get uioned and transformed boundingRect
  40365. // from both itself and its descendants.
  40366. // This mode simplies confining a group of elements in the bounding
  40367. // of their ancester container (e.g., using 'right: 0').
  40368. // 'raw': Only use the boundingRect of itself and before transformed.
  40369. // This mode is similar to css behavior, which is useful when you
  40370. // want an element to be able to overflow its container. (Consider
  40371. // a rotated circle needs to be located in a corner.)
  40372. // info: custom info. enables user to mount some info on elements and use them
  40373. // in event handlers. Update them only when user specified, otherwise, remain.
  40374. // Note: elements is always behind its ancestors in this elements array.
  40375. elements: [],
  40376. parentId: null
  40377. },
  40378. /**
  40379. * Save el options for the sake of the performance (only update modified graphics).
  40380. * The order is the same as those in option. (ancesters -> descendants)
  40381. *
  40382. * @private
  40383. * @type {Array.<Object>}
  40384. */
  40385. _elOptionsToUpdate: null,
  40386. /**
  40387. * @override
  40388. */
  40389. mergeOption: function (option) {
  40390. // Prevent default merge to elements
  40391. var elements = this.option.elements;
  40392. this.option.elements = null;
  40393. GraphicModel.superApply(this, 'mergeOption', arguments);
  40394. this.option.elements = elements;
  40395. },
  40396. /**
  40397. * @override
  40398. */
  40399. optionUpdated: function (newOption, isInit) {
  40400. var thisOption = this.option;
  40401. var newList = (isInit ? thisOption : newOption).elements;
  40402. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  40403. var flattenedList = [];
  40404. this._flatten(newList, flattenedList);
  40405. var mappingResult = mappingToExists(existList, flattenedList);
  40406. makeIdAndName(mappingResult);
  40407. // Clear elOptionsToUpdate
  40408. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  40409. each$1(mappingResult, function (resultItem, index) {
  40410. var newElOption = resultItem.option;
  40411. if (__DEV__) {
  40412. assert$1(
  40413. isObject$1(newElOption) || resultItem.exist,
  40414. 'Empty graphic option definition'
  40415. );
  40416. }
  40417. if (!newElOption) {
  40418. return;
  40419. }
  40420. elOptionsToUpdate.push(newElOption);
  40421. setKeyInfoToNewElOption(resultItem, newElOption);
  40422. mergeNewElOptionToExist(existList, index, newElOption);
  40423. setLayoutInfoToExist(existList[index], newElOption);
  40424. }, this);
  40425. // Clean
  40426. for (var i = existList.length - 1; i >= 0; i--) {
  40427. if (existList[i] == null) {
  40428. existList.splice(i, 1);
  40429. }
  40430. else {
  40431. // $action should be volatile, otherwise option gotten from
  40432. // `getOption` will contain unexpected $action.
  40433. delete existList[i].$action;
  40434. }
  40435. }
  40436. },
  40437. /**
  40438. * Convert
  40439. * [{
  40440. * type: 'group',
  40441. * id: 'xx',
  40442. * children: [{type: 'circle'}, {type: 'polygon'}]
  40443. * }]
  40444. * to
  40445. * [
  40446. * {type: 'group', id: 'xx'},
  40447. * {type: 'circle', parentId: 'xx'},
  40448. * {type: 'polygon', parentId: 'xx'}
  40449. * ]
  40450. *
  40451. * @private
  40452. * @param {Array.<Object>} optionList option list
  40453. * @param {Array.<Object>} result result of flatten
  40454. * @param {Object} parentOption parent option
  40455. */
  40456. _flatten: function (optionList, result, parentOption) {
  40457. each$1(optionList, function (option) {
  40458. if (!option) {
  40459. return;
  40460. }
  40461. if (parentOption) {
  40462. option.parentOption = parentOption;
  40463. }
  40464. result.push(option);
  40465. var children = option.children;
  40466. if (option.type === 'group' && children) {
  40467. this._flatten(children, result, option);
  40468. }
  40469. // Deleting for JSON output, and for not affecting group creation.
  40470. delete option.children;
  40471. }, this);
  40472. },
  40473. // FIXME
  40474. // Pass to view using payload? setOption has a payload?
  40475. useElOptionsToUpdate: function () {
  40476. var els = this._elOptionsToUpdate;
  40477. // Clear to avoid render duplicately when zooming.
  40478. this._elOptionsToUpdate = null;
  40479. return els;
  40480. }
  40481. });
  40482. // -----
  40483. // View
  40484. // -----
  40485. extendComponentView({
  40486. type: 'graphic',
  40487. /**
  40488. * @override
  40489. */
  40490. init: function (ecModel, api) {
  40491. /**
  40492. * @private
  40493. * @type {module:zrender/core/util.HashMap}
  40494. */
  40495. this._elMap = createHashMap();
  40496. /**
  40497. * @private
  40498. * @type {module:echarts/graphic/GraphicModel}
  40499. */
  40500. this._lastGraphicModel;
  40501. },
  40502. /**
  40503. * @override
  40504. */
  40505. render: function (graphicModel, ecModel, api) {
  40506. // Having leveraged between use cases and algorithm complexity, a very
  40507. // simple layout mechanism is used:
  40508. // The size(width/height) can be determined by itself or its parent (not
  40509. // implemented yet), but can not by its children. (Top-down travel)
  40510. // The location(x/y) can be determined by the bounding rect of itself
  40511. // (can including its descendants or not) and the size of its parent.
  40512. // (Bottom-up travel)
  40513. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  40514. // view will be reused.
  40515. if (graphicModel !== this._lastGraphicModel) {
  40516. this._clear();
  40517. }
  40518. this._lastGraphicModel = graphicModel;
  40519. this._updateElements(graphicModel);
  40520. this._relocate(graphicModel, api);
  40521. },
  40522. /**
  40523. * Update graphic elements.
  40524. *
  40525. * @private
  40526. * @param {Object} graphicModel graphic model
  40527. */
  40528. _updateElements: function (graphicModel) {
  40529. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  40530. if (!elOptionsToUpdate) {
  40531. return;
  40532. }
  40533. var elMap = this._elMap;
  40534. var rootGroup = this.group;
  40535. // Top-down tranverse to assign graphic settings to each elements.
  40536. each$1(elOptionsToUpdate, function (elOption) {
  40537. var $action = elOption.$action;
  40538. var id = elOption.id;
  40539. var existEl = elMap.get(id);
  40540. var parentId = elOption.parentId;
  40541. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  40542. var elOptionStyle = elOption.style;
  40543. if (elOption.type === 'text' && elOptionStyle) {
  40544. // In top/bottom mode, textVerticalAlign should not be used, which cause
  40545. // inaccurately locating.
  40546. if (elOption.hv && elOption.hv[1]) {
  40547. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  40548. }
  40549. // Compatible with previous setting: both support fill and textFill,
  40550. // stroke and textStroke.
  40551. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  40552. elOptionStyle.textFill = elOptionStyle.fill
  40553. );
  40554. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  40555. elOptionStyle.textStroke = elOptionStyle.stroke
  40556. );
  40557. }
  40558. // Remove unnecessary props to avoid potential problems.
  40559. var elOptionCleaned = getCleanedElOption(elOption);
  40560. // For simple, do not support parent change, otherwise reorder is needed.
  40561. if (__DEV__) {
  40562. existEl && assert$1(
  40563. targetElParent === existEl.parent,
  40564. 'Changing parent is not supported.'
  40565. );
  40566. }
  40567. if (!$action || $action === 'merge') {
  40568. existEl
  40569. ? existEl.attr(elOptionCleaned)
  40570. : createEl(id, targetElParent, elOptionCleaned, elMap);
  40571. }
  40572. else if ($action === 'replace') {
  40573. removeEl(existEl, elMap);
  40574. createEl(id, targetElParent, elOptionCleaned, elMap);
  40575. }
  40576. else if ($action === 'remove') {
  40577. removeEl(existEl, elMap);
  40578. }
  40579. var el = elMap.get(id);
  40580. if (el) {
  40581. el.__ecGraphicWidthOption = elOption.width;
  40582. el.__ecGraphicHeightOption = elOption.height;
  40583. setEventData(el, graphicModel, elOption);
  40584. }
  40585. });
  40586. },
  40587. /**
  40588. * Locate graphic elements.
  40589. *
  40590. * @private
  40591. * @param {Object} graphicModel graphic model
  40592. * @param {module:echarts/ExtensionAPI} api extension API
  40593. */
  40594. _relocate: function (graphicModel, api) {
  40595. var elOptions = graphicModel.option.elements;
  40596. var rootGroup = this.group;
  40597. var elMap = this._elMap;
  40598. var apiWidth = api.getWidth();
  40599. var apiHeight = api.getHeight();
  40600. // Top-down to calculate percentage width/height of group
  40601. for (var i = 0; i < elOptions.length; i++) {
  40602. var elOption = elOptions[i];
  40603. var el = elMap.get(elOption.id);
  40604. if (!el || !el.isGroup) {
  40605. continue;
  40606. }
  40607. var parentEl = el.parent;
  40608. var isParentRoot = parentEl === rootGroup;
  40609. // Like 'position:absolut' in css, default 0.
  40610. el.__ecGraphicWidth = parsePercent$1(
  40611. el.__ecGraphicWidthOption,
  40612. isParentRoot ? apiWidth : parentEl.__ecGraphicWidth
  40613. ) || 0;
  40614. el.__ecGraphicHeight = parsePercent$1(
  40615. el.__ecGraphicHeightOption,
  40616. isParentRoot ? apiHeight : parentEl.__ecGraphicHeight
  40617. ) || 0;
  40618. }
  40619. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  40620. for (var i = elOptions.length - 1; i >= 0; i--) {
  40621. var elOption = elOptions[i];
  40622. var el = elMap.get(elOption.id);
  40623. if (!el) {
  40624. continue;
  40625. }
  40626. var parentEl = el.parent;
  40627. var containerInfo = parentEl === rootGroup
  40628. ? {
  40629. width: apiWidth,
  40630. height: apiHeight
  40631. }
  40632. : {
  40633. width: parentEl.__ecGraphicWidth,
  40634. height: parentEl.__ecGraphicHeight
  40635. };
  40636. // PENDING
  40637. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  40638. // does not include the rect of [0, 0, group.width, group.height], which
  40639. // is probably weird for users. Should we make a break change for it?
  40640. positionElement(
  40641. el, elOption, containerInfo, null,
  40642. {hv: elOption.hv, boundingMode: elOption.bounding}
  40643. );
  40644. }
  40645. },
  40646. /**
  40647. * Clear all elements.
  40648. *
  40649. * @private
  40650. */
  40651. _clear: function () {
  40652. var elMap = this._elMap;
  40653. elMap.each(function (el) {
  40654. removeEl(el, elMap);
  40655. });
  40656. this._elMap = createHashMap();
  40657. },
  40658. /**
  40659. * @override
  40660. */
  40661. dispose: function () {
  40662. this._clear();
  40663. }
  40664. });
  40665. function createEl(id, targetElParent, elOption, elMap) {
  40666. var graphicType = elOption.type;
  40667. if (__DEV__) {
  40668. assert$1(graphicType, 'graphic type MUST be set');
  40669. }
  40670. var Clz = _nonShapeGraphicElements.hasOwnProperty(graphicType)
  40671. // Those graphic elements are not shapes. They should not be
  40672. // overwritten by users, so do them first.
  40673. ? _nonShapeGraphicElements[graphicType]
  40674. : getShapeClass(graphicType);
  40675. if (__DEV__) {
  40676. assert$1(Clz, 'graphic type can not be found');
  40677. }
  40678. var el = new Clz(elOption);
  40679. targetElParent.add(el);
  40680. elMap.set(id, el);
  40681. el.__ecGraphicId = id;
  40682. }
  40683. function removeEl(existEl, elMap) {
  40684. var existElParent = existEl && existEl.parent;
  40685. if (existElParent) {
  40686. existEl.type === 'group' && existEl.traverse(function (el) {
  40687. removeEl(el, elMap);
  40688. });
  40689. elMap.removeKey(existEl.__ecGraphicId);
  40690. existElParent.remove(existEl);
  40691. }
  40692. }
  40693. // Remove unnecessary props to avoid potential problems.
  40694. function getCleanedElOption(elOption) {
  40695. elOption = extend({}, elOption);
  40696. each$1(
  40697. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  40698. function (name) {
  40699. delete elOption[name];
  40700. }
  40701. );
  40702. return elOption;
  40703. }
  40704. function isSetLoc(obj, props) {
  40705. var isSet;
  40706. each$1(props, function (prop) {
  40707. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  40708. });
  40709. return isSet;
  40710. }
  40711. function setKeyInfoToNewElOption(resultItem, newElOption) {
  40712. var existElOption = resultItem.exist;
  40713. // Set id and type after id assigned.
  40714. newElOption.id = resultItem.keyInfo.id;
  40715. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  40716. // Set parent id if not specified
  40717. if (newElOption.parentId == null) {
  40718. var newElParentOption = newElOption.parentOption;
  40719. if (newElParentOption) {
  40720. newElOption.parentId = newElParentOption.id;
  40721. }
  40722. else if (existElOption) {
  40723. newElOption.parentId = existElOption.parentId;
  40724. }
  40725. }
  40726. // Clear
  40727. newElOption.parentOption = null;
  40728. }
  40729. function mergeNewElOptionToExist(existList, index, newElOption) {
  40730. // Update existing options, for `getOption` feature.
  40731. var newElOptCopy = extend({}, newElOption);
  40732. var existElOption = existList[index];
  40733. var $action = newElOption.$action || 'merge';
  40734. if ($action === 'merge') {
  40735. if (existElOption) {
  40736. if (__DEV__) {
  40737. var newType = newElOption.type;
  40738. assert$1(
  40739. !newType || existElOption.type === newType,
  40740. 'Please set $action: "replace" to change `type`'
  40741. );
  40742. }
  40743. // We can ensure that newElOptCopy and existElOption are not
  40744. // the same object, so `merge` will not change newElOptCopy.
  40745. merge(existElOption, newElOptCopy, true);
  40746. // Rigid body, use ignoreSize.
  40747. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  40748. // Will be used in render.
  40749. copyLayoutParams(newElOption, existElOption);
  40750. }
  40751. else {
  40752. existList[index] = newElOptCopy;
  40753. }
  40754. }
  40755. else if ($action === 'replace') {
  40756. existList[index] = newElOptCopy;
  40757. }
  40758. else if ($action === 'remove') {
  40759. // null will be cleaned later.
  40760. existElOption && (existList[index] = null);
  40761. }
  40762. }
  40763. function setLayoutInfoToExist(existItem, newElOption) {
  40764. if (!existItem) {
  40765. return;
  40766. }
  40767. existItem.hv = newElOption.hv = [
  40768. // Rigid body, dont care `width`.
  40769. isSetLoc(newElOption, ['left', 'right']),
  40770. // Rigid body, dont care `height`.
  40771. isSetLoc(newElOption, ['top', 'bottom'])
  40772. ];
  40773. // Give default group size. Otherwise layout error may occur.
  40774. if (existItem.type === 'group') {
  40775. existItem.width == null && (existItem.width = newElOption.width = 0);
  40776. existItem.height == null && (existItem.height = newElOption.height = 0);
  40777. }
  40778. }
  40779. function setEventData(el, graphicModel, elOption) {
  40780. var eventData = el.eventData;
  40781. // Simple optimize for large amount of elements that no need event.
  40782. if (!el.silent && !el.ignore && !eventData) {
  40783. eventData = el.eventData = {
  40784. componentType: 'graphic',
  40785. componentIndex: graphicModel.componentIndex,
  40786. name: el.name
  40787. };
  40788. }
  40789. // `elOption.info` enables user to mount some info on
  40790. // elements and use them in event handlers.
  40791. if (eventData) {
  40792. eventData.info = el.info;
  40793. }
  40794. }
  40795. /*
  40796. * Licensed to the Apache Software Foundation (ASF) under one
  40797. * or more contributor license agreements. See the NOTICE file
  40798. * distributed with this work for additional information
  40799. * regarding copyright ownership. The ASF licenses this file
  40800. * to you under the Apache License, Version 2.0 (the
  40801. * "License"); you may not use this file except in compliance
  40802. * with the License. You may obtain a copy of the License at
  40803. *
  40804. * http://www.apache.org/licenses/LICENSE-2.0
  40805. *
  40806. * Unless required by applicable law or agreed to in writing,
  40807. * software distributed under the License is distributed on an
  40808. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40809. * KIND, either express or implied. See the License for the
  40810. * specific language governing permissions and limitations
  40811. * under the License.
  40812. */
  40813. /**
  40814. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  40815. * @param {module:echarts/model/Global} ecModel
  40816. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  40817. */
  40818. var findPointFromSeries = function (finder, ecModel) {
  40819. var point = [];
  40820. var seriesIndex = finder.seriesIndex;
  40821. var seriesModel;
  40822. if (seriesIndex == null || !(
  40823. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  40824. )) {
  40825. return {point: []};
  40826. }
  40827. var data = seriesModel.getData();
  40828. var dataIndex = queryDataIndex(data, finder);
  40829. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  40830. return {point: []};
  40831. }
  40832. var el = data.getItemGraphicEl(dataIndex);
  40833. var coordSys = seriesModel.coordinateSystem;
  40834. if (seriesModel.getTooltipPosition) {
  40835. point = seriesModel.getTooltipPosition(dataIndex) || [];
  40836. }
  40837. else if (coordSys && coordSys.dataToPoint) {
  40838. point = coordSys.dataToPoint(
  40839. data.getValues(
  40840. map(coordSys.dimensions, function (dim) {
  40841. return data.mapDimension(dim);
  40842. }), dataIndex, true
  40843. )
  40844. ) || [];
  40845. }
  40846. else if (el) {
  40847. // Use graphic bounding rect
  40848. var rect = el.getBoundingRect().clone();
  40849. rect.applyTransform(el.transform);
  40850. point = [
  40851. rect.x + rect.width / 2,
  40852. rect.y + rect.height / 2
  40853. ];
  40854. }
  40855. return {point: point, el: el};
  40856. };
  40857. /*
  40858. * Licensed to the Apache Software Foundation (ASF) under one
  40859. * or more contributor license agreements. See the NOTICE file
  40860. * distributed with this work for additional information
  40861. * regarding copyright ownership. The ASF licenses this file
  40862. * to you under the Apache License, Version 2.0 (the
  40863. * "License"); you may not use this file except in compliance
  40864. * with the License. You may obtain a copy of the License at
  40865. *
  40866. * http://www.apache.org/licenses/LICENSE-2.0
  40867. *
  40868. * Unless required by applicable law or agreed to in writing,
  40869. * software distributed under the License is distributed on an
  40870. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40871. * KIND, either express or implied. See the License for the
  40872. * specific language governing permissions and limitations
  40873. * under the License.
  40874. */
  40875. var each$7 = each$1;
  40876. var curry$2 = curry;
  40877. var inner$7 = makeInner();
  40878. /**
  40879. * Basic logic: check all axis, if they do not demand show/highlight,
  40880. * then hide/downplay them.
  40881. *
  40882. * @param {Object} coordSysAxesInfo
  40883. * @param {Object} payload
  40884. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  40885. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  40886. * trigger axisPointer and tooltip.
  40887. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  40888. * trigger axisPointer and tooltip.
  40889. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  40890. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  40891. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  40892. * [{
  40893. * axisDim: 'x'|'y'|'angle'|...,
  40894. * axisIndex: ...,
  40895. * value: ...
  40896. * }, ...]
  40897. * @param {Function} [payload.dispatchAction]
  40898. * @param {Object} [payload.tooltipOption]
  40899. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  40900. * which can be specified in dispatchAction
  40901. * @param {module:echarts/model/Global} ecModel
  40902. * @param {module:echarts/ExtensionAPI} api
  40903. * @return {Object} content of event obj for echarts.connect.
  40904. */
  40905. var axisTrigger = function (payload, ecModel, api) {
  40906. var currTrigger = payload.currTrigger;
  40907. var point = [payload.x, payload.y];
  40908. var finder = payload;
  40909. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  40910. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  40911. // Pending
  40912. // See #6121. But we are not able to reproduce it yet.
  40913. if (!coordSysAxesInfo) {
  40914. return;
  40915. }
  40916. if (illegalPoint(point)) {
  40917. // Used in the default behavior of `connection`: use the sample seriesIndex
  40918. // and dataIndex. And also used in the tooltipView trigger.
  40919. point = findPointFromSeries({
  40920. seriesIndex: finder.seriesIndex,
  40921. // Do not use dataIndexInside from other ec instance.
  40922. // FIXME: auto detect it?
  40923. dataIndex: finder.dataIndex
  40924. }, ecModel).point;
  40925. }
  40926. var isIllegalPoint = illegalPoint(point);
  40927. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  40928. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  40929. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  40930. // and dataIndex.
  40931. var inputAxesInfo = finder.axesInfo;
  40932. var axesInfo = coordSysAxesInfo.axesInfo;
  40933. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  40934. var outputFinder = {};
  40935. var showValueMap = {};
  40936. var dataByCoordSys = {list: [], map: {}};
  40937. var updaters = {
  40938. showPointer: curry$2(showPointer, showValueMap),
  40939. showTooltip: curry$2(showTooltip, dataByCoordSys)
  40940. };
  40941. // Process for triggered axes.
  40942. each$7(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  40943. // If a point given, it must be contained by the coordinate system.
  40944. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  40945. each$7(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  40946. var axis = axisInfo.axis;
  40947. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  40948. // If no inputAxesInfo, no axis is restricted.
  40949. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  40950. var val = inputAxisInfo && inputAxisInfo.value;
  40951. if (val == null && !isIllegalPoint) {
  40952. val = axis.pointToData(point);
  40953. }
  40954. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  40955. }
  40956. });
  40957. });
  40958. // Process for linked axes.
  40959. var linkTriggers = {};
  40960. each$7(axesInfo, function (tarAxisInfo, tarKey) {
  40961. var linkGroup = tarAxisInfo.linkGroup;
  40962. // If axis has been triggered in the previous stage, it should not be triggered by link.
  40963. if (linkGroup && !showValueMap[tarKey]) {
  40964. each$7(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  40965. var srcValItem = showValueMap[srcKey];
  40966. // If srcValItem exist, source axis is triggered, so link to target axis.
  40967. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  40968. var val = srcValItem.value;
  40969. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  40970. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  40971. )));
  40972. linkTriggers[tarAxisInfo.key] = val;
  40973. }
  40974. });
  40975. }
  40976. });
  40977. each$7(linkTriggers, function (val, tarKey) {
  40978. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  40979. });
  40980. updateModelActually(showValueMap, axesInfo, outputFinder);
  40981. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  40982. dispatchHighDownActually(axesInfo, dispatchAction, api);
  40983. return outputFinder;
  40984. };
  40985. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  40986. var axis = axisInfo.axis;
  40987. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  40988. return;
  40989. }
  40990. if (!axisInfo.involveSeries) {
  40991. updaters.showPointer(axisInfo, newValue);
  40992. return;
  40993. }
  40994. // Heavy calculation. So put it after axis.containData checking.
  40995. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  40996. var payloadBatch = payloadInfo.payloadBatch;
  40997. var snapToValue = payloadInfo.snapToValue;
  40998. // Fill content of event obj for echarts.connect.
  40999. // By default use the first involved series data as a sample to connect.
  41000. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  41001. extend(outputFinder, payloadBatch[0]);
  41002. }
  41003. // If no linkSource input, this process is for collecting link
  41004. // target, where snap should not be accepted.
  41005. if (!dontSnap && axisInfo.snap) {
  41006. if (axis.containData(snapToValue) && snapToValue != null) {
  41007. newValue = snapToValue;
  41008. }
  41009. }
  41010. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  41011. // Tooltip should always be snapToValue, otherwise there will be
  41012. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  41013. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  41014. }
  41015. function buildPayloadsBySeries(value, axisInfo) {
  41016. var axis = axisInfo.axis;
  41017. var dim = axis.dim;
  41018. var snapToValue = value;
  41019. var payloadBatch = [];
  41020. var minDist = Number.MAX_VALUE;
  41021. var minDiff = -1;
  41022. each$7(axisInfo.seriesModels, function (series, idx) {
  41023. var dataDim = series.getData().mapDimension(dim, true);
  41024. var seriesNestestValue;
  41025. var dataIndices;
  41026. if (series.getAxisTooltipData) {
  41027. var result = series.getAxisTooltipData(dataDim, value, axis);
  41028. dataIndices = result.dataIndices;
  41029. seriesNestestValue = result.nestestValue;
  41030. }
  41031. else {
  41032. dataIndices = series.getData().indicesOfNearest(
  41033. dataDim[0],
  41034. value,
  41035. // Add a threshold to avoid find the wrong dataIndex
  41036. // when data length is not same.
  41037. // false,
  41038. axis.type === 'category' ? 0.5 : null
  41039. );
  41040. if (!dataIndices.length) {
  41041. return;
  41042. }
  41043. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  41044. }
  41045. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  41046. return;
  41047. }
  41048. var diff = value - seriesNestestValue;
  41049. var dist = Math.abs(diff);
  41050. // Consider category case
  41051. if (dist <= minDist) {
  41052. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  41053. minDist = dist;
  41054. minDiff = diff;
  41055. snapToValue = seriesNestestValue;
  41056. payloadBatch.length = 0;
  41057. }
  41058. each$7(dataIndices, function (dataIndex) {
  41059. payloadBatch.push({
  41060. seriesIndex: series.seriesIndex,
  41061. dataIndexInside: dataIndex,
  41062. dataIndex: series.getData().getRawIndex(dataIndex)
  41063. });
  41064. });
  41065. }
  41066. });
  41067. return {
  41068. payloadBatch: payloadBatch,
  41069. snapToValue: snapToValue
  41070. };
  41071. }
  41072. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  41073. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  41074. }
  41075. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  41076. var payloadBatch = payloadInfo.payloadBatch;
  41077. var axis = axisInfo.axis;
  41078. var axisModel = axis.model;
  41079. var axisPointerModel = axisInfo.axisPointerModel;
  41080. // If no data, do not create anything in dataByCoordSys,
  41081. // whose length will be used to judge whether dispatch action.
  41082. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  41083. return;
  41084. }
  41085. var coordSysModel = axisInfo.coordSys.model;
  41086. var coordSysKey = makeKey(coordSysModel);
  41087. var coordSysItem = dataByCoordSys.map[coordSysKey];
  41088. if (!coordSysItem) {
  41089. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  41090. coordSysId: coordSysModel.id,
  41091. coordSysIndex: coordSysModel.componentIndex,
  41092. coordSysType: coordSysModel.type,
  41093. coordSysMainType: coordSysModel.mainType,
  41094. dataByAxis: []
  41095. };
  41096. dataByCoordSys.list.push(coordSysItem);
  41097. }
  41098. coordSysItem.dataByAxis.push({
  41099. axisDim: axis.dim,
  41100. axisIndex: axisModel.componentIndex,
  41101. axisType: axisModel.type,
  41102. axisId: axisModel.id,
  41103. value: value,
  41104. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  41105. // depends that all models have been updated. So it should not be performed
  41106. // here. Considering axisPointerModel used here is volatile, which is hard
  41107. // to be retrieve in TooltipView, we prepare parameters here.
  41108. valueLabelOpt: {
  41109. precision: axisPointerModel.get('label.precision'),
  41110. formatter: axisPointerModel.get('label.formatter')
  41111. },
  41112. seriesDataIndices: payloadBatch.slice()
  41113. });
  41114. }
  41115. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  41116. var outputAxesInfo = outputFinder.axesInfo = [];
  41117. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  41118. each$7(axesInfo, function (axisInfo, key) {
  41119. var option = axisInfo.axisPointerModel.option;
  41120. var valItem = showValueMap[key];
  41121. if (valItem) {
  41122. !axisInfo.useHandle && (option.status = 'show');
  41123. option.value = valItem.value;
  41124. // For label formatter param and highlight.
  41125. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  41126. }
  41127. // When always show (e.g., handle used), remain
  41128. // original value and status.
  41129. else {
  41130. // If hide, value still need to be set, consider
  41131. // click legend to toggle axis blank.
  41132. !axisInfo.useHandle && (option.status = 'hide');
  41133. }
  41134. // If status is 'hide', should be no info in payload.
  41135. option.status === 'show' && outputAxesInfo.push({
  41136. axisDim: axisInfo.axis.dim,
  41137. axisIndex: axisInfo.axis.model.componentIndex,
  41138. value: option.value
  41139. });
  41140. });
  41141. }
  41142. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  41143. // Basic logic: If no showTip required, hideTip will be dispatched.
  41144. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  41145. dispatchAction({type: 'hideTip'});
  41146. return;
  41147. }
  41148. // In most case only one axis (or event one series is used). It is
  41149. // convinient to fetch payload.seriesIndex and payload.dataIndex
  41150. // dirtectly. So put the first seriesIndex and dataIndex of the first
  41151. // axis on the payload.
  41152. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  41153. dispatchAction({
  41154. type: 'showTip',
  41155. escapeConnect: true,
  41156. x: point[0],
  41157. y: point[1],
  41158. tooltipOption: payload.tooltipOption,
  41159. position: payload.position,
  41160. dataIndexInside: sampleItem.dataIndexInside,
  41161. dataIndex: sampleItem.dataIndex,
  41162. seriesIndex: sampleItem.seriesIndex,
  41163. dataByCoordSys: dataByCoordSys.list
  41164. });
  41165. }
  41166. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  41167. // FIXME
  41168. // highlight status modification shoule be a stage of main process?
  41169. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  41170. var zr = api.getZr();
  41171. var highDownKey = 'axisPointerLastHighlights';
  41172. var lastHighlights = inner$7(zr)[highDownKey] || {};
  41173. var newHighlights = inner$7(zr)[highDownKey] = {};
  41174. // Update highlight/downplay status according to axisPointer model.
  41175. // Build hash map and remove duplicate incidentally.
  41176. each$7(axesInfo, function (axisInfo, key) {
  41177. var option = axisInfo.axisPointerModel.option;
  41178. option.status === 'show' && each$7(option.seriesDataIndices, function (batchItem) {
  41179. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  41180. newHighlights[key] = batchItem;
  41181. });
  41182. });
  41183. // Diff.
  41184. var toHighlight = [];
  41185. var toDownplay = [];
  41186. each$1(lastHighlights, function (batchItem, key) {
  41187. !newHighlights[key] && toDownplay.push(batchItem);
  41188. });
  41189. each$1(newHighlights, function (batchItem, key) {
  41190. !lastHighlights[key] && toHighlight.push(batchItem);
  41191. });
  41192. toDownplay.length && api.dispatchAction({
  41193. type: 'downplay', escapeConnect: true, batch: toDownplay
  41194. });
  41195. toHighlight.length && api.dispatchAction({
  41196. type: 'highlight', escapeConnect: true, batch: toHighlight
  41197. });
  41198. }
  41199. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  41200. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  41201. var inputAxisInfo = inputAxesInfo[i];
  41202. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  41203. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  41204. ) {
  41205. return inputAxisInfo;
  41206. }
  41207. }
  41208. }
  41209. function makeMapperParam(axisInfo) {
  41210. var axisModel = axisInfo.axis.model;
  41211. var item = {};
  41212. var dim = item.axisDim = axisInfo.axis.dim;
  41213. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  41214. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  41215. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  41216. return item;
  41217. }
  41218. function illegalPoint(point) {
  41219. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  41220. }
  41221. /*
  41222. * Licensed to the Apache Software Foundation (ASF) under one
  41223. * or more contributor license agreements. See the NOTICE file
  41224. * distributed with this work for additional information
  41225. * regarding copyright ownership. The ASF licenses this file
  41226. * to you under the Apache License, Version 2.0 (the
  41227. * "License"); you may not use this file except in compliance
  41228. * with the License. You may obtain a copy of the License at
  41229. *
  41230. * http://www.apache.org/licenses/LICENSE-2.0
  41231. *
  41232. * Unless required by applicable law or agreed to in writing,
  41233. * software distributed under the License is distributed on an
  41234. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41235. * KIND, either express or implied. See the License for the
  41236. * specific language governing permissions and limitations
  41237. * under the License.
  41238. */
  41239. var AxisPointerModel = extendComponentModel({
  41240. type: 'axisPointer',
  41241. coordSysAxesInfo: null,
  41242. defaultOption: {
  41243. // 'auto' means that show when triggered by tooltip or handle.
  41244. show: 'auto',
  41245. // 'click' | 'mousemove' | 'none'
  41246. triggerOn: null, // set default in AxisPonterView.js
  41247. zlevel: 0,
  41248. z: 50,
  41249. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  41250. // axispointer triggered by tootip determine snap automatically,
  41251. // see `modelHelper`.
  41252. snap: false,
  41253. triggerTooltip: true,
  41254. value: null,
  41255. status: null, // Init value depends on whether handle is used.
  41256. // [group0, group1, ...]
  41257. // Each group can be: {
  41258. // mapper: function () {},
  41259. // singleTooltip: 'multiple', // 'multiple' or 'single'
  41260. // xAxisId: ...,
  41261. // yAxisName: ...,
  41262. // angleAxisIndex: ...
  41263. // }
  41264. // mapper: can be ignored.
  41265. // input: {axisInfo, value}
  41266. // output: {axisInfo, value}
  41267. link: [],
  41268. // Do not set 'auto' here, otherwise global animation: false
  41269. // will not effect at this axispointer.
  41270. animation: null,
  41271. animationDurationUpdate: 200,
  41272. lineStyle: {
  41273. color: '#aaa',
  41274. width: 1,
  41275. type: 'solid'
  41276. },
  41277. shadowStyle: {
  41278. color: 'rgba(150,150,150,0.3)'
  41279. },
  41280. label: {
  41281. show: true,
  41282. formatter: null, // string | Function
  41283. precision: 'auto', // Or a number like 0, 1, 2 ...
  41284. margin: 3,
  41285. color: '#fff',
  41286. padding: [5, 7, 5, 7],
  41287. backgroundColor: 'auto', // default: axis line color
  41288. borderColor: null,
  41289. borderWidth: 0,
  41290. shadowBlur: 3,
  41291. shadowColor: '#aaa'
  41292. // Considering applicability, common style should
  41293. // better not have shadowOffset.
  41294. // shadowOffsetX: 0,
  41295. // shadowOffsetY: 2
  41296. },
  41297. handle: {
  41298. show: false,
  41299. /* eslint-disable */
  41300. 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
  41301. /* eslint-enable */
  41302. size: 45,
  41303. // handle margin is from symbol center to axis, which is stable when circular move.
  41304. margin: 50,
  41305. // color: '#1b8bbd'
  41306. // color: '#2f4554'
  41307. color: '#333',
  41308. shadowBlur: 3,
  41309. shadowColor: '#aaa',
  41310. shadowOffsetX: 0,
  41311. shadowOffsetY: 2,
  41312. // For mobile performance
  41313. throttle: 40
  41314. }
  41315. }
  41316. });
  41317. /*
  41318. * Licensed to the Apache Software Foundation (ASF) under one
  41319. * or more contributor license agreements. See the NOTICE file
  41320. * distributed with this work for additional information
  41321. * regarding copyright ownership. The ASF licenses this file
  41322. * to you under the Apache License, Version 2.0 (the
  41323. * "License"); you may not use this file except in compliance
  41324. * with the License. You may obtain a copy of the License at
  41325. *
  41326. * http://www.apache.org/licenses/LICENSE-2.0
  41327. *
  41328. * Unless required by applicable law or agreed to in writing,
  41329. * software distributed under the License is distributed on an
  41330. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41331. * KIND, either express or implied. See the License for the
  41332. * specific language governing permissions and limitations
  41333. * under the License.
  41334. */
  41335. var inner$8 = makeInner();
  41336. var each$8 = each$1;
  41337. /**
  41338. * @param {string} key
  41339. * @param {module:echarts/ExtensionAPI} api
  41340. * @param {Function} handler
  41341. * param: {string} currTrigger
  41342. * param: {Array.<number>} point
  41343. */
  41344. function register(key, api, handler) {
  41345. if (env$1.node) {
  41346. return;
  41347. }
  41348. var zr = api.getZr();
  41349. inner$8(zr).records || (inner$8(zr).records = {});
  41350. initGlobalListeners(zr, api);
  41351. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  41352. record.handler = handler;
  41353. }
  41354. function initGlobalListeners(zr, api) {
  41355. if (inner$8(zr).initialized) {
  41356. return;
  41357. }
  41358. inner$8(zr).initialized = true;
  41359. useHandler('click', curry(doEnter, 'click'));
  41360. useHandler('mousemove', curry(doEnter, 'mousemove'));
  41361. // useHandler('mouseout', onLeave);
  41362. useHandler('globalout', onLeave);
  41363. function useHandler(eventType, cb) {
  41364. zr.on(eventType, function (e) {
  41365. var dis = makeDispatchAction(api);
  41366. each$8(inner$8(zr).records, function (record) {
  41367. record && cb(record, e, dis.dispatchAction);
  41368. });
  41369. dispatchTooltipFinally(dis.pendings, api);
  41370. });
  41371. }
  41372. }
  41373. function dispatchTooltipFinally(pendings, api) {
  41374. var showLen = pendings.showTip.length;
  41375. var hideLen = pendings.hideTip.length;
  41376. var actuallyPayload;
  41377. if (showLen) {
  41378. actuallyPayload = pendings.showTip[showLen - 1];
  41379. }
  41380. else if (hideLen) {
  41381. actuallyPayload = pendings.hideTip[hideLen - 1];
  41382. }
  41383. if (actuallyPayload) {
  41384. actuallyPayload.dispatchAction = null;
  41385. api.dispatchAction(actuallyPayload);
  41386. }
  41387. }
  41388. function onLeave(record, e, dispatchAction) {
  41389. record.handler('leave', null, dispatchAction);
  41390. }
  41391. function doEnter(currTrigger, record, e, dispatchAction) {
  41392. record.handler(currTrigger, e, dispatchAction);
  41393. }
  41394. function makeDispatchAction(api) {
  41395. var pendings = {
  41396. showTip: [],
  41397. hideTip: []
  41398. };
  41399. // FIXME
  41400. // better approach?
  41401. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  41402. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  41403. // So we have to add "final stage" to merge those dispatched actions.
  41404. var dispatchAction = function (payload) {
  41405. var pendingList = pendings[payload.type];
  41406. if (pendingList) {
  41407. pendingList.push(payload);
  41408. }
  41409. else {
  41410. payload.dispatchAction = dispatchAction;
  41411. api.dispatchAction(payload);
  41412. }
  41413. };
  41414. return {
  41415. dispatchAction: dispatchAction,
  41416. pendings: pendings
  41417. };
  41418. }
  41419. /**
  41420. * @param {string} key
  41421. * @param {module:echarts/ExtensionAPI} api
  41422. */
  41423. function unregister(key, api) {
  41424. if (env$1.node) {
  41425. return;
  41426. }
  41427. var zr = api.getZr();
  41428. var record = (inner$8(zr).records || {})[key];
  41429. if (record) {
  41430. inner$8(zr).records[key] = null;
  41431. }
  41432. }
  41433. /*
  41434. * Licensed to the Apache Software Foundation (ASF) under one
  41435. * or more contributor license agreements. See the NOTICE file
  41436. * distributed with this work for additional information
  41437. * regarding copyright ownership. The ASF licenses this file
  41438. * to you under the Apache License, Version 2.0 (the
  41439. * "License"); you may not use this file except in compliance
  41440. * with the License. You may obtain a copy of the License at
  41441. *
  41442. * http://www.apache.org/licenses/LICENSE-2.0
  41443. *
  41444. * Unless required by applicable law or agreed to in writing,
  41445. * software distributed under the License is distributed on an
  41446. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41447. * KIND, either express or implied. See the License for the
  41448. * specific language governing permissions and limitations
  41449. * under the License.
  41450. */
  41451. var AxisPointerView = extendComponentView({
  41452. type: 'axisPointer',
  41453. render: function (globalAxisPointerModel, ecModel, api) {
  41454. var globalTooltipModel = ecModel.getComponent('tooltip');
  41455. var triggerOn = globalAxisPointerModel.get('triggerOn')
  41456. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  41457. // Register global listener in AxisPointerView to enable
  41458. // AxisPointerView to be independent to Tooltip.
  41459. register(
  41460. 'axisPointer',
  41461. api,
  41462. function (currTrigger, e, dispatchAction) {
  41463. // If 'none', it is not controlled by mouse totally.
  41464. if (triggerOn !== 'none'
  41465. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  41466. ) {
  41467. dispatchAction({
  41468. type: 'updateAxisPointer',
  41469. currTrigger: currTrigger,
  41470. x: e && e.offsetX,
  41471. y: e && e.offsetY
  41472. });
  41473. }
  41474. }
  41475. );
  41476. },
  41477. /**
  41478. * @override
  41479. */
  41480. remove: function (ecModel, api) {
  41481. unregister(api.getZr(), 'axisPointer');
  41482. AxisPointerView.superApply(this._model, 'remove', arguments);
  41483. },
  41484. /**
  41485. * @override
  41486. */
  41487. dispose: function (ecModel, api) {
  41488. unregister('axisPointer', api);
  41489. AxisPointerView.superApply(this._model, 'dispose', arguments);
  41490. }
  41491. });
  41492. /*
  41493. * Licensed to the Apache Software Foundation (ASF) under one
  41494. * or more contributor license agreements. See the NOTICE file
  41495. * distributed with this work for additional information
  41496. * regarding copyright ownership. The ASF licenses this file
  41497. * to you under the Apache License, Version 2.0 (the
  41498. * "License"); you may not use this file except in compliance
  41499. * with the License. You may obtain a copy of the License at
  41500. *
  41501. * http://www.apache.org/licenses/LICENSE-2.0
  41502. *
  41503. * Unless required by applicable law or agreed to in writing,
  41504. * software distributed under the License is distributed on an
  41505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41506. * KIND, either express or implied. See the License for the
  41507. * specific language governing permissions and limitations
  41508. * under the License.
  41509. */
  41510. var inner$9 = makeInner();
  41511. var clone$4 = clone;
  41512. var bind$1 = bind;
  41513. /**
  41514. * Base axis pointer class in 2D.
  41515. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  41516. */
  41517. function BaseAxisPointer() {
  41518. }
  41519. BaseAxisPointer.prototype = {
  41520. /**
  41521. * @private
  41522. */
  41523. _group: null,
  41524. /**
  41525. * @private
  41526. */
  41527. _lastGraphicKey: null,
  41528. /**
  41529. * @private
  41530. */
  41531. _handle: null,
  41532. /**
  41533. * @private
  41534. */
  41535. _dragging: false,
  41536. /**
  41537. * @private
  41538. */
  41539. _lastValue: null,
  41540. /**
  41541. * @private
  41542. */
  41543. _lastStatus: null,
  41544. /**
  41545. * @private
  41546. */
  41547. _payloadInfo: null,
  41548. /**
  41549. * In px, arbitrary value. Do not set too small,
  41550. * no animation is ok for most cases.
  41551. * @protected
  41552. */
  41553. animationThreshold: 15,
  41554. /**
  41555. * @implement
  41556. */
  41557. render: function (axisModel, axisPointerModel, api, forceRender) {
  41558. var value = axisPointerModel.get('value');
  41559. var status = axisPointerModel.get('status');
  41560. // Bind them to `this`, not in closure, otherwise they will not
  41561. // be replaced when user calling setOption in not merge mode.
  41562. this._axisModel = axisModel;
  41563. this._axisPointerModel = axisPointerModel;
  41564. this._api = api;
  41565. // Optimize: `render` will be called repeatly during mouse move.
  41566. // So it is power consuming if performing `render` each time,
  41567. // especially on mobile device.
  41568. if (!forceRender
  41569. && this._lastValue === value
  41570. && this._lastStatus === status
  41571. ) {
  41572. return;
  41573. }
  41574. this._lastValue = value;
  41575. this._lastStatus = status;
  41576. var group = this._group;
  41577. var handle = this._handle;
  41578. if (!status || status === 'hide') {
  41579. // Do not clear here, for animation better.
  41580. group && group.hide();
  41581. handle && handle.hide();
  41582. return;
  41583. }
  41584. group && group.show();
  41585. handle && handle.show();
  41586. // Otherwise status is 'show'
  41587. var elOption = {};
  41588. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  41589. // Enable change axis pointer type.
  41590. var graphicKey = elOption.graphicKey;
  41591. if (graphicKey !== this._lastGraphicKey) {
  41592. this.clear(api);
  41593. }
  41594. this._lastGraphicKey = graphicKey;
  41595. var moveAnimation = this._moveAnimation =
  41596. this.determineAnimation(axisModel, axisPointerModel);
  41597. if (!group) {
  41598. group = this._group = new Group();
  41599. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  41600. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  41601. api.getZr().add(group);
  41602. }
  41603. else {
  41604. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  41605. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  41606. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  41607. }
  41608. updateMandatoryProps(group, axisPointerModel, true);
  41609. this._renderHandle(value);
  41610. },
  41611. /**
  41612. * @implement
  41613. */
  41614. remove: function (api) {
  41615. this.clear(api);
  41616. },
  41617. /**
  41618. * @implement
  41619. */
  41620. dispose: function (api) {
  41621. this.clear(api);
  41622. },
  41623. /**
  41624. * @protected
  41625. */
  41626. determineAnimation: function (axisModel, axisPointerModel) {
  41627. var animation = axisPointerModel.get('animation');
  41628. var axis = axisModel.axis;
  41629. var isCategoryAxis = axis.type === 'category';
  41630. var useSnap = axisPointerModel.get('snap');
  41631. // Value axis without snap always do not snap.
  41632. if (!useSnap && !isCategoryAxis) {
  41633. return false;
  41634. }
  41635. if (animation === 'auto' || animation == null) {
  41636. var animationThreshold = this.animationThreshold;
  41637. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  41638. return true;
  41639. }
  41640. // It is important to auto animation when snap used. Consider if there is
  41641. // a dataZoom, animation will be disabled when too many points exist, while
  41642. // it will be enabled for better visual effect when little points exist.
  41643. if (useSnap) {
  41644. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  41645. var axisExtent = axis.getExtent();
  41646. // Approximate band width
  41647. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  41648. }
  41649. return false;
  41650. }
  41651. return animation === true;
  41652. },
  41653. /**
  41654. * add {pointer, label, graphicKey} to elOption
  41655. * @protected
  41656. */
  41657. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  41658. // Shoule be implemenented by sub-class.
  41659. },
  41660. /**
  41661. * @protected
  41662. */
  41663. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  41664. var pointerOption = elOption.pointer;
  41665. if (pointerOption) {
  41666. var pointerEl = inner$9(group).pointerEl = new graphic[pointerOption.type](
  41667. clone$4(elOption.pointer)
  41668. );
  41669. group.add(pointerEl);
  41670. }
  41671. },
  41672. /**
  41673. * @protected
  41674. */
  41675. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  41676. if (elOption.label) {
  41677. var labelEl = inner$9(group).labelEl = new Rect(
  41678. clone$4(elOption.label)
  41679. );
  41680. group.add(labelEl);
  41681. updateLabelShowHide(labelEl, axisPointerModel);
  41682. }
  41683. },
  41684. /**
  41685. * @protected
  41686. */
  41687. updatePointerEl: function (group, elOption, updateProps$$1) {
  41688. var pointerEl = inner$9(group).pointerEl;
  41689. if (pointerEl && elOption.pointer) {
  41690. pointerEl.setStyle(elOption.pointer.style);
  41691. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  41692. }
  41693. },
  41694. /**
  41695. * @protected
  41696. */
  41697. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  41698. var labelEl = inner$9(group).labelEl;
  41699. if (labelEl) {
  41700. labelEl.setStyle(elOption.label.style);
  41701. updateProps$$1(labelEl, {
  41702. // Consider text length change in vertical axis, animation should
  41703. // be used on shape, otherwise the effect will be weird.
  41704. shape: elOption.label.shape,
  41705. position: elOption.label.position
  41706. });
  41707. updateLabelShowHide(labelEl, axisPointerModel);
  41708. }
  41709. },
  41710. /**
  41711. * @private
  41712. */
  41713. _renderHandle: function (value) {
  41714. if (this._dragging || !this.updateHandleTransform) {
  41715. return;
  41716. }
  41717. var axisPointerModel = this._axisPointerModel;
  41718. var zr = this._api.getZr();
  41719. var handle = this._handle;
  41720. var handleModel = axisPointerModel.getModel('handle');
  41721. var status = axisPointerModel.get('status');
  41722. if (!handleModel.get('show') || !status || status === 'hide') {
  41723. handle && zr.remove(handle);
  41724. this._handle = null;
  41725. return;
  41726. }
  41727. var isInit;
  41728. if (!this._handle) {
  41729. isInit = true;
  41730. handle = this._handle = createIcon(
  41731. handleModel.get('icon'),
  41732. {
  41733. cursor: 'move',
  41734. draggable: true,
  41735. onmousemove: function (e) {
  41736. // Fot mobile devicem, prevent screen slider on the button.
  41737. stop(e.event);
  41738. },
  41739. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  41740. drift: bind$1(this._onHandleDragMove, this),
  41741. ondragend: bind$1(this._onHandleDragEnd, this)
  41742. }
  41743. );
  41744. zr.add(handle);
  41745. }
  41746. updateMandatoryProps(handle, axisPointerModel, false);
  41747. // update style
  41748. var includeStyles = [
  41749. 'color', 'borderColor', 'borderWidth', 'opacity',
  41750. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  41751. ];
  41752. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  41753. // update position
  41754. var handleSize = handleModel.get('size');
  41755. if (!isArray(handleSize)) {
  41756. handleSize = [handleSize, handleSize];
  41757. }
  41758. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  41759. createOrUpdate(
  41760. this,
  41761. '_doDispatchAxisPointer',
  41762. handleModel.get('throttle') || 0,
  41763. 'fixRate'
  41764. );
  41765. this._moveHandleToValue(value, isInit);
  41766. },
  41767. /**
  41768. * @private
  41769. */
  41770. _moveHandleToValue: function (value, isInit) {
  41771. updateProps$1(
  41772. this._axisPointerModel,
  41773. !isInit && this._moveAnimation,
  41774. this._handle,
  41775. getHandleTransProps(this.getHandleTransform(
  41776. value, this._axisModel, this._axisPointerModel
  41777. ))
  41778. );
  41779. },
  41780. /**
  41781. * @private
  41782. */
  41783. _onHandleDragMove: function (dx, dy) {
  41784. var handle = this._handle;
  41785. if (!handle) {
  41786. return;
  41787. }
  41788. this._dragging = true;
  41789. // Persistent for throttle.
  41790. var trans = this.updateHandleTransform(
  41791. getHandleTransProps(handle),
  41792. [dx, dy],
  41793. this._axisModel,
  41794. this._axisPointerModel
  41795. );
  41796. this._payloadInfo = trans;
  41797. handle.stopAnimation();
  41798. handle.attr(getHandleTransProps(trans));
  41799. inner$9(handle).lastProp = null;
  41800. this._doDispatchAxisPointer();
  41801. },
  41802. /**
  41803. * Throttled method.
  41804. * @private
  41805. */
  41806. _doDispatchAxisPointer: function () {
  41807. var handle = this._handle;
  41808. if (!handle) {
  41809. return;
  41810. }
  41811. var payloadInfo = this._payloadInfo;
  41812. var axisModel = this._axisModel;
  41813. this._api.dispatchAction({
  41814. type: 'updateAxisPointer',
  41815. x: payloadInfo.cursorPoint[0],
  41816. y: payloadInfo.cursorPoint[1],
  41817. tooltipOption: payloadInfo.tooltipOption,
  41818. axesInfo: [{
  41819. axisDim: axisModel.axis.dim,
  41820. axisIndex: axisModel.componentIndex
  41821. }]
  41822. });
  41823. },
  41824. /**
  41825. * @private
  41826. */
  41827. _onHandleDragEnd: function (moveAnimation) {
  41828. this._dragging = false;
  41829. var handle = this._handle;
  41830. if (!handle) {
  41831. return;
  41832. }
  41833. var value = this._axisPointerModel.get('value');
  41834. // Consider snap or categroy axis, handle may be not consistent with
  41835. // axisPointer. So move handle to align the exact value position when
  41836. // drag ended.
  41837. this._moveHandleToValue(value);
  41838. // For the effect: tooltip will be shown when finger holding on handle
  41839. // button, and will be hidden after finger left handle button.
  41840. this._api.dispatchAction({
  41841. type: 'hideTip'
  41842. });
  41843. },
  41844. /**
  41845. * Should be implemenented by sub-class if support `handle`.
  41846. * @protected
  41847. * @param {number} value
  41848. * @param {module:echarts/model/Model} axisModel
  41849. * @param {module:echarts/model/Model} axisPointerModel
  41850. * @return {Object} {position: [x, y], rotation: 0}
  41851. */
  41852. getHandleTransform: null,
  41853. /**
  41854. * * Should be implemenented by sub-class if support `handle`.
  41855. * @protected
  41856. * @param {Object} transform {position, rotation}
  41857. * @param {Array.<number>} delta [dx, dy]
  41858. * @param {module:echarts/model/Model} axisModel
  41859. * @param {module:echarts/model/Model} axisPointerModel
  41860. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  41861. */
  41862. updateHandleTransform: null,
  41863. /**
  41864. * @private
  41865. */
  41866. clear: function (api) {
  41867. this._lastValue = null;
  41868. this._lastStatus = null;
  41869. var zr = api.getZr();
  41870. var group = this._group;
  41871. var handle = this._handle;
  41872. if (zr && group) {
  41873. this._lastGraphicKey = null;
  41874. group && zr.remove(group);
  41875. handle && zr.remove(handle);
  41876. this._group = null;
  41877. this._handle = null;
  41878. this._payloadInfo = null;
  41879. }
  41880. },
  41881. /**
  41882. * @protected
  41883. */
  41884. doClear: function () {
  41885. // Implemented by sub-class if necessary.
  41886. },
  41887. /**
  41888. * @protected
  41889. * @param {Array.<number>} xy
  41890. * @param {Array.<number>} wh
  41891. * @param {number} [xDimIndex=0] or 1
  41892. */
  41893. buildLabel: function (xy, wh, xDimIndex) {
  41894. xDimIndex = xDimIndex || 0;
  41895. return {
  41896. x: xy[xDimIndex],
  41897. y: xy[1 - xDimIndex],
  41898. width: wh[xDimIndex],
  41899. height: wh[1 - xDimIndex]
  41900. };
  41901. }
  41902. };
  41903. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  41904. function updateProps$1(animationModel, moveAnimation, el, props) {
  41905. // Animation optimize.
  41906. if (!propsEqual(inner$9(el).lastProp, props)) {
  41907. inner$9(el).lastProp = props;
  41908. moveAnimation
  41909. ? updateProps(el, props, animationModel)
  41910. : (el.stopAnimation(), el.attr(props));
  41911. }
  41912. }
  41913. function propsEqual(lastProps, newProps) {
  41914. if (isObject$1(lastProps) && isObject$1(newProps)) {
  41915. var equals = true;
  41916. each$1(newProps, function (item, key) {
  41917. equals = equals && propsEqual(lastProps[key], item);
  41918. });
  41919. return !!equals;
  41920. }
  41921. else {
  41922. return lastProps === newProps;
  41923. }
  41924. }
  41925. function updateLabelShowHide(labelEl, axisPointerModel) {
  41926. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  41927. }
  41928. function getHandleTransProps(trans) {
  41929. return {
  41930. position: trans.position.slice(),
  41931. rotation: trans.rotation || 0
  41932. };
  41933. }
  41934. function updateMandatoryProps(group, axisPointerModel, silent) {
  41935. var z = axisPointerModel.get('z');
  41936. var zlevel = axisPointerModel.get('zlevel');
  41937. group && group.traverse(function (el) {
  41938. if (el.type !== 'group') {
  41939. z != null && (el.z = z);
  41940. zlevel != null && (el.zlevel = zlevel);
  41941. el.silent = silent;
  41942. }
  41943. });
  41944. }
  41945. enableClassExtend(BaseAxisPointer);
  41946. /*
  41947. * Licensed to the Apache Software Foundation (ASF) under one
  41948. * or more contributor license agreements. See the NOTICE file
  41949. * distributed with this work for additional information
  41950. * regarding copyright ownership. The ASF licenses this file
  41951. * to you under the Apache License, Version 2.0 (the
  41952. * "License"); you may not use this file except in compliance
  41953. * with the License. You may obtain a copy of the License at
  41954. *
  41955. * http://www.apache.org/licenses/LICENSE-2.0
  41956. *
  41957. * Unless required by applicable law or agreed to in writing,
  41958. * software distributed under the License is distributed on an
  41959. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41960. * KIND, either express or implied. See the License for the
  41961. * specific language governing permissions and limitations
  41962. * under the License.
  41963. */
  41964. /**
  41965. * @param {module:echarts/model/Model} axisPointerModel
  41966. */
  41967. function buildElStyle(axisPointerModel) {
  41968. var axisPointerType = axisPointerModel.get('type');
  41969. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  41970. var style;
  41971. if (axisPointerType === 'line') {
  41972. style = styleModel.getLineStyle();
  41973. style.fill = null;
  41974. }
  41975. else if (axisPointerType === 'shadow') {
  41976. style = styleModel.getAreaStyle();
  41977. style.stroke = null;
  41978. }
  41979. return style;
  41980. }
  41981. /**
  41982. * @param {Function} labelPos {align, verticalAlign, position}
  41983. */
  41984. function buildLabelElOption(
  41985. elOption, axisModel, axisPointerModel, api, labelPos
  41986. ) {
  41987. var value = axisPointerModel.get('value');
  41988. var text = getValueLabel(
  41989. value, axisModel.axis, axisModel.ecModel,
  41990. axisPointerModel.get('seriesDataIndices'),
  41991. {
  41992. precision: axisPointerModel.get('label.precision'),
  41993. formatter: axisPointerModel.get('label.formatter')
  41994. }
  41995. );
  41996. var labelModel = axisPointerModel.getModel('label');
  41997. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  41998. var font = labelModel.getFont();
  41999. var textRect = getBoundingRect(text, font);
  42000. var position = labelPos.position;
  42001. var width = textRect.width + paddings[1] + paddings[3];
  42002. var height = textRect.height + paddings[0] + paddings[2];
  42003. // Adjust by align.
  42004. var align = labelPos.align;
  42005. align === 'right' && (position[0] -= width);
  42006. align === 'center' && (position[0] -= width / 2);
  42007. var verticalAlign = labelPos.verticalAlign;
  42008. verticalAlign === 'bottom' && (position[1] -= height);
  42009. verticalAlign === 'middle' && (position[1] -= height / 2);
  42010. // Not overflow ec container
  42011. confineInContainer(position, width, height, api);
  42012. var bgColor = labelModel.get('backgroundColor');
  42013. if (!bgColor || bgColor === 'auto') {
  42014. bgColor = axisModel.get('axisLine.lineStyle.color');
  42015. }
  42016. elOption.label = {
  42017. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  42018. position: position.slice(),
  42019. // TODO: rich
  42020. style: {
  42021. text: text,
  42022. textFont: font,
  42023. textFill: labelModel.getTextColor(),
  42024. textPosition: 'inside',
  42025. textPadding: paddings,
  42026. fill: bgColor,
  42027. stroke: labelModel.get('borderColor') || 'transparent',
  42028. lineWidth: labelModel.get('borderWidth') || 0,
  42029. shadowBlur: labelModel.get('shadowBlur'),
  42030. shadowColor: labelModel.get('shadowColor'),
  42031. shadowOffsetX: labelModel.get('shadowOffsetX'),
  42032. shadowOffsetY: labelModel.get('shadowOffsetY')
  42033. },
  42034. // Lable should be over axisPointer.
  42035. z2: 10
  42036. };
  42037. }
  42038. // Do not overflow ec container
  42039. function confineInContainer(position, width, height, api) {
  42040. var viewWidth = api.getWidth();
  42041. var viewHeight = api.getHeight();
  42042. position[0] = Math.min(position[0] + width, viewWidth) - width;
  42043. position[1] = Math.min(position[1] + height, viewHeight) - height;
  42044. position[0] = Math.max(position[0], 0);
  42045. position[1] = Math.max(position[1], 0);
  42046. }
  42047. /**
  42048. * @param {number} value
  42049. * @param {module:echarts/coord/Axis} axis
  42050. * @param {module:echarts/model/Global} ecModel
  42051. * @param {Object} opt
  42052. * @param {Array.<Object>} seriesDataIndices
  42053. * @param {number|string} opt.precision 'auto' or a number
  42054. * @param {string|Function} opt.formatter label formatter
  42055. */
  42056. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  42057. value = axis.scale.parse(value);
  42058. var text = axis.scale.getLabel(
  42059. // If `precision` is set, width can be fixed (like '12.00500'), which
  42060. // helps to debounce when when moving label.
  42061. value, {precision: opt.precision}
  42062. );
  42063. var formatter = opt.formatter;
  42064. if (formatter) {
  42065. var params = {
  42066. value: getAxisRawValue(axis, value),
  42067. axisDimension: axis.dim,
  42068. axisIndex: axis.index,
  42069. seriesData: []
  42070. };
  42071. each$1(seriesDataIndices, function (idxItem) {
  42072. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  42073. var dataIndex = idxItem.dataIndexInside;
  42074. var dataParams = series && series.getDataParams(dataIndex);
  42075. dataParams && params.seriesData.push(dataParams);
  42076. });
  42077. if (isString(formatter)) {
  42078. text = formatter.replace('{value}', text);
  42079. }
  42080. else if (isFunction$1(formatter)) {
  42081. text = formatter(params);
  42082. }
  42083. }
  42084. return text;
  42085. }
  42086. /**
  42087. * @param {module:echarts/coord/Axis} axis
  42088. * @param {number} value
  42089. * @param {Object} layoutInfo {
  42090. * rotation, position, labelOffset, labelDirection, labelMargin
  42091. * }
  42092. */
  42093. function getTransformedPosition(axis, value, layoutInfo) {
  42094. var transform = create$1();
  42095. rotate(transform, transform, layoutInfo.rotation);
  42096. translate(transform, transform, layoutInfo.position);
  42097. return applyTransform$1([
  42098. axis.dataToCoord(value),
  42099. (layoutInfo.labelOffset || 0)
  42100. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  42101. ], transform);
  42102. }
  42103. function buildCartesianSingleLabelElOption(
  42104. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  42105. ) {
  42106. var textLayout = AxisBuilder.innerTextLayout(
  42107. layoutInfo.rotation, 0, layoutInfo.labelDirection
  42108. );
  42109. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  42110. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  42111. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  42112. align: textLayout.textAlign,
  42113. verticalAlign: textLayout.textVerticalAlign
  42114. });
  42115. }
  42116. /**
  42117. * @param {Array.<number>} p1
  42118. * @param {Array.<number>} p2
  42119. * @param {number} [xDimIndex=0] or 1
  42120. */
  42121. function makeLineShape(p1, p2, xDimIndex) {
  42122. xDimIndex = xDimIndex || 0;
  42123. return {
  42124. x1: p1[xDimIndex],
  42125. y1: p1[1 - xDimIndex],
  42126. x2: p2[xDimIndex],
  42127. y2: p2[1 - xDimIndex]
  42128. };
  42129. }
  42130. /**
  42131. * @param {Array.<number>} xy
  42132. * @param {Array.<number>} wh
  42133. * @param {number} [xDimIndex=0] or 1
  42134. */
  42135. function makeRectShape(xy, wh, xDimIndex) {
  42136. xDimIndex = xDimIndex || 0;
  42137. return {
  42138. x: xy[xDimIndex],
  42139. y: xy[1 - xDimIndex],
  42140. width: wh[xDimIndex],
  42141. height: wh[1 - xDimIndex]
  42142. };
  42143. }
  42144. /*
  42145. * Licensed to the Apache Software Foundation (ASF) under one
  42146. * or more contributor license agreements. See the NOTICE file
  42147. * distributed with this work for additional information
  42148. * regarding copyright ownership. The ASF licenses this file
  42149. * to you under the Apache License, Version 2.0 (the
  42150. * "License"); you may not use this file except in compliance
  42151. * with the License. You may obtain a copy of the License at
  42152. *
  42153. * http://www.apache.org/licenses/LICENSE-2.0
  42154. *
  42155. * Unless required by applicable law or agreed to in writing,
  42156. * software distributed under the License is distributed on an
  42157. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42158. * KIND, either express or implied. See the License for the
  42159. * specific language governing permissions and limitations
  42160. * under the License.
  42161. */
  42162. var CartesianAxisPointer = BaseAxisPointer.extend({
  42163. /**
  42164. * @override
  42165. */
  42166. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  42167. var axis = axisModel.axis;
  42168. var grid = axis.grid;
  42169. var axisPointerType = axisPointerModel.get('type');
  42170. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  42171. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  42172. if (axisPointerType && axisPointerType !== 'none') {
  42173. var elStyle = buildElStyle(axisPointerModel);
  42174. var pointerOption = pointerShapeBuilder[axisPointerType](
  42175. axis, pixelValue, otherExtent
  42176. );
  42177. pointerOption.style = elStyle;
  42178. elOption.graphicKey = pointerOption.type;
  42179. elOption.pointer = pointerOption;
  42180. }
  42181. var layoutInfo = layout$1(grid.model, axisModel);
  42182. buildCartesianSingleLabelElOption(
  42183. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  42184. );
  42185. },
  42186. /**
  42187. * @override
  42188. */
  42189. getHandleTransform: function (value, axisModel, axisPointerModel) {
  42190. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  42191. labelInside: false
  42192. });
  42193. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  42194. return {
  42195. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  42196. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  42197. };
  42198. },
  42199. /**
  42200. * @override
  42201. */
  42202. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  42203. var axis = axisModel.axis;
  42204. var grid = axis.grid;
  42205. var axisExtent = axis.getGlobalExtent(true);
  42206. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  42207. var dimIndex = axis.dim === 'x' ? 0 : 1;
  42208. var currPosition = transform.position;
  42209. currPosition[dimIndex] += delta[dimIndex];
  42210. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  42211. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  42212. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  42213. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  42214. cursorPoint[dimIndex] = currPosition[dimIndex];
  42215. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  42216. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  42217. return {
  42218. position: currPosition,
  42219. rotation: transform.rotation,
  42220. cursorPoint: cursorPoint,
  42221. tooltipOption: tooltipOptions[dimIndex]
  42222. };
  42223. }
  42224. });
  42225. function getCartesian(grid, axis) {
  42226. var opt = {};
  42227. opt[axis.dim + 'AxisIndex'] = axis.index;
  42228. return grid.getCartesian(opt);
  42229. }
  42230. var pointerShapeBuilder = {
  42231. line: function (axis, pixelValue, otherExtent) {
  42232. var targetShape = makeLineShape(
  42233. [pixelValue, otherExtent[0]],
  42234. [pixelValue, otherExtent[1]],
  42235. getAxisDimIndex(axis)
  42236. );
  42237. return {
  42238. type: 'Line',
  42239. subPixelOptimize: true,
  42240. shape: targetShape
  42241. };
  42242. },
  42243. shadow: function (axis, pixelValue, otherExtent) {
  42244. var bandWidth = Math.max(1, axis.getBandWidth());
  42245. var span = otherExtent[1] - otherExtent[0];
  42246. return {
  42247. type: 'Rect',
  42248. shape: makeRectShape(
  42249. [pixelValue - bandWidth / 2, otherExtent[0]],
  42250. [bandWidth, span],
  42251. getAxisDimIndex(axis)
  42252. )
  42253. };
  42254. }
  42255. };
  42256. function getAxisDimIndex(axis) {
  42257. return axis.dim === 'x' ? 0 : 1;
  42258. }
  42259. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  42260. /*
  42261. * Licensed to the Apache Software Foundation (ASF) under one
  42262. * or more contributor license agreements. See the NOTICE file
  42263. * distributed with this work for additional information
  42264. * regarding copyright ownership. The ASF licenses this file
  42265. * to you under the Apache License, Version 2.0 (the
  42266. * "License"); you may not use this file except in compliance
  42267. * with the License. You may obtain a copy of the License at
  42268. *
  42269. * http://www.apache.org/licenses/LICENSE-2.0
  42270. *
  42271. * Unless required by applicable law or agreed to in writing,
  42272. * software distributed under the License is distributed on an
  42273. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42274. * KIND, either express or implied. See the License for the
  42275. * specific language governing permissions and limitations
  42276. * under the License.
  42277. */
  42278. // CartesianAxisPointer is not supposed to be required here. But consider
  42279. // echarts.simple.js and online build tooltip, which only require gridSimple,
  42280. // CartesianAxisPointer should be able to required somewhere.
  42281. registerPreprocessor(function (option) {
  42282. // Always has a global axisPointerModel for default setting.
  42283. if (option) {
  42284. (!option.axisPointer || option.axisPointer.length === 0)
  42285. && (option.axisPointer = {});
  42286. var link = option.axisPointer.link;
  42287. // Normalize to array to avoid object mergin. But if link
  42288. // is not set, remain null/undefined, otherwise it will
  42289. // override existent link setting.
  42290. if (link && !isArray(link)) {
  42291. option.axisPointer.link = [link];
  42292. }
  42293. }
  42294. });
  42295. // This process should proformed after coordinate systems created
  42296. // and series data processed. So put it on statistic processing stage.
  42297. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  42298. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  42299. // allAxesInfo should be updated when setOption performed.
  42300. ecModel.getComponent('axisPointer').coordSysAxesInfo =
  42301. collect(ecModel, api);
  42302. });
  42303. // Broadcast to all views.
  42304. registerAction({
  42305. type: 'updateAxisPointer',
  42306. event: 'updateAxisPointer',
  42307. update: ':updateAxisPointer'
  42308. }, axisTrigger);
  42309. /*
  42310. * Licensed to the Apache Software Foundation (ASF) under one
  42311. * or more contributor license agreements. See the NOTICE file
  42312. * distributed with this work for additional information
  42313. * regarding copyright ownership. The ASF licenses this file
  42314. * to you under the Apache License, Version 2.0 (the
  42315. * "License"); you may not use this file except in compliance
  42316. * with the License. You may obtain a copy of the License at
  42317. *
  42318. * http://www.apache.org/licenses/LICENSE-2.0
  42319. *
  42320. * Unless required by applicable law or agreed to in writing,
  42321. * software distributed under the License is distributed on an
  42322. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42323. * KIND, either express or implied. See the License for the
  42324. * specific language governing permissions and limitations
  42325. * under the License.
  42326. */
  42327. extendComponentModel({
  42328. type: 'tooltip',
  42329. dependencies: ['axisPointer'],
  42330. defaultOption: {
  42331. zlevel: 0,
  42332. z: 60,
  42333. show: true,
  42334. // tooltip主体内容
  42335. showContent: true,
  42336. // 'trigger' only works on coordinate system.
  42337. // 'item' | 'axis' | 'none'
  42338. trigger: 'item',
  42339. // 'click' | 'mousemove' | 'none'
  42340. triggerOn: 'mousemove|click',
  42341. alwaysShowContent: false,
  42342. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  42343. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  42344. // 'auto': use html by default, and use non-html if `document` is not defined
  42345. // 'html': use html for tooltip
  42346. // 'richText': use canvas, svg, and etc. for tooltip
  42347. // 位置 {Array} | {Function}
  42348. // position: null
  42349. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  42350. // align: null,
  42351. // verticalAlign: null,
  42352. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  42353. confine: false,
  42354. // 内容格式器:{string}(Template) ¦ {Function}
  42355. // formatter: null
  42356. showDelay: 0,
  42357. // 隐藏延迟,单位ms
  42358. hideDelay: 100,
  42359. // 动画变换时间,单位s
  42360. transitionDuration: 0.4,
  42361. enterable: false,
  42362. // 提示背景颜色,默认为透明度为0.7的黑色
  42363. backgroundColor: 'rgba(50,50,50,0.7)',
  42364. // 提示边框颜色
  42365. borderColor: '#333',
  42366. // 提示边框圆角,单位px,默认为4
  42367. borderRadius: 4,
  42368. // 提示边框线宽,单位px,默认为0(无边框)
  42369. borderWidth: 0,
  42370. // 提示内边距,单位px,默认各方向内边距为5,
  42371. // 接受数组分别设定上右下左边距,同css
  42372. padding: 5,
  42373. // Extra css text
  42374. extraCssText: '',
  42375. // 坐标轴指示器,坐标轴触发有效
  42376. axisPointer: {
  42377. // 默认为直线
  42378. // 可选为:'line' | 'shadow' | 'cross'
  42379. type: 'line',
  42380. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  42381. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  42382. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  42383. // 极坐标系会默认选择 angle 轴
  42384. axis: 'auto',
  42385. animation: 'auto',
  42386. animationDurationUpdate: 200,
  42387. animationEasingUpdate: 'exponentialOut',
  42388. crossStyle: {
  42389. color: '#999',
  42390. width: 1,
  42391. type: 'dashed',
  42392. // TODO formatter
  42393. textStyle: {}
  42394. }
  42395. // lineStyle and shadowStyle should not be specified here,
  42396. // otherwise it will always override those styles on option.axisPointer.
  42397. },
  42398. textStyle: {
  42399. color: '#fff',
  42400. fontSize: 14
  42401. }
  42402. }
  42403. });
  42404. /*
  42405. * Licensed to the Apache Software Foundation (ASF) under one
  42406. * or more contributor license agreements. See the NOTICE file
  42407. * distributed with this work for additional information
  42408. * regarding copyright ownership. The ASF licenses this file
  42409. * to you under the Apache License, Version 2.0 (the
  42410. * "License"); you may not use this file except in compliance
  42411. * with the License. You may obtain a copy of the License at
  42412. *
  42413. * http://www.apache.org/licenses/LICENSE-2.0
  42414. *
  42415. * Unless required by applicable law or agreed to in writing,
  42416. * software distributed under the License is distributed on an
  42417. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42418. * KIND, either express or implied. See the License for the
  42419. * specific language governing permissions and limitations
  42420. * under the License.
  42421. */
  42422. var each$10 = each$1;
  42423. var toCamelCase$1 = toCamelCase;
  42424. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  42425. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  42426. /**
  42427. * @param {number} duration
  42428. * @return {string}
  42429. * @inner
  42430. */
  42431. function assembleTransition(duration) {
  42432. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  42433. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  42434. + 'top ' + duration + 's ' + transitionCurve;
  42435. return map(vendors, function (vendorPrefix) {
  42436. return vendorPrefix + 'transition:' + transitionText;
  42437. }).join(';');
  42438. }
  42439. /**
  42440. * @param {Object} textStyle
  42441. * @return {string}
  42442. * @inner
  42443. */
  42444. function assembleFont(textStyleModel) {
  42445. var cssText = [];
  42446. var fontSize = textStyleModel.get('fontSize');
  42447. var color = textStyleModel.getTextColor();
  42448. color && cssText.push('color:' + color);
  42449. cssText.push('font:' + textStyleModel.getFont());
  42450. var lineHeight = textStyleModel.get('lineHeight');
  42451. if (lineHeight == null) {
  42452. lineHeight = Math.round(fontSize * 3 / 2);
  42453. }
  42454. fontSize
  42455. && cssText.push('line-height:' + lineHeight + 'px');
  42456. var shadowColor = textStyleModel.get('textShadowColor');
  42457. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  42458. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  42459. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  42460. shadowBlur
  42461. && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px '
  42462. + shadowBlur + 'px ' + shadowColor);
  42463. each$10(['decoration', 'align'], function (name) {
  42464. var val = textStyleModel.get(name);
  42465. val && cssText.push('text-' + name + ':' + val);
  42466. });
  42467. return cssText.join(';');
  42468. }
  42469. /**
  42470. * @param {Object} tooltipModel
  42471. * @return {string}
  42472. * @inner
  42473. */
  42474. function assembleCssText(tooltipModel) {
  42475. var cssText = [];
  42476. var transitionDuration = tooltipModel.get('transitionDuration');
  42477. var backgroundColor = tooltipModel.get('backgroundColor');
  42478. var textStyleModel = tooltipModel.getModel('textStyle');
  42479. var padding = tooltipModel.get('padding');
  42480. // Animation transition. Do not animate when transitionDuration is 0.
  42481. transitionDuration
  42482. && cssText.push(assembleTransition(transitionDuration));
  42483. if (backgroundColor) {
  42484. if (env$1.canvasSupported) {
  42485. cssText.push('background-Color:' + backgroundColor);
  42486. }
  42487. else {
  42488. // for ie
  42489. cssText.push(
  42490. 'background-Color:#' + toHex(backgroundColor)
  42491. );
  42492. cssText.push('filter:alpha(opacity=70)');
  42493. }
  42494. }
  42495. // Border style
  42496. each$10(['width', 'color', 'radius'], function (name) {
  42497. var borderName = 'border-' + name;
  42498. var camelCase = toCamelCase$1(borderName);
  42499. var val = tooltipModel.get(camelCase);
  42500. val != null
  42501. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  42502. });
  42503. // Text style
  42504. cssText.push(assembleFont(textStyleModel));
  42505. // Padding
  42506. if (padding != null) {
  42507. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  42508. }
  42509. return cssText.join(';') + ';';
  42510. }
  42511. // If not able to make, do not modify the input `out`.
  42512. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  42513. var zrPainter = zr && zr.painter;
  42514. if (appendToBody) {
  42515. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  42516. if (zrViewportRoot) {
  42517. // Some APPs might use scale on body, so we support CSS transform here.
  42518. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  42519. }
  42520. }
  42521. else {
  42522. out[0] = zrX;
  42523. out[1] = zrY;
  42524. // xy should be based on canvas root. But tooltipContent is
  42525. // the sibling of canvas root. So padding of ec container
  42526. // should be considered here.
  42527. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  42528. if (viewportRootOffset) {
  42529. out[0] += viewportRootOffset.offsetLeft;
  42530. out[1] += viewportRootOffset.offsetTop;
  42531. }
  42532. }
  42533. out[2] = out[0] / zr.getWidth(); // The ratio of left to width
  42534. out[3] = out[1] / zr.getHeight(); // The ratio of top to height
  42535. }
  42536. /**
  42537. * @alias module:echarts/component/tooltip/TooltipContent
  42538. * @param {HTMLElement} container
  42539. * @param {ExtensionAPI} api
  42540. * @param {Object} [opt]
  42541. * @param {boolean} [opt.appendToBody]
  42542. * `false`: the DOM element will be inside the container. Default value.
  42543. * `true`: the DOM element will be appended to HTML body, which avoid
  42544. * some overflow clip but intrude outside of the container.
  42545. * @constructor
  42546. */
  42547. function TooltipContent(container, api, opt) {
  42548. if (env$1.wxa) {
  42549. return null;
  42550. }
  42551. var el = document.createElement('div');
  42552. el.domBelongToZr = true;
  42553. this.el = el;
  42554. var zr = this._zr = api.getZr();
  42555. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  42556. this._styleCoord = [0, 0, 0, 0]; // [left, top, left/width, top/height]
  42557. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  42558. if (appendToBody) {
  42559. document.body.appendChild(el);
  42560. }
  42561. else {
  42562. container.appendChild(el);
  42563. }
  42564. this._container = container;
  42565. this._show = false;
  42566. /**
  42567. * @private
  42568. */
  42569. this._hideTimeout;
  42570. // FIXME
  42571. // Is it needed to trigger zr event manually if
  42572. // the browser do not support `pointer-events: none`.
  42573. var self = this;
  42574. el.onmouseenter = function () {
  42575. // clear the timeout in hideLater and keep showing tooltip
  42576. if (self._enterable) {
  42577. clearTimeout(self._hideTimeout);
  42578. self._show = true;
  42579. }
  42580. self._inContent = true;
  42581. };
  42582. el.onmousemove = function (e) {
  42583. e = e || window.event;
  42584. if (!self._enterable) {
  42585. // `pointer-events: none` is set to tooltip content div
  42586. // if `enterable` is set as `false`, and `el.onmousemove`
  42587. // can not be triggered. But in browser that do not
  42588. // support `pointer-events`, we need to do this:
  42589. // Try trigger zrender event to avoid mouse
  42590. // in and out shape too frequently
  42591. var handler = zr.handler;
  42592. var zrViewportRoot = zr.painter.getViewportRoot();
  42593. normalizeEvent(zrViewportRoot, e, true);
  42594. handler.dispatch('mousemove', e);
  42595. }
  42596. };
  42597. el.onmouseleave = function () {
  42598. if (self._enterable) {
  42599. if (self._show) {
  42600. self.hideLater(self._hideDelay);
  42601. }
  42602. }
  42603. self._inContent = false;
  42604. };
  42605. }
  42606. TooltipContent.prototype = {
  42607. constructor: TooltipContent,
  42608. /**
  42609. * @private
  42610. * @type {boolean}
  42611. */
  42612. _enterable: true,
  42613. /**
  42614. * Update when tooltip is rendered
  42615. */
  42616. update: function (tooltipModel) {
  42617. // FIXME
  42618. // Move this logic to ec main?
  42619. var container = this._container;
  42620. var stl = container.currentStyle
  42621. || document.defaultView.getComputedStyle(container);
  42622. var domStyle = container.style;
  42623. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  42624. domStyle.position = 'relative';
  42625. }
  42626. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  42627. alwaysShowContent && this._moveTooltipIfResized();
  42628. // Hide the tooltip
  42629. // PENDING
  42630. // this.hide();
  42631. },
  42632. /**
  42633. * when `alwaysShowContent` is true,
  42634. * we should move the tooltip after chart resized
  42635. */
  42636. _moveTooltipIfResized: function () {
  42637. var ratioX = this._styleCoord[2]; // The ratio of left to width
  42638. var ratioY = this._styleCoord[3]; // The ratio of top to height
  42639. var realX = ratioX * this._zr.getWidth();
  42640. var realY = ratioY * this._zr.getHeight();
  42641. this.moveTo(realX, realY);
  42642. },
  42643. show: function (tooltipModel) {
  42644. clearTimeout(this._hideTimeout);
  42645. var el = this.el;
  42646. var styleCoord = this._styleCoord;
  42647. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  42648. // Because of the reason described in:
  42649. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  42650. // we should set initial value to `left` and `top`.
  42651. + ';left:' + styleCoord[0] + 'px;top:' + styleCoord[1] + 'px;'
  42652. + (tooltipModel.get('extraCssText') || '');
  42653. el.style.display = el.innerHTML ? 'block' : 'none';
  42654. // If mouse occasionally move over the tooltip, a mouseout event will be
  42655. // triggered by canvas, and cause some unexpectable result like dragging
  42656. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  42657. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  42658. // scenario.
  42659. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  42660. this._show = true;
  42661. },
  42662. setContent: function (content) {
  42663. this.el.innerHTML = content == null ? '' : content;
  42664. },
  42665. setEnterable: function (enterable) {
  42666. this._enterable = enterable;
  42667. },
  42668. getSize: function () {
  42669. var el = this.el;
  42670. return [el.clientWidth, el.clientHeight];
  42671. },
  42672. moveTo: function (zrX, zrY) {
  42673. var styleCoord = this._styleCoord;
  42674. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  42675. var style = this.el.style;
  42676. style.left = styleCoord[0] + 'px';
  42677. style.top = styleCoord[1] + 'px';
  42678. },
  42679. hide: function () {
  42680. this.el.style.display = 'none';
  42681. this._show = false;
  42682. },
  42683. hideLater: function (time) {
  42684. if (this._show && !(this._inContent && this._enterable)) {
  42685. if (time) {
  42686. this._hideDelay = time;
  42687. // Set show false to avoid invoke hideLater multiple times
  42688. this._show = false;
  42689. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  42690. }
  42691. else {
  42692. this.hide();
  42693. }
  42694. }
  42695. },
  42696. isShow: function () {
  42697. return this._show;
  42698. },
  42699. dispose: function () {
  42700. this.el.parentNode.removeChild(this.el);
  42701. },
  42702. getOuterSize: function () {
  42703. var width = this.el.clientWidth;
  42704. var height = this.el.clientHeight;
  42705. // Consider browser compatibility.
  42706. // IE8 does not support getComputedStyle.
  42707. if (document.defaultView && document.defaultView.getComputedStyle) {
  42708. var stl = document.defaultView.getComputedStyle(this.el);
  42709. if (stl) {
  42710. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  42711. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  42712. }
  42713. }
  42714. return {width: width, height: height};
  42715. }
  42716. };
  42717. /*
  42718. * Licensed to the Apache Software Foundation (ASF) under one
  42719. * or more contributor license agreements. See the NOTICE file
  42720. * distributed with this work for additional information
  42721. * regarding copyright ownership. The ASF licenses this file
  42722. * to you under the Apache License, Version 2.0 (the
  42723. * "License"); you may not use this file except in compliance
  42724. * with the License. You may obtain a copy of the License at
  42725. *
  42726. * http://www.apache.org/licenses/LICENSE-2.0
  42727. *
  42728. * Unless required by applicable law or agreed to in writing,
  42729. * software distributed under the License is distributed on an
  42730. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42731. * KIND, either express or implied. See the License for the
  42732. * specific language governing permissions and limitations
  42733. * under the License.
  42734. */
  42735. // import Group from 'zrender/src/container/Group';
  42736. function makeStyleCoord$1(out, zr, zrX, zrY) {
  42737. out[0] = zrX;
  42738. out[1] = zrY;
  42739. out[2] = out[0] / zr.getWidth(); // The ratio of left to width
  42740. out[3] = out[1] / zr.getHeight(); // The ratio of top to height
  42741. }
  42742. /**
  42743. * @alias module:echarts/component/tooltip/TooltipRichContent
  42744. * @constructor
  42745. */
  42746. function TooltipRichContent(api) {
  42747. var zr = this._zr = api.getZr();
  42748. this._styleCoord = [0, 0, 0, 0]; // [left, top, left/width, top/height]
  42749. makeStyleCoord$1(this._styleCoord, zr, api.getWidth() / 2, api.getHeight() / 2);
  42750. this._show = false;
  42751. /**
  42752. * @private
  42753. */
  42754. this._hideTimeout;
  42755. }
  42756. TooltipRichContent.prototype = {
  42757. constructor: TooltipRichContent,
  42758. /**
  42759. * @private
  42760. * @type {boolean}
  42761. */
  42762. _enterable: true,
  42763. /**
  42764. * Update when tooltip is rendered
  42765. */
  42766. update: function (tooltipModel) {
  42767. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  42768. alwaysShowContent && this._moveTooltipIfResized();
  42769. },
  42770. /**
  42771. * when `alwaysShowContent` is true,
  42772. * we should move the tooltip after chart resized
  42773. */
  42774. _moveTooltipIfResized: function () {
  42775. var ratioX = this._styleCoord[2]; // The ratio of left to width
  42776. var ratioY = this._styleCoord[3]; // The ratio of top to height
  42777. var realX = ratioX * this._zr.getWidth();
  42778. var realY = ratioY * this._zr.getHeight();
  42779. this.moveTo(realX, realY);
  42780. },
  42781. show: function (tooltipModel) {
  42782. if (this._hideTimeout) {
  42783. clearTimeout(this._hideTimeout);
  42784. }
  42785. this.el.attr('show', true);
  42786. this._show = true;
  42787. },
  42788. /**
  42789. * Set tooltip content
  42790. *
  42791. * @param {string} content rich text string of content
  42792. * @param {Object} markerRich rich text style
  42793. * @param {Object} tooltipModel tooltip model
  42794. */
  42795. setContent: function (content, markerRich, tooltipModel) {
  42796. if (this.el) {
  42797. this._zr.remove(this.el);
  42798. }
  42799. var markers = {};
  42800. var text = content;
  42801. var prefix = '{marker';
  42802. var suffix = '|}';
  42803. var startId = text.indexOf(prefix);
  42804. while (startId >= 0) {
  42805. var endId = text.indexOf(suffix);
  42806. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  42807. if (name.indexOf('sub') > -1) {
  42808. markers['marker' + name] = {
  42809. textWidth: 4,
  42810. textHeight: 4,
  42811. textBorderRadius: 2,
  42812. textBackgroundColor: markerRich[name],
  42813. // TODO: textOffset is not implemented for rich text
  42814. textOffset: [3, 0]
  42815. };
  42816. }
  42817. else {
  42818. markers['marker' + name] = {
  42819. textWidth: 10,
  42820. textHeight: 10,
  42821. textBorderRadius: 5,
  42822. textBackgroundColor: markerRich[name]
  42823. };
  42824. }
  42825. text = text.substr(endId + 1);
  42826. startId = text.indexOf('{marker');
  42827. }
  42828. var textStyleModel = tooltipModel.getModel('textStyle');
  42829. var fontSize = textStyleModel.get('fontSize');
  42830. var lineHeight = tooltipModel.get('textLineHeight');
  42831. if (lineHeight == null) {
  42832. lineHeight = Math.round(fontSize * 3 / 2);
  42833. }
  42834. this.el = new Text({
  42835. style: setTextStyle({}, textStyleModel, {
  42836. rich: markers,
  42837. text: content,
  42838. textBackgroundColor: tooltipModel.get('backgroundColor'),
  42839. textBorderRadius: tooltipModel.get('borderRadius'),
  42840. textFill: tooltipModel.get('textStyle.color'),
  42841. textPadding: tooltipModel.get('padding'),
  42842. textLineHeight: lineHeight
  42843. }),
  42844. z: tooltipModel.get('z')
  42845. });
  42846. this._zr.add(this.el);
  42847. var self = this;
  42848. this.el.on('mouseover', function () {
  42849. // clear the timeout in hideLater and keep showing tooltip
  42850. if (self._enterable) {
  42851. clearTimeout(self._hideTimeout);
  42852. self._show = true;
  42853. }
  42854. self._inContent = true;
  42855. });
  42856. this.el.on('mouseout', function () {
  42857. if (self._enterable) {
  42858. if (self._show) {
  42859. self.hideLater(self._hideDelay);
  42860. }
  42861. }
  42862. self._inContent = false;
  42863. });
  42864. },
  42865. setEnterable: function (enterable) {
  42866. this._enterable = enterable;
  42867. },
  42868. getSize: function () {
  42869. var bounding = this.el.getBoundingRect();
  42870. return [bounding.width, bounding.height];
  42871. },
  42872. moveTo: function (x, y) {
  42873. if (this.el) {
  42874. var styleCoord = this._styleCoord;
  42875. makeStyleCoord$1(styleCoord, this._zr, x, y);
  42876. this.el.attr('position', [styleCoord[0], styleCoord[1]]);
  42877. }
  42878. },
  42879. hide: function () {
  42880. if (this.el) {
  42881. this.el.hide();
  42882. }
  42883. this._show = false;
  42884. },
  42885. hideLater: function (time) {
  42886. if (this._show && !(this._inContent && this._enterable)) {
  42887. if (time) {
  42888. this._hideDelay = time;
  42889. // Set show false to avoid invoke hideLater multiple times
  42890. this._show = false;
  42891. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  42892. }
  42893. else {
  42894. this.hide();
  42895. }
  42896. }
  42897. },
  42898. isShow: function () {
  42899. return this._show;
  42900. },
  42901. dispose: function () {
  42902. clearTimeout(this._hideTimeout);
  42903. if (this.el) {
  42904. this._zr.remove(this.el);
  42905. }
  42906. },
  42907. getOuterSize: function () {
  42908. var size = this.getSize();
  42909. return {
  42910. width: size[0],
  42911. height: size[1]
  42912. };
  42913. }
  42914. };
  42915. /*
  42916. * Licensed to the Apache Software Foundation (ASF) under one
  42917. * or more contributor license agreements. See the NOTICE file
  42918. * distributed with this work for additional information
  42919. * regarding copyright ownership. The ASF licenses this file
  42920. * to you under the Apache License, Version 2.0 (the
  42921. * "License"); you may not use this file except in compliance
  42922. * with the License. You may obtain a copy of the License at
  42923. *
  42924. * http://www.apache.org/licenses/LICENSE-2.0
  42925. *
  42926. * Unless required by applicable law or agreed to in writing,
  42927. * software distributed under the License is distributed on an
  42928. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42929. * KIND, either express or implied. See the License for the
  42930. * specific language governing permissions and limitations
  42931. * under the License.
  42932. */
  42933. var bind$2 = bind;
  42934. var each$9 = each$1;
  42935. var parsePercent$2 = parsePercent$1;
  42936. var proxyRect = new Rect({
  42937. shape: {x: -1, y: -1, width: 2, height: 2}
  42938. });
  42939. extendComponentView({
  42940. type: 'tooltip',
  42941. init: function (ecModel, api) {
  42942. if (env$1.node) {
  42943. return;
  42944. }
  42945. var tooltipModel = ecModel.getComponent('tooltip');
  42946. var renderMode = tooltipModel.get('renderMode');
  42947. this._renderMode = getTooltipRenderMode(renderMode);
  42948. var tooltipContent;
  42949. if (this._renderMode === 'html') {
  42950. tooltipContent = new TooltipContent(api.getDom(), api, {
  42951. appendToBody: tooltipModel.get('appendToBody', true)
  42952. });
  42953. this._newLine = '<br/>';
  42954. }
  42955. else {
  42956. tooltipContent = new TooltipRichContent(api);
  42957. this._newLine = '\n';
  42958. }
  42959. this._tooltipContent = tooltipContent;
  42960. },
  42961. render: function (tooltipModel, ecModel, api) {
  42962. if (env$1.node) {
  42963. return;
  42964. }
  42965. // Reset
  42966. this.group.removeAll();
  42967. /**
  42968. * @private
  42969. * @type {module:echarts/component/tooltip/TooltipModel}
  42970. */
  42971. this._tooltipModel = tooltipModel;
  42972. /**
  42973. * @private
  42974. * @type {module:echarts/model/Global}
  42975. */
  42976. this._ecModel = ecModel;
  42977. /**
  42978. * @private
  42979. * @type {module:echarts/ExtensionAPI}
  42980. */
  42981. this._api = api;
  42982. /**
  42983. * Should be cleaned when render.
  42984. * @private
  42985. * @type {Array.<Array.<Object>>}
  42986. */
  42987. this._lastDataByCoordSys = null;
  42988. /**
  42989. * @private
  42990. * @type {boolean}
  42991. */
  42992. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  42993. var tooltipContent = this._tooltipContent;
  42994. tooltipContent.update(tooltipModel);
  42995. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  42996. this._initGlobalListener();
  42997. this._keepShow();
  42998. },
  42999. _initGlobalListener: function () {
  43000. var tooltipModel = this._tooltipModel;
  43001. var triggerOn = tooltipModel.get('triggerOn');
  43002. register(
  43003. 'itemTooltip',
  43004. this._api,
  43005. bind$2(function (currTrigger, e, dispatchAction) {
  43006. // If 'none', it is not controlled by mouse totally.
  43007. if (triggerOn !== 'none') {
  43008. if (triggerOn.indexOf(currTrigger) >= 0) {
  43009. this._tryShow(e, dispatchAction);
  43010. }
  43011. else if (currTrigger === 'leave') {
  43012. this._hide(dispatchAction);
  43013. }
  43014. }
  43015. }, this)
  43016. );
  43017. },
  43018. _keepShow: function () {
  43019. var tooltipModel = this._tooltipModel;
  43020. var ecModel = this._ecModel;
  43021. var api = this._api;
  43022. // Try to keep the tooltip show when refreshing
  43023. if (this._lastX != null
  43024. && this._lastY != null
  43025. // When user is willing to control tooltip totally using API,
  43026. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  43027. // which is not expected.
  43028. && tooltipModel.get('triggerOn') !== 'none'
  43029. ) {
  43030. var self = this;
  43031. clearTimeout(this._refreshUpdateTimeout);
  43032. this._refreshUpdateTimeout = setTimeout(function () {
  43033. // Show tip next tick after other charts are rendered
  43034. // In case highlight action has wrong result
  43035. // FIXME
  43036. !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
  43037. x: self._lastX,
  43038. y: self._lastY
  43039. });
  43040. });
  43041. }
  43042. },
  43043. /**
  43044. * Show tip manually by
  43045. * dispatchAction({
  43046. * type: 'showTip',
  43047. * x: 10,
  43048. * y: 10
  43049. * });
  43050. * Or
  43051. * dispatchAction({
  43052. * type: 'showTip',
  43053. * seriesIndex: 0,
  43054. * dataIndex or dataIndexInside or name
  43055. * });
  43056. *
  43057. * TODO Batch
  43058. */
  43059. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  43060. if (payload.from === this.uid || env$1.node) {
  43061. return;
  43062. }
  43063. var dispatchAction = makeDispatchAction$1(payload, api);
  43064. // Reset ticket
  43065. this._ticket = '';
  43066. // When triggered from axisPointer.
  43067. var dataByCoordSys = payload.dataByCoordSys;
  43068. if (payload.tooltip && payload.x != null && payload.y != null) {
  43069. var el = proxyRect;
  43070. el.position = [payload.x, payload.y];
  43071. el.update();
  43072. el.tooltip = payload.tooltip;
  43073. // Manually show tooltip while view is not using zrender elements.
  43074. this._tryShow({
  43075. offsetX: payload.x,
  43076. offsetY: payload.y,
  43077. target: el
  43078. }, dispatchAction);
  43079. }
  43080. else if (dataByCoordSys) {
  43081. this._tryShow({
  43082. offsetX: payload.x,
  43083. offsetY: payload.y,
  43084. position: payload.position,
  43085. dataByCoordSys: payload.dataByCoordSys,
  43086. tooltipOption: payload.tooltipOption
  43087. }, dispatchAction);
  43088. }
  43089. else if (payload.seriesIndex != null) {
  43090. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  43091. return;
  43092. }
  43093. var pointInfo = findPointFromSeries(payload, ecModel);
  43094. var cx = pointInfo.point[0];
  43095. var cy = pointInfo.point[1];
  43096. if (cx != null && cy != null) {
  43097. this._tryShow({
  43098. offsetX: cx,
  43099. offsetY: cy,
  43100. position: payload.position,
  43101. target: pointInfo.el
  43102. }, dispatchAction);
  43103. }
  43104. }
  43105. else if (payload.x != null && payload.y != null) {
  43106. // FIXME
  43107. // should wrap dispatchAction like `axisPointer/globalListener` ?
  43108. api.dispatchAction({
  43109. type: 'updateAxisPointer',
  43110. x: payload.x,
  43111. y: payload.y
  43112. });
  43113. this._tryShow({
  43114. offsetX: payload.x,
  43115. offsetY: payload.y,
  43116. position: payload.position,
  43117. target: api.getZr().findHover(payload.x, payload.y).target
  43118. }, dispatchAction);
  43119. }
  43120. },
  43121. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  43122. var tooltipContent = this._tooltipContent;
  43123. if (!this._alwaysShowContent && this._tooltipModel) {
  43124. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  43125. }
  43126. this._lastX = this._lastY = null;
  43127. if (payload.from !== this.uid) {
  43128. this._hide(makeDispatchAction$1(payload, api));
  43129. }
  43130. },
  43131. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  43132. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  43133. // and tooltip.
  43134. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  43135. var seriesIndex = payload.seriesIndex;
  43136. var dataIndex = payload.dataIndex;
  43137. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  43138. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  43139. return;
  43140. }
  43141. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  43142. if (!seriesModel) {
  43143. return;
  43144. }
  43145. var data = seriesModel.getData();
  43146. var tooltipModel = buildTooltipModel([
  43147. data.getItemModel(dataIndex),
  43148. seriesModel,
  43149. (seriesModel.coordinateSystem || {}).model,
  43150. tooltipModel
  43151. ]);
  43152. if (tooltipModel.get('trigger') !== 'axis') {
  43153. return;
  43154. }
  43155. api.dispatchAction({
  43156. type: 'updateAxisPointer',
  43157. seriesIndex: seriesIndex,
  43158. dataIndex: dataIndex,
  43159. position: payload.position
  43160. });
  43161. return true;
  43162. },
  43163. _tryShow: function (e, dispatchAction) {
  43164. var el = e.target;
  43165. var tooltipModel = this._tooltipModel;
  43166. if (!tooltipModel) {
  43167. return;
  43168. }
  43169. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  43170. this._lastX = e.offsetX;
  43171. this._lastY = e.offsetY;
  43172. var dataByCoordSys = e.dataByCoordSys;
  43173. if (dataByCoordSys && dataByCoordSys.length) {
  43174. this._showAxisTooltip(dataByCoordSys, e);
  43175. }
  43176. // Always show item tooltip if mouse is on the element with dataIndex
  43177. else if (el && el.dataIndex != null) {
  43178. this._lastDataByCoordSys = null;
  43179. this._showSeriesItemTooltip(e, el, dispatchAction);
  43180. }
  43181. // Tooltip provided directly. Like legend.
  43182. else if (el && el.tooltip) {
  43183. this._lastDataByCoordSys = null;
  43184. this._showComponentItemTooltip(e, el, dispatchAction);
  43185. }
  43186. else {
  43187. this._lastDataByCoordSys = null;
  43188. this._hide(dispatchAction);
  43189. }
  43190. },
  43191. _showOrMove: function (tooltipModel, cb) {
  43192. // showDelay is used in this case: tooltip.enterable is set
  43193. // as true. User intent to move mouse into tooltip and click
  43194. // something. `showDelay` makes it easier to enter the content
  43195. // but tooltip do not move immediately.
  43196. var delay = tooltipModel.get('showDelay');
  43197. cb = bind(cb, this);
  43198. clearTimeout(this._showTimout);
  43199. delay > 0
  43200. ? (this._showTimout = setTimeout(cb, delay))
  43201. : cb();
  43202. },
  43203. _showAxisTooltip: function (dataByCoordSys, e) {
  43204. var ecModel = this._ecModel;
  43205. var globalTooltipModel = this._tooltipModel;
  43206. var point = [e.offsetX, e.offsetY];
  43207. var singleDefaultHTML = [];
  43208. var singleParamsList = [];
  43209. var singleTooltipModel = buildTooltipModel([
  43210. e.tooltipOption,
  43211. globalTooltipModel
  43212. ]);
  43213. var renderMode = this._renderMode;
  43214. var newLine = this._newLine;
  43215. var markers = {};
  43216. each$9(dataByCoordSys, function (itemCoordSys) {
  43217. // var coordParamList = [];
  43218. // var coordDefaultHTML = [];
  43219. // var coordTooltipModel = buildTooltipModel([
  43220. // e.tooltipOption,
  43221. // itemCoordSys.tooltipOption,
  43222. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  43223. // globalTooltipModel
  43224. // ]);
  43225. // var displayMode = coordTooltipModel.get('displayMode');
  43226. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  43227. each$9(itemCoordSys.dataByAxis, function (item) {
  43228. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  43229. var axisValue = item.value;
  43230. var seriesDefaultHTML = [];
  43231. if (!axisModel || axisValue == null) {
  43232. return;
  43233. }
  43234. var valueLabel = getValueLabel(
  43235. axisValue, axisModel.axis, ecModel,
  43236. item.seriesDataIndices,
  43237. item.valueLabelOpt
  43238. );
  43239. each$1(item.seriesDataIndices, function (idxItem) {
  43240. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  43241. var dataIndex = idxItem.dataIndexInside;
  43242. var dataParams = series && series.getDataParams(dataIndex);
  43243. dataParams.axisDim = item.axisDim;
  43244. dataParams.axisIndex = item.axisIndex;
  43245. dataParams.axisType = item.axisType;
  43246. dataParams.axisId = item.axisId;
  43247. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  43248. dataParams.axisValueLabel = valueLabel;
  43249. if (dataParams) {
  43250. singleParamsList.push(dataParams);
  43251. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  43252. var html;
  43253. if (isObject$1(seriesTooltip)) {
  43254. html = seriesTooltip.html;
  43255. var newMarkers = seriesTooltip.markers;
  43256. merge(markers, newMarkers);
  43257. }
  43258. else {
  43259. html = seriesTooltip;
  43260. }
  43261. seriesDefaultHTML.push(html);
  43262. }
  43263. });
  43264. // Default tooltip content
  43265. // FIXME
  43266. // (1) should be the first data which has name?
  43267. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  43268. var firstLine = valueLabel;
  43269. if (renderMode !== 'html') {
  43270. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  43271. }
  43272. else {
  43273. singleDefaultHTML.push(
  43274. (firstLine ? encodeHTML(firstLine) + newLine : '')
  43275. + seriesDefaultHTML.join(newLine)
  43276. );
  43277. }
  43278. });
  43279. }, this);
  43280. // In most case, the second axis is shown upper than the first one.
  43281. singleDefaultHTML.reverse();
  43282. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  43283. var positionExpr = e.position;
  43284. this._showOrMove(singleTooltipModel, function () {
  43285. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  43286. this._updatePosition(
  43287. singleTooltipModel,
  43288. positionExpr,
  43289. point[0], point[1],
  43290. this._tooltipContent,
  43291. singleParamsList
  43292. );
  43293. }
  43294. else {
  43295. this._showTooltipContent(
  43296. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  43297. point[0], point[1], positionExpr, undefined, markers
  43298. );
  43299. }
  43300. });
  43301. // Do not trigger events here, because this branch only be entered
  43302. // from dispatchAction.
  43303. },
  43304. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  43305. var ecModel = this._ecModel;
  43306. // Use dataModel in element if possible
  43307. // Used when mouseover on a element like markPoint or edge
  43308. // In which case, the data is not main data in series.
  43309. var seriesIndex = el.seriesIndex;
  43310. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  43311. // For example, graph link.
  43312. var dataModel = el.dataModel || seriesModel;
  43313. var dataIndex = el.dataIndex;
  43314. var dataType = el.dataType;
  43315. var data = dataModel.getData(dataType);
  43316. var tooltipModel = buildTooltipModel([
  43317. data.getItemModel(dataIndex),
  43318. dataModel,
  43319. seriesModel && (seriesModel.coordinateSystem || {}).model,
  43320. this._tooltipModel
  43321. ]);
  43322. var tooltipTrigger = tooltipModel.get('trigger');
  43323. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  43324. return;
  43325. }
  43326. var params = dataModel.getDataParams(dataIndex, dataType);
  43327. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  43328. var defaultHtml;
  43329. var markers;
  43330. if (isObject$1(seriesTooltip)) {
  43331. defaultHtml = seriesTooltip.html;
  43332. markers = seriesTooltip.markers;
  43333. }
  43334. else {
  43335. defaultHtml = seriesTooltip;
  43336. markers = null;
  43337. }
  43338. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  43339. this._showOrMove(tooltipModel, function () {
  43340. this._showTooltipContent(
  43341. tooltipModel, defaultHtml, params, asyncTicket,
  43342. e.offsetX, e.offsetY, e.position, e.target, markers
  43343. );
  43344. });
  43345. // FIXME
  43346. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  43347. dispatchAction({
  43348. type: 'showTip',
  43349. dataIndexInside: dataIndex,
  43350. dataIndex: data.getRawIndex(dataIndex),
  43351. seriesIndex: seriesIndex,
  43352. from: this.uid
  43353. });
  43354. },
  43355. _showComponentItemTooltip: function (e, el, dispatchAction) {
  43356. var tooltipOpt = el.tooltip;
  43357. if (typeof tooltipOpt === 'string') {
  43358. var content = tooltipOpt;
  43359. tooltipOpt = {
  43360. content: content,
  43361. // Fixed formatter
  43362. formatter: content
  43363. };
  43364. }
  43365. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  43366. var defaultHtml = subTooltipModel.get('content');
  43367. var asyncTicket = Math.random();
  43368. // Do not check whether `trigger` is 'none' here, because `trigger`
  43369. // only works on coordinate system. In fact, we have not found case
  43370. // that requires setting `trigger` nothing on component yet.
  43371. this._showOrMove(subTooltipModel, function () {
  43372. this._showTooltipContent(
  43373. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  43374. asyncTicket, e.offsetX, e.offsetY, e.position, el
  43375. );
  43376. });
  43377. // If not dispatch showTip, tip may be hide triggered by axis.
  43378. dispatchAction({
  43379. type: 'showTip',
  43380. from: this.uid
  43381. });
  43382. },
  43383. _showTooltipContent: function (
  43384. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  43385. ) {
  43386. // Reset ticket
  43387. this._ticket = '';
  43388. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  43389. return;
  43390. }
  43391. var tooltipContent = this._tooltipContent;
  43392. var formatter = tooltipModel.get('formatter');
  43393. positionExpr = positionExpr || tooltipModel.get('position');
  43394. var html = defaultHtml;
  43395. if (formatter && typeof formatter === 'string') {
  43396. html = formatTpl(formatter, params, true);
  43397. }
  43398. else if (typeof formatter === 'function') {
  43399. var callback = bind$2(function (cbTicket, html) {
  43400. if (cbTicket === this._ticket) {
  43401. tooltipContent.setContent(html, markers, tooltipModel);
  43402. this._updatePosition(
  43403. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  43404. );
  43405. }
  43406. }, this);
  43407. this._ticket = asyncTicket;
  43408. html = formatter(params, asyncTicket, callback);
  43409. }
  43410. tooltipContent.setContent(html, markers, tooltipModel);
  43411. tooltipContent.show(tooltipModel);
  43412. this._updatePosition(
  43413. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  43414. );
  43415. },
  43416. /**
  43417. * @param {string|Function|Array.<number>|Object} positionExpr
  43418. * @param {number} x Mouse x
  43419. * @param {number} y Mouse y
  43420. * @param {boolean} confine Whether confine tooltip content in view rect.
  43421. * @param {Object|<Array.<Object>} params
  43422. * @param {module:zrender/Element} el target element
  43423. * @param {module:echarts/ExtensionAPI} api
  43424. * @return {Array.<number>}
  43425. */
  43426. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  43427. var viewWidth = this._api.getWidth();
  43428. var viewHeight = this._api.getHeight();
  43429. positionExpr = positionExpr || tooltipModel.get('position');
  43430. var contentSize = content.getSize();
  43431. var align = tooltipModel.get('align');
  43432. var vAlign = tooltipModel.get('verticalAlign');
  43433. var rect = el && el.getBoundingRect().clone();
  43434. el && rect.applyTransform(el.transform);
  43435. if (typeof positionExpr === 'function') {
  43436. // Callback of position can be an array or a string specify the position
  43437. positionExpr = positionExpr([x, y], params, content.el, rect, {
  43438. viewSize: [viewWidth, viewHeight],
  43439. contentSize: contentSize.slice()
  43440. });
  43441. }
  43442. if (isArray(positionExpr)) {
  43443. x = parsePercent$2(positionExpr[0], viewWidth);
  43444. y = parsePercent$2(positionExpr[1], viewHeight);
  43445. }
  43446. else if (isObject$1(positionExpr)) {
  43447. positionExpr.width = contentSize[0];
  43448. positionExpr.height = contentSize[1];
  43449. var layoutRect = getLayoutRect(
  43450. positionExpr, {width: viewWidth, height: viewHeight}
  43451. );
  43452. x = layoutRect.x;
  43453. y = layoutRect.y;
  43454. align = null;
  43455. // When positionExpr is left/top/right/bottom,
  43456. // align and verticalAlign will not work.
  43457. vAlign = null;
  43458. }
  43459. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  43460. else if (typeof positionExpr === 'string' && el) {
  43461. var pos = calcTooltipPosition(
  43462. positionExpr, rect, contentSize
  43463. );
  43464. x = pos[0];
  43465. y = pos[1];
  43466. }
  43467. else {
  43468. var pos = refixTooltipPosition(
  43469. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  43470. );
  43471. x = pos[0];
  43472. y = pos[1];
  43473. }
  43474. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  43475. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  43476. if (tooltipModel.get('confine')) {
  43477. var pos = confineTooltipPosition(
  43478. x, y, content, viewWidth, viewHeight
  43479. );
  43480. x = pos[0];
  43481. y = pos[1];
  43482. }
  43483. content.moveTo(x, y);
  43484. },
  43485. // FIXME
  43486. // Should we remove this but leave this to user?
  43487. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  43488. var lastCoordSys = this._lastDataByCoordSys;
  43489. var contentNotChanged = !!lastCoordSys
  43490. && lastCoordSys.length === dataByCoordSys.length;
  43491. contentNotChanged && each$9(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  43492. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  43493. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  43494. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  43495. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  43496. contentNotChanged && each$9(lastDataByAxis, function (lastItem, indexAxis) {
  43497. var thisItem = thisDataByAxis[indexAxis] || {};
  43498. var lastIndices = lastItem.seriesDataIndices || [];
  43499. var newIndices = thisItem.seriesDataIndices || [];
  43500. contentNotChanged
  43501. &= lastItem.value === thisItem.value
  43502. && lastItem.axisType === thisItem.axisType
  43503. && lastItem.axisId === thisItem.axisId
  43504. && lastIndices.length === newIndices.length;
  43505. contentNotChanged && each$9(lastIndices, function (lastIdxItem, j) {
  43506. var newIdxItem = newIndices[j];
  43507. contentNotChanged
  43508. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  43509. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  43510. });
  43511. });
  43512. });
  43513. this._lastDataByCoordSys = dataByCoordSys;
  43514. return !!contentNotChanged;
  43515. },
  43516. _hide: function (dispatchAction) {
  43517. // Do not directly hideLater here, because this behavior may be prevented
  43518. // in dispatchAction when showTip is dispatched.
  43519. // FIXME
  43520. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  43521. this._lastDataByCoordSys = null;
  43522. dispatchAction({
  43523. type: 'hideTip',
  43524. from: this.uid
  43525. });
  43526. },
  43527. dispose: function (ecModel, api) {
  43528. if (env$1.node) {
  43529. return;
  43530. }
  43531. this._tooltipContent.dispose();
  43532. unregister('itemTooltip', api);
  43533. }
  43534. });
  43535. /**
  43536. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  43537. * From top to bottom. (the last one should be globalTooltipModel);
  43538. */
  43539. function buildTooltipModel(modelCascade) {
  43540. var resultModel = modelCascade.pop();
  43541. while (modelCascade.length) {
  43542. var tooltipOpt = modelCascade.pop();
  43543. if (tooltipOpt) {
  43544. if (Model.isInstance(tooltipOpt)) {
  43545. tooltipOpt = tooltipOpt.get('tooltip', true);
  43546. }
  43547. // In each data item tooltip can be simply write:
  43548. // {
  43549. // value: 10,
  43550. // tooltip: 'Something you need to know'
  43551. // }
  43552. if (typeof tooltipOpt === 'string') {
  43553. tooltipOpt = {formatter: tooltipOpt};
  43554. }
  43555. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  43556. }
  43557. }
  43558. return resultModel;
  43559. }
  43560. function makeDispatchAction$1(payload, api) {
  43561. return payload.dispatchAction || bind(api.dispatchAction, api);
  43562. }
  43563. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  43564. var size = content.getOuterSize();
  43565. var width = size.width;
  43566. var height = size.height;
  43567. if (gapH != null) {
  43568. if (x + width + gapH > viewWidth) {
  43569. x -= width + gapH;
  43570. }
  43571. else {
  43572. x += gapH;
  43573. }
  43574. }
  43575. if (gapV != null) {
  43576. if (y + height + gapV > viewHeight) {
  43577. y -= height + gapV;
  43578. }
  43579. else {
  43580. y += gapV;
  43581. }
  43582. }
  43583. return [x, y];
  43584. }
  43585. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  43586. var size = content.getOuterSize();
  43587. var width = size.width;
  43588. var height = size.height;
  43589. x = Math.min(x + width, viewWidth) - width;
  43590. y = Math.min(y + height, viewHeight) - height;
  43591. x = Math.max(x, 0);
  43592. y = Math.max(y, 0);
  43593. return [x, y];
  43594. }
  43595. function calcTooltipPosition(position, rect, contentSize) {
  43596. var domWidth = contentSize[0];
  43597. var domHeight = contentSize[1];
  43598. var gap = 5;
  43599. var x = 0;
  43600. var y = 0;
  43601. var rectWidth = rect.width;
  43602. var rectHeight = rect.height;
  43603. switch (position) {
  43604. case 'inside':
  43605. x = rect.x + rectWidth / 2 - domWidth / 2;
  43606. y = rect.y + rectHeight / 2 - domHeight / 2;
  43607. break;
  43608. case 'top':
  43609. x = rect.x + rectWidth / 2 - domWidth / 2;
  43610. y = rect.y - domHeight - gap;
  43611. break;
  43612. case 'bottom':
  43613. x = rect.x + rectWidth / 2 - domWidth / 2;
  43614. y = rect.y + rectHeight + gap;
  43615. break;
  43616. case 'left':
  43617. x = rect.x - domWidth - gap;
  43618. y = rect.y + rectHeight / 2 - domHeight / 2;
  43619. break;
  43620. case 'right':
  43621. x = rect.x + rectWidth + gap;
  43622. y = rect.y + rectHeight / 2 - domHeight / 2;
  43623. }
  43624. return [x, y];
  43625. }
  43626. function isCenterAlign(align) {
  43627. return align === 'center' || align === 'middle';
  43628. }
  43629. /*
  43630. * Licensed to the Apache Software Foundation (ASF) under one
  43631. * or more contributor license agreements. See the NOTICE file
  43632. * distributed with this work for additional information
  43633. * regarding copyright ownership. The ASF licenses this file
  43634. * to you under the Apache License, Version 2.0 (the
  43635. * "License"); you may not use this file except in compliance
  43636. * with the License. You may obtain a copy of the License at
  43637. *
  43638. * http://www.apache.org/licenses/LICENSE-2.0
  43639. *
  43640. * Unless required by applicable law or agreed to in writing,
  43641. * software distributed under the License is distributed on an
  43642. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43643. * KIND, either express or implied. See the License for the
  43644. * specific language governing permissions and limitations
  43645. * under the License.
  43646. */
  43647. // FIXME Better way to pack data in graphic element
  43648. /**
  43649. * @action
  43650. * @property {string} type
  43651. * @property {number} seriesIndex
  43652. * @property {number} dataIndex
  43653. * @property {number} [x]
  43654. * @property {number} [y]
  43655. */
  43656. registerAction(
  43657. {
  43658. type: 'showTip',
  43659. event: 'showTip',
  43660. update: 'tooltip:manuallyShowTip'
  43661. },
  43662. // noop
  43663. function () {}
  43664. );
  43665. registerAction(
  43666. {
  43667. type: 'hideTip',
  43668. event: 'hideTip',
  43669. update: 'tooltip:manuallyHideTip'
  43670. },
  43671. // noop
  43672. function () {}
  43673. );
  43674. /*
  43675. * Licensed to the Apache Software Foundation (ASF) under one
  43676. * or more contributor license agreements. See the NOTICE file
  43677. * distributed with this work for additional information
  43678. * regarding copyright ownership. The ASF licenses this file
  43679. * to you under the Apache License, Version 2.0 (the
  43680. * "License"); you may not use this file except in compliance
  43681. * with the License. You may obtain a copy of the License at
  43682. *
  43683. * http://www.apache.org/licenses/LICENSE-2.0
  43684. *
  43685. * Unless required by applicable law or agreed to in writing,
  43686. * software distributed under the License is distributed on an
  43687. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43688. * KIND, either express or implied. See the License for the
  43689. * specific language governing permissions and limitations
  43690. * under the License.
  43691. */
  43692. var langSelector = lang.legend.selector;
  43693. var defaultSelectorOption = {
  43694. all: {
  43695. type: 'all',
  43696. title: clone(langSelector.all)
  43697. },
  43698. inverse: {
  43699. type: 'inverse',
  43700. title: clone(langSelector.inverse)
  43701. }
  43702. };
  43703. var LegendModel = extendComponentModel({
  43704. type: 'legend.plain',
  43705. dependencies: ['series'],
  43706. layoutMode: {
  43707. type: 'box',
  43708. // legend.width/height are maxWidth/maxHeight actually,
  43709. // whereas realy width/height is calculated by its content.
  43710. // (Setting {left: 10, right: 10} does not make sense).
  43711. // So consider the case:
  43712. // `setOption({legend: {left: 10});`
  43713. // then `setOption({legend: {right: 10});`
  43714. // The previous `left` should be cleared by setting `ignoreSize`.
  43715. ignoreSize: true
  43716. },
  43717. init: function (option, parentModel, ecModel) {
  43718. this.mergeDefaultAndTheme(option, ecModel);
  43719. option.selected = option.selected || {};
  43720. this._updateSelector(option);
  43721. },
  43722. mergeOption: function (option) {
  43723. LegendModel.superCall(this, 'mergeOption', option);
  43724. this._updateSelector(option);
  43725. },
  43726. _updateSelector: function (option) {
  43727. var selector = option.selector;
  43728. if (selector === true) {
  43729. selector = option.selector = ['all', 'inverse'];
  43730. }
  43731. if (isArray(selector)) {
  43732. each$1(selector, function (item, index) {
  43733. isString(item) && (item = {type: item});
  43734. selector[index] = merge(item, defaultSelectorOption[item.type]);
  43735. });
  43736. }
  43737. },
  43738. optionUpdated: function () {
  43739. this._updateData(this.ecModel);
  43740. var legendData = this._data;
  43741. // If selectedMode is single, try to select one
  43742. if (legendData[0] && this.get('selectedMode') === 'single') {
  43743. var hasSelected = false;
  43744. // If has any selected in option.selected
  43745. for (var i = 0; i < legendData.length; i++) {
  43746. var name = legendData[i].get('name');
  43747. if (this.isSelected(name)) {
  43748. // Force to unselect others
  43749. this.select(name);
  43750. hasSelected = true;
  43751. break;
  43752. }
  43753. }
  43754. // Try select the first if selectedMode is single
  43755. !hasSelected && this.select(legendData[0].get('name'));
  43756. }
  43757. },
  43758. _updateData: function (ecModel) {
  43759. var potentialData = [];
  43760. var availableNames = [];
  43761. ecModel.eachRawSeries(function (seriesModel) {
  43762. var seriesName = seriesModel.name;
  43763. availableNames.push(seriesName);
  43764. var isPotential;
  43765. if (seriesModel.legendVisualProvider) {
  43766. var provider = seriesModel.legendVisualProvider;
  43767. var names = provider.getAllNames();
  43768. if (!ecModel.isSeriesFiltered(seriesModel)) {
  43769. availableNames = availableNames.concat(names);
  43770. }
  43771. if (names.length) {
  43772. potentialData = potentialData.concat(names);
  43773. }
  43774. else {
  43775. isPotential = true;
  43776. }
  43777. }
  43778. else {
  43779. isPotential = true;
  43780. }
  43781. if (isPotential && isNameSpecified(seriesModel)) {
  43782. potentialData.push(seriesModel.name);
  43783. }
  43784. });
  43785. /**
  43786. * @type {Array.<string>}
  43787. * @private
  43788. */
  43789. this._availableNames = availableNames;
  43790. // If legend.data not specified in option, use availableNames as data,
  43791. // which is convinient for user preparing option.
  43792. var rawData = this.get('data') || potentialData;
  43793. var legendData = map(rawData, function (dataItem) {
  43794. // Can be string or number
  43795. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  43796. dataItem = {
  43797. name: dataItem
  43798. };
  43799. }
  43800. return new Model(dataItem, this, this.ecModel);
  43801. }, this);
  43802. /**
  43803. * @type {Array.<module:echarts/model/Model>}
  43804. * @private
  43805. */
  43806. this._data = legendData;
  43807. },
  43808. /**
  43809. * @return {Array.<module:echarts/model/Model>}
  43810. */
  43811. getData: function () {
  43812. return this._data;
  43813. },
  43814. /**
  43815. * @param {string} name
  43816. */
  43817. select: function (name) {
  43818. var selected = this.option.selected;
  43819. var selectedMode = this.get('selectedMode');
  43820. if (selectedMode === 'single') {
  43821. var data = this._data;
  43822. each$1(data, function (dataItem) {
  43823. selected[dataItem.get('name')] = false;
  43824. });
  43825. }
  43826. selected[name] = true;
  43827. },
  43828. /**
  43829. * @param {string} name
  43830. */
  43831. unSelect: function (name) {
  43832. if (this.get('selectedMode') !== 'single') {
  43833. this.option.selected[name] = false;
  43834. }
  43835. },
  43836. /**
  43837. * @param {string} name
  43838. */
  43839. toggleSelected: function (name) {
  43840. var selected = this.option.selected;
  43841. // Default is true
  43842. if (!selected.hasOwnProperty(name)) {
  43843. selected[name] = true;
  43844. }
  43845. this[selected[name] ? 'unSelect' : 'select'](name);
  43846. },
  43847. allSelect: function () {
  43848. var data = this._data;
  43849. var selected = this.option.selected;
  43850. each$1(data, function (dataItem) {
  43851. selected[dataItem.get('name', true)] = true;
  43852. });
  43853. },
  43854. inverseSelect: function () {
  43855. var data = this._data;
  43856. var selected = this.option.selected;
  43857. each$1(data, function (dataItem) {
  43858. var name = dataItem.get('name', true);
  43859. // Initially, default value is true
  43860. if (!selected.hasOwnProperty(name)) {
  43861. selected[name] = true;
  43862. }
  43863. selected[name] = !selected[name];
  43864. });
  43865. },
  43866. /**
  43867. * @param {string} name
  43868. */
  43869. isSelected: function (name) {
  43870. var selected = this.option.selected;
  43871. return !(selected.hasOwnProperty(name) && !selected[name])
  43872. && indexOf(this._availableNames, name) >= 0;
  43873. },
  43874. getOrient: function () {
  43875. return this.get('orient') === 'vertical'
  43876. ? {index: 1, name: 'vertical'}
  43877. : {index: 0, name: 'horizontal'};
  43878. },
  43879. defaultOption: {
  43880. // 一级层叠
  43881. zlevel: 0,
  43882. // 二级层叠
  43883. z: 4,
  43884. show: true,
  43885. // 布局方式,默认为水平布局,可选为:
  43886. // 'horizontal' | 'vertical'
  43887. orient: 'horizontal',
  43888. left: 'center',
  43889. // right: 'center',
  43890. top: 0,
  43891. // bottom: null,
  43892. // 水平对齐
  43893. // 'auto' | 'left' | 'right'
  43894. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  43895. align: 'auto',
  43896. backgroundColor: 'rgba(0,0,0,0)',
  43897. // 图例边框颜色
  43898. borderColor: '#ccc',
  43899. borderRadius: 0,
  43900. // 图例边框线宽,单位px,默认为0(无边框)
  43901. borderWidth: 0,
  43902. // 图例内边距,单位px,默认各方向内边距为5,
  43903. // 接受数组分别设定上右下左边距,同css
  43904. padding: 5,
  43905. // 各个item之间的间隔,单位px,默认为10,
  43906. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  43907. itemGap: 10,
  43908. // the width of legend symbol
  43909. itemWidth: 25,
  43910. // the height of legend symbol
  43911. itemHeight: 14,
  43912. // the color of unselected legend symbol
  43913. inactiveColor: '#ccc',
  43914. // the borderColor of unselected legend symbol
  43915. inactiveBorderColor: '#ccc',
  43916. itemStyle: {
  43917. // the default borderWidth of legend symbol
  43918. borderWidth: 0
  43919. },
  43920. textStyle: {
  43921. // 图例文字颜色
  43922. color: '#333'
  43923. },
  43924. // formatter: '',
  43925. // 选择模式,默认开启图例开关
  43926. selectedMode: true,
  43927. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  43928. // selected: null,
  43929. // 图例内容(详见legend.data,数组中每一项代表一个item
  43930. // data: [],
  43931. // Usage:
  43932. // selector: [{type: 'all or inverse', title: xxx}]
  43933. // or
  43934. // selector: true
  43935. // or
  43936. // selector: ['all', 'inverse']
  43937. selector: false,
  43938. selectorLabel: {
  43939. show: true,
  43940. borderRadius: 10,
  43941. padding: [3, 5, 3, 5],
  43942. fontSize: 12,
  43943. fontFamily: ' sans-serif',
  43944. color: '#666',
  43945. borderWidth: 1,
  43946. borderColor: '#666'
  43947. },
  43948. emphasis: {
  43949. selectorLabel: {
  43950. show: true,
  43951. color: '#eee',
  43952. backgroundColor: '#666'
  43953. }
  43954. },
  43955. // Value can be 'start' or 'end'
  43956. selectorPosition: 'auto',
  43957. selectorItemGap: 7,
  43958. selectorButtonGap: 10,
  43959. // Tooltip 相关配置
  43960. tooltip: {
  43961. show: false
  43962. }
  43963. }
  43964. });
  43965. /*
  43966. * Licensed to the Apache Software Foundation (ASF) under one
  43967. * or more contributor license agreements. See the NOTICE file
  43968. * distributed with this work for additional information
  43969. * regarding copyright ownership. The ASF licenses this file
  43970. * to you under the Apache License, Version 2.0 (the
  43971. * "License"); you may not use this file except in compliance
  43972. * with the License. You may obtain a copy of the License at
  43973. *
  43974. * http://www.apache.org/licenses/LICENSE-2.0
  43975. *
  43976. * Unless required by applicable law or agreed to in writing,
  43977. * software distributed under the License is distributed on an
  43978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43979. * KIND, either express or implied. See the License for the
  43980. * specific language governing permissions and limitations
  43981. * under the License.
  43982. */
  43983. function legendSelectActionHandler(methodName, payload, ecModel) {
  43984. var selectedMap = {};
  43985. var isToggleSelect = methodName === 'toggleSelected';
  43986. var isSelected;
  43987. // Update all legend components
  43988. ecModel.eachComponent('legend', function (legendModel) {
  43989. if (isToggleSelect && isSelected != null) {
  43990. // Force other legend has same selected status
  43991. // Or the first is toggled to true and other are toggled to false
  43992. // In the case one legend has some item unSelected in option. And if other legend
  43993. // doesn't has the item, they will assume it is selected.
  43994. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  43995. }
  43996. else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  43997. legendModel[methodName]();
  43998. }
  43999. else {
  44000. legendModel[methodName](payload.name);
  44001. isSelected = legendModel.isSelected(payload.name);
  44002. }
  44003. var legendData = legendModel.getData();
  44004. each$1(legendData, function (model) {
  44005. var name = model.get('name');
  44006. // Wrap element
  44007. if (name === '\n' || name === '') {
  44008. return;
  44009. }
  44010. var isItemSelected = legendModel.isSelected(name);
  44011. if (selectedMap.hasOwnProperty(name)) {
  44012. // Unselected if any legend is unselected
  44013. selectedMap[name] = selectedMap[name] && isItemSelected;
  44014. }
  44015. else {
  44016. selectedMap[name] = isItemSelected;
  44017. }
  44018. });
  44019. });
  44020. // Return the event explicitly
  44021. return (methodName === 'allSelect' || methodName === 'inverseSelect')
  44022. ? {
  44023. selected: selectedMap
  44024. }
  44025. : {
  44026. name: payload.name,
  44027. selected: selectedMap
  44028. };
  44029. }
  44030. /**
  44031. * @event legendToggleSelect
  44032. * @type {Object}
  44033. * @property {string} type 'legendToggleSelect'
  44034. * @property {string} [from]
  44035. * @property {string} name Series name or data item name
  44036. */
  44037. registerAction(
  44038. 'legendToggleSelect', 'legendselectchanged',
  44039. curry(legendSelectActionHandler, 'toggleSelected')
  44040. );
  44041. registerAction(
  44042. 'legendAllSelect', 'legendselectall',
  44043. curry(legendSelectActionHandler, 'allSelect')
  44044. );
  44045. registerAction(
  44046. 'legendInverseSelect', 'legendinverseselect',
  44047. curry(legendSelectActionHandler, 'inverseSelect')
  44048. );
  44049. /**
  44050. * @event legendSelect
  44051. * @type {Object}
  44052. * @property {string} type 'legendSelect'
  44053. * @property {string} name Series name or data item name
  44054. */
  44055. registerAction(
  44056. 'legendSelect', 'legendselected',
  44057. curry(legendSelectActionHandler, 'select')
  44058. );
  44059. /**
  44060. * @event legendUnSelect
  44061. * @type {Object}
  44062. * @property {string} type 'legendUnSelect'
  44063. * @property {string} name Series name or data item name
  44064. */
  44065. registerAction(
  44066. 'legendUnSelect', 'legendunselected',
  44067. curry(legendSelectActionHandler, 'unSelect')
  44068. );
  44069. /*
  44070. * Licensed to the Apache Software Foundation (ASF) under one
  44071. * or more contributor license agreements. See the NOTICE file
  44072. * distributed with this work for additional information
  44073. * regarding copyright ownership. The ASF licenses this file
  44074. * to you under the Apache License, Version 2.0 (the
  44075. * "License"); you may not use this file except in compliance
  44076. * with the License. You may obtain a copy of the License at
  44077. *
  44078. * http://www.apache.org/licenses/LICENSE-2.0
  44079. *
  44080. * Unless required by applicable law or agreed to in writing,
  44081. * software distributed under the License is distributed on an
  44082. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44083. * KIND, either express or implied. See the License for the
  44084. * specific language governing permissions and limitations
  44085. * under the License.
  44086. */
  44087. /**
  44088. * Layout list like component.
  44089. * It will box layout each items in group of component and then position the whole group in the viewport
  44090. * @param {module:zrender/group/Group} group
  44091. * @param {module:echarts/model/Component} componentModel
  44092. * @param {module:echarts/ExtensionAPI}
  44093. */
  44094. function layout$2(group, componentModel, api) {
  44095. var boxLayoutParams = componentModel.getBoxLayoutParams();
  44096. var padding = componentModel.get('padding');
  44097. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  44098. var rect = getLayoutRect(
  44099. boxLayoutParams,
  44100. viewportSize,
  44101. padding
  44102. );
  44103. box(
  44104. componentModel.get('orient'),
  44105. group,
  44106. componentModel.get('itemGap'),
  44107. rect.width,
  44108. rect.height
  44109. );
  44110. positionElement(
  44111. group,
  44112. boxLayoutParams,
  44113. viewportSize,
  44114. padding
  44115. );
  44116. }
  44117. function makeBackground(rect, componentModel) {
  44118. var padding = normalizeCssArray$1(
  44119. componentModel.get('padding')
  44120. );
  44121. var style = componentModel.getItemStyle(['color', 'opacity']);
  44122. style.fill = componentModel.get('backgroundColor');
  44123. var rect = new Rect({
  44124. shape: {
  44125. x: rect.x - padding[3],
  44126. y: rect.y - padding[0],
  44127. width: rect.width + padding[1] + padding[3],
  44128. height: rect.height + padding[0] + padding[2],
  44129. r: componentModel.get('borderRadius')
  44130. },
  44131. style: style,
  44132. silent: true,
  44133. z2: -1
  44134. });
  44135. // FIXME
  44136. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  44137. // and background rect when setting like `left: 0`, `top: 0`.
  44138. // graphic.subPixelOptimizeRect(rect);
  44139. return rect;
  44140. }
  44141. /*
  44142. * Licensed to the Apache Software Foundation (ASF) under one
  44143. * or more contributor license agreements. See the NOTICE file
  44144. * distributed with this work for additional information
  44145. * regarding copyright ownership. The ASF licenses this file
  44146. * to you under the Apache License, Version 2.0 (the
  44147. * "License"); you may not use this file except in compliance
  44148. * with the License. You may obtain a copy of the License at
  44149. *
  44150. * http://www.apache.org/licenses/LICENSE-2.0
  44151. *
  44152. * Unless required by applicable law or agreed to in writing,
  44153. * software distributed under the License is distributed on an
  44154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44155. * KIND, either express or implied. See the License for the
  44156. * specific language governing permissions and limitations
  44157. * under the License.
  44158. */
  44159. var curry$3 = curry;
  44160. var each$11 = each$1;
  44161. var Group$2 = Group;
  44162. var LegendView = extendComponentView({
  44163. type: 'legend.plain',
  44164. newlineDisabled: false,
  44165. /**
  44166. * @override
  44167. */
  44168. init: function () {
  44169. /**
  44170. * @private
  44171. * @type {module:zrender/container/Group}
  44172. */
  44173. this.group.add(this._contentGroup = new Group$2());
  44174. /**
  44175. * @private
  44176. * @type {module:zrender/Element}
  44177. */
  44178. this._backgroundEl;
  44179. /**
  44180. * @private
  44181. * @type {module:zrender/container/Group}
  44182. */
  44183. this.group.add(this._selectorGroup = new Group$2());
  44184. /**
  44185. * If first rendering, `contentGroup.position` is [0, 0], which
  44186. * does not make sense and may cause unexepcted animation if adopted.
  44187. * @private
  44188. * @type {boolean}
  44189. */
  44190. this._isFirstRender = true;
  44191. },
  44192. /**
  44193. * @protected
  44194. */
  44195. getContentGroup: function () {
  44196. return this._contentGroup;
  44197. },
  44198. /**
  44199. * @protected
  44200. */
  44201. getSelectorGroup: function () {
  44202. return this._selectorGroup;
  44203. },
  44204. /**
  44205. * @override
  44206. */
  44207. render: function (legendModel, ecModel, api) {
  44208. var isFirstRender = this._isFirstRender;
  44209. this._isFirstRender = false;
  44210. this.resetInner();
  44211. if (!legendModel.get('show', true)) {
  44212. return;
  44213. }
  44214. var itemAlign = legendModel.get('align');
  44215. var orient = legendModel.get('orient');
  44216. if (!itemAlign || itemAlign === 'auto') {
  44217. itemAlign = (
  44218. legendModel.get('left') === 'right'
  44219. && orient === 'vertical'
  44220. ) ? 'right' : 'left';
  44221. }
  44222. var selector = legendModel.get('selector', true);
  44223. var selectorPosition = legendModel.get('selectorPosition', true);
  44224. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  44225. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  44226. }
  44227. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  44228. // Perform layout.
  44229. var positionInfo = legendModel.getBoxLayoutParams();
  44230. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  44231. var padding = legendModel.get('padding');
  44232. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  44233. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  44234. // Place mainGroup, based on the calculated `mainRect`.
  44235. var layoutRect = getLayoutRect(
  44236. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  44237. viewportSize,
  44238. padding
  44239. );
  44240. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  44241. // Render background after group is layout.
  44242. this.group.add(
  44243. this._backgroundEl = makeBackground(mainRect, legendModel)
  44244. );
  44245. },
  44246. /**
  44247. * @protected
  44248. */
  44249. resetInner: function () {
  44250. this.getContentGroup().removeAll();
  44251. this._backgroundEl && this.group.remove(this._backgroundEl);
  44252. this.getSelectorGroup().removeAll();
  44253. },
  44254. /**
  44255. * @protected
  44256. */
  44257. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  44258. var contentGroup = this.getContentGroup();
  44259. var legendDrawnMap = createHashMap();
  44260. var selectMode = legendModel.get('selectedMode');
  44261. var excludeSeriesId = [];
  44262. ecModel.eachRawSeries(function (seriesModel) {
  44263. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  44264. });
  44265. each$11(legendModel.getData(), function (itemModel, dataIndex) {
  44266. var name = itemModel.get('name');
  44267. // Use empty string or \n as a newline string
  44268. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  44269. contentGroup.add(new Group$2({
  44270. newline: true
  44271. }));
  44272. return;
  44273. }
  44274. // Representitive series.
  44275. var seriesModel = ecModel.getSeriesByName(name)[0];
  44276. if (legendDrawnMap.get(name)) {
  44277. // Have been drawed
  44278. return;
  44279. }
  44280. // Legend to control series.
  44281. if (seriesModel) {
  44282. var data = seriesModel.getData();
  44283. var color = data.getVisual('color');
  44284. var borderColor = data.getVisual('borderColor');
  44285. // If color is a callback function
  44286. if (typeof color === 'function') {
  44287. // Use the first data
  44288. color = color(seriesModel.getDataParams(0));
  44289. }
  44290. // If borderColor is a callback function
  44291. if (typeof borderColor === 'function') {
  44292. // Use the first data
  44293. borderColor = borderColor(seriesModel.getDataParams(0));
  44294. }
  44295. // Using rect symbol defaultly
  44296. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  44297. var symbolType = data.getVisual('symbol');
  44298. var itemGroup = this._createItem(
  44299. name, dataIndex, itemModel, legendModel,
  44300. legendSymbolType, symbolType,
  44301. itemAlign, color, borderColor,
  44302. selectMode
  44303. );
  44304. itemGroup.on('click', curry$3(dispatchSelectAction, name, null, api, excludeSeriesId))
  44305. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  44306. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  44307. legendDrawnMap.set(name, true);
  44308. }
  44309. else {
  44310. // Legend to control data. In pie and funnel.
  44311. ecModel.eachRawSeries(function (seriesModel) {
  44312. // In case multiple series has same data name
  44313. if (legendDrawnMap.get(name)) {
  44314. return;
  44315. }
  44316. if (seriesModel.legendVisualProvider) {
  44317. var provider = seriesModel.legendVisualProvider;
  44318. if (!provider.containName(name)) {
  44319. return;
  44320. }
  44321. var idx = provider.indexOfName(name);
  44322. var color = provider.getItemVisual(idx, 'color');
  44323. var borderColor = provider.getItemVisual(idx, 'borderColor');
  44324. var legendSymbolType = 'roundRect';
  44325. var itemGroup = this._createItem(
  44326. name, dataIndex, itemModel, legendModel,
  44327. legendSymbolType, null,
  44328. itemAlign, color, borderColor,
  44329. selectMode
  44330. );
  44331. // FIXME: consider different series has items with the same name.
  44332. itemGroup.on('click', curry$3(dispatchSelectAction, null, name, api, excludeSeriesId))
  44333. // Should not specify the series name, consider legend controls
  44334. // more than one pie series.
  44335. .on('mouseover', curry$3(dispatchHighlightAction, null, name, api, excludeSeriesId))
  44336. .on('mouseout', curry$3(dispatchDownplayAction, null, name, api, excludeSeriesId));
  44337. legendDrawnMap.set(name, true);
  44338. }
  44339. }, this);
  44340. }
  44341. if (__DEV__) {
  44342. if (!legendDrawnMap.get(name)) {
  44343. console.warn(
  44344. name + ' series not exists. Legend data should be same with series name or data name.'
  44345. );
  44346. }
  44347. }
  44348. }, this);
  44349. if (selector) {
  44350. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  44351. }
  44352. },
  44353. _createSelector: function (selector, legendModel, api, orient, selectorPosition) {
  44354. var selectorGroup = this.getSelectorGroup();
  44355. each$11(selector, function (selectorItem) {
  44356. createSelectorButton(selectorItem);
  44357. });
  44358. function createSelectorButton(selectorItem) {
  44359. var type = selectorItem.type;
  44360. var labelText = new Text({
  44361. style: {
  44362. x: 0,
  44363. y: 0,
  44364. align: 'center',
  44365. verticalAlign: 'middle'
  44366. },
  44367. onclick: function () {
  44368. api.dispatchAction({
  44369. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  44370. });
  44371. }
  44372. });
  44373. selectorGroup.add(labelText);
  44374. var labelModel = legendModel.getModel('selectorLabel');
  44375. var emphasisLabelModel = legendModel.getModel('emphasis.selectorLabel');
  44376. setLabelStyle(
  44377. labelText.style, labelText.hoverStyle = {}, labelModel, emphasisLabelModel,
  44378. {
  44379. defaultText: selectorItem.title,
  44380. isRectText: false
  44381. }
  44382. );
  44383. setHoverStyle(labelText);
  44384. }
  44385. },
  44386. _createItem: function (
  44387. name, dataIndex, itemModel, legendModel,
  44388. legendSymbolType, symbolType,
  44389. itemAlign, color, borderColor, selectMode
  44390. ) {
  44391. var itemWidth = legendModel.get('itemWidth');
  44392. var itemHeight = legendModel.get('itemHeight');
  44393. var inactiveColor = legendModel.get('inactiveColor');
  44394. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  44395. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  44396. var legendModelItemStyle = legendModel.getModel('itemStyle');
  44397. var isSelected = legendModel.isSelected(name);
  44398. var itemGroup = new Group$2();
  44399. var textStyleModel = itemModel.getModel('textStyle');
  44400. var itemIcon = itemModel.get('icon');
  44401. var tooltipModel = itemModel.getModel('tooltip');
  44402. var legendGlobalTooltipModel = tooltipModel.parentModel;
  44403. // Use user given icon first
  44404. legendSymbolType = itemIcon || legendSymbolType;
  44405. var legendSymbol = createSymbol(
  44406. legendSymbolType,
  44407. 0,
  44408. 0,
  44409. itemWidth,
  44410. itemHeight,
  44411. isSelected ? color : inactiveColor,
  44412. // symbolKeepAspect default true for legend
  44413. symbolKeepAspect == null ? true : symbolKeepAspect
  44414. );
  44415. itemGroup.add(
  44416. setSymbolStyle(
  44417. legendSymbol, legendSymbolType, legendModelItemStyle,
  44418. borderColor, inactiveBorderColor, isSelected
  44419. )
  44420. );
  44421. // Compose symbols
  44422. // PENDING
  44423. if (!itemIcon && symbolType
  44424. // At least show one symbol, can't be all none
  44425. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  44426. ) {
  44427. var size = itemHeight * 0.8;
  44428. if (symbolType === 'none') {
  44429. symbolType = 'circle';
  44430. }
  44431. var legendSymbolCenter = createSymbol(
  44432. symbolType,
  44433. (itemWidth - size) / 2,
  44434. (itemHeight - size) / 2,
  44435. size,
  44436. size,
  44437. isSelected ? color : inactiveColor,
  44438. // symbolKeepAspect default true for legend
  44439. symbolKeepAspect == null ? true : symbolKeepAspect
  44440. );
  44441. // Put symbol in the center
  44442. itemGroup.add(
  44443. setSymbolStyle(
  44444. legendSymbolCenter, symbolType, legendModelItemStyle,
  44445. borderColor, inactiveBorderColor, isSelected
  44446. )
  44447. );
  44448. }
  44449. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  44450. var textAlign = itemAlign;
  44451. var formatter = legendModel.get('formatter');
  44452. var content = name;
  44453. if (typeof formatter === 'string' && formatter) {
  44454. content = formatter.replace('{name}', name != null ? name : '');
  44455. }
  44456. else if (typeof formatter === 'function') {
  44457. content = formatter(name);
  44458. }
  44459. itemGroup.add(new Text({
  44460. style: setTextStyle({}, textStyleModel, {
  44461. text: content,
  44462. x: textX,
  44463. y: itemHeight / 2,
  44464. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  44465. textAlign: textAlign,
  44466. textVerticalAlign: 'middle'
  44467. })
  44468. }));
  44469. // Add a invisible rect to increase the area of mouse hover
  44470. var hitRect = new Rect({
  44471. shape: itemGroup.getBoundingRect(),
  44472. invisible: true,
  44473. tooltip: tooltipModel.get('show') ? extend({
  44474. content: name,
  44475. // Defaul formatter
  44476. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  44477. return name;
  44478. },
  44479. formatterParams: {
  44480. componentType: 'legend',
  44481. legendIndex: legendModel.componentIndex,
  44482. name: name,
  44483. $vars: ['name']
  44484. }
  44485. }, tooltipModel.option) : null
  44486. });
  44487. itemGroup.add(hitRect);
  44488. itemGroup.eachChild(function (child) {
  44489. child.silent = true;
  44490. });
  44491. hitRect.silent = !selectMode;
  44492. this.getContentGroup().add(itemGroup);
  44493. setHoverStyle(itemGroup);
  44494. itemGroup.__legendDataIndex = dataIndex;
  44495. return itemGroup;
  44496. },
  44497. /**
  44498. * @protected
  44499. */
  44500. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  44501. var contentGroup = this.getContentGroup();
  44502. var selectorGroup = this.getSelectorGroup();
  44503. // Place items in contentGroup.
  44504. box(
  44505. legendModel.get('orient'),
  44506. contentGroup,
  44507. legendModel.get('itemGap'),
  44508. maxSize.width,
  44509. maxSize.height
  44510. );
  44511. var contentRect = contentGroup.getBoundingRect();
  44512. var contentPos = [-contentRect.x, -contentRect.y];
  44513. if (selector) {
  44514. // Place buttons in selectorGroup
  44515. box(
  44516. // Buttons in selectorGroup always layout horizontally
  44517. 'horizontal',
  44518. selectorGroup,
  44519. legendModel.get('selectorItemGap', true)
  44520. );
  44521. var selectorRect = selectorGroup.getBoundingRect();
  44522. var selectorPos = [-selectorRect.x, -selectorRect.y];
  44523. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  44524. var orientIdx = legendModel.getOrient().index;
  44525. var wh = orientIdx === 0 ? 'width' : 'height';
  44526. var hw = orientIdx === 0 ? 'height' : 'width';
  44527. var yx = orientIdx === 0 ? 'y' : 'x';
  44528. if (selectorPosition === 'end') {
  44529. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  44530. }
  44531. else {
  44532. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  44533. }
  44534. //Always align selector to content as 'middle'
  44535. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  44536. selectorGroup.attr('position', selectorPos);
  44537. contentGroup.attr('position', contentPos);
  44538. var mainRect = {x: 0, y: 0};
  44539. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  44540. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  44541. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  44542. return mainRect;
  44543. }
  44544. else {
  44545. contentGroup.attr('position', contentPos);
  44546. return this.group.getBoundingRect();
  44547. }
  44548. },
  44549. /**
  44550. * @protected
  44551. */
  44552. remove: function () {
  44553. this.getContentGroup().removeAll();
  44554. this._isFirstRender = true;
  44555. }
  44556. });
  44557. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected) {
  44558. var itemStyle;
  44559. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  44560. itemStyle = legendModelItemStyle.getItemStyle();
  44561. symbol.style.stroke = borderColor;
  44562. if (!isSelected) {
  44563. itemStyle.stroke = inactiveBorderColor;
  44564. }
  44565. }
  44566. else {
  44567. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  44568. }
  44569. return symbol.setStyle(itemStyle);
  44570. }
  44571. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  44572. // downplay before unselect
  44573. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  44574. api.dispatchAction({
  44575. type: 'legendToggleSelect',
  44576. name: seriesName != null ? seriesName : dataName
  44577. });
  44578. // highlight after select
  44579. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  44580. }
  44581. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  44582. // If element hover will move to a hoverLayer.
  44583. var el = api.getZr().storage.getDisplayList()[0];
  44584. if (!(el && el.useHoverLayer)) {
  44585. api.dispatchAction({
  44586. type: 'highlight',
  44587. seriesName: seriesName,
  44588. name: dataName,
  44589. excludeSeriesId: excludeSeriesId
  44590. });
  44591. }
  44592. }
  44593. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  44594. // If element hover will move to a hoverLayer.
  44595. var el = api.getZr().storage.getDisplayList()[0];
  44596. if (!(el && el.useHoverLayer)) {
  44597. api.dispatchAction({
  44598. type: 'downplay',
  44599. seriesName: seriesName,
  44600. name: dataName,
  44601. excludeSeriesId: excludeSeriesId
  44602. });
  44603. }
  44604. }
  44605. /*
  44606. * Licensed to the Apache Software Foundation (ASF) under one
  44607. * or more contributor license agreements. See the NOTICE file
  44608. * distributed with this work for additional information
  44609. * regarding copyright ownership. The ASF licenses this file
  44610. * to you under the Apache License, Version 2.0 (the
  44611. * "License"); you may not use this file except in compliance
  44612. * with the License. You may obtain a copy of the License at
  44613. *
  44614. * http://www.apache.org/licenses/LICENSE-2.0
  44615. *
  44616. * Unless required by applicable law or agreed to in writing,
  44617. * software distributed under the License is distributed on an
  44618. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44619. * KIND, either express or implied. See the License for the
  44620. * specific language governing permissions and limitations
  44621. * under the License.
  44622. */
  44623. var legendFilter = function (ecModel) {
  44624. var legendModels = ecModel.findComponents({
  44625. mainType: 'legend'
  44626. });
  44627. if (legendModels && legendModels.length) {
  44628. ecModel.filterSeries(function (series) {
  44629. // If in any legend component the status is not selected.
  44630. // Because in legend series is assumed selected when it is not in the legend data.
  44631. for (var i = 0; i < legendModels.length; i++) {
  44632. if (!legendModels[i].isSelected(series.name)) {
  44633. return false;
  44634. }
  44635. }
  44636. return true;
  44637. });
  44638. }
  44639. };
  44640. /*
  44641. * Licensed to the Apache Software Foundation (ASF) under one
  44642. * or more contributor license agreements. See the NOTICE file
  44643. * distributed with this work for additional information
  44644. * regarding copyright ownership. The ASF licenses this file
  44645. * to you under the Apache License, Version 2.0 (the
  44646. * "License"); you may not use this file except in compliance
  44647. * with the License. You may obtain a copy of the License at
  44648. *
  44649. * http://www.apache.org/licenses/LICENSE-2.0
  44650. *
  44651. * Unless required by applicable law or agreed to in writing,
  44652. * software distributed under the License is distributed on an
  44653. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44654. * KIND, either express or implied. See the License for the
  44655. * specific language governing permissions and limitations
  44656. * under the License.
  44657. */
  44658. // Do not contain scrollable legend, for sake of file size.
  44659. // Series Filter
  44660. registerProcessor(PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  44661. ComponentModel.registerSubTypeDefaulter('legend', function () {
  44662. // Default 'plain' when no type specified.
  44663. return 'plain';
  44664. });
  44665. /*
  44666. * Licensed to the Apache Software Foundation (ASF) under one
  44667. * or more contributor license agreements. See the NOTICE file
  44668. * distributed with this work for additional information
  44669. * regarding copyright ownership. The ASF licenses this file
  44670. * to you under the Apache License, Version 2.0 (the
  44671. * "License"); you may not use this file except in compliance
  44672. * with the License. You may obtain a copy of the License at
  44673. *
  44674. * http://www.apache.org/licenses/LICENSE-2.0
  44675. *
  44676. * Unless required by applicable law or agreed to in writing,
  44677. * software distributed under the License is distributed on an
  44678. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44679. * KIND, either express or implied. See the License for the
  44680. * specific language governing permissions and limitations
  44681. * under the License.
  44682. */
  44683. var ScrollableLegendModel = LegendModel.extend({
  44684. type: 'legend.scroll',
  44685. /**
  44686. * @param {number} scrollDataIndex
  44687. */
  44688. setScrollDataIndex: function (scrollDataIndex) {
  44689. this.option.scrollDataIndex = scrollDataIndex;
  44690. },
  44691. defaultOption: {
  44692. scrollDataIndex: 0,
  44693. pageButtonItemGap: 5,
  44694. pageButtonGap: null,
  44695. pageButtonPosition: 'end', // 'start' or 'end'
  44696. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  44697. pageIcons: {
  44698. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  44699. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  44700. },
  44701. pageIconColor: '#2f4554',
  44702. pageIconInactiveColor: '#aaa',
  44703. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  44704. pageTextStyle: {
  44705. color: '#333'
  44706. },
  44707. animationDurationUpdate: 800
  44708. },
  44709. /**
  44710. * @override
  44711. */
  44712. init: function (option, parentModel, ecModel, extraOpt) {
  44713. var inputPositionParams = getLayoutParams(option);
  44714. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  44715. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  44716. },
  44717. /**
  44718. * @override
  44719. */
  44720. mergeOption: function (option, extraOpt) {
  44721. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  44722. mergeAndNormalizeLayoutParams(this, this.option, option);
  44723. }
  44724. });
  44725. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  44726. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  44727. var orient = legendModel.getOrient();
  44728. var ignoreSize = [1, 1];
  44729. ignoreSize[orient.index] = 0;
  44730. mergeLayoutParam(target, raw, {
  44731. type: 'box', ignoreSize: ignoreSize
  44732. });
  44733. }
  44734. /*
  44735. * Licensed to the Apache Software Foundation (ASF) under one
  44736. * or more contributor license agreements. See the NOTICE file
  44737. * distributed with this work for additional information
  44738. * regarding copyright ownership. The ASF licenses this file
  44739. * to you under the Apache License, Version 2.0 (the
  44740. * "License"); you may not use this file except in compliance
  44741. * with the License. You may obtain a copy of the License at
  44742. *
  44743. * http://www.apache.org/licenses/LICENSE-2.0
  44744. *
  44745. * Unless required by applicable law or agreed to in writing,
  44746. * software distributed under the License is distributed on an
  44747. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44748. * KIND, either express or implied. See the License for the
  44749. * specific language governing permissions and limitations
  44750. * under the License.
  44751. */
  44752. /**
  44753. * Separate legend and scrollable legend to reduce package size.
  44754. */
  44755. var Group$3 = Group;
  44756. var WH = ['width', 'height'];
  44757. var XY = ['x', 'y'];
  44758. var ScrollableLegendView = LegendView.extend({
  44759. type: 'legend.scroll',
  44760. newlineDisabled: true,
  44761. init: function () {
  44762. ScrollableLegendView.superCall(this, 'init');
  44763. /**
  44764. * @private
  44765. * @type {number} For `scroll`.
  44766. */
  44767. this._currentIndex = 0;
  44768. /**
  44769. * @private
  44770. * @type {module:zrender/container/Group}
  44771. */
  44772. this.group.add(this._containerGroup = new Group$3());
  44773. this._containerGroup.add(this.getContentGroup());
  44774. /**
  44775. * @private
  44776. * @type {module:zrender/container/Group}
  44777. */
  44778. this.group.add(this._controllerGroup = new Group$3());
  44779. /**
  44780. *
  44781. * @private
  44782. */
  44783. this._showController;
  44784. },
  44785. /**
  44786. * @override
  44787. */
  44788. resetInner: function () {
  44789. ScrollableLegendView.superCall(this, 'resetInner');
  44790. this._controllerGroup.removeAll();
  44791. this._containerGroup.removeClipPath();
  44792. this._containerGroup.__rectSize = null;
  44793. },
  44794. /**
  44795. * @override
  44796. */
  44797. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  44798. var me = this;
  44799. // Render content items.
  44800. ScrollableLegendView.superCall(this, 'renderInner', itemAlign,
  44801. legendModel, ecModel, api, selector, orient, selectorPosition);
  44802. var controllerGroup = this._controllerGroup;
  44803. // FIXME: support be 'auto' adapt to size number text length,
  44804. // e.g., '3/12345' should not overlap with the control arrow button.
  44805. var pageIconSize = legendModel.get('pageIconSize', true);
  44806. if (!isArray(pageIconSize)) {
  44807. pageIconSize = [pageIconSize, pageIconSize];
  44808. }
  44809. createPageButton('pagePrev', 0);
  44810. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  44811. controllerGroup.add(new Text({
  44812. name: 'pageText',
  44813. style: {
  44814. textFill: pageTextStyleModel.getTextColor(),
  44815. font: pageTextStyleModel.getFont(),
  44816. textVerticalAlign: 'middle',
  44817. textAlign: 'center'
  44818. },
  44819. silent: true
  44820. }));
  44821. createPageButton('pageNext', 1);
  44822. function createPageButton(name, iconIdx) {
  44823. var pageDataIndexName = name + 'DataIndex';
  44824. var icon = createIcon(
  44825. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  44826. {
  44827. // Buttons will be created in each render, so we do not need
  44828. // to worry about avoiding using legendModel kept in scope.
  44829. onclick: bind(
  44830. me._pageGo, me, pageDataIndexName, legendModel, api
  44831. )
  44832. },
  44833. {
  44834. x: -pageIconSize[0] / 2,
  44835. y: -pageIconSize[1] / 2,
  44836. width: pageIconSize[0],
  44837. height: pageIconSize[1]
  44838. }
  44839. );
  44840. icon.name = name;
  44841. controllerGroup.add(icon);
  44842. }
  44843. },
  44844. /**
  44845. * @override
  44846. */
  44847. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  44848. var selectorGroup = this.getSelectorGroup();
  44849. var orientIdx = legendModel.getOrient().index;
  44850. var wh = WH[orientIdx];
  44851. var xy = XY[orientIdx];
  44852. var hw = WH[1 - orientIdx];
  44853. var yx = XY[1 - orientIdx];
  44854. selector && box(
  44855. // Buttons in selectorGroup always layout horizontally
  44856. 'horizontal',
  44857. selectorGroup,
  44858. legendModel.get('selectorItemGap', true)
  44859. );
  44860. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  44861. var selectorRect = selectorGroup.getBoundingRect();
  44862. var selectorPos = [-selectorRect.x, -selectorRect.y];
  44863. var processMaxSize = clone(maxSize);
  44864. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  44865. var mainRect = this._layoutContentAndController(legendModel, isFirstRender,
  44866. processMaxSize, orientIdx, wh, hw, yx
  44867. );
  44868. if (selector) {
  44869. if (selectorPosition === 'end') {
  44870. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  44871. }
  44872. else {
  44873. var offset = selectorRect[wh] + selectorButtonGap;
  44874. selectorPos[orientIdx] -= offset;
  44875. mainRect[xy] -= offset;
  44876. }
  44877. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  44878. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  44879. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  44880. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  44881. selectorGroup.attr('position', selectorPos);
  44882. }
  44883. return mainRect;
  44884. },
  44885. _layoutContentAndController: function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx) {
  44886. var contentGroup = this.getContentGroup();
  44887. var containerGroup = this._containerGroup;
  44888. var controllerGroup = this._controllerGroup;
  44889. // Place items in contentGroup.
  44890. box(
  44891. legendModel.get('orient'),
  44892. contentGroup,
  44893. legendModel.get('itemGap'),
  44894. !orientIdx ? null : maxSize.width,
  44895. orientIdx ? null : maxSize.height
  44896. );
  44897. box(
  44898. // Buttons in controller are layout always horizontally.
  44899. 'horizontal',
  44900. controllerGroup,
  44901. legendModel.get('pageButtonItemGap', true)
  44902. );
  44903. var contentRect = contentGroup.getBoundingRect();
  44904. var controllerRect = controllerGroup.getBoundingRect();
  44905. var showController = this._showController = contentRect[wh] > maxSize[wh];
  44906. var contentPos = [-contentRect.x, -contentRect.y];
  44907. // Remain contentPos when scroll animation perfroming.
  44908. // If first rendering, `contentGroup.position` is [0, 0], which
  44909. // does not make sense and may cause unexepcted animation if adopted.
  44910. if (!isFirstRender) {
  44911. contentPos[orientIdx] = contentGroup.position[orientIdx];
  44912. }
  44913. // Layout container group based on 0.
  44914. var containerPos = [0, 0];
  44915. var controllerPos = [-controllerRect.x, -controllerRect.y];
  44916. var pageButtonGap = retrieve2(
  44917. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  44918. );
  44919. // Place containerGroup and controllerGroup and contentGroup.
  44920. if (showController) {
  44921. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  44922. // controller is on the right / bottom.
  44923. if (pageButtonPosition === 'end') {
  44924. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  44925. }
  44926. // controller is on the left / top.
  44927. else {
  44928. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  44929. }
  44930. }
  44931. // Always align controller to content as 'middle'.
  44932. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  44933. contentGroup.attr('position', contentPos);
  44934. containerGroup.attr('position', containerPos);
  44935. controllerGroup.attr('position', controllerPos);
  44936. // Calculate `mainRect` and set `clipPath`.
  44937. // mainRect should not be calculated by `this.group.getBoundingRect()`
  44938. // for sake of the overflow.
  44939. var mainRect = {x: 0, y: 0};
  44940. // Consider content may be overflow (should be clipped).
  44941. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  44942. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  44943. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  44944. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  44945. containerGroup.__rectSize = maxSize[wh];
  44946. if (showController) {
  44947. var clipShape = {x: 0, y: 0};
  44948. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  44949. clipShape[hw] = mainRect[hw];
  44950. containerGroup.setClipPath(new Rect({shape: clipShape}));
  44951. // Consider content may be larger than container, container rect
  44952. // can not be obtained from `containerGroup.getBoundingRect()`.
  44953. containerGroup.__rectSize = clipShape[wh];
  44954. }
  44955. else {
  44956. // Do not remove or ignore controller. Keep them set as placeholders.
  44957. controllerGroup.eachChild(function (child) {
  44958. child.attr({invisible: true, silent: true});
  44959. });
  44960. }
  44961. // Content translate animation.
  44962. var pageInfo = this._getPageInfo(legendModel);
  44963. pageInfo.pageIndex != null && updateProps(
  44964. contentGroup,
  44965. {position: pageInfo.contentPosition},
  44966. // When switch from "show controller" to "not show controller", view should be
  44967. // updated immediately without animation, otherwise causes weird effect.
  44968. showController ? legendModel : false
  44969. );
  44970. this._updatePageInfoView(legendModel, pageInfo);
  44971. return mainRect;
  44972. },
  44973. _pageGo: function (to, legendModel, api) {
  44974. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  44975. scrollDataIndex != null && api.dispatchAction({
  44976. type: 'legendScroll',
  44977. scrollDataIndex: scrollDataIndex,
  44978. legendId: legendModel.id
  44979. });
  44980. },
  44981. _updatePageInfoView: function (legendModel, pageInfo) {
  44982. var controllerGroup = this._controllerGroup;
  44983. each$1(['pagePrev', 'pageNext'], function (name) {
  44984. var canJump = pageInfo[name + 'DataIndex'] != null;
  44985. var icon = controllerGroup.childOfName(name);
  44986. if (icon) {
  44987. icon.setStyle(
  44988. 'fill',
  44989. canJump
  44990. ? legendModel.get('pageIconColor', true)
  44991. : legendModel.get('pageIconInactiveColor', true)
  44992. );
  44993. icon.cursor = canJump ? 'pointer' : 'default';
  44994. }
  44995. });
  44996. var pageText = controllerGroup.childOfName('pageText');
  44997. var pageFormatter = legendModel.get('pageFormatter');
  44998. var pageIndex = pageInfo.pageIndex;
  44999. var current = pageIndex != null ? pageIndex + 1 : 0;
  45000. var total = pageInfo.pageCount;
  45001. pageText && pageFormatter && pageText.setStyle(
  45002. 'text',
  45003. isString(pageFormatter)
  45004. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  45005. : pageFormatter({current: current, total: total})
  45006. );
  45007. },
  45008. /**
  45009. * @param {module:echarts/model/Model} legendModel
  45010. * @return {Object} {
  45011. * contentPosition: Array.<number>, null when data item not found.
  45012. * pageIndex: number, null when data item not found.
  45013. * pageCount: number, always be a number, can be 0.
  45014. * pagePrevDataIndex: number, null when no previous page.
  45015. * pageNextDataIndex: number, null when no next page.
  45016. * }
  45017. */
  45018. _getPageInfo: function (legendModel) {
  45019. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  45020. var contentGroup = this.getContentGroup();
  45021. var containerRectSize = this._containerGroup.__rectSize;
  45022. var orientIdx = legendModel.getOrient().index;
  45023. var wh = WH[orientIdx];
  45024. var xy = XY[orientIdx];
  45025. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  45026. var children = contentGroup.children();
  45027. var targetItem = children[targetItemIndex];
  45028. var itemCount = children.length;
  45029. var pCount = !itemCount ? 0 : 1;
  45030. var result = {
  45031. contentPosition: contentGroup.position.slice(),
  45032. pageCount: pCount,
  45033. pageIndex: pCount - 1,
  45034. pagePrevDataIndex: null,
  45035. pageNextDataIndex: null
  45036. };
  45037. if (!targetItem) {
  45038. return result;
  45039. }
  45040. var targetItemInfo = getItemInfo(targetItem);
  45041. result.contentPosition[orientIdx] = -targetItemInfo.s;
  45042. // Strategy:
  45043. // (1) Always align based on the left/top most item.
  45044. // (2) It is user-friendly that the last item shown in the
  45045. // current window is shown at the begining of next window.
  45046. // Otherwise if half of the last item is cut by the window,
  45047. // it will have no chance to display entirely.
  45048. // (3) Consider that item size probably be different, we
  45049. // have calculate pageIndex by size rather than item index,
  45050. // and we can not get page index directly by division.
  45051. // (4) The window is to narrow to contain more than
  45052. // one item, we should make sure that the page can be fliped.
  45053. for (var i = targetItemIndex + 1,
  45054. winStartItemInfo = targetItemInfo,
  45055. winEndItemInfo = targetItemInfo,
  45056. currItemInfo = null;
  45057. i <= itemCount;
  45058. ++i
  45059. ) {
  45060. currItemInfo = getItemInfo(children[i]);
  45061. if (
  45062. // Half of the last item is out of the window.
  45063. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  45064. // If the current item does not intersect with the window, the new page
  45065. // can be started at the current item or the last item.
  45066. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  45067. ) {
  45068. if (winEndItemInfo.i > winStartItemInfo.i) {
  45069. winStartItemInfo = winEndItemInfo;
  45070. }
  45071. else { // e.g., when page size is smaller than item size.
  45072. winStartItemInfo = currItemInfo;
  45073. }
  45074. if (winStartItemInfo) {
  45075. if (result.pageNextDataIndex == null) {
  45076. result.pageNextDataIndex = winStartItemInfo.i;
  45077. }
  45078. ++result.pageCount;
  45079. }
  45080. }
  45081. winEndItemInfo = currItemInfo;
  45082. }
  45083. for (var i = targetItemIndex - 1,
  45084. winStartItemInfo = targetItemInfo,
  45085. winEndItemInfo = targetItemInfo,
  45086. currItemInfo = null;
  45087. i >= -1;
  45088. --i
  45089. ) {
  45090. currItemInfo = getItemInfo(children[i]);
  45091. if (
  45092. // If the the end item does not intersect with the window started
  45093. // from the current item, a page can be settled.
  45094. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  45095. // e.g., when page size is smaller than item size.
  45096. && winStartItemInfo.i < winEndItemInfo.i
  45097. ) {
  45098. winEndItemInfo = winStartItemInfo;
  45099. if (result.pagePrevDataIndex == null) {
  45100. result.pagePrevDataIndex = winStartItemInfo.i;
  45101. }
  45102. ++result.pageCount;
  45103. ++result.pageIndex;
  45104. }
  45105. winStartItemInfo = currItemInfo;
  45106. }
  45107. return result;
  45108. function getItemInfo(el) {
  45109. if (el) {
  45110. var itemRect = el.getBoundingRect();
  45111. var start = itemRect[xy] + el.position[orientIdx];
  45112. return {
  45113. s: start,
  45114. e: start + itemRect[wh],
  45115. i: el.__legendDataIndex
  45116. };
  45117. }
  45118. }
  45119. function intersect(itemInfo, winStart) {
  45120. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  45121. }
  45122. },
  45123. _findTargetItemIndex: function (targetDataIndex) {
  45124. if (!this._showController) {
  45125. return 0;
  45126. }
  45127. var index;
  45128. var contentGroup = this.getContentGroup();
  45129. var defaultIndex;
  45130. contentGroup.eachChild(function (child, idx) {
  45131. var legendDataIdx = child.__legendDataIndex;
  45132. // FIXME
  45133. // If the given targetDataIndex (from model) is illegal,
  45134. // we use defaultIndex. But the index on the legend model and
  45135. // action payload is still illegal. That case will not be
  45136. // changed until some scenario requires.
  45137. if (defaultIndex == null && legendDataIdx != null) {
  45138. defaultIndex = idx;
  45139. }
  45140. if (legendDataIdx === targetDataIndex) {
  45141. index = idx;
  45142. }
  45143. });
  45144. return index != null ? index : defaultIndex;
  45145. }
  45146. });
  45147. /*
  45148. * Licensed to the Apache Software Foundation (ASF) under one
  45149. * or more contributor license agreements. See the NOTICE file
  45150. * distributed with this work for additional information
  45151. * regarding copyright ownership. The ASF licenses this file
  45152. * to you under the Apache License, Version 2.0 (the
  45153. * "License"); you may not use this file except in compliance
  45154. * with the License. You may obtain a copy of the License at
  45155. *
  45156. * http://www.apache.org/licenses/LICENSE-2.0
  45157. *
  45158. * Unless required by applicable law or agreed to in writing,
  45159. * software distributed under the License is distributed on an
  45160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45161. * KIND, either express or implied. See the License for the
  45162. * specific language governing permissions and limitations
  45163. * under the License.
  45164. */
  45165. /**
  45166. * @event legendScroll
  45167. * @type {Object}
  45168. * @property {string} type 'legendScroll'
  45169. * @property {string} scrollDataIndex
  45170. */
  45171. registerAction(
  45172. 'legendScroll', 'legendscroll',
  45173. function (payload, ecModel) {
  45174. var scrollDataIndex = payload.scrollDataIndex;
  45175. scrollDataIndex != null && ecModel.eachComponent(
  45176. {mainType: 'legend', subType: 'scroll', query: payload},
  45177. function (legendModel) {
  45178. legendModel.setScrollDataIndex(scrollDataIndex);
  45179. }
  45180. );
  45181. }
  45182. );
  45183. /*
  45184. * Licensed to the Apache Software Foundation (ASF) under one
  45185. * or more contributor license agreements. See the NOTICE file
  45186. * distributed with this work for additional information
  45187. * regarding copyright ownership. The ASF licenses this file
  45188. * to you under the Apache License, Version 2.0 (the
  45189. * "License"); you may not use this file except in compliance
  45190. * with the License. You may obtain a copy of the License at
  45191. *
  45192. * http://www.apache.org/licenses/LICENSE-2.0
  45193. *
  45194. * Unless required by applicable law or agreed to in writing,
  45195. * software distributed under the License is distributed on an
  45196. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45197. * KIND, either express or implied. See the License for the
  45198. * specific language governing permissions and limitations
  45199. * under the License.
  45200. */
  45201. /**
  45202. * Legend component entry file8
  45203. */
  45204. /*
  45205. * Licensed to the Apache Software Foundation (ASF) under one
  45206. * or more contributor license agreements. See the NOTICE file
  45207. * distributed with this work for additional information
  45208. * regarding copyright ownership. The ASF licenses this file
  45209. * to you under the Apache License, Version 2.0 (the
  45210. * "License"); you may not use this file except in compliance
  45211. * with the License. You may obtain a copy of the License at
  45212. *
  45213. * http://www.apache.org/licenses/LICENSE-2.0
  45214. *
  45215. * Unless required by applicable law or agreed to in writing,
  45216. * software distributed under the License is distributed on an
  45217. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45218. * KIND, either express or implied. See the License for the
  45219. * specific language governing permissions and limitations
  45220. * under the License.
  45221. */
  45222. /*
  45223. * Licensed to the Apache Software Foundation (ASF) under one
  45224. * or more contributor license agreements. See the NOTICE file
  45225. * distributed with this work for additional information
  45226. * regarding copyright ownership. The ASF licenses this file
  45227. * to you under the Apache License, Version 2.0 (the
  45228. * "License"); you may not use this file except in compliance
  45229. * with the License. You may obtain a copy of the License at
  45230. *
  45231. * http://www.apache.org/licenses/LICENSE-2.0
  45232. *
  45233. * Unless required by applicable law or agreed to in writing,
  45234. * software distributed under the License is distributed on an
  45235. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45236. * KIND, either express or implied. See the License for the
  45237. * specific language governing permissions and limitations
  45238. * under the License.
  45239. */
  45240. // Model
  45241. extendComponentModel({
  45242. type: 'title',
  45243. layoutMode: {type: 'box', ignoreSize: true},
  45244. defaultOption: {
  45245. // 一级层叠
  45246. zlevel: 0,
  45247. // 二级层叠
  45248. z: 6,
  45249. show: true,
  45250. text: '',
  45251. // 超链接跳转
  45252. // link: null,
  45253. // 仅支持self | blank
  45254. target: 'blank',
  45255. subtext: '',
  45256. // 超链接跳转
  45257. // sublink: null,
  45258. // 仅支持self | blank
  45259. subtarget: 'blank',
  45260. // 'center' ¦ 'left' ¦ 'right'
  45261. // ¦ {number}(x坐标,单位px)
  45262. left: 0,
  45263. // 'top' ¦ 'bottom' ¦ 'center'
  45264. // ¦ {number}(y坐标,单位px)
  45265. top: 0,
  45266. // 水平对齐
  45267. // 'auto' | 'left' | 'right' | 'center'
  45268. // 默认根据 left 的位置判断是左对齐还是右对齐
  45269. // textAlign: null
  45270. //
  45271. // 垂直对齐
  45272. // 'auto' | 'top' | 'bottom' | 'middle'
  45273. // 默认根据 top 位置判断是上对齐还是下对齐
  45274. // textVerticalAlign: null
  45275. // textBaseline: null // The same as textVerticalAlign.
  45276. backgroundColor: 'rgba(0,0,0,0)',
  45277. // 标题边框颜色
  45278. borderColor: '#ccc',
  45279. // 标题边框线宽,单位px,默认为0(无边框)
  45280. borderWidth: 0,
  45281. // 标题内边距,单位px,默认各方向内边距为5,
  45282. // 接受数组分别设定上右下左边距,同css
  45283. padding: 5,
  45284. // 主副标题纵向间隔,单位px,默认为10,
  45285. itemGap: 10,
  45286. textStyle: {
  45287. fontSize: 18,
  45288. fontWeight: 'bolder',
  45289. color: '#333'
  45290. },
  45291. subtextStyle: {
  45292. color: '#aaa'
  45293. }
  45294. }
  45295. });
  45296. // View
  45297. extendComponentView({
  45298. type: 'title',
  45299. render: function (titleModel, ecModel, api) {
  45300. this.group.removeAll();
  45301. if (!titleModel.get('show')) {
  45302. return;
  45303. }
  45304. var group = this.group;
  45305. var textStyleModel = titleModel.getModel('textStyle');
  45306. var subtextStyleModel = titleModel.getModel('subtextStyle');
  45307. var textAlign = titleModel.get('textAlign');
  45308. var textVerticalAlign = retrieve2(
  45309. titleModel.get('textBaseline'), titleModel.get('textVerticalAlign')
  45310. );
  45311. var textEl = new Text({
  45312. style: setTextStyle({}, textStyleModel, {
  45313. text: titleModel.get('text'),
  45314. textFill: textStyleModel.getTextColor()
  45315. }, {disableBox: true}),
  45316. z2: 10
  45317. });
  45318. var textRect = textEl.getBoundingRect();
  45319. var subText = titleModel.get('subtext');
  45320. var subTextEl = new Text({
  45321. style: setTextStyle({}, subtextStyleModel, {
  45322. text: subText,
  45323. textFill: subtextStyleModel.getTextColor(),
  45324. y: textRect.height + titleModel.get('itemGap'),
  45325. textVerticalAlign: 'top'
  45326. }, {disableBox: true}),
  45327. z2: 10
  45328. });
  45329. var link = titleModel.get('link');
  45330. var sublink = titleModel.get('sublink');
  45331. var triggerEvent = titleModel.get('triggerEvent', true);
  45332. textEl.silent = !link && !triggerEvent;
  45333. subTextEl.silent = !sublink && !triggerEvent;
  45334. if (link) {
  45335. textEl.on('click', function () {
  45336. windowOpen(link, '_' + titleModel.get('target'));
  45337. });
  45338. }
  45339. if (sublink) {
  45340. subTextEl.on('click', function () {
  45341. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  45342. });
  45343. }
  45344. textEl.eventData = subTextEl.eventData = triggerEvent
  45345. ? {
  45346. componentType: 'title',
  45347. componentIndex: titleModel.componentIndex
  45348. }
  45349. : null;
  45350. group.add(textEl);
  45351. subText && group.add(subTextEl);
  45352. // If no subText, but add subTextEl, there will be an empty line.
  45353. var groupRect = group.getBoundingRect();
  45354. var layoutOption = titleModel.getBoxLayoutParams();
  45355. layoutOption.width = groupRect.width;
  45356. layoutOption.height = groupRect.height;
  45357. var layoutRect = getLayoutRect(
  45358. layoutOption, {
  45359. width: api.getWidth(),
  45360. height: api.getHeight()
  45361. }, titleModel.get('padding')
  45362. );
  45363. // Adjust text align based on position
  45364. if (!textAlign) {
  45365. // Align left if title is on the left. center and right is same
  45366. textAlign = titleModel.get('left') || titleModel.get('right');
  45367. if (textAlign === 'middle') {
  45368. textAlign = 'center';
  45369. }
  45370. // Adjust layout by text align
  45371. if (textAlign === 'right') {
  45372. layoutRect.x += layoutRect.width;
  45373. }
  45374. else if (textAlign === 'center') {
  45375. layoutRect.x += layoutRect.width / 2;
  45376. }
  45377. }
  45378. if (!textVerticalAlign) {
  45379. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  45380. if (textVerticalAlign === 'center') {
  45381. textVerticalAlign = 'middle';
  45382. }
  45383. if (textVerticalAlign === 'bottom') {
  45384. layoutRect.y += layoutRect.height;
  45385. }
  45386. else if (textVerticalAlign === 'middle') {
  45387. layoutRect.y += layoutRect.height / 2;
  45388. }
  45389. textVerticalAlign = textVerticalAlign || 'top';
  45390. }
  45391. group.attr('position', [layoutRect.x, layoutRect.y]);
  45392. var alignStyle = {
  45393. textAlign: textAlign,
  45394. textVerticalAlign: textVerticalAlign
  45395. };
  45396. textEl.setStyle(alignStyle);
  45397. subTextEl.setStyle(alignStyle);
  45398. // Render background
  45399. // Get groupRect again because textAlign has been changed
  45400. groupRect = group.getBoundingRect();
  45401. var padding = layoutRect.margin;
  45402. var style = titleModel.getItemStyle(['color', 'opacity']);
  45403. style.fill = titleModel.get('backgroundColor');
  45404. var rect = new Rect({
  45405. shape: {
  45406. x: groupRect.x - padding[3],
  45407. y: groupRect.y - padding[0],
  45408. width: groupRect.width + padding[1] + padding[3],
  45409. height: groupRect.height + padding[0] + padding[2],
  45410. r: titleModel.get('borderRadius')
  45411. },
  45412. style: style,
  45413. subPixelOptimize: true,
  45414. silent: true
  45415. });
  45416. group.add(rect);
  45417. }
  45418. });
  45419. /*
  45420. * Licensed to the Apache Software Foundation (ASF) under one
  45421. * or more contributor license agreements. See the NOTICE file
  45422. * distributed with this work for additional information
  45423. * regarding copyright ownership. The ASF licenses this file
  45424. * to you under the Apache License, Version 2.0 (the
  45425. * "License"); you may not use this file except in compliance
  45426. * with the License. You may obtain a copy of the License at
  45427. *
  45428. * http://www.apache.org/licenses/LICENSE-2.0
  45429. *
  45430. * Unless required by applicable law or agreed to in writing,
  45431. * software distributed under the License is distributed on an
  45432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45433. * KIND, either express or implied. See the License for the
  45434. * specific language governing permissions and limitations
  45435. * under the License.
  45436. */
  45437. var addCommas$1 = addCommas;
  45438. var encodeHTML$1 = encodeHTML;
  45439. function fillLabel(opt) {
  45440. defaultEmphasis(opt, 'label', ['show']);
  45441. }
  45442. var MarkerModel = extendComponentModel({
  45443. type: 'marker',
  45444. dependencies: ['series', 'grid', 'polar', 'geo'],
  45445. /**
  45446. * @overrite
  45447. */
  45448. init: function (option, parentModel, ecModel) {
  45449. if (__DEV__) {
  45450. if (this.type === 'marker') {
  45451. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  45452. }
  45453. }
  45454. this.mergeDefaultAndTheme(option, ecModel);
  45455. this._mergeOption(option, ecModel, false, true);
  45456. },
  45457. /**
  45458. * @return {boolean}
  45459. */
  45460. isAnimationEnabled: function () {
  45461. if (env$1.node) {
  45462. return false;
  45463. }
  45464. var hostSeries = this.__hostSeries;
  45465. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  45466. },
  45467. /**
  45468. * @overrite
  45469. */
  45470. mergeOption: function (newOpt, ecModel) {
  45471. this._mergeOption(newOpt, ecModel, false, false);
  45472. },
  45473. _mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  45474. var MarkerModel = this.constructor;
  45475. var modelPropName = this.mainType + 'Model';
  45476. if (!createdBySelf) {
  45477. ecModel.eachSeries(function (seriesModel) {
  45478. var markerOpt = seriesModel.get(this.mainType, true);
  45479. var markerModel = seriesModel[modelPropName];
  45480. if (!markerOpt || !markerOpt.data) {
  45481. seriesModel[modelPropName] = null;
  45482. return;
  45483. }
  45484. if (!markerModel) {
  45485. if (isInit) {
  45486. // Default label emphasis `position` and `show`
  45487. fillLabel(markerOpt);
  45488. }
  45489. each$1(markerOpt.data, function (item) {
  45490. // FIXME Overwrite fillLabel method ?
  45491. if (item instanceof Array) {
  45492. fillLabel(item[0]);
  45493. fillLabel(item[1]);
  45494. }
  45495. else {
  45496. fillLabel(item);
  45497. }
  45498. });
  45499. markerModel = new MarkerModel(
  45500. markerOpt, this, ecModel
  45501. );
  45502. extend(markerModel, {
  45503. mainType: this.mainType,
  45504. // Use the same series index and name
  45505. seriesIndex: seriesModel.seriesIndex,
  45506. name: seriesModel.name,
  45507. createdBySelf: true
  45508. });
  45509. markerModel.__hostSeries = seriesModel;
  45510. }
  45511. else {
  45512. markerModel._mergeOption(markerOpt, ecModel, true);
  45513. }
  45514. seriesModel[modelPropName] = markerModel;
  45515. }, this);
  45516. }
  45517. },
  45518. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  45519. var data = this.getData();
  45520. var value = this.getRawValue(dataIndex);
  45521. var formattedValue = isArray(value)
  45522. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  45523. var name = data.getName(dataIndex);
  45524. var html = encodeHTML$1(this.name);
  45525. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  45526. if (value != null || name) {
  45527. html += newLine;
  45528. }
  45529. if (name) {
  45530. html += encodeHTML$1(name);
  45531. if (value != null) {
  45532. html += ' : ';
  45533. }
  45534. }
  45535. if (value != null) {
  45536. html += encodeHTML$1(formattedValue);
  45537. }
  45538. return html;
  45539. },
  45540. getData: function () {
  45541. return this._data;
  45542. },
  45543. setData: function (data) {
  45544. this._data = data;
  45545. }
  45546. });
  45547. mixin(MarkerModel, dataFormatMixin);
  45548. /*
  45549. * Licensed to the Apache Software Foundation (ASF) under one
  45550. * or more contributor license agreements. See the NOTICE file
  45551. * distributed with this work for additional information
  45552. * regarding copyright ownership. The ASF licenses this file
  45553. * to you under the Apache License, Version 2.0 (the
  45554. * "License"); you may not use this file except in compliance
  45555. * with the License. You may obtain a copy of the License at
  45556. *
  45557. * http://www.apache.org/licenses/LICENSE-2.0
  45558. *
  45559. * Unless required by applicable law or agreed to in writing,
  45560. * software distributed under the License is distributed on an
  45561. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45562. * KIND, either express or implied. See the License for the
  45563. * specific language governing permissions and limitations
  45564. * under the License.
  45565. */
  45566. MarkerModel.extend({
  45567. type: 'markPoint',
  45568. defaultOption: {
  45569. zlevel: 0,
  45570. z: 5,
  45571. symbol: 'pin',
  45572. symbolSize: 50,
  45573. //symbolRotate: 0,
  45574. //symbolOffset: [0, 0]
  45575. tooltip: {
  45576. trigger: 'item'
  45577. },
  45578. label: {
  45579. show: true,
  45580. position: 'inside'
  45581. },
  45582. itemStyle: {
  45583. borderWidth: 2
  45584. },
  45585. emphasis: {
  45586. label: {
  45587. show: true
  45588. }
  45589. }
  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 indexOf$1 = indexOf;
  45611. function hasXOrY(item) {
  45612. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  45613. }
  45614. function hasXAndY(item) {
  45615. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  45616. }
  45617. // Make it simple, do not visit all stacked value to count precision.
  45618. // function getPrecision(data, valueAxisDim, dataIndex) {
  45619. // var precision = -1;
  45620. // var stackedDim = data.mapDimension(valueAxisDim);
  45621. // do {
  45622. // precision = Math.max(
  45623. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  45624. // precision
  45625. // );
  45626. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  45627. // if (stackedOnSeries) {
  45628. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  45629. // data = stackedOnSeries.getData();
  45630. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  45631. // stackedDim = data.getCalculationInfo('stackedDimension');
  45632. // }
  45633. // else {
  45634. // data = null;
  45635. // }
  45636. // } while (data);
  45637. // return precision;
  45638. // }
  45639. function markerTypeCalculatorWithExtent(
  45640. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  45641. ) {
  45642. var coordArr = [];
  45643. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  45644. var calcDataDim = stacked
  45645. ? data.getCalculationInfo('stackResultDimension')
  45646. : targetDataDim;
  45647. var value = numCalculate(data, calcDataDim, mlType);
  45648. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  45649. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  45650. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  45651. var coordArrValue = data.get(targetDataDim, dataIndex);
  45652. // Make it simple, do not visit all stacked value to count precision.
  45653. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  45654. precision = Math.min(precision, 20);
  45655. if (precision >= 0) {
  45656. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  45657. }
  45658. return [coordArr, coordArrValue];
  45659. }
  45660. var curry$4 = curry;
  45661. // TODO Specified percent
  45662. var markerTypeCalculator = {
  45663. /**
  45664. * @method
  45665. * @param {module:echarts/data/List} data
  45666. * @param {string} baseAxisDim
  45667. * @param {string} valueAxisDim
  45668. */
  45669. min: curry$4(markerTypeCalculatorWithExtent, 'min'),
  45670. /**
  45671. * @method
  45672. * @param {module:echarts/data/List} data
  45673. * @param {string} baseAxisDim
  45674. * @param {string} valueAxisDim
  45675. */
  45676. max: curry$4(markerTypeCalculatorWithExtent, 'max'),
  45677. /**
  45678. * @method
  45679. * @param {module:echarts/data/List} data
  45680. * @param {string} baseAxisDim
  45681. * @param {string} valueAxisDim
  45682. */
  45683. average: curry$4(markerTypeCalculatorWithExtent, 'average')
  45684. };
  45685. /**
  45686. * Transform markPoint data item to format used in List by do the following
  45687. * 1. Calculate statistic like `max`, `min`, `average`
  45688. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  45689. * @param {module:echarts/model/Series} seriesModel
  45690. * @param {module:echarts/coord/*} [coordSys]
  45691. * @param {Object} item
  45692. * @return {Object}
  45693. */
  45694. function dataTransform(seriesModel, item) {
  45695. var data = seriesModel.getData();
  45696. var coordSys = seriesModel.coordinateSystem;
  45697. // 1. If not specify the position with pixel directly
  45698. // 2. If `coord` is not a data array. Which uses `xAxis`,
  45699. // `yAxis` to specify the coord on each dimension
  45700. // parseFloat first because item.x and item.y can be percent string like '20%'
  45701. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  45702. var dims = coordSys.dimensions;
  45703. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  45704. // Clone the option
  45705. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  45706. item = clone(item);
  45707. if (item.type
  45708. && markerTypeCalculator[item.type]
  45709. && axisInfo.baseAxis && axisInfo.valueAxis
  45710. ) {
  45711. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  45712. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  45713. var coordInfo = markerTypeCalculator[item.type](
  45714. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  45715. otherCoordIndex, targetCoordIndex
  45716. );
  45717. item.coord = coordInfo[0];
  45718. // Force to use the value of calculated value.
  45719. // let item use the value without stack.
  45720. item.value = coordInfo[1];
  45721. }
  45722. else {
  45723. // FIXME Only has one of xAxis and yAxis.
  45724. var coord = [
  45725. item.xAxis != null ? item.xAxis : item.radiusAxis,
  45726. item.yAxis != null ? item.yAxis : item.angleAxis
  45727. ];
  45728. // Each coord support max, min, average
  45729. for (var i = 0; i < 2; i++) {
  45730. if (markerTypeCalculator[coord[i]]) {
  45731. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  45732. }
  45733. }
  45734. item.coord = coord;
  45735. }
  45736. }
  45737. return item;
  45738. }
  45739. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  45740. var ret = {};
  45741. if (item.valueIndex != null || item.valueDim != null) {
  45742. ret.valueDataDim = item.valueIndex != null
  45743. ? data.getDimension(item.valueIndex) : item.valueDim;
  45744. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  45745. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  45746. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  45747. }
  45748. else {
  45749. ret.baseAxis = seriesModel.getBaseAxis();
  45750. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  45751. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  45752. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  45753. }
  45754. return ret;
  45755. }
  45756. function dataDimToCoordDim(seriesModel, dataDim) {
  45757. var data = seriesModel.getData();
  45758. var dimensions = data.dimensions;
  45759. dataDim = data.getDimension(dataDim);
  45760. for (var i = 0; i < dimensions.length; i++) {
  45761. var dimItem = data.getDimensionInfo(dimensions[i]);
  45762. if (dimItem.name === dataDim) {
  45763. return dimItem.coordDim;
  45764. }
  45765. }
  45766. }
  45767. /**
  45768. * Filter data which is out of coordinateSystem range
  45769. * [dataFilter description]
  45770. * @param {module:echarts/coord/*} [coordSys]
  45771. * @param {Object} item
  45772. * @return {boolean}
  45773. */
  45774. function dataFilter$1(coordSys, item) {
  45775. // Alwalys return true if there is no coordSys
  45776. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  45777. ? coordSys.containData(item.coord) : true;
  45778. }
  45779. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  45780. // x, y, radius, angle
  45781. if (dimIndex < 2) {
  45782. return item.coord && item.coord[dimIndex];
  45783. }
  45784. return item.value;
  45785. }
  45786. function numCalculate(data, valueDataDim, type) {
  45787. if (type === 'average') {
  45788. var sum = 0;
  45789. var count = 0;
  45790. data.each(valueDataDim, function (val, idx) {
  45791. if (!isNaN(val)) {
  45792. sum += val;
  45793. count++;
  45794. }
  45795. });
  45796. return sum / count;
  45797. }
  45798. else if (type === 'median') {
  45799. return data.getMedian(valueDataDim);
  45800. }
  45801. else {
  45802. // max & min
  45803. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  45804. }
  45805. }
  45806. /*
  45807. * Licensed to the Apache Software Foundation (ASF) under one
  45808. * or more contributor license agreements. See the NOTICE file
  45809. * distributed with this work for additional information
  45810. * regarding copyright ownership. The ASF licenses this file
  45811. * to you under the Apache License, Version 2.0 (the
  45812. * "License"); you may not use this file except in compliance
  45813. * with the License. You may obtain a copy of the License at
  45814. *
  45815. * http://www.apache.org/licenses/LICENSE-2.0
  45816. *
  45817. * Unless required by applicable law or agreed to in writing,
  45818. * software distributed under the License is distributed on an
  45819. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45820. * KIND, either express or implied. See the License for the
  45821. * specific language governing permissions and limitations
  45822. * under the License.
  45823. */
  45824. var MarkerView = extendComponentView({
  45825. type: 'marker',
  45826. init: function () {
  45827. /**
  45828. * Markline grouped by series
  45829. * @private
  45830. * @type {module:zrender/core/util.HashMap}
  45831. */
  45832. this.markerGroupMap = createHashMap();
  45833. },
  45834. render: function (markerModel, ecModel, api) {
  45835. var markerGroupMap = this.markerGroupMap;
  45836. markerGroupMap.each(function (item) {
  45837. item.__keep = false;
  45838. });
  45839. var markerModelKey = this.type + 'Model';
  45840. ecModel.eachSeries(function (seriesModel) {
  45841. var markerModel = seriesModel[markerModelKey];
  45842. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  45843. }, this);
  45844. markerGroupMap.each(function (item) {
  45845. !item.__keep && this.group.remove(item.group);
  45846. }, this);
  45847. },
  45848. renderSeries: function () {}
  45849. });
  45850. /*
  45851. * Licensed to the Apache Software Foundation (ASF) under one
  45852. * or more contributor license agreements. See the NOTICE file
  45853. * distributed with this work for additional information
  45854. * regarding copyright ownership. The ASF licenses this file
  45855. * to you under the Apache License, Version 2.0 (the
  45856. * "License"); you may not use this file except in compliance
  45857. * with the License. You may obtain a copy of the License at
  45858. *
  45859. * http://www.apache.org/licenses/LICENSE-2.0
  45860. *
  45861. * Unless required by applicable law or agreed to in writing,
  45862. * software distributed under the License is distributed on an
  45863. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45864. * KIND, either express or implied. See the License for the
  45865. * specific language governing permissions and limitations
  45866. * under the License.
  45867. */
  45868. function updateMarkerLayout(mpData, seriesModel, api) {
  45869. var coordSys = seriesModel.coordinateSystem;
  45870. mpData.each(function (idx) {
  45871. var itemModel = mpData.getItemModel(idx);
  45872. var point;
  45873. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  45874. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  45875. if (!isNaN(xPx) && !isNaN(yPx)) {
  45876. point = [xPx, yPx];
  45877. }
  45878. // Chart like bar may have there own marker positioning logic
  45879. else if (seriesModel.getMarkerPosition) {
  45880. // Use the getMarkerPoisition
  45881. point = seriesModel.getMarkerPosition(
  45882. mpData.getValues(mpData.dimensions, idx)
  45883. );
  45884. }
  45885. else if (coordSys) {
  45886. var x = mpData.get(coordSys.dimensions[0], idx);
  45887. var y = mpData.get(coordSys.dimensions[1], idx);
  45888. point = coordSys.dataToPoint([x, y]);
  45889. }
  45890. // Use x, y if has any
  45891. if (!isNaN(xPx)) {
  45892. point[0] = xPx;
  45893. }
  45894. if (!isNaN(yPx)) {
  45895. point[1] = yPx;
  45896. }
  45897. mpData.setItemLayout(idx, point);
  45898. });
  45899. }
  45900. MarkerView.extend({
  45901. type: 'markPoint',
  45902. // updateLayout: function (markPointModel, ecModel, api) {
  45903. // ecModel.eachSeries(function (seriesModel) {
  45904. // var mpModel = seriesModel.markPointModel;
  45905. // if (mpModel) {
  45906. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45907. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  45908. // }
  45909. // }, this);
  45910. // },
  45911. updateTransform: function (markPointModel, ecModel, api) {
  45912. ecModel.eachSeries(function (seriesModel) {
  45913. var mpModel = seriesModel.markPointModel;
  45914. if (mpModel) {
  45915. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45916. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  45917. }
  45918. }, this);
  45919. },
  45920. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  45921. var coordSys = seriesModel.coordinateSystem;
  45922. var seriesId = seriesModel.id;
  45923. var seriesData = seriesModel.getData();
  45924. var symbolDrawMap = this.markerGroupMap;
  45925. var symbolDraw = symbolDrawMap.get(seriesId)
  45926. || symbolDrawMap.set(seriesId, new SymbolDraw());
  45927. var mpData = createList$1(coordSys, seriesModel, mpModel);
  45928. // FIXME
  45929. mpModel.setData(mpData);
  45930. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45931. mpData.each(function (idx) {
  45932. var itemModel = mpData.getItemModel(idx);
  45933. var symbol = itemModel.getShallow('symbol');
  45934. var symbolSize = itemModel.getShallow('symbolSize');
  45935. var symbolRotate = itemModel.getShallow('symbolRotate');
  45936. var isFnSymbol = isFunction$1(symbol);
  45937. var isFnSymbolSize = isFunction$1(symbolSize);
  45938. var isFnSymbolRotate = isFunction$1(symbolRotate);
  45939. if (isFnSymbol || isFnSymbolSize || isFnSymbolRotate) {
  45940. var rawIdx = mpModel.getRawValue(idx);
  45941. var dataParams = mpModel.getDataParams(idx);
  45942. if (isFnSymbol) {
  45943. symbol = symbol(rawIdx, dataParams);
  45944. }
  45945. if (isFnSymbolSize) {
  45946. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  45947. symbolSize = symbolSize(rawIdx, dataParams);
  45948. }
  45949. if (isFnSymbolRotate) {
  45950. symbolRotate = symbolRotate(rawIdx, dataParams);
  45951. }
  45952. }
  45953. mpData.setItemVisual(idx, {
  45954. symbol: symbol,
  45955. symbolSize: symbolSize,
  45956. symbolRotate: symbolRotate,
  45957. color: itemModel.get('itemStyle.color')
  45958. || seriesData.getVisual('color')
  45959. });
  45960. });
  45961. // TODO Text are wrong
  45962. symbolDraw.updateData(mpData);
  45963. this.group.add(symbolDraw.group);
  45964. // Set host model for tooltip
  45965. // FIXME
  45966. mpData.eachItemGraphicEl(function (el) {
  45967. el.traverse(function (child) {
  45968. child.dataModel = mpModel;
  45969. });
  45970. });
  45971. symbolDraw.__keep = true;
  45972. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  45973. }
  45974. });
  45975. /**
  45976. * @inner
  45977. * @param {module:echarts/coord/*} [coordSys]
  45978. * @param {module:echarts/model/Series} seriesModel
  45979. * @param {module:echarts/model/Model} mpModel
  45980. */
  45981. function createList$1(coordSys, seriesModel, mpModel) {
  45982. var coordDimsInfos;
  45983. if (coordSys) {
  45984. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  45985. var info = seriesModel.getData().getDimensionInfo(
  45986. seriesModel.getData().mapDimension(coordDim)
  45987. ) || {};
  45988. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  45989. return defaults({name: coordDim}, info);
  45990. });
  45991. }
  45992. else {
  45993. coordDimsInfos = [{
  45994. name: 'value',
  45995. type: 'float'
  45996. }];
  45997. }
  45998. var mpData = new List(coordDimsInfos, mpModel);
  45999. var dataOpt = map(mpModel.get('data'), curry(
  46000. dataTransform, seriesModel
  46001. ));
  46002. if (coordSys) {
  46003. dataOpt = filter(
  46004. dataOpt, curry(dataFilter$1, coordSys)
  46005. );
  46006. }
  46007. mpData.initData(dataOpt, null,
  46008. coordSys ? dimValueGetter : function (item) {
  46009. return item.value;
  46010. }
  46011. );
  46012. return mpData;
  46013. }
  46014. /*
  46015. * Licensed to the Apache Software Foundation (ASF) under one
  46016. * or more contributor license agreements. See the NOTICE file
  46017. * distributed with this work for additional information
  46018. * regarding copyright ownership. The ASF licenses this file
  46019. * to you under the Apache License, Version 2.0 (the
  46020. * "License"); you may not use this file except in compliance
  46021. * with the License. You may obtain a copy of the License at
  46022. *
  46023. * http://www.apache.org/licenses/LICENSE-2.0
  46024. *
  46025. * Unless required by applicable law or agreed to in writing,
  46026. * software distributed under the License is distributed on an
  46027. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46028. * KIND, either express or implied. See the License for the
  46029. * specific language governing permissions and limitations
  46030. * under the License.
  46031. */
  46032. // HINT Markpoint can't be used too much
  46033. registerPreprocessor(function (opt) {
  46034. // Make sure markPoint component is enabled
  46035. opt.markPoint = opt.markPoint || {};
  46036. });
  46037. /*
  46038. * Licensed to the Apache Software Foundation (ASF) under one
  46039. * or more contributor license agreements. See the NOTICE file
  46040. * distributed with this work for additional information
  46041. * regarding copyright ownership. The ASF licenses this file
  46042. * to you under the Apache License, Version 2.0 (the
  46043. * "License"); you may not use this file except in compliance
  46044. * with the License. You may obtain a copy of the License at
  46045. *
  46046. * http://www.apache.org/licenses/LICENSE-2.0
  46047. *
  46048. * Unless required by applicable law or agreed to in writing,
  46049. * software distributed under the License is distributed on an
  46050. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46051. * KIND, either express or implied. See the License for the
  46052. * specific language governing permissions and limitations
  46053. * under the License.
  46054. */
  46055. MarkerModel.extend({
  46056. type: 'markLine',
  46057. defaultOption: {
  46058. zlevel: 0,
  46059. z: 5,
  46060. symbol: ['circle', 'arrow'],
  46061. symbolSize: [8, 16],
  46062. //symbolRotate: 0,
  46063. precision: 2,
  46064. tooltip: {
  46065. trigger: 'item'
  46066. },
  46067. label: {
  46068. show: true,
  46069. position: 'end',
  46070. distance: 5
  46071. },
  46072. lineStyle: {
  46073. type: 'dashed'
  46074. },
  46075. emphasis: {
  46076. label: {
  46077. show: true
  46078. },
  46079. lineStyle: {
  46080. width: 3
  46081. }
  46082. },
  46083. animationEasing: 'linear'
  46084. }
  46085. });
  46086. /*
  46087. * Licensed to the Apache Software Foundation (ASF) under one
  46088. * or more contributor license agreements. See the NOTICE file
  46089. * distributed with this work for additional information
  46090. * regarding copyright ownership. The ASF licenses this file
  46091. * to you under the Apache License, Version 2.0 (the
  46092. * "License"); you may not use this file except in compliance
  46093. * with the License. You may obtain a copy of the License at
  46094. *
  46095. * http://www.apache.org/licenses/LICENSE-2.0
  46096. *
  46097. * Unless required by applicable law or agreed to in writing,
  46098. * software distributed under the License is distributed on an
  46099. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46100. * KIND, either express or implied. See the License for the
  46101. * specific language governing permissions and limitations
  46102. * under the License.
  46103. */
  46104. /**
  46105. * Line path for bezier and straight line draw
  46106. */
  46107. var straightLineProto = Line.prototype;
  46108. var bezierCurveProto = BezierCurve.prototype;
  46109. function isLine(shape) {
  46110. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  46111. }
  46112. var LinePath = extendShape({
  46113. type: 'ec-line',
  46114. style: {
  46115. stroke: '#000',
  46116. fill: null
  46117. },
  46118. shape: {
  46119. x1: 0,
  46120. y1: 0,
  46121. x2: 0,
  46122. y2: 0,
  46123. percent: 1,
  46124. cpx1: null,
  46125. cpy1: null
  46126. },
  46127. buildPath: function (ctx, shape) {
  46128. this[isLine(shape) ? '_buildPathLine' : '_buildPathCurve'](ctx, shape);
  46129. },
  46130. _buildPathLine: straightLineProto.buildPath,
  46131. _buildPathCurve: bezierCurveProto.buildPath,
  46132. pointAt: function (t) {
  46133. return this[isLine(this.shape) ? '_pointAtLine' : '_pointAtCurve'](t);
  46134. },
  46135. _pointAtLine: straightLineProto.pointAt,
  46136. _pointAtCurve: bezierCurveProto.pointAt,
  46137. tangentAt: function (t) {
  46138. var shape = this.shape;
  46139. var p = isLine(shape)
  46140. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  46141. : this._tangentAtCurve(t);
  46142. return normalize(p, p);
  46143. },
  46144. _tangentAtCurve: bezierCurveProto.tangentAt
  46145. });
  46146. /*
  46147. * Licensed to the Apache Software Foundation (ASF) under one
  46148. * or more contributor license agreements. See the NOTICE file
  46149. * distributed with this work for additional information
  46150. * regarding copyright ownership. The ASF licenses this file
  46151. * to you under the Apache License, Version 2.0 (the
  46152. * "License"); you may not use this file except in compliance
  46153. * with the License. You may obtain a copy of the License at
  46154. *
  46155. * http://www.apache.org/licenses/LICENSE-2.0
  46156. *
  46157. * Unless required by applicable law or agreed to in writing,
  46158. * software distributed under the License is distributed on an
  46159. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46160. * KIND, either express or implied. See the License for the
  46161. * specific language governing permissions and limitations
  46162. * under the License.
  46163. */
  46164. /**
  46165. * @module echarts/chart/helper/Line
  46166. */
  46167. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  46168. function makeSymbolTypeKey(symbolCategory) {
  46169. return '_' + symbolCategory + 'Type';
  46170. }
  46171. /**
  46172. * @inner
  46173. */
  46174. function createSymbol$1(name, lineData, idx) {
  46175. var symbolType = lineData.getItemVisual(idx, name);
  46176. if (!symbolType || symbolType === 'none') {
  46177. return;
  46178. }
  46179. var color = lineData.getItemVisual(idx, 'color');
  46180. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  46181. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  46182. if (!isArray(symbolSize)) {
  46183. symbolSize = [symbolSize, symbolSize];
  46184. }
  46185. var symbolPath = createSymbol(
  46186. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  46187. symbolSize[0], symbolSize[1], color
  46188. );
  46189. // rotate by default if symbolRotate is not specified or NaN
  46190. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate)
  46191. ? void 0
  46192. : +symbolRotate * Math.PI / 180 || 0;
  46193. symbolPath.name = name;
  46194. return symbolPath;
  46195. }
  46196. function createLine(points) {
  46197. var line = new LinePath({
  46198. name: 'line',
  46199. subPixelOptimize: true
  46200. });
  46201. setLinePoints(line.shape, points);
  46202. return line;
  46203. }
  46204. function setLinePoints(targetShape, points) {
  46205. targetShape.x1 = points[0][0];
  46206. targetShape.y1 = points[0][1];
  46207. targetShape.x2 = points[1][0];
  46208. targetShape.y2 = points[1][1];
  46209. targetShape.percent = 1;
  46210. var cp1 = points[2];
  46211. if (cp1) {
  46212. targetShape.cpx1 = cp1[0];
  46213. targetShape.cpy1 = cp1[1];
  46214. }
  46215. else {
  46216. targetShape.cpx1 = NaN;
  46217. targetShape.cpy1 = NaN;
  46218. }
  46219. }
  46220. function updateSymbolAndLabelBeforeLineUpdate() {
  46221. var lineGroup = this;
  46222. var symbolFrom = lineGroup.childOfName('fromSymbol');
  46223. var symbolTo = lineGroup.childOfName('toSymbol');
  46224. var label = lineGroup.childOfName('label');
  46225. // Quick reject
  46226. if (!symbolFrom && !symbolTo && label.ignore) {
  46227. return;
  46228. }
  46229. var invScale = 1;
  46230. var parentNode = this.parent;
  46231. while (parentNode) {
  46232. if (parentNode.scale) {
  46233. invScale /= parentNode.scale[0];
  46234. }
  46235. parentNode = parentNode.parent;
  46236. }
  46237. var line = lineGroup.childOfName('line');
  46238. // If line not changed
  46239. // FIXME Parent scale changed
  46240. if (!this.__dirty && !line.__dirty) {
  46241. return;
  46242. }
  46243. var percent = line.shape.percent;
  46244. var fromPos = line.pointAt(0);
  46245. var toPos = line.pointAt(percent);
  46246. var d = sub([], toPos, fromPos);
  46247. normalize(d, d);
  46248. if (symbolFrom) {
  46249. symbolFrom.attr('position', fromPos);
  46250. // Fix #12388
  46251. // when symbol is set to be 'arrow' in markLine,
  46252. // symbolRotate value will be ignored, and compulsively use tangent angle.
  46253. // rotate by default if symbol rotation is not specified
  46254. var specifiedRotation = symbolFrom.__specifiedRotation;
  46255. if (specifiedRotation == null) {
  46256. var tangent = line.tangentAt(0);
  46257. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  46258. tangent[1], tangent[0]
  46259. ));
  46260. }
  46261. else {
  46262. symbolFrom.attr('rotation', specifiedRotation);
  46263. }
  46264. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  46265. }
  46266. if (symbolTo) {
  46267. symbolTo.attr('position', toPos);
  46268. // Fix #12388
  46269. // when symbol is set to be 'arrow' in markLine,
  46270. // symbolRotate value will be ignored, and compulsively use tangent angle.
  46271. // rotate by default if symbol rotation is not specified
  46272. var specifiedRotation = symbolTo.__specifiedRotation;
  46273. if (specifiedRotation == null) {
  46274. var tangent = line.tangentAt(1);
  46275. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  46276. tangent[1], tangent[0]
  46277. ));
  46278. }
  46279. else {
  46280. symbolTo.attr('rotation', specifiedRotation);
  46281. }
  46282. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  46283. }
  46284. if (!label.ignore) {
  46285. label.attr('position', toPos);
  46286. var textPosition;
  46287. var textAlign;
  46288. var textVerticalAlign;
  46289. var textOrigin;
  46290. var distance$$1 = label.__labelDistance;
  46291. var distanceX = distance$$1[0] * invScale;
  46292. var distanceY = distance$$1[1] * invScale;
  46293. var halfPercent = percent / 2;
  46294. var tangent = line.tangentAt(halfPercent);
  46295. var n = [tangent[1], -tangent[0]];
  46296. var cp = line.pointAt(halfPercent);
  46297. if (n[1] > 0) {
  46298. n[0] = -n[0];
  46299. n[1] = -n[1];
  46300. }
  46301. var dir = tangent[0] < 0 ? -1 : 1;
  46302. if (label.__position !== 'start' && label.__position !== 'end') {
  46303. var rotation = -Math.atan2(tangent[1], tangent[0]);
  46304. if (toPos[0] < fromPos[0]) {
  46305. rotation = Math.PI + rotation;
  46306. }
  46307. label.attr('rotation', rotation);
  46308. }
  46309. var dy;
  46310. switch (label.__position) {
  46311. case 'insideStartTop':
  46312. case 'insideMiddleTop':
  46313. case 'insideEndTop':
  46314. case 'middle':
  46315. dy = -distanceY;
  46316. textVerticalAlign = 'bottom';
  46317. break;
  46318. case 'insideStartBottom':
  46319. case 'insideMiddleBottom':
  46320. case 'insideEndBottom':
  46321. dy = distanceY;
  46322. textVerticalAlign = 'top';
  46323. break;
  46324. default:
  46325. dy = 0;
  46326. textVerticalAlign = 'middle';
  46327. }
  46328. switch (label.__position) {
  46329. case 'end':
  46330. textPosition = [d[0] * distanceX + toPos[0], d[1] * distanceY + toPos[1]];
  46331. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  46332. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  46333. break;
  46334. case 'start':
  46335. textPosition = [-d[0] * distanceX + fromPos[0], -d[1] * distanceY + fromPos[1]];
  46336. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  46337. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  46338. break;
  46339. case 'insideStartTop':
  46340. case 'insideStart':
  46341. case 'insideStartBottom':
  46342. textPosition = [distanceX * dir + fromPos[0], fromPos[1] + dy];
  46343. textAlign = tangent[0] < 0 ? 'right' : 'left';
  46344. textOrigin = [-distanceX * dir, -dy];
  46345. break;
  46346. case 'insideMiddleTop':
  46347. case 'insideMiddle':
  46348. case 'insideMiddleBottom':
  46349. case 'middle':
  46350. textPosition = [cp[0], cp[1] + dy];
  46351. textAlign = 'center';
  46352. textOrigin = [0, -dy];
  46353. break;
  46354. case 'insideEndTop':
  46355. case 'insideEnd':
  46356. case 'insideEndBottom':
  46357. textPosition = [-distanceX * dir + toPos[0], toPos[1] + dy];
  46358. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  46359. textOrigin = [distanceX * dir, -dy];
  46360. break;
  46361. }
  46362. label.attr({
  46363. style: {
  46364. // Use the user specified text align and baseline first
  46365. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  46366. textAlign: label.__textAlign || textAlign
  46367. },
  46368. position: textPosition,
  46369. scale: [invScale, invScale],
  46370. origin: textOrigin
  46371. });
  46372. }
  46373. }
  46374. /**
  46375. * @constructor
  46376. * @extends {module:zrender/graphic/Group}
  46377. * @alias {module:echarts/chart/helper/Line}
  46378. */
  46379. function Line$1(lineData, idx, seriesScope) {
  46380. Group.call(this);
  46381. this._createLine(lineData, idx, seriesScope);
  46382. }
  46383. var lineProto = Line$1.prototype;
  46384. // Update symbol position and rotation
  46385. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  46386. lineProto._createLine = function (lineData, idx, seriesScope) {
  46387. var seriesModel = lineData.hostModel;
  46388. var linePoints = lineData.getItemLayout(idx);
  46389. var line = createLine(linePoints);
  46390. line.shape.percent = 0;
  46391. initProps(line, {
  46392. shape: {
  46393. percent: 1
  46394. }
  46395. }, seriesModel, idx);
  46396. this.add(line);
  46397. var label = new Text({
  46398. name: 'label',
  46399. // FIXME
  46400. // Temporary solution for `focusNodeAdjacency`.
  46401. // line label do not use the opacity of lineStyle.
  46402. lineLabelOriginalOpacity: 1
  46403. });
  46404. this.add(label);
  46405. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46406. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46407. // symbols must added after line to make sure
  46408. // it will be updated after line#update.
  46409. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  46410. this.add(symbol);
  46411. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  46412. }, this);
  46413. this._updateCommonStl(lineData, idx, seriesScope);
  46414. };
  46415. lineProto.updateData = function (lineData, idx, seriesScope) {
  46416. var seriesModel = lineData.hostModel;
  46417. var line = this.childOfName('line');
  46418. var linePoints = lineData.getItemLayout(idx);
  46419. var target = {
  46420. shape: {}
  46421. };
  46422. setLinePoints(target.shape, linePoints);
  46423. updateProps(line, target, seriesModel, idx);
  46424. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46425. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  46426. var key = makeSymbolTypeKey(symbolCategory);
  46427. // Symbol changed
  46428. if (this[key] !== symbolType) {
  46429. this.remove(this.childOfName(symbolCategory));
  46430. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46431. this.add(symbol);
  46432. }
  46433. this[key] = symbolType;
  46434. }, this);
  46435. this._updateCommonStl(lineData, idx, seriesScope);
  46436. };
  46437. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  46438. var seriesModel = lineData.hostModel;
  46439. var line = this.childOfName('line');
  46440. var lineStyle = seriesScope && seriesScope.lineStyle;
  46441. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  46442. var labelModel = seriesScope && seriesScope.labelModel;
  46443. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  46444. // Optimization for large dataset
  46445. if (!seriesScope || lineData.hasItemOption) {
  46446. var itemModel = lineData.getItemModel(idx);
  46447. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  46448. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  46449. labelModel = itemModel.getModel('label');
  46450. hoverLabelModel = itemModel.getModel('emphasis.label');
  46451. }
  46452. var visualColor = lineData.getItemVisual(idx, 'color');
  46453. var visualOpacity = retrieve3(
  46454. lineData.getItemVisual(idx, 'opacity'),
  46455. lineStyle.opacity,
  46456. 1
  46457. );
  46458. line.useStyle(defaults(
  46459. {
  46460. strokeNoScale: true,
  46461. fill: 'none',
  46462. stroke: visualColor,
  46463. opacity: visualOpacity
  46464. },
  46465. lineStyle
  46466. ));
  46467. line.hoverStyle = hoverLineStyle;
  46468. // Update symbol
  46469. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46470. var symbol = this.childOfName(symbolCategory);
  46471. if (symbol) {
  46472. symbol.setColor(visualColor);
  46473. symbol.setStyle({
  46474. opacity: visualOpacity
  46475. });
  46476. }
  46477. }, this);
  46478. var showLabel = labelModel.getShallow('show');
  46479. var hoverShowLabel = hoverLabelModel.getShallow('show');
  46480. var label = this.childOfName('label');
  46481. var defaultLabelColor;
  46482. var baseText;
  46483. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  46484. if (showLabel || hoverShowLabel) {
  46485. defaultLabelColor = visualColor || '#000';
  46486. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  46487. if (baseText == null) {
  46488. var rawVal = seriesModel.getRawValue(idx);
  46489. baseText = rawVal == null
  46490. ? lineData.getName(idx)
  46491. : isFinite(rawVal)
  46492. ? round$1(rawVal)
  46493. : rawVal;
  46494. }
  46495. }
  46496. var normalText = showLabel ? baseText : null;
  46497. var emphasisText = hoverShowLabel
  46498. ? retrieve2(
  46499. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  46500. baseText
  46501. )
  46502. : null;
  46503. var labelStyle = label.style;
  46504. // Always set `textStyle` even if `normalStyle.text` is null, because default
  46505. // values have to be set on `normalStyle`.
  46506. if (normalText != null || emphasisText != null) {
  46507. setTextStyle(label.style, labelModel, {
  46508. text: normalText
  46509. }, {
  46510. autoColor: defaultLabelColor
  46511. });
  46512. label.__textAlign = labelStyle.textAlign;
  46513. label.__verticalAlign = labelStyle.textVerticalAlign;
  46514. // 'start', 'middle', 'end'
  46515. label.__position = labelModel.get('position') || 'middle';
  46516. var distance$$1 = labelModel.get('distance');
  46517. if (!isArray(distance$$1)) {
  46518. distance$$1 = [distance$$1, distance$$1];
  46519. }
  46520. label.__labelDistance = distance$$1;
  46521. }
  46522. if (emphasisText != null) {
  46523. // Only these properties supported in this emphasis style here.
  46524. label.hoverStyle = {
  46525. text: emphasisText,
  46526. textFill: hoverLabelModel.getTextColor(true),
  46527. // For merging hover style to normal style, do not use
  46528. // `hoverLabelModel.getFont()` here.
  46529. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  46530. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  46531. fontSize: hoverLabelModel.getShallow('fontSize'),
  46532. fontFamily: hoverLabelModel.getShallow('fontFamily')
  46533. };
  46534. }
  46535. else {
  46536. label.hoverStyle = {
  46537. text: null
  46538. };
  46539. }
  46540. label.ignore = !showLabel && !hoverShowLabel;
  46541. setHoverStyle(this);
  46542. };
  46543. lineProto.highlight = function () {
  46544. this.trigger('emphasis');
  46545. };
  46546. lineProto.downplay = function () {
  46547. this.trigger('normal');
  46548. };
  46549. lineProto.updateLayout = function (lineData, idx) {
  46550. this.setLinePoints(lineData.getItemLayout(idx));
  46551. };
  46552. lineProto.setLinePoints = function (points) {
  46553. var linePath = this.childOfName('line');
  46554. setLinePoints(linePath.shape, points);
  46555. linePath.dirty();
  46556. };
  46557. inherits(Line$1, Group);
  46558. /*
  46559. * Licensed to the Apache Software Foundation (ASF) under one
  46560. * or more contributor license agreements. See the NOTICE file
  46561. * distributed with this work for additional information
  46562. * regarding copyright ownership. The ASF licenses this file
  46563. * to you under the Apache License, Version 2.0 (the
  46564. * "License"); you may not use this file except in compliance
  46565. * with the License. You may obtain a copy of the License at
  46566. *
  46567. * http://www.apache.org/licenses/LICENSE-2.0
  46568. *
  46569. * Unless required by applicable law or agreed to in writing,
  46570. * software distributed under the License is distributed on an
  46571. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46572. * KIND, either express or implied. See the License for the
  46573. * specific language governing permissions and limitations
  46574. * under the License.
  46575. */
  46576. /**
  46577. * @module echarts/chart/helper/LineDraw
  46578. */
  46579. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  46580. /**
  46581. * @alias module:echarts/component/marker/LineDraw
  46582. * @constructor
  46583. */
  46584. function LineDraw(ctor) {
  46585. this._ctor = ctor || Line$1;
  46586. this.group = new Group();
  46587. }
  46588. var lineDrawProto = LineDraw.prototype;
  46589. lineDrawProto.isPersistent = function () {
  46590. return true;
  46591. };
  46592. /**
  46593. * @param {module:echarts/data/List} lineData
  46594. */
  46595. lineDrawProto.updateData = function (lineData) {
  46596. var lineDraw = this;
  46597. var group = lineDraw.group;
  46598. var oldLineData = lineDraw._lineData;
  46599. lineDraw._lineData = lineData;
  46600. // There is no oldLineData only when first rendering or switching from
  46601. // stream mode to normal mode, where previous elements should be removed.
  46602. if (!oldLineData) {
  46603. group.removeAll();
  46604. }
  46605. var seriesScope = makeSeriesScope$1(lineData);
  46606. lineData.diff(oldLineData)
  46607. .add(function (idx) {
  46608. doAdd(lineDraw, lineData, idx, seriesScope);
  46609. })
  46610. .update(function (newIdx, oldIdx) {
  46611. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  46612. })
  46613. .remove(function (idx) {
  46614. group.remove(oldLineData.getItemGraphicEl(idx));
  46615. })
  46616. .execute();
  46617. };
  46618. function doAdd(lineDraw, lineData, idx, seriesScope) {
  46619. var itemLayout = lineData.getItemLayout(idx);
  46620. if (!lineNeedsDraw(itemLayout)) {
  46621. return;
  46622. }
  46623. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  46624. lineData.setItemGraphicEl(idx, el);
  46625. lineDraw.group.add(el);
  46626. }
  46627. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  46628. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  46629. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  46630. lineDraw.group.remove(itemEl);
  46631. return;
  46632. }
  46633. if (!itemEl) {
  46634. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  46635. }
  46636. else {
  46637. itemEl.updateData(newLineData, newIdx, seriesScope);
  46638. }
  46639. newLineData.setItemGraphicEl(newIdx, itemEl);
  46640. lineDraw.group.add(itemEl);
  46641. }
  46642. lineDrawProto.updateLayout = function () {
  46643. var lineData = this._lineData;
  46644. // Do not support update layout in incremental mode.
  46645. if (!lineData) {
  46646. return;
  46647. }
  46648. lineData.eachItemGraphicEl(function (el, idx) {
  46649. el.updateLayout(lineData, idx);
  46650. }, this);
  46651. };
  46652. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  46653. this._seriesScope = makeSeriesScope$1(lineData);
  46654. this._lineData = null;
  46655. this.group.removeAll();
  46656. };
  46657. function isEffectObject(el) {
  46658. return el.animators && el.animators.length > 0;
  46659. }
  46660. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  46661. function updateIncrementalAndHover(el) {
  46662. if (!el.isGroup && !isEffectObject(el)) {
  46663. el.incremental = el.useHoverLayer = true;
  46664. }
  46665. }
  46666. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  46667. var itemLayout = lineData.getItemLayout(idx);
  46668. if (lineNeedsDraw(itemLayout)) {
  46669. var el = new this._ctor(lineData, idx, this._seriesScope);
  46670. el.traverse(updateIncrementalAndHover);
  46671. this.group.add(el);
  46672. lineData.setItemGraphicEl(idx, el);
  46673. }
  46674. }
  46675. };
  46676. function makeSeriesScope$1(lineData) {
  46677. var hostModel = lineData.hostModel;
  46678. return {
  46679. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  46680. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  46681. labelModel: hostModel.getModel('label'),
  46682. hoverLabelModel: hostModel.getModel('emphasis.label')
  46683. };
  46684. }
  46685. lineDrawProto.remove = function () {
  46686. this._clearIncremental();
  46687. this._incremental = null;
  46688. this.group.removeAll();
  46689. };
  46690. lineDrawProto._clearIncremental = function () {
  46691. var incremental = this._incremental;
  46692. if (incremental) {
  46693. incremental.clearDisplaybles();
  46694. }
  46695. };
  46696. function isPointNaN(pt) {
  46697. return isNaN(pt[0]) || isNaN(pt[1]);
  46698. }
  46699. function lineNeedsDraw(pts) {
  46700. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  46701. }
  46702. /*
  46703. * Licensed to the Apache Software Foundation (ASF) under one
  46704. * or more contributor license agreements. See the NOTICE file
  46705. * distributed with this work for additional information
  46706. * regarding copyright ownership. The ASF licenses this file
  46707. * to you under the Apache License, Version 2.0 (the
  46708. * "License"); you may not use this file except in compliance
  46709. * with the License. You may obtain a copy of the License at
  46710. *
  46711. * http://www.apache.org/licenses/LICENSE-2.0
  46712. *
  46713. * Unless required by applicable law or agreed to in writing,
  46714. * software distributed under the License is distributed on an
  46715. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46716. * KIND, either express or implied. See the License for the
  46717. * specific language governing permissions and limitations
  46718. * under the License.
  46719. */
  46720. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  46721. var data = seriesModel.getData();
  46722. // Special type markLine like 'min', 'max', 'average', 'median'
  46723. var mlType = item.type;
  46724. if (!isArray(item)
  46725. && (
  46726. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  46727. // In case
  46728. // data: [{
  46729. // yAxis: 10
  46730. // }]
  46731. || (item.xAxis != null || item.yAxis != null)
  46732. )
  46733. ) {
  46734. var valueAxis;
  46735. var value;
  46736. if (item.yAxis != null || item.xAxis != null) {
  46737. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  46738. value = retrieve(item.yAxis, item.xAxis);
  46739. }
  46740. else {
  46741. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  46742. valueAxis = axisInfo.valueAxis;
  46743. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  46744. value = numCalculate(data, valueDataDim, mlType);
  46745. }
  46746. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  46747. var baseIndex = 1 - valueIndex;
  46748. var mlFrom = clone(item);
  46749. var mlTo = {};
  46750. mlFrom.type = null;
  46751. mlFrom.coord = [];
  46752. mlTo.coord = [];
  46753. mlFrom.coord[baseIndex] = -Infinity;
  46754. mlTo.coord[baseIndex] = Infinity;
  46755. var precision = mlModel.get('precision');
  46756. if (precision >= 0 && typeof value === 'number') {
  46757. value = +value.toFixed(Math.min(precision, 20));
  46758. }
  46759. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  46760. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  46761. type: mlType,
  46762. valueIndex: item.valueIndex,
  46763. // Force to use the value of calculated value.
  46764. value: value
  46765. }];
  46766. }
  46767. item = [
  46768. dataTransform(seriesModel, item[0]),
  46769. dataTransform(seriesModel, item[1]),
  46770. extend({}, item[2])
  46771. ];
  46772. // Avoid line data type is extended by from(to) data type
  46773. item[2].type = item[2].type || '';
  46774. // Merge from option and to option into line option
  46775. merge(item[2], item[0]);
  46776. merge(item[2], item[1]);
  46777. return item;
  46778. };
  46779. function isInifinity(val) {
  46780. return !isNaN(val) && !isFinite(val);
  46781. }
  46782. // If a markLine has one dim
  46783. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  46784. var otherDimIndex = 1 - dimIndex;
  46785. var dimName = coordSys.dimensions[dimIndex];
  46786. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  46787. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  46788. }
  46789. function markLineFilter(coordSys, item) {
  46790. if (coordSys.type === 'cartesian2d') {
  46791. var fromCoord = item[0].coord;
  46792. var toCoord = item[1].coord;
  46793. // In case
  46794. // {
  46795. // markLine: {
  46796. // data: [{ yAxis: 2 }]
  46797. // }
  46798. // }
  46799. if (
  46800. fromCoord && toCoord
  46801. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  46802. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  46803. ) {
  46804. return true;
  46805. }
  46806. }
  46807. return dataFilter$1(coordSys, item[0])
  46808. && dataFilter$1(coordSys, item[1]);
  46809. }
  46810. function updateSingleMarkerEndLayout(
  46811. data, idx, isFrom, seriesModel, api
  46812. ) {
  46813. var coordSys = seriesModel.coordinateSystem;
  46814. var itemModel = data.getItemModel(idx);
  46815. var point;
  46816. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  46817. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  46818. if (!isNaN(xPx) && !isNaN(yPx)) {
  46819. point = [xPx, yPx];
  46820. }
  46821. else {
  46822. // Chart like bar may have there own marker positioning logic
  46823. if (seriesModel.getMarkerPosition) {
  46824. // Use the getMarkerPoisition
  46825. point = seriesModel.getMarkerPosition(
  46826. data.getValues(data.dimensions, idx)
  46827. );
  46828. }
  46829. else {
  46830. var dims = coordSys.dimensions;
  46831. var x = data.get(dims[0], idx);
  46832. var y = data.get(dims[1], idx);
  46833. point = coordSys.dataToPoint([x, y]);
  46834. }
  46835. // Expand line to the edge of grid if value on one axis is Inifnity
  46836. // In case
  46837. // markLine: {
  46838. // data: [{
  46839. // yAxis: 2
  46840. // // or
  46841. // type: 'average'
  46842. // }]
  46843. // }
  46844. if (coordSys.type === 'cartesian2d') {
  46845. var xAxis = coordSys.getAxis('x');
  46846. var yAxis = coordSys.getAxis('y');
  46847. var dims = coordSys.dimensions;
  46848. if (isInifinity(data.get(dims[0], idx))) {
  46849. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  46850. }
  46851. else if (isInifinity(data.get(dims[1], idx))) {
  46852. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  46853. }
  46854. }
  46855. // Use x, y if has any
  46856. if (!isNaN(xPx)) {
  46857. point[0] = xPx;
  46858. }
  46859. if (!isNaN(yPx)) {
  46860. point[1] = yPx;
  46861. }
  46862. }
  46863. data.setItemLayout(idx, point);
  46864. }
  46865. MarkerView.extend({
  46866. type: 'markLine',
  46867. // updateLayout: function (markLineModel, ecModel, api) {
  46868. // ecModel.eachSeries(function (seriesModel) {
  46869. // var mlModel = seriesModel.markLineModel;
  46870. // if (mlModel) {
  46871. // var mlData = mlModel.getData();
  46872. // var fromData = mlModel.__from;
  46873. // var toData = mlModel.__to;
  46874. // // Update visual and layout of from symbol and to symbol
  46875. // fromData.each(function (idx) {
  46876. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  46877. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  46878. // });
  46879. // // Update layout of line
  46880. // mlData.each(function (idx) {
  46881. // mlData.setItemLayout(idx, [
  46882. // fromData.getItemLayout(idx),
  46883. // toData.getItemLayout(idx)
  46884. // ]);
  46885. // });
  46886. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  46887. // }
  46888. // }, this);
  46889. // },
  46890. updateTransform: function (markLineModel, ecModel, api) {
  46891. ecModel.eachSeries(function (seriesModel) {
  46892. var mlModel = seriesModel.markLineModel;
  46893. if (mlModel) {
  46894. var mlData = mlModel.getData();
  46895. var fromData = mlModel.__from;
  46896. var toData = mlModel.__to;
  46897. // Update visual and layout of from symbol and to symbol
  46898. fromData.each(function (idx) {
  46899. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  46900. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  46901. });
  46902. // Update layout of line
  46903. mlData.each(function (idx) {
  46904. mlData.setItemLayout(idx, [
  46905. fromData.getItemLayout(idx),
  46906. toData.getItemLayout(idx)
  46907. ]);
  46908. });
  46909. this.markerGroupMap.get(seriesModel.id).updateLayout();
  46910. }
  46911. }, this);
  46912. },
  46913. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  46914. var coordSys = seriesModel.coordinateSystem;
  46915. var seriesId = seriesModel.id;
  46916. var seriesData = seriesModel.getData();
  46917. var lineDrawMap = this.markerGroupMap;
  46918. var lineDraw = lineDrawMap.get(seriesId)
  46919. || lineDrawMap.set(seriesId, new LineDraw());
  46920. this.group.add(lineDraw.group);
  46921. var mlData = createList$2(coordSys, seriesModel, mlModel);
  46922. var fromData = mlData.from;
  46923. var toData = mlData.to;
  46924. var lineData = mlData.line;
  46925. mlModel.__from = fromData;
  46926. mlModel.__to = toData;
  46927. // Line data for tooltip and formatter
  46928. mlModel.setData(lineData);
  46929. var symbolType = mlModel.get('symbol');
  46930. var symbolSize = mlModel.get('symbolSize');
  46931. if (!isArray(symbolType)) {
  46932. symbolType = [symbolType, symbolType];
  46933. }
  46934. if (typeof symbolSize === 'number') {
  46935. symbolSize = [symbolSize, symbolSize];
  46936. }
  46937. // Update visual and layout of from symbol and to symbol
  46938. mlData.from.each(function (idx) {
  46939. updateDataVisualAndLayout(fromData, idx, true);
  46940. updateDataVisualAndLayout(toData, idx, false);
  46941. });
  46942. // Update visual and layout of line
  46943. lineData.each(function (idx) {
  46944. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  46945. lineData.setItemVisual(idx, {
  46946. color: lineColor || fromData.getItemVisual(idx, 'color')
  46947. });
  46948. lineData.setItemLayout(idx, [
  46949. fromData.getItemLayout(idx),
  46950. toData.getItemLayout(idx)
  46951. ]);
  46952. lineData.setItemVisual(idx, {
  46953. 'fromSymbolRotate': fromData.getItemVisual(idx, 'symbolRotate'),
  46954. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  46955. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  46956. 'toSymbolRotate': toData.getItemVisual(idx, 'symbolRotate'),
  46957. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  46958. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  46959. });
  46960. });
  46961. lineDraw.updateData(lineData);
  46962. // Set host model for tooltip
  46963. // FIXME
  46964. mlData.line.eachItemGraphicEl(function (el, idx) {
  46965. el.traverse(function (child) {
  46966. child.dataModel = mlModel;
  46967. });
  46968. });
  46969. function updateDataVisualAndLayout(data, idx, isFrom) {
  46970. var itemModel = data.getItemModel(idx);
  46971. updateSingleMarkerEndLayout(
  46972. data, idx, isFrom, seriesModel, api
  46973. );
  46974. data.setItemVisual(idx, {
  46975. symbolRotate: itemModel.get('symbolRotate'),
  46976. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  46977. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  46978. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  46979. });
  46980. }
  46981. lineDraw.__keep = true;
  46982. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  46983. }
  46984. });
  46985. /**
  46986. * @inner
  46987. * @param {module:echarts/coord/*} coordSys
  46988. * @param {module:echarts/model/Series} seriesModel
  46989. * @param {module:echarts/model/Model} mpModel
  46990. */
  46991. function createList$2(coordSys, seriesModel, mlModel) {
  46992. var coordDimsInfos;
  46993. if (coordSys) {
  46994. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  46995. var info = seriesModel.getData().getDimensionInfo(
  46996. seriesModel.getData().mapDimension(coordDim)
  46997. ) || {};
  46998. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  46999. return defaults({name: coordDim}, info);
  47000. });
  47001. }
  47002. else {
  47003. coordDimsInfos = [{
  47004. name: 'value',
  47005. type: 'float'
  47006. }];
  47007. }
  47008. var fromData = new List(coordDimsInfos, mlModel);
  47009. var toData = new List(coordDimsInfos, mlModel);
  47010. // No dimensions
  47011. var lineData = new List([], mlModel);
  47012. var optData = map(mlModel.get('data'), curry(
  47013. markLineTransform, seriesModel, coordSys, mlModel
  47014. ));
  47015. if (coordSys) {
  47016. optData = filter(
  47017. optData, curry(markLineFilter, coordSys)
  47018. );
  47019. }
  47020. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  47021. return item.value;
  47022. };
  47023. fromData.initData(
  47024. map(optData, function (item) {
  47025. return item[0];
  47026. }),
  47027. null,
  47028. dimValueGetter$$1
  47029. );
  47030. toData.initData(
  47031. map(optData, function (item) {
  47032. return item[1];
  47033. }),
  47034. null,
  47035. dimValueGetter$$1
  47036. );
  47037. lineData.initData(
  47038. map(optData, function (item) {
  47039. return item[2];
  47040. })
  47041. );
  47042. lineData.hasItemOption = true;
  47043. return {
  47044. from: fromData,
  47045. to: toData,
  47046. line: lineData
  47047. };
  47048. }
  47049. /*
  47050. * Licensed to the Apache Software Foundation (ASF) under one
  47051. * or more contributor license agreements. See the NOTICE file
  47052. * distributed with this work for additional information
  47053. * regarding copyright ownership. The ASF licenses this file
  47054. * to you under the Apache License, Version 2.0 (the
  47055. * "License"); you may not use this file except in compliance
  47056. * with the License. You may obtain a copy of the License at
  47057. *
  47058. * http://www.apache.org/licenses/LICENSE-2.0
  47059. *
  47060. * Unless required by applicable law or agreed to in writing,
  47061. * software distributed under the License is distributed on an
  47062. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47063. * KIND, either express or implied. See the License for the
  47064. * specific language governing permissions and limitations
  47065. * under the License.
  47066. */
  47067. registerPreprocessor(function (opt) {
  47068. // Make sure markLine component is enabled
  47069. opt.markLine = opt.markLine || {};
  47070. });
  47071. /*
  47072. * Licensed to the Apache Software Foundation (ASF) under one
  47073. * or more contributor license agreements. See the NOTICE file
  47074. * distributed with this work for additional information
  47075. * regarding copyright ownership. The ASF licenses this file
  47076. * to you under the Apache License, Version 2.0 (the
  47077. * "License"); you may not use this file except in compliance
  47078. * with the License. You may obtain a copy of the License at
  47079. *
  47080. * http://www.apache.org/licenses/LICENSE-2.0
  47081. *
  47082. * Unless required by applicable law or agreed to in writing,
  47083. * software distributed under the License is distributed on an
  47084. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47085. * KIND, either express or implied. See the License for the
  47086. * specific language governing permissions and limitations
  47087. * under the License.
  47088. */
  47089. MarkerModel.extend({
  47090. type: 'markArea',
  47091. defaultOption: {
  47092. zlevel: 0,
  47093. // PENDING
  47094. z: 1,
  47095. tooltip: {
  47096. trigger: 'item'
  47097. },
  47098. // markArea should fixed on the coordinate system
  47099. animation: false,
  47100. label: {
  47101. show: true,
  47102. position: 'top'
  47103. },
  47104. itemStyle: {
  47105. // color and borderColor default to use color from series
  47106. // color: 'auto'
  47107. // borderColor: 'auto'
  47108. borderWidth: 0
  47109. },
  47110. emphasis: {
  47111. label: {
  47112. show: true,
  47113. position: 'top'
  47114. }
  47115. }
  47116. }
  47117. });
  47118. /*
  47119. * Licensed to the Apache Software Foundation (ASF) under one
  47120. * or more contributor license agreements. See the NOTICE file
  47121. * distributed with this work for additional information
  47122. * regarding copyright ownership. The ASF licenses this file
  47123. * to you under the Apache License, Version 2.0 (the
  47124. * "License"); you may not use this file except in compliance
  47125. * with the License. You may obtain a copy of the License at
  47126. *
  47127. * http://www.apache.org/licenses/LICENSE-2.0
  47128. *
  47129. * Unless required by applicable law or agreed to in writing,
  47130. * software distributed under the License is distributed on an
  47131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47132. * KIND, either express or implied. See the License for the
  47133. * specific language governing permissions and limitations
  47134. * under the License.
  47135. */
  47136. // TODO Better on polar
  47137. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  47138. var lt = dataTransform(seriesModel, item[0]);
  47139. var rb = dataTransform(seriesModel, item[1]);
  47140. var retrieve$$1 = retrieve;
  47141. // FIXME make sure lt is less than rb
  47142. var ltCoord = lt.coord;
  47143. var rbCoord = rb.coord;
  47144. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  47145. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  47146. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  47147. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  47148. // Merge option into one
  47149. var result = mergeAll([{}, lt, rb]);
  47150. result.coord = [
  47151. lt.coord, rb.coord
  47152. ];
  47153. result.x0 = lt.x;
  47154. result.y0 = lt.y;
  47155. result.x1 = rb.x;
  47156. result.y1 = rb.y;
  47157. return result;
  47158. };
  47159. function isInifinity$1(val) {
  47160. return !isNaN(val) && !isFinite(val);
  47161. }
  47162. // If a markArea has one dim
  47163. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  47164. var otherDimIndex = 1 - dimIndex;
  47165. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  47166. }
  47167. function markAreaFilter(coordSys, item) {
  47168. var fromCoord = item.coord[0];
  47169. var toCoord = item.coord[1];
  47170. if (coordSys.type === 'cartesian2d') {
  47171. // In case
  47172. // {
  47173. // markArea: {
  47174. // data: [{ yAxis: 2 }]
  47175. // }
  47176. // }
  47177. if (
  47178. fromCoord && toCoord
  47179. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  47180. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  47181. ) {
  47182. return true;
  47183. }
  47184. }
  47185. return dataFilter$1(coordSys, {
  47186. coord: fromCoord,
  47187. x: item.x0,
  47188. y: item.y0
  47189. })
  47190. || dataFilter$1(coordSys, {
  47191. coord: toCoord,
  47192. x: item.x1,
  47193. y: item.y1
  47194. });
  47195. }
  47196. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  47197. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  47198. var coordSys = seriesModel.coordinateSystem;
  47199. var itemModel = data.getItemModel(idx);
  47200. var point;
  47201. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  47202. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  47203. if (!isNaN(xPx) && !isNaN(yPx)) {
  47204. point = [xPx, yPx];
  47205. }
  47206. else {
  47207. // Chart like bar may have there own marker positioning logic
  47208. if (seriesModel.getMarkerPosition) {
  47209. // Use the getMarkerPoisition
  47210. point = seriesModel.getMarkerPosition(
  47211. data.getValues(dims, idx)
  47212. );
  47213. }
  47214. else {
  47215. var x = data.get(dims[0], idx);
  47216. var y = data.get(dims[1], idx);
  47217. var pt = [x, y];
  47218. coordSys.clampData && coordSys.clampData(pt, pt);
  47219. point = coordSys.dataToPoint(pt, true);
  47220. }
  47221. if (coordSys.type === 'cartesian2d') {
  47222. var xAxis = coordSys.getAxis('x');
  47223. var yAxis = coordSys.getAxis('y');
  47224. var x = data.get(dims[0], idx);
  47225. var y = data.get(dims[1], idx);
  47226. if (isInifinity$1(x)) {
  47227. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  47228. }
  47229. else if (isInifinity$1(y)) {
  47230. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  47231. }
  47232. }
  47233. // Use x, y if has any
  47234. if (!isNaN(xPx)) {
  47235. point[0] = xPx;
  47236. }
  47237. if (!isNaN(yPx)) {
  47238. point[1] = yPx;
  47239. }
  47240. }
  47241. return point;
  47242. }
  47243. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  47244. MarkerView.extend({
  47245. type: 'markArea',
  47246. // updateLayout: function (markAreaModel, ecModel, api) {
  47247. // ecModel.eachSeries(function (seriesModel) {
  47248. // var maModel = seriesModel.markAreaModel;
  47249. // if (maModel) {
  47250. // var areaData = maModel.getData();
  47251. // areaData.each(function (idx) {
  47252. // var points = zrUtil.map(dimPermutations, function (dim) {
  47253. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  47254. // });
  47255. // // Layout
  47256. // areaData.setItemLayout(idx, points);
  47257. // var el = areaData.getItemGraphicEl(idx);
  47258. // el.setShape('points', points);
  47259. // });
  47260. // }
  47261. // }, this);
  47262. // },
  47263. updateTransform: function (markAreaModel, ecModel, api) {
  47264. ecModel.eachSeries(function (seriesModel) {
  47265. var maModel = seriesModel.markAreaModel;
  47266. if (maModel) {
  47267. var areaData = maModel.getData();
  47268. areaData.each(function (idx) {
  47269. var points = map(dimPermutations, function (dim) {
  47270. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  47271. });
  47272. // Layout
  47273. areaData.setItemLayout(idx, points);
  47274. var el = areaData.getItemGraphicEl(idx);
  47275. el.setShape('points', points);
  47276. });
  47277. }
  47278. }, this);
  47279. },
  47280. renderSeries: function (seriesModel, maModel, ecModel, api) {
  47281. var coordSys = seriesModel.coordinateSystem;
  47282. var seriesId = seriesModel.id;
  47283. var seriesData = seriesModel.getData();
  47284. var areaGroupMap = this.markerGroupMap;
  47285. var polygonGroup = areaGroupMap.get(seriesId)
  47286. || areaGroupMap.set(seriesId, {group: new Group()});
  47287. this.group.add(polygonGroup.group);
  47288. polygonGroup.__keep = true;
  47289. var areaData = createList$3(coordSys, seriesModel, maModel);
  47290. // Line data for tooltip and formatter
  47291. maModel.setData(areaData);
  47292. // Update visual and layout of line
  47293. areaData.each(function (idx) {
  47294. // Layout
  47295. var points = map(dimPermutations, function (dim) {
  47296. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  47297. });
  47298. // If none of the area is inside coordSys, allClipped is set to be true
  47299. // in layout so that label will not be displayed. See #12591
  47300. var allClipped = true;
  47301. each$1(dimPermutations, function (dim) {
  47302. if (!allClipped) {
  47303. return;
  47304. }
  47305. var xValue = areaData.get(dim[0], idx);
  47306. var yValue = areaData.get(dim[1], idx);
  47307. // If is infinity, the axis should be considered not clipped
  47308. if ((isInifinity$1(xValue) || coordSys.getAxis('x').containData(xValue))
  47309. && (isInifinity$1(yValue) || coordSys.getAxis('y').containData(yValue))
  47310. ) {
  47311. allClipped = false;
  47312. }
  47313. });
  47314. areaData.setItemLayout(idx, {
  47315. points: points,
  47316. allClipped: allClipped
  47317. });
  47318. // Visual
  47319. areaData.setItemVisual(idx, {
  47320. color: seriesData.getVisual('color')
  47321. });
  47322. });
  47323. areaData.diff(polygonGroup.__data)
  47324. .add(function (idx) {
  47325. var layout = areaData.getItemLayout(idx);
  47326. if (!layout.allClipped) {
  47327. var polygon = new Polygon({
  47328. shape: {
  47329. points: layout.points
  47330. }
  47331. });
  47332. areaData.setItemGraphicEl(idx, polygon);
  47333. polygonGroup.group.add(polygon);
  47334. }
  47335. })
  47336. .update(function (newIdx, oldIdx) {
  47337. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  47338. var layout = areaData.getItemLayout(newIdx);
  47339. if (!layout.allClipped) {
  47340. if (polygon) {
  47341. updateProps(polygon, {
  47342. shape: {
  47343. points: layout.points
  47344. }
  47345. }, maModel, newIdx);
  47346. }
  47347. else {
  47348. polygon = new Polygon({
  47349. shape: {
  47350. points: layout.points
  47351. }
  47352. });
  47353. }
  47354. areaData.setItemGraphicEl(newIdx, polygon);
  47355. polygonGroup.group.add(polygon);
  47356. }
  47357. else if (polygon) {
  47358. polygonGroup.group.remove(polygon);
  47359. }
  47360. })
  47361. .remove(function (idx) {
  47362. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  47363. polygonGroup.group.remove(polygon);
  47364. })
  47365. .execute();
  47366. areaData.eachItemGraphicEl(function (polygon, idx) {
  47367. var itemModel = areaData.getItemModel(idx);
  47368. var labelModel = itemModel.getModel('label');
  47369. var labelHoverModel = itemModel.getModel('emphasis.label');
  47370. var color = areaData.getItemVisual(idx, 'color');
  47371. polygon.useStyle(
  47372. defaults(
  47373. itemModel.getModel('itemStyle').getItemStyle(),
  47374. {
  47375. fill: modifyAlpha(color, 0.4),
  47376. stroke: color
  47377. }
  47378. )
  47379. );
  47380. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  47381. setLabelStyle(
  47382. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  47383. {
  47384. labelFetcher: maModel,
  47385. labelDataIndex: idx,
  47386. defaultText: areaData.getName(idx) || '',
  47387. isRectText: true,
  47388. autoColor: color
  47389. }
  47390. );
  47391. setHoverStyle(polygon, {});
  47392. polygon.dataModel = maModel;
  47393. });
  47394. polygonGroup.__data = areaData;
  47395. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  47396. }
  47397. });
  47398. /**
  47399. * @inner
  47400. * @param {module:echarts/coord/*} coordSys
  47401. * @param {module:echarts/model/Series} seriesModel
  47402. * @param {module:echarts/model/Model} mpModel
  47403. */
  47404. function createList$3(coordSys, seriesModel, maModel) {
  47405. var coordDimsInfos;
  47406. var areaData;
  47407. var dims = ['x0', 'y0', 'x1', 'y1'];
  47408. if (coordSys) {
  47409. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  47410. var data = seriesModel.getData();
  47411. var info = data.getDimensionInfo(
  47412. data.mapDimension(coordDim)
  47413. ) || {};
  47414. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  47415. return defaults({name: coordDim}, info);
  47416. });
  47417. areaData = new List(map(dims, function (dim, idx) {
  47418. return {
  47419. name: dim,
  47420. type: coordDimsInfos[idx % 2].type
  47421. };
  47422. }), maModel);
  47423. }
  47424. else {
  47425. coordDimsInfos = [{
  47426. name: 'value',
  47427. type: 'float'
  47428. }];
  47429. areaData = new List(coordDimsInfos, maModel);
  47430. }
  47431. var optData = map(maModel.get('data'), curry(
  47432. markAreaTransform, seriesModel, coordSys, maModel
  47433. ));
  47434. if (coordSys) {
  47435. optData = filter(
  47436. optData, curry(markAreaFilter, coordSys)
  47437. );
  47438. }
  47439. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  47440. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  47441. } : function (item) {
  47442. return item.value;
  47443. };
  47444. areaData.initData(optData, null, dimValueGetter$$1);
  47445. areaData.hasItemOption = true;
  47446. return areaData;
  47447. }
  47448. /*
  47449. * Licensed to the Apache Software Foundation (ASF) under one
  47450. * or more contributor license agreements. See the NOTICE file
  47451. * distributed with this work for additional information
  47452. * regarding copyright ownership. The ASF licenses this file
  47453. * to you under the Apache License, Version 2.0 (the
  47454. * "License"); you may not use this file except in compliance
  47455. * with the License. You may obtain a copy of the License at
  47456. *
  47457. * http://www.apache.org/licenses/LICENSE-2.0
  47458. *
  47459. * Unless required by applicable law or agreed to in writing,
  47460. * software distributed under the License is distributed on an
  47461. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47462. * KIND, either express or implied. See the License for the
  47463. * specific language governing permissions and limitations
  47464. * under the License.
  47465. */
  47466. registerPreprocessor(function (opt) {
  47467. // Make sure markArea component is enabled
  47468. opt.markArea = opt.markArea || {};
  47469. });
  47470. /*
  47471. * Licensed to the Apache Software Foundation (ASF) under one
  47472. * or more contributor license agreements. See the NOTICE file
  47473. * distributed with this work for additional information
  47474. * regarding copyright ownership. The ASF licenses this file
  47475. * to you under the Apache License, Version 2.0 (the
  47476. * "License"); you may not use this file except in compliance
  47477. * with the License. You may obtain a copy of the License at
  47478. *
  47479. * http://www.apache.org/licenses/LICENSE-2.0
  47480. *
  47481. * Unless required by applicable law or agreed to in writing,
  47482. * software distributed under the License is distributed on an
  47483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47484. * KIND, either express or implied. See the License for the
  47485. * specific language governing permissions and limitations
  47486. * under the License.
  47487. */
  47488. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  47489. // Default 'slider' when no type specified.
  47490. return 'slider';
  47491. });
  47492. /*
  47493. * Licensed to the Apache Software Foundation (ASF) under one
  47494. * or more contributor license agreements. See the NOTICE file
  47495. * distributed with this work for additional information
  47496. * regarding copyright ownership. The ASF licenses this file
  47497. * to you under the Apache License, Version 2.0 (the
  47498. * "License"); you may not use this file except in compliance
  47499. * with the License. You may obtain a copy of the License at
  47500. *
  47501. * http://www.apache.org/licenses/LICENSE-2.0
  47502. *
  47503. * Unless required by applicable law or agreed to in writing,
  47504. * software distributed under the License is distributed on an
  47505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47506. * KIND, either express or implied. See the License for the
  47507. * specific language governing permissions and limitations
  47508. * under the License.
  47509. */
  47510. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  47511. // Supported coords.
  47512. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  47513. /**
  47514. * @param {string} coordType
  47515. * @return {boolean}
  47516. */
  47517. function isCoordSupported(coordType) {
  47518. return indexOf(COORDS, coordType) >= 0;
  47519. }
  47520. /**
  47521. * Create "each" method to iterate names.
  47522. *
  47523. * @pubilc
  47524. * @param {Array.<string>} names
  47525. * @param {Array.<string>=} attrs
  47526. * @return {Function}
  47527. */
  47528. function createNameEach(names, attrs) {
  47529. names = names.slice();
  47530. var capitalNames = map(names, capitalFirst);
  47531. attrs = (attrs || []).slice();
  47532. var capitalAttrs = map(attrs, capitalFirst);
  47533. return function (callback, context) {
  47534. each$1(names, function (name, index) {
  47535. var nameObj = {name: name, capital: capitalNames[index]};
  47536. for (var j = 0; j < attrs.length; j++) {
  47537. nameObj[attrs[j]] = name + capitalAttrs[j];
  47538. }
  47539. callback.call(context, nameObj);
  47540. });
  47541. };
  47542. }
  47543. /**
  47544. * Iterate each dimension name.
  47545. *
  47546. * @public
  47547. * @param {Function} callback The parameter is like:
  47548. * {
  47549. * name: 'angle',
  47550. * capital: 'Angle',
  47551. * axis: 'angleAxis',
  47552. * axisIndex: 'angleAixs',
  47553. * index: 'angleIndex'
  47554. * }
  47555. * @param {Object} context
  47556. */
  47557. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  47558. /**
  47559. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  47560. * dataZoomModels and 'links' make up one or more graphics.
  47561. * This function finds the graphic where the source dataZoomModel is in.
  47562. *
  47563. * @public
  47564. * @param {Function} forEachNode Node iterator.
  47565. * @param {Function} forEachEdgeType edgeType iterator
  47566. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  47567. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  47568. */
  47569. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  47570. return function (sourceNode) {
  47571. var result = {
  47572. nodes: [],
  47573. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  47574. };
  47575. forEachEdgeType(function (edgeType) {
  47576. result.records[edgeType.name] = {};
  47577. });
  47578. if (!sourceNode) {
  47579. return result;
  47580. }
  47581. absorb(sourceNode, result);
  47582. var existsLink;
  47583. do {
  47584. existsLink = false;
  47585. forEachNode(processSingleNode);
  47586. }
  47587. while (existsLink);
  47588. function processSingleNode(node) {
  47589. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  47590. absorb(node, result);
  47591. existsLink = true;
  47592. }
  47593. }
  47594. return result;
  47595. };
  47596. function isNodeAbsorded(node, result) {
  47597. return indexOf(result.nodes, node) >= 0;
  47598. }
  47599. function isLinked(node, result) {
  47600. var hasLink = false;
  47601. forEachEdgeType(function (edgeType) {
  47602. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  47603. result.records[edgeType.name][edgeId] && (hasLink = true);
  47604. });
  47605. });
  47606. return hasLink;
  47607. }
  47608. function absorb(node, result) {
  47609. result.nodes.push(node);
  47610. forEachEdgeType(function (edgeType) {
  47611. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  47612. result.records[edgeType.name][edgeId] = true;
  47613. });
  47614. });
  47615. }
  47616. }
  47617. /*
  47618. * Licensed to the Apache Software Foundation (ASF) under one
  47619. * or more contributor license agreements. See the NOTICE file
  47620. * distributed with this work for additional information
  47621. * regarding copyright ownership. The ASF licenses this file
  47622. * to you under the Apache License, Version 2.0 (the
  47623. * "License"); you may not use this file except in compliance
  47624. * with the License. You may obtain a copy of the License at
  47625. *
  47626. * http://www.apache.org/licenses/LICENSE-2.0
  47627. *
  47628. * Unless required by applicable law or agreed to in writing,
  47629. * software distributed under the License is distributed on an
  47630. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47631. * KIND, either express or implied. See the License for the
  47632. * specific language governing permissions and limitations
  47633. * under the License.
  47634. */
  47635. /**
  47636. * Calculate slider move result.
  47637. * Usage:
  47638. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  47639. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  47640. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  47641. *
  47642. * @param {number} delta Move length.
  47643. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  47644. * handleEnds will be modified in this method.
  47645. * @param {Array.<number>} extent handleEnds is restricted by extent.
  47646. * extent[0] should less or equals than extent[1].
  47647. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds.
  47648. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  47649. * If not set, handle0 and cross handle1. If set as a non-negative
  47650. * number (including `0`), handles will push each other when reaching
  47651. * the minSpan.
  47652. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  47653. * @return {Array.<number>} The input handleEnds.
  47654. */
  47655. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  47656. delta = delta || 0;
  47657. var extentSpan = extent[1] - extent[0];
  47658. // Notice maxSpan and minSpan can be null/undefined.
  47659. if (minSpan != null) {
  47660. minSpan = restrict(minSpan, [0, extentSpan]);
  47661. }
  47662. if (maxSpan != null) {
  47663. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  47664. }
  47665. if (handleIndex === 'all') {
  47666. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  47667. handleSpan = restrict(handleSpan, [0, extentSpan]);
  47668. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  47669. handleIndex = 0;
  47670. }
  47671. handleEnds[0] = restrict(handleEnds[0], extent);
  47672. handleEnds[1] = restrict(handleEnds[1], extent);
  47673. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  47674. handleEnds[handleIndex] += delta;
  47675. // Restrict in extent.
  47676. var extentMinSpan = minSpan || 0;
  47677. var realExtent = extent.slice();
  47678. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  47679. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  47680. // Expand span.
  47681. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47682. if (minSpan != null && (
  47683. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  47684. )) {
  47685. // If minSpan exists, 'cross' is forbidden.
  47686. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  47687. }
  47688. // Shrink span.
  47689. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47690. if (maxSpan != null && currDistSign.span > maxSpan) {
  47691. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  47692. }
  47693. return handleEnds;
  47694. };
  47695. function getSpanSign(handleEnds, handleIndex) {
  47696. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  47697. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  47698. // is at left of handleEnds[1] for non-cross case.
  47699. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  47700. }
  47701. function restrict(value, extend) {
  47702. return Math.min(
  47703. extend[1] != null ? extend[1] : Infinity,
  47704. Math.max(extend[0] != null ? extend[0] : -Infinity, value)
  47705. );
  47706. }
  47707. /*
  47708. * Licensed to the Apache Software Foundation (ASF) under one
  47709. * or more contributor license agreements. See the NOTICE file
  47710. * distributed with this work for additional information
  47711. * regarding copyright ownership. The ASF licenses this file
  47712. * to you under the Apache License, Version 2.0 (the
  47713. * "License"); you may not use this file except in compliance
  47714. * with the License. You may obtain a copy of the License at
  47715. *
  47716. * http://www.apache.org/licenses/LICENSE-2.0
  47717. *
  47718. * Unless required by applicable law or agreed to in writing,
  47719. * software distributed under the License is distributed on an
  47720. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47721. * KIND, either express or implied. See the License for the
  47722. * specific language governing permissions and limitations
  47723. * under the License.
  47724. */
  47725. var each$13 = each$1;
  47726. var asc$1 = asc;
  47727. /**
  47728. * Operate single axis.
  47729. * One axis can only operated by one axis operator.
  47730. * Different dataZoomModels may be defined to operate the same axis.
  47731. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  47732. * So dataZoomModels share one axisProxy in that case.
  47733. *
  47734. * @class
  47735. */
  47736. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  47737. /**
  47738. * @private
  47739. * @type {string}
  47740. */
  47741. this._dimName = dimName;
  47742. /**
  47743. * @private
  47744. */
  47745. this._axisIndex = axisIndex;
  47746. /**
  47747. * @private
  47748. * @type {Array.<number>}
  47749. */
  47750. this._valueWindow;
  47751. /**
  47752. * @private
  47753. * @type {Array.<number>}
  47754. */
  47755. this._percentWindow;
  47756. /**
  47757. * @private
  47758. * @type {Array.<number>}
  47759. */
  47760. this._dataExtent;
  47761. /**
  47762. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  47763. * @private
  47764. * @type {Object}
  47765. */
  47766. this._minMaxSpan;
  47767. /**
  47768. * @readOnly
  47769. * @type {module: echarts/model/Global}
  47770. */
  47771. this.ecModel = ecModel;
  47772. /**
  47773. * @private
  47774. * @type {module: echarts/component/dataZoom/DataZoomModel}
  47775. */
  47776. this._dataZoomModel = dataZoomModel;
  47777. // /**
  47778. // * @readOnly
  47779. // * @private
  47780. // */
  47781. // this.hasSeriesStacked;
  47782. };
  47783. AxisProxy.prototype = {
  47784. constructor: AxisProxy,
  47785. /**
  47786. * Whether the axisProxy is hosted by dataZoomModel.
  47787. *
  47788. * @public
  47789. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47790. * @return {boolean}
  47791. */
  47792. hostedBy: function (dataZoomModel) {
  47793. return this._dataZoomModel === dataZoomModel;
  47794. },
  47795. /**
  47796. * @return {Array.<number>} Value can only be NaN or finite value.
  47797. */
  47798. getDataValueWindow: function () {
  47799. return this._valueWindow.slice();
  47800. },
  47801. /**
  47802. * @return {Array.<number>}
  47803. */
  47804. getDataPercentWindow: function () {
  47805. return this._percentWindow.slice();
  47806. },
  47807. /**
  47808. * @public
  47809. * @param {number} axisIndex
  47810. * @return {Array} seriesModels
  47811. */
  47812. getTargetSeriesModels: function () {
  47813. var seriesModels = [];
  47814. var ecModel = this.ecModel;
  47815. ecModel.eachSeries(function (seriesModel) {
  47816. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  47817. var dimName = this._dimName;
  47818. var axisModel = ecModel.queryComponents({
  47819. mainType: dimName + 'Axis',
  47820. index: seriesModel.get(dimName + 'AxisIndex'),
  47821. id: seriesModel.get(dimName + 'AxisId')
  47822. })[0];
  47823. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  47824. seriesModels.push(seriesModel);
  47825. }
  47826. }
  47827. }, this);
  47828. return seriesModels;
  47829. },
  47830. getAxisModel: function () {
  47831. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  47832. },
  47833. getOtherAxisModel: function () {
  47834. var axisDim = this._dimName;
  47835. var ecModel = this.ecModel;
  47836. var axisModel = this.getAxisModel();
  47837. var isCartesian = axisDim === 'x' || axisDim === 'y';
  47838. var otherAxisDim;
  47839. var coordSysIndexName;
  47840. if (isCartesian) {
  47841. coordSysIndexName = 'gridIndex';
  47842. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  47843. }
  47844. else {
  47845. coordSysIndexName = 'polarIndex';
  47846. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  47847. }
  47848. var foundOtherAxisModel;
  47849. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  47850. if ((otherAxisModel.get(coordSysIndexName) || 0)
  47851. === (axisModel.get(coordSysIndexName) || 0)
  47852. ) {
  47853. foundOtherAxisModel = otherAxisModel;
  47854. }
  47855. });
  47856. return foundOtherAxisModel;
  47857. },
  47858. getMinMaxSpan: function () {
  47859. return clone(this._minMaxSpan);
  47860. },
  47861. /**
  47862. * Only calculate by given range and this._dataExtent, do not change anything.
  47863. *
  47864. * @param {Object} opt
  47865. * @param {number} [opt.start]
  47866. * @param {number} [opt.end]
  47867. * @param {number} [opt.startValue]
  47868. * @param {number} [opt.endValue]
  47869. */
  47870. calculateDataWindow: function (opt) {
  47871. var dataExtent = this._dataExtent;
  47872. var axisModel = this.getAxisModel();
  47873. var scale = axisModel.axis.scale;
  47874. var rangePropMode = this._dataZoomModel.getRangePropMode();
  47875. var percentExtent = [0, 100];
  47876. var percentWindow = [];
  47877. var valueWindow = [];
  47878. var hasPropModeValue;
  47879. each$13(['start', 'end'], function (prop, idx) {
  47880. var boundPercent = opt[prop];
  47881. var boundValue = opt[prop + 'Value'];
  47882. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  47883. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  47884. // but not min/max of axis, which will be calculated by data window then).
  47885. // The former one is suitable for cases that a dataZoom component controls multiple
  47886. // axes with different unit or extent, and the latter one is suitable for accurate
  47887. // zoom by pixel (e.g., in dataZoomSelect).
  47888. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  47889. // only when setOption or dispatchAction, otherwise it remains its original value.
  47890. // (Why not only record `percentProp` and always map to `valueProp`? Because
  47891. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  47892. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  47893. // data extent. All of values that are overflow the `dataExtent` will be calculated
  47894. // to percent '100%').
  47895. if (rangePropMode[idx] === 'percent') {
  47896. boundPercent == null && (boundPercent = percentExtent[idx]);
  47897. // Use scale.parse to math round for category or time axis.
  47898. boundValue = scale.parse(linearMap(
  47899. boundPercent, percentExtent, dataExtent
  47900. ));
  47901. }
  47902. else {
  47903. hasPropModeValue = true;
  47904. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  47905. // Calculating `percent` from `value` may be not accurate, because
  47906. // This calculation can not be inversed, because all of values that
  47907. // are overflow the `dataExtent` will be calculated to percent '100%'
  47908. boundPercent = linearMap(
  47909. boundValue, dataExtent, percentExtent
  47910. );
  47911. }
  47912. // valueWindow[idx] = round(boundValue);
  47913. // percentWindow[idx] = round(boundPercent);
  47914. valueWindow[idx] = boundValue;
  47915. percentWindow[idx] = boundPercent;
  47916. });
  47917. asc$1(valueWindow);
  47918. asc$1(percentWindow);
  47919. // The windows from user calling of `dispatchAction` might be out of the extent,
  47920. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  47921. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  47922. // where API is able to initialize/modify the window size even though `zoomLock`
  47923. // specified.
  47924. var spans = this._minMaxSpan;
  47925. hasPropModeValue
  47926. ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false)
  47927. : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  47928. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  47929. var suffix = toValue ? 'Span' : 'ValueSpan';
  47930. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  47931. for (var i = 0; i < 2; i++) {
  47932. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  47933. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  47934. }
  47935. }
  47936. return {
  47937. valueWindow: valueWindow,
  47938. percentWindow: percentWindow
  47939. };
  47940. },
  47941. /**
  47942. * Notice: reset should not be called before series.restoreData() called,
  47943. * so it is recommanded to be called in "process stage" but not "model init
  47944. * stage".
  47945. *
  47946. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47947. */
  47948. reset: function (dataZoomModel) {
  47949. if (dataZoomModel !== this._dataZoomModel) {
  47950. return;
  47951. }
  47952. var targetSeries = this.getTargetSeriesModels();
  47953. // Culculate data window and data extent, and record them.
  47954. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  47955. // this.hasSeriesStacked = false;
  47956. // each(targetSeries, function (series) {
  47957. // var data = series.getData();
  47958. // var dataDim = data.mapDimension(this._dimName);
  47959. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  47960. // if (stackedDimension && stackedDimension === dataDim) {
  47961. // this.hasSeriesStacked = true;
  47962. // }
  47963. // }, this);
  47964. // `calculateDataWindow` uses min/maxSpan.
  47965. setMinMaxSpan(this);
  47966. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  47967. this._valueWindow = dataWindow.valueWindow;
  47968. this._percentWindow = dataWindow.percentWindow;
  47969. // Update axis setting then.
  47970. setAxisModel(this);
  47971. },
  47972. /**
  47973. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47974. */
  47975. restore: function (dataZoomModel) {
  47976. if (dataZoomModel !== this._dataZoomModel) {
  47977. return;
  47978. }
  47979. this._valueWindow = this._percentWindow = null;
  47980. setAxisModel(this, true);
  47981. },
  47982. /**
  47983. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47984. */
  47985. filterData: function (dataZoomModel, api) {
  47986. if (dataZoomModel !== this._dataZoomModel) {
  47987. return;
  47988. }
  47989. var axisDim = this._dimName;
  47990. var seriesModels = this.getTargetSeriesModels();
  47991. var filterMode = dataZoomModel.get('filterMode');
  47992. var valueWindow = this._valueWindow;
  47993. if (filterMode === 'none') {
  47994. return;
  47995. }
  47996. // FIXME
  47997. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  47998. // with NaN data, NaN will be filtered and stack will be wrong.
  47999. // So we need to force the mode to be set empty.
  48000. // In fect, it is not a big deal that do not support filterMode-'filter'
  48001. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  48002. // selection" some day, which might need "adapt to data extent on the
  48003. // otherAxis", which is disabled by filterMode-'empty'.
  48004. // But currently, stack has been fixed to based on value but not index,
  48005. // so this is not an issue any more.
  48006. // var otherAxisModel = this.getOtherAxisModel();
  48007. // if (dataZoomModel.get('$fromToolbox')
  48008. // && otherAxisModel
  48009. // && otherAxisModel.hasSeriesStacked
  48010. // ) {
  48011. // filterMode = 'empty';
  48012. // }
  48013. // TODO
  48014. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  48015. each$13(seriesModels, function (seriesModel) {
  48016. var seriesData = seriesModel.getData();
  48017. var dataDims = seriesData.mapDimension(axisDim, true);
  48018. if (!dataDims.length) {
  48019. return;
  48020. }
  48021. if (filterMode === 'weakFilter') {
  48022. seriesData.filterSelf(function (dataIndex) {
  48023. var leftOut;
  48024. var rightOut;
  48025. var hasValue;
  48026. for (var i = 0; i < dataDims.length; i++) {
  48027. var value = seriesData.get(dataDims[i], dataIndex);
  48028. var thisHasValue = !isNaN(value);
  48029. var thisLeftOut = value < valueWindow[0];
  48030. var thisRightOut = value > valueWindow[1];
  48031. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  48032. return true;
  48033. }
  48034. thisHasValue && (hasValue = true);
  48035. thisLeftOut && (leftOut = true);
  48036. thisRightOut && (rightOut = true);
  48037. }
  48038. // If both left out and right out, do not filter.
  48039. return hasValue && leftOut && rightOut;
  48040. });
  48041. }
  48042. else {
  48043. each$13(dataDims, function (dim) {
  48044. if (filterMode === 'empty') {
  48045. seriesModel.setData(
  48046. seriesData = seriesData.map(dim, function (value) {
  48047. return !isInWindow(value) ? NaN : value;
  48048. })
  48049. );
  48050. }
  48051. else {
  48052. var range = {};
  48053. range[dim] = valueWindow;
  48054. // console.time('select');
  48055. seriesData.selectRange(range);
  48056. // console.timeEnd('select');
  48057. }
  48058. });
  48059. }
  48060. each$13(dataDims, function (dim) {
  48061. seriesData.setApproximateExtent(valueWindow, dim);
  48062. });
  48063. });
  48064. function isInWindow(value) {
  48065. return value >= valueWindow[0] && value <= valueWindow[1];
  48066. }
  48067. }
  48068. };
  48069. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  48070. var dataExtent = [Infinity, -Infinity];
  48071. each$13(seriesModels, function (seriesModel) {
  48072. var seriesData = seriesModel.getData();
  48073. if (seriesData) {
  48074. each$13(seriesData.mapDimension(axisDim, true), function (dim) {
  48075. var seriesExtent = seriesData.getApproximateExtent(dim);
  48076. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  48077. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  48078. });
  48079. }
  48080. });
  48081. if (dataExtent[1] < dataExtent[0]) {
  48082. dataExtent = [NaN, NaN];
  48083. }
  48084. // It is important to get "consistent" extent when more then one axes is
  48085. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  48086. // when zooming. But it is difficult to know what is "consistent", considering
  48087. // axes have different type or even different meanings (For example, two
  48088. // time axes are used to compare data of the same date in different years).
  48089. // So basically dataZoom just obtains extent by series.data (in category axis
  48090. // extent can be obtained from axis.data).
  48091. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  48092. // consistent.
  48093. fixExtentByAxis(axisProxy, dataExtent);
  48094. return dataExtent;
  48095. }
  48096. function fixExtentByAxis(axisProxy, dataExtent) {
  48097. var axisModel = axisProxy.getAxisModel();
  48098. var min = axisModel.getMin(true);
  48099. // For category axis, if min/max/scale are not set, extent is determined
  48100. // by axis.data by default.
  48101. var isCategoryAxis = axisModel.get('type') === 'category';
  48102. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  48103. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  48104. dataExtent[0] = min;
  48105. }
  48106. else if (isCategoryAxis) {
  48107. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  48108. }
  48109. var max = axisModel.getMax(true);
  48110. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  48111. dataExtent[1] = max;
  48112. }
  48113. else if (isCategoryAxis) {
  48114. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  48115. }
  48116. if (!axisModel.get('scale', true)) {
  48117. dataExtent[0] > 0 && (dataExtent[0] = 0);
  48118. dataExtent[1] < 0 && (dataExtent[1] = 0);
  48119. }
  48120. // For value axis, if min/max/scale are not set, we just use the extent obtained
  48121. // by series data, which may be a little different from the extent calculated by
  48122. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  48123. // little when zooming. So it will not be fixed until some users require it strongly.
  48124. return dataExtent;
  48125. }
  48126. function setAxisModel(axisProxy, isRestore) {
  48127. var axisModel = axisProxy.getAxisModel();
  48128. var percentWindow = axisProxy._percentWindow;
  48129. var valueWindow = axisProxy._valueWindow;
  48130. if (!percentWindow) {
  48131. return;
  48132. }
  48133. // [0, 500]: arbitrary value, guess axis extent.
  48134. var precision = getPixelPrecision(valueWindow, [0, 500]);
  48135. precision = Math.min(precision, 20);
  48136. // isRestore or isFull
  48137. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  48138. axisModel.setRange(
  48139. useOrigin ? null : +valueWindow[0].toFixed(precision),
  48140. useOrigin ? null : +valueWindow[1].toFixed(precision)
  48141. );
  48142. }
  48143. function setMinMaxSpan(axisProxy) {
  48144. var minMaxSpan = axisProxy._minMaxSpan = {};
  48145. var dataZoomModel = axisProxy._dataZoomModel;
  48146. var dataExtent = axisProxy._dataExtent;
  48147. each$13(['min', 'max'], function (minMax) {
  48148. var percentSpan = dataZoomModel.get(minMax + 'Span');
  48149. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  48150. valueSpan != null && (valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan));
  48151. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  48152. if (valueSpan != null) {
  48153. percentSpan = linearMap(
  48154. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  48155. );
  48156. }
  48157. else if (percentSpan != null) {
  48158. valueSpan = linearMap(
  48159. percentSpan, [0, 100], dataExtent, true
  48160. ) - dataExtent[0];
  48161. }
  48162. minMaxSpan[minMax + 'Span'] = percentSpan;
  48163. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  48164. });
  48165. }
  48166. /*
  48167. * Licensed to the Apache Software Foundation (ASF) under one
  48168. * or more contributor license agreements. See the NOTICE file
  48169. * distributed with this work for additional information
  48170. * regarding copyright ownership. The ASF licenses this file
  48171. * to you under the Apache License, Version 2.0 (the
  48172. * "License"); you may not use this file except in compliance
  48173. * with the License. You may obtain a copy of the License at
  48174. *
  48175. * http://www.apache.org/licenses/LICENSE-2.0
  48176. *
  48177. * Unless required by applicable law or agreed to in writing,
  48178. * software distributed under the License is distributed on an
  48179. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48180. * KIND, either express or implied. See the License for the
  48181. * specific language governing permissions and limitations
  48182. * under the License.
  48183. */
  48184. var each$12 = each$1;
  48185. var eachAxisDim = eachAxisDim$1;
  48186. var DataZoomModel = extendComponentModel({
  48187. type: 'dataZoom',
  48188. dependencies: [
  48189. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  48190. ],
  48191. /**
  48192. * @protected
  48193. */
  48194. defaultOption: {
  48195. zlevel: 0,
  48196. z: 4, // Higher than normal component (z: 2).
  48197. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  48198. xAxisIndex: null, // Default the first horizontal category axis.
  48199. yAxisIndex: null, // Default the first vertical category axis.
  48200. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  48201. // 'filter': data items which are out of window will be removed. This option is
  48202. // applicable when filtering outliers. For each data item, it will be
  48203. // filtered if one of the relevant dimensions is out of the window.
  48204. // 'weakFilter': data items which are out of window will be removed. This option
  48205. // is applicable when filtering outliers. For each data item, it will be
  48206. // filtered only if all of the relevant dimensions are out of the same
  48207. // side of the window.
  48208. // 'empty': data items which are out of window will be set to empty.
  48209. // This option is applicable when user should not neglect
  48210. // that there are some data items out of window.
  48211. // 'none': Do not filter.
  48212. // Taking line chart as an example, line will be broken in
  48213. // the filtered points when filterModel is set to 'empty', but
  48214. // be connected when set to 'filter'.
  48215. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  48216. // default 100. Do not throttle when use null/undefined.
  48217. // If animation === true and animationDurationUpdate > 0,
  48218. // default value is 100, otherwise 20.
  48219. start: 0, // Start percent. 0 ~ 100
  48220. end: 100, // End percent. 0 ~ 100
  48221. startValue: null, // Start value. If startValue specified, start is ignored.
  48222. endValue: null, // End value. If endValue specified, end is ignored.
  48223. minSpan: null, // 0 ~ 100
  48224. maxSpan: null, // 0 ~ 100
  48225. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  48226. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  48227. rangeMode: null // Array, can be 'value' or 'percent'.
  48228. },
  48229. /**
  48230. * @override
  48231. */
  48232. init: function (option, parentModel, ecModel) {
  48233. /**
  48234. * key like x_0, y_1
  48235. * @private
  48236. * @type {Object}
  48237. */
  48238. this._dataIntervalByAxis = {};
  48239. /**
  48240. * @private
  48241. */
  48242. this._dataInfo = {};
  48243. /**
  48244. * key like x_0, y_1
  48245. * @private
  48246. */
  48247. this._axisProxies = {};
  48248. /**
  48249. * @readOnly
  48250. */
  48251. this.textStyleModel;
  48252. /**
  48253. * @private
  48254. */
  48255. this._autoThrottle = true;
  48256. /**
  48257. * It is `[rangeModeForMin, rangeModeForMax]`.
  48258. * The optional values for `rangeMode`:
  48259. * + `'value'` mode: the axis extent will always be determined by
  48260. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  48261. * how data like and how `axis.min` and `axis.max` are.
  48262. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  48263. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  48264. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  48265. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  48266. *
  48267. * For example, when users are using dynamic data (update data periodically via `setOption`),
  48268. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  48269. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  48270. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  48271. *
  48272. * @private
  48273. */
  48274. this._rangePropMode = ['percent', 'percent'];
  48275. var inputRawOption = retrieveRawOption(option);
  48276. /**
  48277. * Suppose a "main process" start at the point that model prepared (that is,
  48278. * model initialized or merged or method called in `action`).
  48279. * We should keep the `main process` idempotent, that is, given a set of values
  48280. * on `option`, we get the same result.
  48281. *
  48282. * But sometimes, values on `option` will be updated for providing users
  48283. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  48284. * should not be the base/input of the `main process`.
  48285. *
  48286. * So in that case we should save and keep the input of the `main process`
  48287. * separately, called `settledOption`.
  48288. *
  48289. * For example, consider the case:
  48290. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  48291. * where the original input `option.startValue`, `option.endValue` are earsed by
  48292. * calculated value.
  48293. * (Step)2) click the legend to hide and show a series,
  48294. * where the new range is calculated by the earsed `startValue` and `endValue`,
  48295. * which brings incorrect result.
  48296. *
  48297. * @readOnly
  48298. */
  48299. this.settledOption = inputRawOption;
  48300. this.mergeDefaultAndTheme(option, ecModel);
  48301. this.doInit(inputRawOption);
  48302. },
  48303. /**
  48304. * @override
  48305. */
  48306. mergeOption: function (newOption) {
  48307. var inputRawOption = retrieveRawOption(newOption);
  48308. //FIX #2591
  48309. merge(this.option, newOption, true);
  48310. merge(this.settledOption, inputRawOption, true);
  48311. this.doInit(inputRawOption);
  48312. },
  48313. /**
  48314. * @protected
  48315. */
  48316. doInit: function (inputRawOption) {
  48317. var thisOption = this.option;
  48318. // Disable realtime view update if canvas is not supported.
  48319. if (!env$1.canvasSupported) {
  48320. thisOption.realtime = false;
  48321. }
  48322. this._setDefaultThrottle(inputRawOption);
  48323. updateRangeUse(this, inputRawOption);
  48324. var settledOption = this.settledOption;
  48325. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  48326. // start/end has higher priority over startValue/endValue if they
  48327. // both set, but we should make chart.setOption({endValue: 1000})
  48328. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  48329. if (this._rangePropMode[index] === 'value') {
  48330. thisOption[names[0]] = settledOption[names[0]] = null;
  48331. }
  48332. // Otherwise do nothing and use the merge result.
  48333. }, this);
  48334. this.textStyleModel = this.getModel('textStyle');
  48335. this._resetTarget();
  48336. this._giveAxisProxies();
  48337. },
  48338. /**
  48339. * @private
  48340. */
  48341. _giveAxisProxies: function () {
  48342. var axisProxies = this._axisProxies;
  48343. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  48344. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  48345. // If exists, share axisProxy with other dataZoomModels.
  48346. var axisProxy = axisModel.__dzAxisProxy || (
  48347. // Use the first dataZoomModel as the main model of axisProxy.
  48348. axisModel.__dzAxisProxy = new AxisProxy(
  48349. dimNames.name, axisIndex, this, ecModel
  48350. )
  48351. );
  48352. // FIXME
  48353. // dispose __dzAxisProxy
  48354. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  48355. }, this);
  48356. },
  48357. /**
  48358. * @private
  48359. */
  48360. _resetTarget: function () {
  48361. var thisOption = this.option;
  48362. var autoMode = this._judgeAutoMode();
  48363. eachAxisDim(function (dimNames) {
  48364. var axisIndexName = dimNames.axisIndex;
  48365. thisOption[axisIndexName] = normalizeToArray(
  48366. thisOption[axisIndexName]
  48367. );
  48368. }, this);
  48369. if (autoMode === 'axisIndex') {
  48370. this._autoSetAxisIndex();
  48371. }
  48372. else if (autoMode === 'orient') {
  48373. this._autoSetOrient();
  48374. }
  48375. },
  48376. /**
  48377. * @private
  48378. */
  48379. _judgeAutoMode: function () {
  48380. // Auto set only works for setOption at the first time.
  48381. // The following is user's reponsibility. So using merged
  48382. // option is OK.
  48383. var thisOption = this.option;
  48384. var hasIndexSpecified = false;
  48385. eachAxisDim(function (dimNames) {
  48386. // When user set axisIndex as a empty array, we think that user specify axisIndex
  48387. // but do not want use auto mode. Because empty array may be encountered when
  48388. // some error occured.
  48389. if (thisOption[dimNames.axisIndex] != null) {
  48390. hasIndexSpecified = true;
  48391. }
  48392. }, this);
  48393. var orient = thisOption.orient;
  48394. if (orient == null && hasIndexSpecified) {
  48395. return 'orient';
  48396. }
  48397. else if (!hasIndexSpecified) {
  48398. if (orient == null) {
  48399. thisOption.orient = 'horizontal';
  48400. }
  48401. return 'axisIndex';
  48402. }
  48403. },
  48404. /**
  48405. * @private
  48406. */
  48407. _autoSetAxisIndex: function () {
  48408. var autoAxisIndex = true;
  48409. var orient = this.get('orient', true);
  48410. var thisOption = this.option;
  48411. var dependentModels = this.dependentModels;
  48412. if (autoAxisIndex) {
  48413. // Find axis that parallel to dataZoom as default.
  48414. var dimName = orient === 'vertical' ? 'y' : 'x';
  48415. if (dependentModels[dimName + 'Axis'].length) {
  48416. thisOption[dimName + 'AxisIndex'] = [0];
  48417. autoAxisIndex = false;
  48418. }
  48419. else {
  48420. each$12(dependentModels.singleAxis, function (singleAxisModel) {
  48421. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  48422. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  48423. autoAxisIndex = false;
  48424. }
  48425. });
  48426. }
  48427. }
  48428. if (autoAxisIndex) {
  48429. // Find the first category axis as default. (consider polar)
  48430. eachAxisDim(function (dimNames) {
  48431. if (!autoAxisIndex) {
  48432. return;
  48433. }
  48434. var axisIndices = [];
  48435. var axisModels = this.dependentModels[dimNames.axis];
  48436. if (axisModels.length && !axisIndices.length) {
  48437. for (var i = 0, len = axisModels.length; i < len; i++) {
  48438. if (axisModels[i].get('type') === 'category') {
  48439. axisIndices.push(i);
  48440. }
  48441. }
  48442. }
  48443. thisOption[dimNames.axisIndex] = axisIndices;
  48444. if (axisIndices.length) {
  48445. autoAxisIndex = false;
  48446. }
  48447. }, this);
  48448. }
  48449. if (autoAxisIndex) {
  48450. // FIXME
  48451. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  48452. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  48453. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  48454. // dataZoom component auto adopts series that reference to
  48455. // both xAxis and yAxis which type is 'value'.
  48456. this.ecModel.eachSeries(function (seriesModel) {
  48457. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  48458. eachAxisDim(function (dimNames) {
  48459. var axisIndices = thisOption[dimNames.axisIndex];
  48460. var axisIndex = seriesModel.get(dimNames.axisIndex);
  48461. var axisId = seriesModel.get(dimNames.axisId);
  48462. var axisModel = seriesModel.ecModel.queryComponents({
  48463. mainType: dimNames.axis,
  48464. index: axisIndex,
  48465. id: axisId
  48466. })[0];
  48467. if (__DEV__) {
  48468. if (!axisModel) {
  48469. throw new Error(
  48470. dimNames.axis + ' "' + retrieve(
  48471. axisIndex,
  48472. axisId,
  48473. 0
  48474. ) + '" not found'
  48475. );
  48476. }
  48477. }
  48478. axisIndex = axisModel.componentIndex;
  48479. if (indexOf(axisIndices, axisIndex) < 0) {
  48480. axisIndices.push(axisIndex);
  48481. }
  48482. });
  48483. }
  48484. }, this);
  48485. }
  48486. },
  48487. /**
  48488. * @private
  48489. */
  48490. _autoSetOrient: function () {
  48491. var dim;
  48492. // Find the first axis
  48493. this.eachTargetAxis(function (dimNames) {
  48494. !dim && (dim = dimNames.name);
  48495. }, this);
  48496. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  48497. },
  48498. /**
  48499. * @private
  48500. */
  48501. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  48502. // FIXME
  48503. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  48504. // 例如series.type === scatter时。
  48505. var is = true;
  48506. eachAxisDim(function (dimNames) {
  48507. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  48508. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  48509. if (!axisModel || axisModel.get('type') !== axisType) {
  48510. is = false;
  48511. }
  48512. }, this);
  48513. return is;
  48514. },
  48515. /**
  48516. * @private
  48517. */
  48518. _setDefaultThrottle: function (inputRawOption) {
  48519. // When first time user set throttle, auto throttle ends.
  48520. if (inputRawOption.hasOwnProperty('throttle')) {
  48521. this._autoThrottle = false;
  48522. }
  48523. if (this._autoThrottle) {
  48524. var globalOption = this.ecModel.option;
  48525. this.option.throttle = (
  48526. globalOption.animation && globalOption.animationDurationUpdate > 0
  48527. ) ? 100 : 20;
  48528. }
  48529. },
  48530. /**
  48531. * @public
  48532. */
  48533. getFirstTargetAxisModel: function () {
  48534. var firstAxisModel;
  48535. eachAxisDim(function (dimNames) {
  48536. if (firstAxisModel == null) {
  48537. var indices = this.get(dimNames.axisIndex);
  48538. if (indices.length) {
  48539. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  48540. }
  48541. }
  48542. }, this);
  48543. return firstAxisModel;
  48544. },
  48545. /**
  48546. * @public
  48547. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  48548. */
  48549. eachTargetAxis: function (callback, context) {
  48550. var ecModel = this.ecModel;
  48551. eachAxisDim(function (dimNames) {
  48552. each$12(
  48553. this.get(dimNames.axisIndex),
  48554. function (axisIndex) {
  48555. callback.call(context, dimNames, axisIndex, this, ecModel);
  48556. },
  48557. this
  48558. );
  48559. }, this);
  48560. },
  48561. /**
  48562. * @param {string} dimName
  48563. * @param {number} axisIndex
  48564. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  48565. */
  48566. getAxisProxy: function (dimName, axisIndex) {
  48567. return this._axisProxies[dimName + '_' + axisIndex];
  48568. },
  48569. /**
  48570. * @param {string} dimName
  48571. * @param {number} axisIndex
  48572. * @return {module:echarts/model/Model} If not found, return null/undefined.
  48573. */
  48574. getAxisModel: function (dimName, axisIndex) {
  48575. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  48576. return axisProxy && axisProxy.getAxisModel();
  48577. },
  48578. /**
  48579. * If not specified, set to undefined.
  48580. *
  48581. * @public
  48582. * @param {Object} opt
  48583. * @param {number} [opt.start]
  48584. * @param {number} [opt.end]
  48585. * @param {number} [opt.startValue]
  48586. * @param {number} [opt.endValue]
  48587. */
  48588. setRawRange: function (opt) {
  48589. var thisOption = this.option;
  48590. var settledOption = this.settledOption;
  48591. each$12([['start', 'startValue'], ['end', 'endValue']], function (names) {
  48592. // Consider the pair <start, startValue>:
  48593. // If one has value and the other one is `null/undefined`, we both set them
  48594. // to `settledOption`. This strategy enables the feature to clear the original
  48595. // value in `settledOption` to `null/undefined`.
  48596. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  48597. // and keep `settledOption` with the original value. This strategy enables users to
  48598. // only set <end or endValue> but not set <start or startValue> when calling
  48599. // `dispatchAction`.
  48600. // The pair <end, endValue> is treated in the same way.
  48601. if (opt[names[0]] != null || opt[names[1]] != null) {
  48602. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  48603. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  48604. }
  48605. }, this);
  48606. updateRangeUse(this, opt);
  48607. },
  48608. /**
  48609. * @public
  48610. * @param {Object} opt
  48611. * @param {number} [opt.start]
  48612. * @param {number} [opt.end]
  48613. * @param {number} [opt.startValue]
  48614. * @param {number} [opt.endValue]
  48615. */
  48616. setCalculatedRange: function (opt) {
  48617. var option = this.option;
  48618. each$12(['start', 'startValue', 'end', 'endValue'], function (name) {
  48619. option[name] = opt[name];
  48620. });
  48621. },
  48622. /**
  48623. * @public
  48624. * @return {Array.<number>} [startPercent, endPercent]
  48625. */
  48626. getPercentRange: function () {
  48627. var axisProxy = this.findRepresentativeAxisProxy();
  48628. if (axisProxy) {
  48629. return axisProxy.getDataPercentWindow();
  48630. }
  48631. },
  48632. /**
  48633. * @public
  48634. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  48635. *
  48636. * @param {string} [axisDimName]
  48637. * @param {number} [axisIndex]
  48638. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  48639. */
  48640. getValueRange: function (axisDimName, axisIndex) {
  48641. if (axisDimName == null && axisIndex == null) {
  48642. var axisProxy = this.findRepresentativeAxisProxy();
  48643. if (axisProxy) {
  48644. return axisProxy.getDataValueWindow();
  48645. }
  48646. }
  48647. else {
  48648. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  48649. }
  48650. },
  48651. /**
  48652. * @public
  48653. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  48654. * corresponding to the axisModel
  48655. * @return {module:echarts/component/dataZoom/AxisProxy}
  48656. */
  48657. findRepresentativeAxisProxy: function (axisModel) {
  48658. if (axisModel) {
  48659. return axisModel.__dzAxisProxy;
  48660. }
  48661. // Find the first hosted axisProxy
  48662. var axisProxies = this._axisProxies;
  48663. for (var key in axisProxies) {
  48664. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  48665. return axisProxies[key];
  48666. }
  48667. }
  48668. // If no hosted axis find not hosted axisProxy.
  48669. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  48670. // and the option.start or option.end settings are different. The percentRange
  48671. // should follow axisProxy.
  48672. // (We encounter this problem in toolbox data zoom.)
  48673. for (var key in axisProxies) {
  48674. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  48675. return axisProxies[key];
  48676. }
  48677. }
  48678. },
  48679. /**
  48680. * @return {Array.<string>}
  48681. */
  48682. getRangePropMode: function () {
  48683. return this._rangePropMode.slice();
  48684. }
  48685. });
  48686. /**
  48687. * Retrieve the those raw params from option, which will be cached separately.
  48688. * becasue they will be overwritten by normalized/calculated values in the main
  48689. * process.
  48690. */
  48691. function retrieveRawOption(option) {
  48692. var ret = {};
  48693. each$12(
  48694. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  48695. function (name) {
  48696. option.hasOwnProperty(name) && (ret[name] = option[name]);
  48697. }
  48698. );
  48699. return ret;
  48700. }
  48701. function updateRangeUse(dataZoomModel, inputRawOption) {
  48702. var rangePropMode = dataZoomModel._rangePropMode;
  48703. var rangeModeInOption = dataZoomModel.get('rangeMode');
  48704. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  48705. var percentSpecified = inputRawOption[names[0]] != null;
  48706. var valueSpecified = inputRawOption[names[1]] != null;
  48707. if (percentSpecified && !valueSpecified) {
  48708. rangePropMode[index] = 'percent';
  48709. }
  48710. else if (!percentSpecified && valueSpecified) {
  48711. rangePropMode[index] = 'value';
  48712. }
  48713. else if (rangeModeInOption) {
  48714. rangePropMode[index] = rangeModeInOption[index];
  48715. }
  48716. else if (percentSpecified) { // percentSpecified && valueSpecified
  48717. rangePropMode[index] = 'percent';
  48718. }
  48719. // else remain its original setting.
  48720. });
  48721. }
  48722. /*
  48723. * Licensed to the Apache Software Foundation (ASF) under one
  48724. * or more contributor license agreements. See the NOTICE file
  48725. * distributed with this work for additional information
  48726. * regarding copyright ownership. The ASF licenses this file
  48727. * to you under the Apache License, Version 2.0 (the
  48728. * "License"); you may not use this file except in compliance
  48729. * with the License. You may obtain a copy of the License at
  48730. *
  48731. * http://www.apache.org/licenses/LICENSE-2.0
  48732. *
  48733. * Unless required by applicable law or agreed to in writing,
  48734. * software distributed under the License is distributed on an
  48735. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48736. * KIND, either express or implied. See the License for the
  48737. * specific language governing permissions and limitations
  48738. * under the License.
  48739. */
  48740. var DataZoomView = Component$1.extend({
  48741. type: 'dataZoom',
  48742. render: function (dataZoomModel, ecModel, api, payload) {
  48743. this.dataZoomModel = dataZoomModel;
  48744. this.ecModel = ecModel;
  48745. this.api = api;
  48746. },
  48747. /**
  48748. * Find the first target coordinate system.
  48749. *
  48750. * @protected
  48751. * @return {Object} {
  48752. * grid: [
  48753. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  48754. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  48755. * ...
  48756. * ], // cartesians must not be null/undefined.
  48757. * polar: [
  48758. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  48759. * ...
  48760. * ], // polars must not be null/undefined.
  48761. * singleAxis: [
  48762. * {model: coord0, axisModels: [], coordIndex: 0}
  48763. * ]
  48764. */
  48765. getTargetCoordInfo: function () {
  48766. var dataZoomModel = this.dataZoomModel;
  48767. var ecModel = this.ecModel;
  48768. var coordSysLists = {};
  48769. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  48770. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  48771. if (axisModel) {
  48772. var coordModel = axisModel.getCoordSysModel();
  48773. coordModel && save(
  48774. coordModel,
  48775. axisModel,
  48776. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  48777. coordModel.componentIndex
  48778. );
  48779. }
  48780. }, this);
  48781. function save(coordModel, axisModel, store, coordIndex) {
  48782. var item;
  48783. for (var i = 0; i < store.length; i++) {
  48784. if (store[i].model === coordModel) {
  48785. item = store[i];
  48786. break;
  48787. }
  48788. }
  48789. if (!item) {
  48790. store.push(item = {
  48791. model: coordModel, axisModels: [], coordIndex: coordIndex
  48792. });
  48793. }
  48794. item.axisModels.push(axisModel);
  48795. }
  48796. return coordSysLists;
  48797. }
  48798. });
  48799. /*
  48800. * Licensed to the Apache Software Foundation (ASF) under one
  48801. * or more contributor license agreements. See the NOTICE file
  48802. * distributed with this work for additional information
  48803. * regarding copyright ownership. The ASF licenses this file
  48804. * to you under the Apache License, Version 2.0 (the
  48805. * "License"); you may not use this file except in compliance
  48806. * with the License. You may obtain a copy of the License at
  48807. *
  48808. * http://www.apache.org/licenses/LICENSE-2.0
  48809. *
  48810. * Unless required by applicable law or agreed to in writing,
  48811. * software distributed under the License is distributed on an
  48812. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48813. * KIND, either express or implied. See the License for the
  48814. * specific language governing permissions and limitations
  48815. * under the License.
  48816. */
  48817. var SliderZoomModel = DataZoomModel.extend({
  48818. type: 'dataZoom.slider',
  48819. layoutMode: 'box',
  48820. /**
  48821. * @protected
  48822. */
  48823. defaultOption: {
  48824. show: true,
  48825. // ph => placeholder. Using placehoder here because
  48826. // deault value can only be drived in view stage.
  48827. right: 'ph', // Default align to grid rect.
  48828. top: 'ph', // Default align to grid rect.
  48829. width: 'ph', // Default align to grid rect.
  48830. height: 'ph', // Default align to grid rect.
  48831. left: null, // Default align to grid rect.
  48832. bottom: null, // Default align to grid rect.
  48833. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  48834. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  48835. // highest priority, remain for compatibility of
  48836. // previous version, but not recommended any more.
  48837. dataBackground: {
  48838. lineStyle: {
  48839. color: '#2f4554',
  48840. width: 0.5,
  48841. opacity: 0.3
  48842. },
  48843. areaStyle: {
  48844. color: 'rgba(47,69,84,0.3)',
  48845. opacity: 0.3
  48846. }
  48847. },
  48848. borderColor: '#ddd', // border color of the box. For compatibility,
  48849. // if dataBackgroundColor is set, borderColor
  48850. // is ignored.
  48851. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  48852. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  48853. // 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',
  48854. /* eslint-disable */
  48855. 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',
  48856. /* eslint-enable */
  48857. // Percent of the slider height
  48858. handleSize: '100%',
  48859. handleStyle: {
  48860. color: '#a7b7cc'
  48861. },
  48862. labelPrecision: null,
  48863. labelFormatter: null,
  48864. showDetail: true,
  48865. showDataShadow: 'auto', // Default auto decision.
  48866. realtime: true,
  48867. zoomLock: false, // Whether disable zoom.
  48868. textStyle: {
  48869. color: '#333'
  48870. }
  48871. }
  48872. });
  48873. /*
  48874. * Licensed to the Apache Software Foundation (ASF) under one
  48875. * or more contributor license agreements. See the NOTICE file
  48876. * distributed with this work for additional information
  48877. * regarding copyright ownership. The ASF licenses this file
  48878. * to you under the Apache License, Version 2.0 (the
  48879. * "License"); you may not use this file except in compliance
  48880. * with the License. You may obtain a copy of the License at
  48881. *
  48882. * http://www.apache.org/licenses/LICENSE-2.0
  48883. *
  48884. * Unless required by applicable law or agreed to in writing,
  48885. * software distributed under the License is distributed on an
  48886. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48887. * KIND, either express or implied. See the License for the
  48888. * specific language governing permissions and limitations
  48889. * under the License.
  48890. */
  48891. var Rect$1 = Rect;
  48892. var linearMap$1 = linearMap;
  48893. var asc$2 = asc;
  48894. var bind$3 = bind;
  48895. var each$14 = each$1;
  48896. // Constants
  48897. var DEFAULT_LOCATION_EDGE_GAP = 7;
  48898. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  48899. var DEFAULT_FILLER_SIZE = 30;
  48900. var HORIZONTAL = 'horizontal';
  48901. var VERTICAL = 'vertical';
  48902. var LABEL_GAP = 5;
  48903. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  48904. var SliderZoomView = DataZoomView.extend({
  48905. type: 'dataZoom.slider',
  48906. init: function (ecModel, api) {
  48907. /**
  48908. * @private
  48909. * @type {Object}
  48910. */
  48911. this._displayables = {};
  48912. /**
  48913. * @private
  48914. * @type {string}
  48915. */
  48916. this._orient;
  48917. /**
  48918. * [0, 100]
  48919. * @private
  48920. */
  48921. this._range;
  48922. /**
  48923. * [coord of the first handle, coord of the second handle]
  48924. * @private
  48925. */
  48926. this._handleEnds;
  48927. /**
  48928. * [length, thick]
  48929. * @private
  48930. * @type {Array.<number>}
  48931. */
  48932. this._size;
  48933. /**
  48934. * @private
  48935. * @type {number}
  48936. */
  48937. this._handleWidth;
  48938. /**
  48939. * @private
  48940. * @type {number}
  48941. */
  48942. this._handleHeight;
  48943. /**
  48944. * @private
  48945. */
  48946. this._location;
  48947. /**
  48948. * @private
  48949. */
  48950. this._dragging;
  48951. /**
  48952. * @private
  48953. */
  48954. this._dataShadowInfo;
  48955. this.api = api;
  48956. },
  48957. /**
  48958. * @override
  48959. */
  48960. render: function (dataZoomModel, ecModel, api, payload) {
  48961. SliderZoomView.superApply(this, 'render', arguments);
  48962. createOrUpdate(
  48963. this,
  48964. '_dispatchZoomAction',
  48965. this.dataZoomModel.get('throttle'),
  48966. 'fixRate'
  48967. );
  48968. this._orient = dataZoomModel.get('orient');
  48969. if (this.dataZoomModel.get('show') === false) {
  48970. this.group.removeAll();
  48971. return;
  48972. }
  48973. // Notice: this._resetInterval() should not be executed when payload.type
  48974. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  48975. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  48976. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  48977. this._buildView();
  48978. }
  48979. this._updateView();
  48980. },
  48981. /**
  48982. * @override
  48983. */
  48984. remove: function () {
  48985. SliderZoomView.superApply(this, 'remove', arguments);
  48986. clear(this, '_dispatchZoomAction');
  48987. },
  48988. /**
  48989. * @override
  48990. */
  48991. dispose: function () {
  48992. SliderZoomView.superApply(this, 'dispose', arguments);
  48993. clear(this, '_dispatchZoomAction');
  48994. },
  48995. _buildView: function () {
  48996. var thisGroup = this.group;
  48997. thisGroup.removeAll();
  48998. this._resetLocation();
  48999. this._resetInterval();
  49000. var barGroup = this._displayables.barGroup = new Group();
  49001. this._renderBackground();
  49002. this._renderHandle();
  49003. this._renderDataShadow();
  49004. thisGroup.add(barGroup);
  49005. this._positionGroup();
  49006. },
  49007. /**
  49008. * @private
  49009. */
  49010. _resetLocation: function () {
  49011. var dataZoomModel = this.dataZoomModel;
  49012. var api = this.api;
  49013. // If some of x/y/width/height are not specified,
  49014. // auto-adapt according to target grid.
  49015. var coordRect = this._findCoordRect();
  49016. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  49017. // Default align by coordinate system rect.
  49018. var positionInfo = this._orient === HORIZONTAL
  49019. ? {
  49020. // Why using 'right', because right should be used in vertical,
  49021. // and it is better to be consistent for dealing with position param merge.
  49022. right: ecSize.width - coordRect.x - coordRect.width,
  49023. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  49024. width: coordRect.width,
  49025. height: DEFAULT_FILLER_SIZE
  49026. }
  49027. : { // vertical
  49028. right: DEFAULT_LOCATION_EDGE_GAP,
  49029. top: coordRect.y,
  49030. width: DEFAULT_FILLER_SIZE,
  49031. height: coordRect.height
  49032. };
  49033. // Do not write back to option and replace value 'ph', because
  49034. // the 'ph' value should be recalculated when resize.
  49035. var layoutParams = getLayoutParams(dataZoomModel.option);
  49036. // Replace the placeholder value.
  49037. each$1(['right', 'top', 'width', 'height'], function (name) {
  49038. if (layoutParams[name] === 'ph') {
  49039. layoutParams[name] = positionInfo[name];
  49040. }
  49041. });
  49042. var layoutRect = getLayoutRect(
  49043. layoutParams,
  49044. ecSize,
  49045. dataZoomModel.padding
  49046. );
  49047. this._location = {x: layoutRect.x, y: layoutRect.y};
  49048. this._size = [layoutRect.width, layoutRect.height];
  49049. this._orient === VERTICAL && this._size.reverse();
  49050. },
  49051. /**
  49052. * @private
  49053. */
  49054. _positionGroup: function () {
  49055. var thisGroup = this.group;
  49056. var location = this._location;
  49057. var orient = this._orient;
  49058. // Just use the first axis to determine mapping.
  49059. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  49060. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  49061. var barGroup = this._displayables.barGroup;
  49062. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  49063. // Transform barGroup.
  49064. barGroup.attr(
  49065. (orient === HORIZONTAL && !inverse)
  49066. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  49067. : (orient === HORIZONTAL && inverse)
  49068. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  49069. : (orient === VERTICAL && !inverse)
  49070. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  49071. // Dont use Math.PI, considering shadow direction.
  49072. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  49073. );
  49074. // Position barGroup
  49075. var rect = thisGroup.getBoundingRect([barGroup]);
  49076. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  49077. },
  49078. /**
  49079. * @private
  49080. */
  49081. _getViewExtent: function () {
  49082. return [0, this._size[0]];
  49083. },
  49084. _renderBackground: function () {
  49085. var dataZoomModel = this.dataZoomModel;
  49086. var size = this._size;
  49087. var barGroup = this._displayables.barGroup;
  49088. barGroup.add(new Rect$1({
  49089. silent: true,
  49090. shape: {
  49091. x: 0, y: 0, width: size[0], height: size[1]
  49092. },
  49093. style: {
  49094. fill: dataZoomModel.get('backgroundColor')
  49095. },
  49096. z2: -40
  49097. }));
  49098. // Click panel, over shadow, below handles.
  49099. barGroup.add(new Rect$1({
  49100. shape: {
  49101. x: 0, y: 0, width: size[0], height: size[1]
  49102. },
  49103. style: {
  49104. fill: 'transparent'
  49105. },
  49106. z2: 0,
  49107. onclick: bind(this._onClickPanelClick, this)
  49108. }));
  49109. },
  49110. _renderDataShadow: function () {
  49111. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  49112. if (!info) {
  49113. return;
  49114. }
  49115. var size = this._size;
  49116. var seriesModel = info.series;
  49117. var data = seriesModel.getRawData();
  49118. var otherDim = seriesModel.getShadowDim
  49119. ? seriesModel.getShadowDim() // @see candlestick
  49120. : info.otherDim;
  49121. if (otherDim == null) {
  49122. return;
  49123. }
  49124. var otherDataExtent = data.getDataExtent(otherDim);
  49125. // Nice extent.
  49126. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  49127. otherDataExtent = [
  49128. otherDataExtent[0] - otherOffset,
  49129. otherDataExtent[1] + otherOffset
  49130. ];
  49131. var otherShadowExtent = [0, size[1]];
  49132. var thisShadowExtent = [0, size[0]];
  49133. var areaPoints = [[size[0], 0], [0, 0]];
  49134. var linePoints = [];
  49135. var step = thisShadowExtent[1] / (data.count() - 1);
  49136. var thisCoord = 0;
  49137. // Optimize for large data shadow
  49138. var stride = Math.round(data.count() / size[0]);
  49139. var lastIsEmpty;
  49140. data.each([otherDim], function (value, index) {
  49141. if (stride > 0 && (index % stride)) {
  49142. thisCoord += step;
  49143. return;
  49144. }
  49145. // FIXME
  49146. // Should consider axis.min/axis.max when drawing dataShadow.
  49147. // FIXME
  49148. // 应该使用统一的空判断?还是在list里进行空判断?
  49149. var isEmpty = value == null || isNaN(value) || value === '';
  49150. // See #4235.
  49151. var otherCoord = isEmpty
  49152. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  49153. // Attempt to draw data shadow precisely when there are empty value.
  49154. if (isEmpty && !lastIsEmpty && index) {
  49155. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  49156. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  49157. }
  49158. else if (!isEmpty && lastIsEmpty) {
  49159. areaPoints.push([thisCoord, 0]);
  49160. linePoints.push([thisCoord, 0]);
  49161. }
  49162. areaPoints.push([thisCoord, otherCoord]);
  49163. linePoints.push([thisCoord, otherCoord]);
  49164. thisCoord += step;
  49165. lastIsEmpty = isEmpty;
  49166. });
  49167. var dataZoomModel = this.dataZoomModel;
  49168. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  49169. this._displayables.barGroup.add(new Polygon({
  49170. shape: {points: areaPoints},
  49171. style: defaults(
  49172. {fill: dataZoomModel.get('dataBackgroundColor')},
  49173. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  49174. ),
  49175. silent: true,
  49176. z2: -20
  49177. }));
  49178. this._displayables.barGroup.add(new Polyline({
  49179. shape: {points: linePoints},
  49180. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  49181. silent: true,
  49182. z2: -19
  49183. }));
  49184. },
  49185. _prepareDataShadowInfo: function () {
  49186. var dataZoomModel = this.dataZoomModel;
  49187. var showDataShadow = dataZoomModel.get('showDataShadow');
  49188. if (showDataShadow === false) {
  49189. return;
  49190. }
  49191. // Find a representative series.
  49192. var result;
  49193. var ecModel = this.ecModel;
  49194. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  49195. var seriesModels = dataZoomModel
  49196. .getAxisProxy(dimNames.name, axisIndex)
  49197. .getTargetSeriesModels();
  49198. each$1(seriesModels, function (seriesModel) {
  49199. if (result) {
  49200. return;
  49201. }
  49202. if (showDataShadow !== true && indexOf(
  49203. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  49204. ) < 0
  49205. ) {
  49206. return;
  49207. }
  49208. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  49209. var otherDim = getOtherDim(dimNames.name);
  49210. var otherAxisInverse;
  49211. var coordSys = seriesModel.coordinateSystem;
  49212. if (otherDim != null && coordSys.getOtherAxis) {
  49213. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  49214. }
  49215. otherDim = seriesModel.getData().mapDimension(otherDim);
  49216. result = {
  49217. thisAxis: thisAxis,
  49218. series: seriesModel,
  49219. thisDim: dimNames.name,
  49220. otherDim: otherDim,
  49221. otherAxisInverse: otherAxisInverse
  49222. };
  49223. }, this);
  49224. }, this);
  49225. return result;
  49226. },
  49227. _renderHandle: function () {
  49228. var displaybles = this._displayables;
  49229. var handles = displaybles.handles = [];
  49230. var handleLabels = displaybles.handleLabels = [];
  49231. var barGroup = this._displayables.barGroup;
  49232. var size = this._size;
  49233. var dataZoomModel = this.dataZoomModel;
  49234. barGroup.add(displaybles.filler = new Rect$1({
  49235. draggable: true,
  49236. cursor: getCursor(this._orient),
  49237. drift: bind$3(this._onDragMove, this, 'all'),
  49238. ondragstart: bind$3(this._showDataInfo, this, true),
  49239. ondragend: bind$3(this._onDragEnd, this),
  49240. onmouseover: bind$3(this._showDataInfo, this, true),
  49241. onmouseout: bind$3(this._showDataInfo, this, false),
  49242. style: {
  49243. fill: dataZoomModel.get('fillerColor'),
  49244. textPosition: 'inside'
  49245. }
  49246. }));
  49247. // Frame border.
  49248. barGroup.add(new Rect$1({
  49249. silent: true,
  49250. subPixelOptimize: true,
  49251. shape: {
  49252. x: 0,
  49253. y: 0,
  49254. width: size[0],
  49255. height: size[1]
  49256. },
  49257. style: {
  49258. stroke: dataZoomModel.get('dataBackgroundColor')
  49259. || dataZoomModel.get('borderColor'),
  49260. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  49261. fill: 'rgba(0,0,0,0)'
  49262. }
  49263. }));
  49264. each$14([0, 1], function (handleIndex) {
  49265. var path = createIcon(
  49266. dataZoomModel.get('handleIcon'),
  49267. {
  49268. cursor: getCursor(this._orient),
  49269. draggable: true,
  49270. drift: bind$3(this._onDragMove, this, handleIndex),
  49271. ondragend: bind$3(this._onDragEnd, this),
  49272. onmouseover: bind$3(this._showDataInfo, this, true),
  49273. onmouseout: bind$3(this._showDataInfo, this, false)
  49274. },
  49275. {x: -1, y: 0, width: 2, height: 2}
  49276. );
  49277. var bRect = path.getBoundingRect();
  49278. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  49279. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  49280. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  49281. var handleColor = dataZoomModel.get('handleColor');
  49282. // Compatitable with previous version
  49283. if (handleColor != null) {
  49284. path.style.fill = handleColor;
  49285. }
  49286. barGroup.add(handles[handleIndex] = path);
  49287. var textStyleModel = dataZoomModel.textStyleModel;
  49288. this.group.add(
  49289. handleLabels[handleIndex] = new Text({
  49290. silent: true,
  49291. invisible: true,
  49292. style: {
  49293. x: 0, y: 0, text: '',
  49294. textVerticalAlign: 'middle',
  49295. textAlign: 'center',
  49296. textFill: textStyleModel.getTextColor(),
  49297. textFont: textStyleModel.getFont()
  49298. },
  49299. z2: 10
  49300. }));
  49301. }, this);
  49302. },
  49303. /**
  49304. * @private
  49305. */
  49306. _resetInterval: function () {
  49307. var range = this._range = this.dataZoomModel.getPercentRange();
  49308. var viewExtent = this._getViewExtent();
  49309. this._handleEnds = [
  49310. linearMap$1(range[0], [0, 100], viewExtent, true),
  49311. linearMap$1(range[1], [0, 100], viewExtent, true)
  49312. ];
  49313. },
  49314. /**
  49315. * @private
  49316. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  49317. * @param {number} delta
  49318. * @return {boolean} changed
  49319. */
  49320. _updateInterval: function (handleIndex, delta) {
  49321. var dataZoomModel = this.dataZoomModel;
  49322. var handleEnds = this._handleEnds;
  49323. var viewExtend = this._getViewExtent();
  49324. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  49325. var percentExtent = [0, 100];
  49326. sliderMove(
  49327. delta,
  49328. handleEnds,
  49329. viewExtend,
  49330. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  49331. minMaxSpan.minSpan != null
  49332. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  49333. minMaxSpan.maxSpan != null
  49334. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  49335. );
  49336. var lastRange = this._range;
  49337. var range = this._range = asc$2([
  49338. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  49339. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  49340. ]);
  49341. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  49342. },
  49343. /**
  49344. * @private
  49345. */
  49346. _updateView: function (nonRealtime) {
  49347. var displaybles = this._displayables;
  49348. var handleEnds = this._handleEnds;
  49349. var handleInterval = asc$2(handleEnds.slice());
  49350. var size = this._size;
  49351. each$14([0, 1], function (handleIndex) {
  49352. // Handles
  49353. var handle = displaybles.handles[handleIndex];
  49354. var handleHeight = this._handleHeight;
  49355. handle.attr({
  49356. scale: [handleHeight / 2, handleHeight / 2],
  49357. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  49358. });
  49359. }, this);
  49360. // Filler
  49361. displaybles.filler.setShape({
  49362. x: handleInterval[0],
  49363. y: 0,
  49364. width: handleInterval[1] - handleInterval[0],
  49365. height: size[1]
  49366. });
  49367. this._updateDataInfo(nonRealtime);
  49368. },
  49369. /**
  49370. * @private
  49371. */
  49372. _updateDataInfo: function (nonRealtime) {
  49373. var dataZoomModel = this.dataZoomModel;
  49374. var displaybles = this._displayables;
  49375. var handleLabels = displaybles.handleLabels;
  49376. var orient = this._orient;
  49377. var labelTexts = ['', ''];
  49378. // FIXME
  49379. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  49380. if (dataZoomModel.get('showDetail')) {
  49381. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  49382. if (axisProxy) {
  49383. var axis = axisProxy.getAxisModel().axis;
  49384. var range = this._range;
  49385. var dataInterval = nonRealtime
  49386. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  49387. ? axisProxy.calculateDataWindow({
  49388. start: range[0], end: range[1]
  49389. }).valueWindow
  49390. : axisProxy.getDataValueWindow();
  49391. labelTexts = [
  49392. this._formatLabel(dataInterval[0], axis),
  49393. this._formatLabel(dataInterval[1], axis)
  49394. ];
  49395. }
  49396. }
  49397. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  49398. setLabel.call(this, 0);
  49399. setLabel.call(this, 1);
  49400. function setLabel(handleIndex) {
  49401. // Label
  49402. // Text should not transform by barGroup.
  49403. // Ignore handlers transform
  49404. var barTransform = getTransform(
  49405. displaybles.handles[handleIndex].parent, this.group
  49406. );
  49407. var direction = transformDirection(
  49408. handleIndex === 0 ? 'right' : 'left', barTransform
  49409. );
  49410. var offset = this._handleWidth / 2 + LABEL_GAP;
  49411. var textPoint = applyTransform$1(
  49412. [
  49413. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  49414. this._size[1] / 2
  49415. ],
  49416. barTransform
  49417. );
  49418. handleLabels[handleIndex].setStyle({
  49419. x: textPoint[0],
  49420. y: textPoint[1],
  49421. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  49422. textAlign: orient === HORIZONTAL ? direction : 'center',
  49423. text: labelTexts[handleIndex]
  49424. });
  49425. }
  49426. },
  49427. /**
  49428. * @private
  49429. */
  49430. _formatLabel: function (value, axis) {
  49431. var dataZoomModel = this.dataZoomModel;
  49432. var labelFormatter = dataZoomModel.get('labelFormatter');
  49433. var labelPrecision = dataZoomModel.get('labelPrecision');
  49434. if (labelPrecision == null || labelPrecision === 'auto') {
  49435. labelPrecision = axis.getPixelPrecision();
  49436. }
  49437. var valueStr = (value == null || isNaN(value))
  49438. ? ''
  49439. // FIXME Glue code
  49440. : (axis.type === 'category' || axis.type === 'time')
  49441. ? axis.scale.getLabel(Math.round(value))
  49442. // param of toFixed should less then 20.
  49443. : value.toFixed(Math.min(labelPrecision, 20));
  49444. return isFunction$1(labelFormatter)
  49445. ? labelFormatter(value, valueStr)
  49446. : isString(labelFormatter)
  49447. ? labelFormatter.replace('{value}', valueStr)
  49448. : valueStr;
  49449. },
  49450. /**
  49451. * @private
  49452. * @param {boolean} showOrHide true: show, false: hide
  49453. */
  49454. _showDataInfo: function (showOrHide) {
  49455. // Always show when drgging.
  49456. showOrHide = this._dragging || showOrHide;
  49457. var handleLabels = this._displayables.handleLabels;
  49458. handleLabels[0].attr('invisible', !showOrHide);
  49459. handleLabels[1].attr('invisible', !showOrHide);
  49460. },
  49461. _onDragMove: function (handleIndex, dx, dy, event) {
  49462. this._dragging = true;
  49463. // For mobile device, prevent screen slider on the button.
  49464. stop(event.event);
  49465. // Transform dx, dy to bar coordination.
  49466. var barTransform = this._displayables.barGroup.getLocalTransform();
  49467. var vertex = applyTransform$1([dx, dy], barTransform, true);
  49468. var changed = this._updateInterval(handleIndex, vertex[0]);
  49469. var realtime = this.dataZoomModel.get('realtime');
  49470. this._updateView(!realtime);
  49471. // Avoid dispatch dataZoom repeatly but range not changed,
  49472. // which cause bad visual effect when progressive enabled.
  49473. changed && realtime && this._dispatchZoomAction();
  49474. },
  49475. _onDragEnd: function () {
  49476. this._dragging = false;
  49477. this._showDataInfo(false);
  49478. // While in realtime mode and stream mode, dispatch action when
  49479. // drag end will cause the whole view rerender, which is unnecessary.
  49480. var realtime = this.dataZoomModel.get('realtime');
  49481. !realtime && this._dispatchZoomAction();
  49482. },
  49483. _onClickPanelClick: function (e) {
  49484. var size = this._size;
  49485. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  49486. if (localPoint[0] < 0 || localPoint[0] > size[0]
  49487. || localPoint[1] < 0 || localPoint[1] > size[1]
  49488. ) {
  49489. return;
  49490. }
  49491. var handleEnds = this._handleEnds;
  49492. var center = (handleEnds[0] + handleEnds[1]) / 2;
  49493. var changed = this._updateInterval('all', localPoint[0] - center);
  49494. this._updateView();
  49495. changed && this._dispatchZoomAction();
  49496. },
  49497. /**
  49498. * This action will be throttled.
  49499. * @private
  49500. */
  49501. _dispatchZoomAction: function () {
  49502. var range = this._range;
  49503. this.api.dispatchAction({
  49504. type: 'dataZoom',
  49505. from: this.uid,
  49506. dataZoomId: this.dataZoomModel.id,
  49507. start: range[0],
  49508. end: range[1]
  49509. });
  49510. },
  49511. /**
  49512. * @private
  49513. */
  49514. _findCoordRect: function () {
  49515. // Find the grid coresponding to the first axis referred by dataZoom.
  49516. var rect;
  49517. each$14(this.getTargetCoordInfo(), function (coordInfoList) {
  49518. if (!rect && coordInfoList.length) {
  49519. var coordSys = coordInfoList[0].model.coordinateSystem;
  49520. rect = coordSys.getRect && coordSys.getRect();
  49521. }
  49522. });
  49523. if (!rect) {
  49524. var width = this.api.getWidth();
  49525. var height = this.api.getHeight();
  49526. rect = {
  49527. x: width * 0.2,
  49528. y: height * 0.2,
  49529. width: width * 0.6,
  49530. height: height * 0.6
  49531. };
  49532. }
  49533. return rect;
  49534. }
  49535. });
  49536. function getOtherDim(thisDim) {
  49537. // FIXME
  49538. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  49539. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  49540. return map$$1[thisDim];
  49541. }
  49542. function getCursor(orient) {
  49543. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  49544. }
  49545. /*
  49546. * Licensed to the Apache Software Foundation (ASF) under one
  49547. * or more contributor license agreements. See the NOTICE file
  49548. * distributed with this work for additional information
  49549. * regarding copyright ownership. The ASF licenses this file
  49550. * to you under the Apache License, Version 2.0 (the
  49551. * "License"); you may not use this file except in compliance
  49552. * with the License. You may obtain a copy of the License at
  49553. *
  49554. * http://www.apache.org/licenses/LICENSE-2.0
  49555. *
  49556. * Unless required by applicable law or agreed to in writing,
  49557. * software distributed under the License is distributed on an
  49558. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49559. * KIND, either express or implied. See the License for the
  49560. * specific language governing permissions and limitations
  49561. * under the License.
  49562. */
  49563. registerProcessor({
  49564. // `dataZoomProcessor` will only be performed in needed series. Consider if
  49565. // there is a line series and a pie series, it is better not to update the
  49566. // line series if only pie series is needed to be updated.
  49567. getTargetSeries: function (ecModel) {
  49568. var seriesModelMap = createHashMap();
  49569. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  49570. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  49571. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  49572. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  49573. seriesModelMap.set(seriesModel.uid, seriesModel);
  49574. });
  49575. });
  49576. });
  49577. return seriesModelMap;
  49578. },
  49579. modifyOutputEnd: true,
  49580. // Consider appendData, where filter should be performed. Because data process is
  49581. // in block mode currently, it is not need to worry about that the overallProgress
  49582. // execute every frame.
  49583. overallReset: function (ecModel, api) {
  49584. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  49585. // We calculate window and reset axis here but not in model
  49586. // init stage and not after action dispatch handler, because
  49587. // reset should be called after seriesData.restoreData.
  49588. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  49589. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  49590. });
  49591. // Caution: data zoom filtering is order sensitive when using
  49592. // percent range and no min/max/scale set on axis.
  49593. // For example, we have dataZoom definition:
  49594. // [
  49595. // {xAxisIndex: 0, start: 30, end: 70},
  49596. // {yAxisIndex: 0, start: 20, end: 80}
  49597. // ]
  49598. // In this case, [20, 80] of y-dataZoom should be based on data
  49599. // that have filtered by x-dataZoom using range of [30, 70],
  49600. // but should not be based on full raw data. Thus sliding
  49601. // x-dataZoom will change both ranges of xAxis and yAxis,
  49602. // while sliding y-dataZoom will only change the range of yAxis.
  49603. // So we should filter x-axis after reset x-axis immediately,
  49604. // and then reset y-axis and filter y-axis.
  49605. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  49606. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  49607. });
  49608. });
  49609. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  49610. // Fullfill all of the range props so that user
  49611. // is able to get them from chart.getOption().
  49612. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  49613. var percentRange = axisProxy.getDataPercentWindow();
  49614. var valueRange = axisProxy.getDataValueWindow();
  49615. dataZoomModel.setCalculatedRange({
  49616. start: percentRange[0],
  49617. end: percentRange[1],
  49618. startValue: valueRange[0],
  49619. endValue: valueRange[1]
  49620. });
  49621. });
  49622. }
  49623. });
  49624. /*
  49625. * Licensed to the Apache Software Foundation (ASF) under one
  49626. * or more contributor license agreements. See the NOTICE file
  49627. * distributed with this work for additional information
  49628. * regarding copyright ownership. The ASF licenses this file
  49629. * to you under the Apache License, Version 2.0 (the
  49630. * "License"); you may not use this file except in compliance
  49631. * with the License. You may obtain a copy of the License at
  49632. *
  49633. * http://www.apache.org/licenses/LICENSE-2.0
  49634. *
  49635. * Unless required by applicable law or agreed to in writing,
  49636. * software distributed under the License is distributed on an
  49637. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49638. * KIND, either express or implied. See the License for the
  49639. * specific language governing permissions and limitations
  49640. * under the License.
  49641. */
  49642. registerAction('dataZoom', function (payload, ecModel) {
  49643. var linkedNodesFinder = createLinkedNodesFinder(
  49644. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  49645. eachAxisDim$1,
  49646. function (model, dimNames) {
  49647. return model.get(dimNames.axisIndex);
  49648. }
  49649. );
  49650. var effectedModels = [];
  49651. ecModel.eachComponent(
  49652. {mainType: 'dataZoom', query: payload},
  49653. function (model, index) {
  49654. effectedModels.push.apply(
  49655. effectedModels, linkedNodesFinder(model).nodes
  49656. );
  49657. }
  49658. );
  49659. each$1(effectedModels, function (dataZoomModel, index) {
  49660. dataZoomModel.setRawRange({
  49661. start: payload.start,
  49662. end: payload.end,
  49663. startValue: payload.startValue,
  49664. endValue: payload.endValue
  49665. });
  49666. });
  49667. });
  49668. /*
  49669. * Licensed to the Apache Software Foundation (ASF) under one
  49670. * or more contributor license agreements. See the NOTICE file
  49671. * distributed with this work for additional information
  49672. * regarding copyright ownership. The ASF licenses this file
  49673. * to you under the Apache License, Version 2.0 (the
  49674. * "License"); you may not use this file except in compliance
  49675. * with the License. You may obtain a copy of the License at
  49676. *
  49677. * http://www.apache.org/licenses/LICENSE-2.0
  49678. *
  49679. * Unless required by applicable law or agreed to in writing,
  49680. * software distributed under the License is distributed on an
  49681. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49682. * KIND, either express or implied. See the License for the
  49683. * specific language governing permissions and limitations
  49684. * under the License.
  49685. */
  49686. /*
  49687. * Licensed to the Apache Software Foundation (ASF) under one
  49688. * or more contributor license agreements. See the NOTICE file
  49689. * distributed with this work for additional information
  49690. * regarding copyright ownership. The ASF licenses this file
  49691. * to you under the Apache License, Version 2.0 (the
  49692. * "License"); you may not use this file except in compliance
  49693. * with the License. You may obtain a copy of the License at
  49694. *
  49695. * http://www.apache.org/licenses/LICENSE-2.0
  49696. *
  49697. * Unless required by applicable law or agreed to in writing,
  49698. * software distributed under the License is distributed on an
  49699. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49700. * KIND, either express or implied. See the License for the
  49701. * specific language governing permissions and limitations
  49702. * under the License.
  49703. */
  49704. DataZoomModel.extend({
  49705. type: 'dataZoom.inside',
  49706. /**
  49707. * @protected
  49708. */
  49709. defaultOption: {
  49710. disabled: false, // Whether disable this inside zoom.
  49711. zoomLock: false, // Whether disable zoom but only pan.
  49712. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49713. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49714. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49715. preventDefaultMouseMove: true
  49716. }
  49717. });
  49718. /*
  49719. * Licensed to the Apache Software Foundation (ASF) under one
  49720. * or more contributor license agreements. See the NOTICE file
  49721. * distributed with this work for additional information
  49722. * regarding copyright ownership. The ASF licenses this file
  49723. * to you under the Apache License, Version 2.0 (the
  49724. * "License"); you may not use this file except in compliance
  49725. * with the License. You may obtain a copy of the License at
  49726. *
  49727. * http://www.apache.org/licenses/LICENSE-2.0
  49728. *
  49729. * Unless required by applicable law or agreed to in writing,
  49730. * software distributed under the License is distributed on an
  49731. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49732. * KIND, either express or implied. See the License for the
  49733. * specific language governing permissions and limitations
  49734. * under the License.
  49735. */
  49736. var ATTR$1 = '\0_ec_interaction_mutex';
  49737. function take(zr, resourceKey, userKey) {
  49738. var store = getStore(zr);
  49739. store[resourceKey] = userKey;
  49740. }
  49741. function release(zr, resourceKey, userKey) {
  49742. var store = getStore(zr);
  49743. var uKey = store[resourceKey];
  49744. if (uKey === userKey) {
  49745. store[resourceKey] = null;
  49746. }
  49747. }
  49748. function isTaken(zr, resourceKey) {
  49749. return !!getStore(zr)[resourceKey];
  49750. }
  49751. function getStore(zr) {
  49752. return zr[ATTR$1] || (zr[ATTR$1] = {});
  49753. }
  49754. /**
  49755. * payload: {
  49756. * type: 'takeGlobalCursor',
  49757. * key: 'dataZoomSelect', or 'brush', or ...,
  49758. * If no userKey, release global cursor.
  49759. * }
  49760. */
  49761. registerAction(
  49762. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  49763. function () {}
  49764. );
  49765. /*
  49766. * Licensed to the Apache Software Foundation (ASF) under one
  49767. * or more contributor license agreements. See the NOTICE file
  49768. * distributed with this work for additional information
  49769. * regarding copyright ownership. The ASF licenses this file
  49770. * to you under the Apache License, Version 2.0 (the
  49771. * "License"); you may not use this file except in compliance
  49772. * with the License. You may obtain a copy of the License at
  49773. *
  49774. * http://www.apache.org/licenses/LICENSE-2.0
  49775. *
  49776. * Unless required by applicable law or agreed to in writing,
  49777. * software distributed under the License is distributed on an
  49778. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49779. * KIND, either express or implied. See the License for the
  49780. * specific language governing permissions and limitations
  49781. * under the License.
  49782. */
  49783. /**
  49784. * @alias module:echarts/component/helper/RoamController
  49785. * @constructor
  49786. * @mixin {module:zrender/mixin/Eventful}
  49787. *
  49788. * @param {module:zrender/zrender~ZRender} zr
  49789. */
  49790. function RoamController(zr) {
  49791. /**
  49792. * @type {Function}
  49793. */
  49794. this.pointerChecker;
  49795. /**
  49796. * @type {module:zrender}
  49797. */
  49798. this._zr = zr;
  49799. /**
  49800. * @type {Object}
  49801. */
  49802. this._opt = {};
  49803. // Avoid two roamController bind the same handler
  49804. var bind$$1 = bind;
  49805. var mousedownHandler = bind$$1(mousedown, this);
  49806. var mousemoveHandler = bind$$1(mousemove, this);
  49807. var mouseupHandler = bind$$1(mouseup, this);
  49808. var mousewheelHandler = bind$$1(mousewheel, this);
  49809. var pinchHandler = bind$$1(pinch, this);
  49810. Eventful.call(this);
  49811. /**
  49812. * @param {Function} pointerChecker
  49813. * input: x, y
  49814. * output: boolean
  49815. */
  49816. this.setPointerChecker = function (pointerChecker) {
  49817. this.pointerChecker = pointerChecker;
  49818. };
  49819. /**
  49820. * Notice: only enable needed types. For example, if 'zoom'
  49821. * is not needed, 'zoom' should not be enabled, otherwise
  49822. * default mousewheel behaviour (scroll page) will be disabled.
  49823. *
  49824. * @param {boolean|string} [controlType=true] Specify the control type,
  49825. * which can be null/undefined or true/false
  49826. * or 'pan/move' or 'zoom'/'scale'
  49827. * @param {Object} [opt]
  49828. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49829. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49830. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49831. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  49832. */
  49833. this.enable = function (controlType, opt) {
  49834. // Disable previous first
  49835. this.disable();
  49836. this._opt = defaults(clone(opt) || {}, {
  49837. zoomOnMouseWheel: true,
  49838. moveOnMouseMove: true,
  49839. // By default, wheel do not trigger move.
  49840. moveOnMouseWheel: false,
  49841. preventDefaultMouseMove: true
  49842. });
  49843. if (controlType == null) {
  49844. controlType = true;
  49845. }
  49846. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  49847. zr.on('mousedown', mousedownHandler);
  49848. zr.on('mousemove', mousemoveHandler);
  49849. zr.on('mouseup', mouseupHandler);
  49850. }
  49851. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  49852. zr.on('mousewheel', mousewheelHandler);
  49853. zr.on('pinch', pinchHandler);
  49854. }
  49855. };
  49856. this.disable = function () {
  49857. zr.off('mousedown', mousedownHandler);
  49858. zr.off('mousemove', mousemoveHandler);
  49859. zr.off('mouseup', mouseupHandler);
  49860. zr.off('mousewheel', mousewheelHandler);
  49861. zr.off('pinch', pinchHandler);
  49862. };
  49863. this.dispose = this.disable;
  49864. this.isDragging = function () {
  49865. return this._dragging;
  49866. };
  49867. this.isPinching = function () {
  49868. return this._pinching;
  49869. };
  49870. }
  49871. mixin(RoamController, Eventful);
  49872. function mousedown(e) {
  49873. if (isMiddleOrRightButtonOnMouseUpDown(e)
  49874. || (e.target && e.target.draggable)
  49875. ) {
  49876. return;
  49877. }
  49878. var x = e.offsetX;
  49879. var y = e.offsetY;
  49880. // Only check on mosedown, but not mousemove.
  49881. // Mouse can be out of target when mouse moving.
  49882. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  49883. this._x = x;
  49884. this._y = y;
  49885. this._dragging = true;
  49886. }
  49887. }
  49888. function mousemove(e) {
  49889. if (!this._dragging
  49890. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  49891. || e.gestureEvent === 'pinch'
  49892. || isTaken(this._zr, 'globalPan')
  49893. ) {
  49894. return;
  49895. }
  49896. var x = e.offsetX;
  49897. var y = e.offsetY;
  49898. var oldX = this._x;
  49899. var oldY = this._y;
  49900. var dx = x - oldX;
  49901. var dy = y - oldY;
  49902. this._x = x;
  49903. this._y = y;
  49904. this._opt.preventDefaultMouseMove && stop(e.event);
  49905. trigger(this, 'pan', 'moveOnMouseMove', e, {
  49906. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  49907. });
  49908. }
  49909. function mouseup(e) {
  49910. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  49911. this._dragging = false;
  49912. }
  49913. }
  49914. function mousewheel(e) {
  49915. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  49916. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  49917. var wheelDelta = e.wheelDelta;
  49918. var absWheelDeltaDelta = Math.abs(wheelDelta);
  49919. var originX = e.offsetX;
  49920. var originY = e.offsetY;
  49921. // wheelDelta maybe -0 in chrome mac.
  49922. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  49923. return;
  49924. }
  49925. // If both `shouldZoom` and `shouldMove` is true, trigger
  49926. // their event both, and the final behavior is determined
  49927. // by event listener themselves.
  49928. if (shouldZoom) {
  49929. // Convenience:
  49930. // Mac and VM Windows on Mac: scroll up: zoom out.
  49931. // Windows: scroll up: zoom in.
  49932. // FIXME: Should do more test in different environment.
  49933. // wheelDelta is too complicated in difference nvironment
  49934. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  49935. // although it has been normallized by zrender.
  49936. // wheelDelta of mouse wheel is bigger than touch pad.
  49937. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  49938. var scale = wheelDelta > 0 ? factor : 1 / factor;
  49939. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  49940. scale: scale, originX: originX, originY: originY
  49941. });
  49942. }
  49943. if (shouldMove) {
  49944. // FIXME: Should do more test in different environment.
  49945. var absDelta = Math.abs(wheelDelta);
  49946. // wheelDelta of mouse wheel is bigger than touch pad.
  49947. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  49948. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  49949. scrollDelta: scrollDelta, originX: originX, originY: originY
  49950. });
  49951. }
  49952. }
  49953. function pinch(e) {
  49954. if (isTaken(this._zr, 'globalPan')) {
  49955. return;
  49956. }
  49957. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  49958. checkPointerAndTrigger(this, 'zoom', null, e, {
  49959. scale: scale, originX: e.pinchX, originY: e.pinchY
  49960. });
  49961. }
  49962. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  49963. if (controller.pointerChecker
  49964. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  49965. ) {
  49966. // When mouse is out of roamController rect,
  49967. // default befavoius should not be be disabled, otherwise
  49968. // page sliding is disabled, contrary to expectation.
  49969. stop(e.event);
  49970. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  49971. }
  49972. }
  49973. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  49974. // Also provide behavior checker for event listener, for some case that
  49975. // multiple components share one listener.
  49976. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  49977. controller.trigger(eventName, contollerEvent);
  49978. }
  49979. // settings: {
  49980. // zoomOnMouseWheel
  49981. // moveOnMouseMove
  49982. // moveOnMouseWheel
  49983. // }
  49984. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49985. function isAvailableBehavior(behaviorToCheck, e, settings) {
  49986. var setting = settings[behaviorToCheck];
  49987. return !behaviorToCheck || (
  49988. setting && (!isString(setting) || e.event[setting + 'Key'])
  49989. );
  49990. }
  49991. /*
  49992. * Licensed to the Apache Software Foundation (ASF) under one
  49993. * or more contributor license agreements. See the NOTICE file
  49994. * distributed with this work for additional information
  49995. * regarding copyright ownership. The ASF licenses this file
  49996. * to you under the Apache License, Version 2.0 (the
  49997. * "License"); you may not use this file except in compliance
  49998. * with the License. You may obtain a copy of the License at
  49999. *
  50000. * http://www.apache.org/licenses/LICENSE-2.0
  50001. *
  50002. * Unless required by applicable law or agreed to in writing,
  50003. * software distributed under the License is distributed on an
  50004. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50005. * KIND, either express or implied. See the License for the
  50006. * specific language governing permissions and limitations
  50007. * under the License.
  50008. */
  50009. // Only create one roam controller for each coordinate system.
  50010. // one roam controller might be refered by two inside data zoom
  50011. // components (for example, one for x and one for y). When user
  50012. // pan or zoom, only dispatch one action for those data zoom
  50013. // components.
  50014. var ATTR = '\0_ec_dataZoom_roams';
  50015. /**
  50016. * @public
  50017. * @param {module:echarts/ExtensionAPI} api
  50018. * @param {Object} dataZoomInfo
  50019. * @param {string} dataZoomInfo.coordId
  50020. * @param {Function} dataZoomInfo.containsPoint
  50021. * @param {Array.<string>} dataZoomInfo.allCoordIds
  50022. * @param {string} dataZoomInfo.dataZoomId
  50023. * @param {Object} dataZoomInfo.getRange
  50024. * @param {Function} dataZoomInfo.getRange.pan
  50025. * @param {Function} dataZoomInfo.getRange.zoom
  50026. * @param {Function} dataZoomInfo.getRange.scrollMove
  50027. * @param {boolean} dataZoomInfo.dataZoomModel
  50028. */
  50029. function register$1(api, dataZoomInfo) {
  50030. var store = giveStore(api);
  50031. var theDataZoomId = dataZoomInfo.dataZoomId;
  50032. var theCoordId = dataZoomInfo.coordId;
  50033. // Do clean when a dataZoom changes its target coordnate system.
  50034. // Avoid memory leak, dispose all not-used-registered.
  50035. each$1(store, function (record, coordId) {
  50036. var dataZoomInfos = record.dataZoomInfos;
  50037. if (dataZoomInfos[theDataZoomId]
  50038. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  50039. ) {
  50040. delete dataZoomInfos[theDataZoomId];
  50041. record.count--;
  50042. }
  50043. });
  50044. cleanStore(store);
  50045. var record = store[theCoordId];
  50046. // Create if needed.
  50047. if (!record) {
  50048. record = store[theCoordId] = {
  50049. coordId: theCoordId,
  50050. dataZoomInfos: {},
  50051. count: 0
  50052. };
  50053. record.controller = createController(api, record);
  50054. record.dispatchAction = curry(dispatchAction, api);
  50055. }
  50056. // Update reference of dataZoom.
  50057. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  50058. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  50059. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  50060. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  50061. // Consider resize, area should be always updated.
  50062. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  50063. // Update throttle.
  50064. createOrUpdate(
  50065. record,
  50066. 'dispatchAction',
  50067. dataZoomInfo.dataZoomModel.get('throttle', true),
  50068. 'fixRate'
  50069. );
  50070. }
  50071. /**
  50072. * @public
  50073. * @param {module:echarts/ExtensionAPI} api
  50074. * @param {string} dataZoomId
  50075. */
  50076. function unregister$1(api, dataZoomId) {
  50077. var store = giveStore(api);
  50078. each$1(store, function (record) {
  50079. record.controller.dispose();
  50080. var dataZoomInfos = record.dataZoomInfos;
  50081. if (dataZoomInfos[dataZoomId]) {
  50082. delete dataZoomInfos[dataZoomId];
  50083. record.count--;
  50084. }
  50085. });
  50086. cleanStore(store);
  50087. }
  50088. /**
  50089. * @public
  50090. */
  50091. function generateCoordId(coordModel) {
  50092. return coordModel.type + '\0_' + coordModel.id;
  50093. }
  50094. /**
  50095. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  50096. * @type {Array.<Object>}
  50097. */
  50098. function giveStore(api) {
  50099. // Mount store on zrender instance, so that we do not
  50100. // need to worry about dispose.
  50101. var zr = api.getZr();
  50102. return zr[ATTR] || (zr[ATTR] = {});
  50103. }
  50104. function createController(api, newRecord) {
  50105. var controller = new RoamController(api.getZr());
  50106. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  50107. controller.on(eventName, function (event) {
  50108. var batch = [];
  50109. each$1(newRecord.dataZoomInfos, function (info) {
  50110. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  50111. // moveOnMouseWheel, ...) enabled.
  50112. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  50113. return;
  50114. }
  50115. var method = (info.getRange || {})[eventName];
  50116. var range = method && method(newRecord.controller, event);
  50117. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  50118. dataZoomId: info.dataZoomId,
  50119. start: range[0],
  50120. end: range[1]
  50121. });
  50122. });
  50123. batch.length && newRecord.dispatchAction(batch);
  50124. });
  50125. });
  50126. return controller;
  50127. }
  50128. function cleanStore(store) {
  50129. each$1(store, function (record, coordId) {
  50130. if (!record.count) {
  50131. record.controller.dispose();
  50132. delete store[coordId];
  50133. }
  50134. });
  50135. }
  50136. /**
  50137. * This action will be throttled.
  50138. */
  50139. function dispatchAction(api, batch) {
  50140. api.dispatchAction({
  50141. type: 'dataZoom',
  50142. batch: batch
  50143. });
  50144. }
  50145. /**
  50146. * Merge roamController settings when multiple dataZooms share one roamController.
  50147. */
  50148. function mergeControllerParams(dataZoomInfos) {
  50149. var controlType;
  50150. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  50151. // as string, it is probably revert to reserved word by compress tool. See #7411.
  50152. var prefix = 'type_';
  50153. var typePriority = {
  50154. 'type_true': 2,
  50155. 'type_move': 1,
  50156. 'type_false': 0,
  50157. 'type_undefined': -1
  50158. };
  50159. var preventDefaultMouseMove = true;
  50160. each$1(dataZoomInfos, function (dataZoomInfo) {
  50161. var dataZoomModel = dataZoomInfo.dataZoomModel;
  50162. var oneType = dataZoomModel.get('disabled', true)
  50163. ? false
  50164. : dataZoomModel.get('zoomLock', true)
  50165. ? 'move'
  50166. : true;
  50167. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  50168. controlType = oneType;
  50169. }
  50170. // Prevent default move event by default. If one false, do not prevent. Otherwise
  50171. // users may be confused why it does not work when multiple insideZooms exist.
  50172. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  50173. });
  50174. return {
  50175. controlType: controlType,
  50176. opt: {
  50177. // RoamController will enable all of these functionalities,
  50178. // and the final behavior is determined by its event listener
  50179. // provided by each inside zoom.
  50180. zoomOnMouseWheel: true,
  50181. moveOnMouseMove: true,
  50182. moveOnMouseWheel: true,
  50183. preventDefaultMouseMove: !!preventDefaultMouseMove
  50184. }
  50185. };
  50186. }
  50187. /*
  50188. * Licensed to the Apache Software Foundation (ASF) under one
  50189. * or more contributor license agreements. See the NOTICE file
  50190. * distributed with this work for additional information
  50191. * regarding copyright ownership. The ASF licenses this file
  50192. * to you under the Apache License, Version 2.0 (the
  50193. * "License"); you may not use this file except in compliance
  50194. * with the License. You may obtain a copy of the License at
  50195. *
  50196. * http://www.apache.org/licenses/LICENSE-2.0
  50197. *
  50198. * Unless required by applicable law or agreed to in writing,
  50199. * software distributed under the License is distributed on an
  50200. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50201. * KIND, either express or implied. See the License for the
  50202. * specific language governing permissions and limitations
  50203. * under the License.
  50204. */
  50205. var bind$4 = bind;
  50206. var InsideZoomView = DataZoomView.extend({
  50207. type: 'dataZoom.inside',
  50208. /**
  50209. * @override
  50210. */
  50211. init: function (ecModel, api) {
  50212. /**
  50213. * 'throttle' is used in this.dispatchAction, so we save range
  50214. * to avoid missing some 'pan' info.
  50215. * @private
  50216. * @type {Array.<number>}
  50217. */
  50218. this._range;
  50219. },
  50220. /**
  50221. * @override
  50222. */
  50223. render: function (dataZoomModel, ecModel, api, payload) {
  50224. InsideZoomView.superApply(this, 'render', arguments);
  50225. // Hence the `throttle` util ensures to preserve command order,
  50226. // here simply updating range all the time will not cause missing
  50227. // any of the the roam change.
  50228. this._range = dataZoomModel.getPercentRange();
  50229. // Reset controllers.
  50230. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  50231. var allCoordIds = map(coordInfoList, function (coordInfo) {
  50232. return generateCoordId(coordInfo.model);
  50233. });
  50234. each$1(coordInfoList, function (coordInfo) {
  50235. var coordModel = coordInfo.model;
  50236. var getRange = {};
  50237. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  50238. getRange[eventName] = bind$4(roamHandlers[eventName], this, coordInfo, coordSysName);
  50239. }, this);
  50240. register$1(
  50241. api,
  50242. {
  50243. coordId: generateCoordId(coordModel),
  50244. allCoordIds: allCoordIds,
  50245. containsPoint: function (e, x, y) {
  50246. return coordModel.coordinateSystem.containPoint([x, y]);
  50247. },
  50248. dataZoomId: dataZoomModel.id,
  50249. dataZoomModel: dataZoomModel,
  50250. getRange: getRange
  50251. }
  50252. );
  50253. }, this);
  50254. }, this);
  50255. },
  50256. /**
  50257. * @override
  50258. */
  50259. dispose: function () {
  50260. unregister$1(this.api, this.dataZoomModel.id);
  50261. InsideZoomView.superApply(this, 'dispose', arguments);
  50262. this._range = null;
  50263. }
  50264. });
  50265. var roamHandlers = {
  50266. /**
  50267. * @this {module:echarts/component/dataZoom/InsideZoomView}
  50268. */
  50269. zoom: function (coordInfo, coordSysName, controller, e) {
  50270. var lastRange = this._range;
  50271. var range = lastRange.slice();
  50272. // Calculate transform by the first axis.
  50273. var axisModel = coordInfo.axisModels[0];
  50274. if (!axisModel) {
  50275. return;
  50276. }
  50277. var directionInfo = getDirectionInfo[coordSysName](
  50278. null, [e.originX, e.originY], axisModel, controller, coordInfo
  50279. );
  50280. var percentPoint = (
  50281. directionInfo.signal > 0
  50282. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  50283. : (directionInfo.pixel - directionInfo.pixelStart)
  50284. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  50285. var scale = Math.max(1 / e.scale, 0);
  50286. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  50287. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  50288. // Restrict range.
  50289. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  50290. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  50291. this._range = range;
  50292. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  50293. return range;
  50294. }
  50295. },
  50296. /**
  50297. * @this {module:echarts/component/dataZoom/InsideZoomView}
  50298. */
  50299. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  50300. var directionInfo = getDirectionInfo[coordSysName](
  50301. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  50302. );
  50303. return directionInfo.signal
  50304. * (range[1] - range[0])
  50305. * directionInfo.pixel / directionInfo.pixelLength;
  50306. }),
  50307. /**
  50308. * @this {module:echarts/component/dataZoom/InsideZoomView}
  50309. */
  50310. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  50311. var directionInfo = getDirectionInfo[coordSysName](
  50312. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  50313. );
  50314. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  50315. })
  50316. };
  50317. function makeMover(getPercentDelta) {
  50318. return function (coordInfo, coordSysName, controller, e) {
  50319. var lastRange = this._range;
  50320. var range = lastRange.slice();
  50321. // Calculate transform by the first axis.
  50322. var axisModel = coordInfo.axisModels[0];
  50323. if (!axisModel) {
  50324. return;
  50325. }
  50326. var percentDelta = getPercentDelta(
  50327. range, axisModel, coordInfo, coordSysName, controller, e
  50328. );
  50329. sliderMove(percentDelta, range, [0, 100], 'all');
  50330. this._range = range;
  50331. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  50332. return range;
  50333. }
  50334. };
  50335. }
  50336. var getDirectionInfo = {
  50337. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  50338. var axis = axisModel.axis;
  50339. var ret = {};
  50340. var rect = coordInfo.model.coordinateSystem.getRect();
  50341. oldPoint = oldPoint || [0, 0];
  50342. if (axis.dim === 'x') {
  50343. ret.pixel = newPoint[0] - oldPoint[0];
  50344. ret.pixelLength = rect.width;
  50345. ret.pixelStart = rect.x;
  50346. ret.signal = axis.inverse ? 1 : -1;
  50347. }
  50348. else { // axis.dim === 'y'
  50349. ret.pixel = newPoint[1] - oldPoint[1];
  50350. ret.pixelLength = rect.height;
  50351. ret.pixelStart = rect.y;
  50352. ret.signal = axis.inverse ? -1 : 1;
  50353. }
  50354. return ret;
  50355. },
  50356. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  50357. var axis = axisModel.axis;
  50358. var ret = {};
  50359. var polar = coordInfo.model.coordinateSystem;
  50360. var radiusExtent = polar.getRadiusAxis().getExtent();
  50361. var angleExtent = polar.getAngleAxis().getExtent();
  50362. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  50363. newPoint = polar.pointToCoord(newPoint);
  50364. if (axisModel.mainType === 'radiusAxis') {
  50365. ret.pixel = newPoint[0] - oldPoint[0];
  50366. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  50367. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  50368. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  50369. ret.pixelStart = radiusExtent[0];
  50370. ret.signal = axis.inverse ? 1 : -1;
  50371. }
  50372. else { // 'angleAxis'
  50373. ret.pixel = newPoint[1] - oldPoint[1];
  50374. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  50375. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  50376. ret.pixelLength = angleExtent[1] - angleExtent[0];
  50377. ret.pixelStart = angleExtent[0];
  50378. ret.signal = axis.inverse ? -1 : 1;
  50379. }
  50380. return ret;
  50381. },
  50382. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  50383. var axis = axisModel.axis;
  50384. var rect = coordInfo.model.coordinateSystem.getRect();
  50385. var ret = {};
  50386. oldPoint = oldPoint || [0, 0];
  50387. if (axis.orient === 'horizontal') {
  50388. ret.pixel = newPoint[0] - oldPoint[0];
  50389. ret.pixelLength = rect.width;
  50390. ret.pixelStart = rect.x;
  50391. ret.signal = axis.inverse ? 1 : -1;
  50392. }
  50393. else { // 'vertical'
  50394. ret.pixel = newPoint[1] - oldPoint[1];
  50395. ret.pixelLength = rect.height;
  50396. ret.pixelStart = rect.y;
  50397. ret.signal = axis.inverse ? -1 : 1;
  50398. }
  50399. return ret;
  50400. }
  50401. };
  50402. /*
  50403. * Licensed to the Apache Software Foundation (ASF) under one
  50404. * or more contributor license agreements. See the NOTICE file
  50405. * distributed with this work for additional information
  50406. * regarding copyright ownership. The ASF licenses this file
  50407. * to you under the Apache License, Version 2.0 (the
  50408. * "License"); you may not use this file except in compliance
  50409. * with the License. You may obtain a copy of the License at
  50410. *
  50411. * http://www.apache.org/licenses/LICENSE-2.0
  50412. *
  50413. * Unless required by applicable law or agreed to in writing,
  50414. * software distributed under the License is distributed on an
  50415. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50416. * KIND, either express or implied. See the License for the
  50417. * specific language governing permissions and limitations
  50418. * under the License.
  50419. */
  50420. /*
  50421. * Licensed to the Apache Software Foundation (ASF) under one
  50422. * or more contributor license agreements. See the NOTICE file
  50423. * distributed with this work for additional information
  50424. * regarding copyright ownership. The ASF licenses this file
  50425. * to you under the Apache License, Version 2.0 (the
  50426. * "License"); you may not use this file except in compliance
  50427. * with the License. You may obtain a copy of the License at
  50428. *
  50429. * http://www.apache.org/licenses/LICENSE-2.0
  50430. *
  50431. * Unless required by applicable law or agreed to in writing,
  50432. * software distributed under the License is distributed on an
  50433. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50434. * KIND, either express or implied. See the License for the
  50435. * specific language governing permissions and limitations
  50436. * under the License.
  50437. */
  50438. // Do not include './dataZoomSelect',
  50439. // since it only work for toolbox dataZoom.
  50440. /*
  50441. * Licensed to the Apache Software Foundation (ASF) under one
  50442. * or more contributor license agreements. See the NOTICE file
  50443. * distributed with this work for additional information
  50444. * regarding copyright ownership. The ASF licenses this file
  50445. * to you under the Apache License, Version 2.0 (the
  50446. * "License"); you may not use this file except in compliance
  50447. * with the License. You may obtain a copy of the License at
  50448. *
  50449. * http://www.apache.org/licenses/LICENSE-2.0
  50450. *
  50451. * Unless required by applicable law or agreed to in writing,
  50452. * software distributed under the License is distributed on an
  50453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50454. * KIND, either express or implied. See the License for the
  50455. * specific language governing permissions and limitations
  50456. * under the License.
  50457. */
  50458. var features = {};
  50459. function register$2(name, ctor) {
  50460. features[name] = ctor;
  50461. }
  50462. function get$1(name) {
  50463. return features[name];
  50464. }
  50465. /*
  50466. * Licensed to the Apache Software Foundation (ASF) under one
  50467. * or more contributor license agreements. See the NOTICE file
  50468. * distributed with this work for additional information
  50469. * regarding copyright ownership. The ASF licenses this file
  50470. * to you under the Apache License, Version 2.0 (the
  50471. * "License"); you may not use this file except in compliance
  50472. * with the License. You may obtain a copy of the License at
  50473. *
  50474. * http://www.apache.org/licenses/LICENSE-2.0
  50475. *
  50476. * Unless required by applicable law or agreed to in writing,
  50477. * software distributed under the License is distributed on an
  50478. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50479. * KIND, either express or implied. See the License for the
  50480. * specific language governing permissions and limitations
  50481. * under the License.
  50482. */
  50483. var ToolboxModel = extendComponentModel({
  50484. type: 'toolbox',
  50485. layoutMode: {
  50486. type: 'box',
  50487. ignoreSize: true
  50488. },
  50489. optionUpdated: function () {
  50490. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  50491. each$1(this.option.feature, function (featureOpt, featureName) {
  50492. var Feature = get$1(featureName);
  50493. Feature && merge(featureOpt, Feature.defaultOption);
  50494. });
  50495. },
  50496. defaultOption: {
  50497. show: true,
  50498. z: 6,
  50499. zlevel: 0,
  50500. orient: 'horizontal',
  50501. left: 'right',
  50502. top: 'top',
  50503. // right
  50504. // bottom
  50505. backgroundColor: 'transparent',
  50506. borderColor: '#ccc',
  50507. borderRadius: 0,
  50508. borderWidth: 0,
  50509. padding: 5,
  50510. itemSize: 15,
  50511. itemGap: 8,
  50512. showTitle: true,
  50513. iconStyle: {
  50514. borderColor: '#666',
  50515. color: 'none'
  50516. },
  50517. emphasis: {
  50518. iconStyle: {
  50519. borderColor: '#3E98C5'
  50520. }
  50521. },
  50522. // textStyle: {},
  50523. // feature
  50524. tooltip: {
  50525. show: false
  50526. }
  50527. }
  50528. });
  50529. /*
  50530. * Licensed to the Apache Software Foundation (ASF) under one
  50531. * or more contributor license agreements. See the NOTICE file
  50532. * distributed with this work for additional information
  50533. * regarding copyright ownership. The ASF licenses this file
  50534. * to you under the Apache License, Version 2.0 (the
  50535. * "License"); you may not use this file except in compliance
  50536. * with the License. You may obtain a copy of the License at
  50537. *
  50538. * http://www.apache.org/licenses/LICENSE-2.0
  50539. *
  50540. * Unless required by applicable law or agreed to in writing,
  50541. * software distributed under the License is distributed on an
  50542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50543. * KIND, either express or implied. See the License for the
  50544. * specific language governing permissions and limitations
  50545. * under the License.
  50546. */
  50547. extendComponentView({
  50548. type: 'toolbox',
  50549. render: function (toolboxModel, ecModel, api, payload) {
  50550. var group = this.group;
  50551. group.removeAll();
  50552. if (!toolboxModel.get('show')) {
  50553. return;
  50554. }
  50555. var itemSize = +toolboxModel.get('itemSize');
  50556. var featureOpts = toolboxModel.get('feature') || {};
  50557. var features = this._features || (this._features = {});
  50558. var featureNames = [];
  50559. each$1(featureOpts, function (opt, name) {
  50560. featureNames.push(name);
  50561. });
  50562. (new DataDiffer(this._featureNames || [], featureNames))
  50563. .add(processFeature)
  50564. .update(processFeature)
  50565. .remove(curry(processFeature, null))
  50566. .execute();
  50567. // Keep for diff.
  50568. this._featureNames = featureNames;
  50569. function processFeature(newIndex, oldIndex) {
  50570. var featureName = featureNames[newIndex];
  50571. var oldName = featureNames[oldIndex];
  50572. var featureOpt = featureOpts[featureName];
  50573. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  50574. var feature;
  50575. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  50576. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  50577. featureOpt.title = payload.newTitle;
  50578. }
  50579. if (featureName && !oldName) { // Create
  50580. if (isUserFeatureName(featureName)) {
  50581. feature = {
  50582. model: featureModel,
  50583. onclick: featureModel.option.onclick,
  50584. featureName: featureName
  50585. };
  50586. }
  50587. else {
  50588. var Feature = get$1(featureName);
  50589. if (!Feature) {
  50590. return;
  50591. }
  50592. feature = new Feature(featureModel, ecModel, api);
  50593. }
  50594. features[featureName] = feature;
  50595. }
  50596. else {
  50597. feature = features[oldName];
  50598. // If feature does not exsit.
  50599. if (!feature) {
  50600. return;
  50601. }
  50602. feature.model = featureModel;
  50603. feature.ecModel = ecModel;
  50604. feature.api = api;
  50605. }
  50606. if (!featureName && oldName) {
  50607. feature.dispose && feature.dispose(ecModel, api);
  50608. return;
  50609. }
  50610. if (!featureModel.get('show') || feature.unusable) {
  50611. feature.remove && feature.remove(ecModel, api);
  50612. return;
  50613. }
  50614. createIconPaths(featureModel, feature, featureName);
  50615. featureModel.setIconStatus = function (iconName, status) {
  50616. var option = this.option;
  50617. var iconPaths = this.iconPaths;
  50618. option.iconStatus = option.iconStatus || {};
  50619. option.iconStatus[iconName] = status;
  50620. // FIXME
  50621. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  50622. };
  50623. if (feature.render) {
  50624. feature.render(featureModel, ecModel, api, payload);
  50625. }
  50626. }
  50627. function createIconPaths(featureModel, feature, featureName) {
  50628. var iconStyleModel = featureModel.getModel('iconStyle');
  50629. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  50630. // If one feature has mutiple icon. they are orginaized as
  50631. // {
  50632. // icon: {
  50633. // foo: '',
  50634. // bar: ''
  50635. // },
  50636. // title: {
  50637. // foo: '',
  50638. // bar: ''
  50639. // }
  50640. // }
  50641. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  50642. var titles = featureModel.get('title') || {};
  50643. if (typeof icons === 'string') {
  50644. var icon = icons;
  50645. var title = titles;
  50646. icons = {};
  50647. titles = {};
  50648. icons[featureName] = icon;
  50649. titles[featureName] = title;
  50650. }
  50651. var iconPaths = featureModel.iconPaths = {};
  50652. each$1(icons, function (iconStr, iconName) {
  50653. var path = createIcon(
  50654. iconStr,
  50655. {},
  50656. {
  50657. x: -itemSize / 2,
  50658. y: -itemSize / 2,
  50659. width: itemSize,
  50660. height: itemSize
  50661. }
  50662. );
  50663. path.setStyle(iconStyleModel.getItemStyle());
  50664. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  50665. // Text position calculation
  50666. path.setStyle({
  50667. text: titles[iconName],
  50668. textAlign: iconStyleEmphasisModel.get('textAlign'),
  50669. textBorderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  50670. textPadding: iconStyleEmphasisModel.get('textPadding'),
  50671. textFill: null
  50672. });
  50673. var tooltipModel = toolboxModel.getModel('tooltip');
  50674. if (tooltipModel && tooltipModel.get('show')) {
  50675. path.attr('tooltip', extend({
  50676. content: titles[iconName],
  50677. formatter: tooltipModel.get('formatter', true)
  50678. || function () {
  50679. return titles[iconName];
  50680. },
  50681. formatterParams: {
  50682. componentType: 'toolbox',
  50683. name: iconName,
  50684. title: titles[iconName],
  50685. $vars: ['name', 'title']
  50686. },
  50687. position: tooltipModel.get('position', true) || 'bottom'
  50688. }, tooltipModel.option));
  50689. }
  50690. setHoverStyle(path);
  50691. if (toolboxModel.get('showTitle')) {
  50692. path.__title = titles[iconName];
  50693. path.on('mouseover', function () {
  50694. // Should not reuse above hoverStyle, which might be modified.
  50695. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  50696. var defaultTextPosition = toolboxModel.get('orient') === 'vertical'
  50697. ? (toolboxModel.get('right') == null ? 'right' : 'left')
  50698. : (toolboxModel.get('bottom') == null ? 'bottom' : 'top');
  50699. path.setStyle({
  50700. textFill: iconStyleEmphasisModel.get('textFill')
  50701. || hoverStyle.fill || hoverStyle.stroke || '#000',
  50702. textBackgroundColor: iconStyleEmphasisModel.get('textBackgroundColor'),
  50703. textPosition: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  50704. });
  50705. })
  50706. .on('mouseout', function () {
  50707. path.setStyle({
  50708. textFill: null,
  50709. textBackgroundColor: null
  50710. });
  50711. });
  50712. }
  50713. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  50714. group.add(path);
  50715. path.on('click', bind(
  50716. feature.onclick, feature, ecModel, api, iconName
  50717. ));
  50718. iconPaths[iconName] = path;
  50719. });
  50720. }
  50721. layout$2(group, toolboxModel, api);
  50722. // Render background after group is layout
  50723. // FIXME
  50724. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  50725. // Adjust icon title positions to avoid them out of screen
  50726. group.eachChild(function (icon) {
  50727. var titleText = icon.__title;
  50728. var hoverStyle = icon.hoverStyle;
  50729. // May be background element
  50730. if (hoverStyle && titleText) {
  50731. var rect = getBoundingRect(
  50732. titleText, makeFont(hoverStyle)
  50733. );
  50734. var offsetX = icon.position[0] + group.position[0];
  50735. var offsetY = icon.position[1] + group.position[1] + itemSize;
  50736. var needPutOnTop = false;
  50737. if (offsetY + rect.height > api.getHeight()) {
  50738. hoverStyle.textPosition = 'top';
  50739. needPutOnTop = true;
  50740. }
  50741. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  50742. if (offsetX + rect.width / 2 > api.getWidth()) {
  50743. hoverStyle.textPosition = ['100%', topOffset];
  50744. hoverStyle.textAlign = 'right';
  50745. }
  50746. else if (offsetX - rect.width / 2 < 0) {
  50747. hoverStyle.textPosition = [0, topOffset];
  50748. hoverStyle.textAlign = 'left';
  50749. }
  50750. }
  50751. });
  50752. },
  50753. updateView: function (toolboxModel, ecModel, api, payload) {
  50754. each$1(this._features, function (feature) {
  50755. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  50756. });
  50757. },
  50758. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  50759. // zrUtil.each(this._features, function (feature) {
  50760. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  50761. // });
  50762. // },
  50763. remove: function (ecModel, api) {
  50764. each$1(this._features, function (feature) {
  50765. feature.remove && feature.remove(ecModel, api);
  50766. });
  50767. this.group.removeAll();
  50768. },
  50769. dispose: function (ecModel, api) {
  50770. each$1(this._features, function (feature) {
  50771. feature.dispose && feature.dispose(ecModel, api);
  50772. });
  50773. }
  50774. });
  50775. function isUserFeatureName(featureName) {
  50776. return featureName.indexOf('my') === 0;
  50777. }
  50778. /*
  50779. * Licensed to the Apache Software Foundation (ASF) under one
  50780. * or more contributor license agreements. See the NOTICE file
  50781. * distributed with this work for additional information
  50782. * regarding copyright ownership. The ASF licenses this file
  50783. * to you under the Apache License, Version 2.0 (the
  50784. * "License"); you may not use this file except in compliance
  50785. * with the License. You may obtain a copy of the License at
  50786. *
  50787. * http://www.apache.org/licenses/LICENSE-2.0
  50788. *
  50789. * Unless required by applicable law or agreed to in writing,
  50790. * software distributed under the License is distributed on an
  50791. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50792. * KIND, either express or implied. See the License for the
  50793. * specific language governing permissions and limitations
  50794. * under the License.
  50795. */
  50796. /* global Uint8Array */
  50797. var saveAsImageLang = lang.toolbox.saveAsImage;
  50798. function SaveAsImage(model) {
  50799. this.model = model;
  50800. }
  50801. SaveAsImage.defaultOption = {
  50802. show: true,
  50803. 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',
  50804. title: saveAsImageLang.title,
  50805. type: 'png',
  50806. // Default use option.backgroundColor
  50807. // backgroundColor: '#fff',
  50808. connectedBackgroundColor: '#fff',
  50809. name: '',
  50810. excludeComponents: ['toolbox'],
  50811. pixelRatio: 1,
  50812. lang: saveAsImageLang.lang.slice()
  50813. };
  50814. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  50815. var proto$2 = SaveAsImage.prototype;
  50816. proto$2.onclick = function (ecModel, api) {
  50817. var model = this.model;
  50818. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  50819. var isSvg = api.getZr().painter.getType() === 'svg';
  50820. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  50821. var url = api.getConnectedDataURL({
  50822. type: type,
  50823. backgroundColor: model.get('backgroundColor', true)
  50824. || ecModel.get('backgroundColor') || '#fff',
  50825. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  50826. excludeComponents: model.get('excludeComponents'),
  50827. pixelRatio: model.get('pixelRatio')
  50828. });
  50829. // Chrome and Firefox
  50830. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  50831. var $a = document.createElement('a');
  50832. $a.download = title + '.' + type;
  50833. $a.target = '_blank';
  50834. $a.href = url;
  50835. var evt = new MouseEvent('click', {
  50836. // some micro front-end framework, window maybe is a Proxy
  50837. view: document.defaultView,
  50838. bubbles: true,
  50839. cancelable: false
  50840. });
  50841. $a.dispatchEvent(evt);
  50842. }
  50843. // IE
  50844. else {
  50845. if (window.navigator.msSaveOrOpenBlob) {
  50846. var bstr = atob(url.split(',')[1]);
  50847. var n = bstr.length;
  50848. var u8arr = new Uint8Array(n);
  50849. while (n--) {
  50850. u8arr[n] = bstr.charCodeAt(n);
  50851. }
  50852. var blob = new Blob([u8arr]);
  50853. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  50854. }
  50855. else {
  50856. var lang$$1 = model.get('lang');
  50857. var html = ''
  50858. + '<body style="margin:0;">'
  50859. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  50860. + '</body>';
  50861. var tab = window.open();
  50862. tab.document.write(html);
  50863. }
  50864. }
  50865. };
  50866. register$2(
  50867. 'saveAsImage', SaveAsImage
  50868. );
  50869. /*
  50870. * Licensed to the Apache Software Foundation (ASF) under one
  50871. * or more contributor license agreements. See the NOTICE file
  50872. * distributed with this work for additional information
  50873. * regarding copyright ownership. The ASF licenses this file
  50874. * to you under the Apache License, Version 2.0 (the
  50875. * "License"); you may not use this file except in compliance
  50876. * with the License. You may obtain a copy of the License at
  50877. *
  50878. * http://www.apache.org/licenses/LICENSE-2.0
  50879. *
  50880. * Unless required by applicable law or agreed to in writing,
  50881. * software distributed under the License is distributed on an
  50882. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50883. * KIND, either express or implied. See the License for the
  50884. * specific language governing permissions and limitations
  50885. * under the License.
  50886. */
  50887. var magicTypeLang = lang.toolbox.magicType;
  50888. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  50889. function MagicType(model) {
  50890. this.model = model;
  50891. }
  50892. MagicType.defaultOption = {
  50893. show: true,
  50894. type: [],
  50895. // Icon group
  50896. icon: {
  50897. /* eslint-disable */
  50898. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  50899. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  50900. 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
  50901. /* eslint-enable */
  50902. },
  50903. // `line`, `bar`, `stack`, `tiled`
  50904. title: clone(magicTypeLang.title),
  50905. option: {},
  50906. seriesIndex: {}
  50907. };
  50908. var proto$3 = MagicType.prototype;
  50909. proto$3.getIcons = function () {
  50910. var model = this.model;
  50911. var availableIcons = model.get('icon');
  50912. var icons = {};
  50913. each$1(model.get('type'), function (type) {
  50914. if (availableIcons[type]) {
  50915. icons[type] = availableIcons[type];
  50916. }
  50917. });
  50918. return icons;
  50919. };
  50920. var seriesOptGenreator = {
  50921. 'line': function (seriesType, seriesId, seriesModel, model) {
  50922. if (seriesType === 'bar') {
  50923. return merge({
  50924. id: seriesId,
  50925. type: 'line',
  50926. // Preserve data related option
  50927. data: seriesModel.get('data'),
  50928. stack: seriesModel.get('stack'),
  50929. markPoint: seriesModel.get('markPoint'),
  50930. markLine: seriesModel.get('markLine')
  50931. }, model.get('option.line') || {}, true);
  50932. }
  50933. },
  50934. 'bar': function (seriesType, seriesId, seriesModel, model) {
  50935. if (seriesType === 'line') {
  50936. return merge({
  50937. id: seriesId,
  50938. type: 'bar',
  50939. // Preserve data related option
  50940. data: seriesModel.get('data'),
  50941. stack: seriesModel.get('stack'),
  50942. markPoint: seriesModel.get('markPoint'),
  50943. markLine: seriesModel.get('markLine')
  50944. }, model.get('option.bar') || {}, true);
  50945. }
  50946. },
  50947. 'stack': function (seriesType, seriesId, seriesModel, model) {
  50948. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  50949. if (seriesType === 'line' || seriesType === 'bar') {
  50950. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  50951. return merge({
  50952. id: seriesId,
  50953. stack: isStack ? '' : INNER_STACK_KEYWORD
  50954. }, model.get('option.stack') || {}, true);
  50955. }
  50956. }
  50957. };
  50958. var radioTypes = [
  50959. ['line', 'bar'],
  50960. ['stack']
  50961. ];
  50962. proto$3.onclick = function (ecModel, api, type) {
  50963. var model = this.model;
  50964. var seriesIndex = model.get('seriesIndex.' + type);
  50965. // Not supported magicType
  50966. if (!seriesOptGenreator[type]) {
  50967. return;
  50968. }
  50969. var newOption = {
  50970. series: []
  50971. };
  50972. var generateNewSeriesTypes = function (seriesModel) {
  50973. var seriesType = seriesModel.subType;
  50974. var seriesId = seriesModel.id;
  50975. var newSeriesOpt = seriesOptGenreator[type](
  50976. seriesType, seriesId, seriesModel, model
  50977. );
  50978. if (newSeriesOpt) {
  50979. // PENDING If merge original option?
  50980. defaults(newSeriesOpt, seriesModel.option);
  50981. newOption.series.push(newSeriesOpt);
  50982. }
  50983. // Modify boundaryGap
  50984. var coordSys = seriesModel.coordinateSystem;
  50985. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  50986. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  50987. if (categoryAxis) {
  50988. var axisDim = categoryAxis.dim;
  50989. var axisType = axisDim + 'Axis';
  50990. var axisModel = ecModel.queryComponents({
  50991. mainType: axisType,
  50992. index: seriesModel.get(name + 'Index'),
  50993. id: seriesModel.get(name + 'Id')
  50994. })[0];
  50995. var axisIndex = axisModel.componentIndex;
  50996. newOption[axisType] = newOption[axisType] || [];
  50997. for (var i = 0; i <= axisIndex; i++) {
  50998. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  50999. }
  51000. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  51001. }
  51002. }
  51003. };
  51004. each$1(radioTypes, function (radio) {
  51005. if (indexOf(radio, type) >= 0) {
  51006. each$1(radio, function (item) {
  51007. model.setIconStatus(item, 'normal');
  51008. });
  51009. }
  51010. });
  51011. model.setIconStatus(type, 'emphasis');
  51012. ecModel.eachComponent(
  51013. {
  51014. mainType: 'series',
  51015. query: seriesIndex == null ? null : {
  51016. seriesIndex: seriesIndex
  51017. }
  51018. }, generateNewSeriesTypes
  51019. );
  51020. var newTitle;
  51021. // Change title of stack
  51022. if (type === 'stack') {
  51023. var isStack = newOption.series && newOption.series[0] && newOption.series[0].stack === INNER_STACK_KEYWORD;
  51024. newTitle = isStack
  51025. ? merge({ stack: magicTypeLang.title.tiled }, magicTypeLang.title)
  51026. : clone(magicTypeLang.title);
  51027. }
  51028. api.dispatchAction({
  51029. type: 'changeMagicType',
  51030. currentType: type,
  51031. newOption: newOption,
  51032. newTitle: newTitle,
  51033. featureName: 'magicType'
  51034. });
  51035. };
  51036. registerAction({
  51037. type: 'changeMagicType',
  51038. event: 'magicTypeChanged',
  51039. update: 'prepareAndUpdate'
  51040. }, function (payload, ecModel) {
  51041. ecModel.mergeOption(payload.newOption);
  51042. });
  51043. register$2('magicType', MagicType);
  51044. /*
  51045. * Licensed to the Apache Software Foundation (ASF) under one
  51046. * or more contributor license agreements. See the NOTICE file
  51047. * distributed with this work for additional information
  51048. * regarding copyright ownership. The ASF licenses this file
  51049. * to you under the Apache License, Version 2.0 (the
  51050. * "License"); you may not use this file except in compliance
  51051. * with the License. You may obtain a copy of the License at
  51052. *
  51053. * http://www.apache.org/licenses/LICENSE-2.0
  51054. *
  51055. * Unless required by applicable law or agreed to in writing,
  51056. * software distributed under the License is distributed on an
  51057. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51058. * KIND, either express or implied. See the License for the
  51059. * specific language governing permissions and limitations
  51060. * under the License.
  51061. */
  51062. var dataViewLang = lang.toolbox.dataView;
  51063. var BLOCK_SPLITER = new Array(60).join('-');
  51064. var ITEM_SPLITER = '\t';
  51065. /**
  51066. * Group series into two types
  51067. * 1. on category axis, like line, bar
  51068. * 2. others, like scatter, pie
  51069. * @param {module:echarts/model/Global} ecModel
  51070. * @return {Object}
  51071. * @inner
  51072. */
  51073. function groupSeries(ecModel) {
  51074. var seriesGroupByCategoryAxis = {};
  51075. var otherSeries = [];
  51076. var meta = [];
  51077. ecModel.eachRawSeries(function (seriesModel) {
  51078. var coordSys = seriesModel.coordinateSystem;
  51079. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  51080. var baseAxis = coordSys.getBaseAxis();
  51081. if (baseAxis.type === 'category') {
  51082. var key = baseAxis.dim + '_' + baseAxis.index;
  51083. if (!seriesGroupByCategoryAxis[key]) {
  51084. seriesGroupByCategoryAxis[key] = {
  51085. categoryAxis: baseAxis,
  51086. valueAxis: coordSys.getOtherAxis(baseAxis),
  51087. series: []
  51088. };
  51089. meta.push({
  51090. axisDim: baseAxis.dim,
  51091. axisIndex: baseAxis.index
  51092. });
  51093. }
  51094. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  51095. }
  51096. else {
  51097. otherSeries.push(seriesModel);
  51098. }
  51099. }
  51100. else {
  51101. otherSeries.push(seriesModel);
  51102. }
  51103. });
  51104. return {
  51105. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  51106. other: otherSeries,
  51107. meta: meta
  51108. };
  51109. }
  51110. /**
  51111. * Assemble content of series on cateogory axis
  51112. * @param {Array.<module:echarts/model/Series>} series
  51113. * @return {string}
  51114. * @inner
  51115. */
  51116. function assembleSeriesWithCategoryAxis(series) {
  51117. var tables = [];
  51118. each$1(series, function (group, key) {
  51119. var categoryAxis = group.categoryAxis;
  51120. var valueAxis = group.valueAxis;
  51121. var valueAxisDim = valueAxis.dim;
  51122. var headers = [' '].concat(map(group.series, function (series) {
  51123. return series.name;
  51124. }));
  51125. var columns = [categoryAxis.model.getCategories()];
  51126. each$1(group.series, function (series) {
  51127. var rawData = series.getRawData();
  51128. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  51129. return val;
  51130. }));
  51131. });
  51132. // Assemble table content
  51133. var lines = [headers.join(ITEM_SPLITER)];
  51134. for (var i = 0; i < columns[0].length; i++) {
  51135. var items = [];
  51136. for (var j = 0; j < columns.length; j++) {
  51137. items.push(columns[j][i]);
  51138. }
  51139. lines.push(items.join(ITEM_SPLITER));
  51140. }
  51141. tables.push(lines.join('\n'));
  51142. });
  51143. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  51144. }
  51145. /**
  51146. * Assemble content of other series
  51147. * @param {Array.<module:echarts/model/Series>} series
  51148. * @return {string}
  51149. * @inner
  51150. */
  51151. function assembleOtherSeries(series) {
  51152. return map(series, function (series) {
  51153. var data = series.getRawData();
  51154. var lines = [series.name];
  51155. var vals = [];
  51156. data.each(data.dimensions, function () {
  51157. var argLen = arguments.length;
  51158. var dataIndex = arguments[argLen - 1];
  51159. var name = data.getName(dataIndex);
  51160. for (var i = 0; i < argLen - 1; i++) {
  51161. vals[i] = arguments[i];
  51162. }
  51163. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  51164. });
  51165. return lines.join('\n');
  51166. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  51167. }
  51168. /**
  51169. * @param {module:echarts/model/Global}
  51170. * @return {Object}
  51171. * @inner
  51172. */
  51173. function getContentFromModel(ecModel) {
  51174. var result = groupSeries(ecModel);
  51175. return {
  51176. value: filter([
  51177. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  51178. assembleOtherSeries(result.other)
  51179. ], function (str) {
  51180. return str.replace(/[\n\t\s]/g, '');
  51181. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  51182. meta: result.meta
  51183. };
  51184. }
  51185. function trim$1(str) {
  51186. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  51187. }
  51188. /**
  51189. * If a block is tsv format
  51190. */
  51191. function isTSVFormat(block) {
  51192. // Simple method to find out if a block is tsv format
  51193. var firstLine = block.slice(0, block.indexOf('\n'));
  51194. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  51195. return true;
  51196. }
  51197. }
  51198. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  51199. /**
  51200. * @param {string} tsv
  51201. * @return {Object}
  51202. */
  51203. function parseTSVContents(tsv) {
  51204. var tsvLines = tsv.split(/\n+/g);
  51205. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  51206. var categories = [];
  51207. var series = map(headers, function (header) {
  51208. return {
  51209. name: header,
  51210. data: []
  51211. };
  51212. });
  51213. for (var i = 0; i < tsvLines.length; i++) {
  51214. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  51215. categories.push(items.shift());
  51216. for (var j = 0; j < items.length; j++) {
  51217. series[j] && (series[j].data[i] = items[j]);
  51218. }
  51219. }
  51220. return {
  51221. series: series,
  51222. categories: categories
  51223. };
  51224. }
  51225. /**
  51226. * @param {string} str
  51227. * @return {Array.<Object>}
  51228. * @inner
  51229. */
  51230. function parseListContents(str) {
  51231. var lines = str.split(/\n+/g);
  51232. var seriesName = trim$1(lines.shift());
  51233. var data = [];
  51234. for (var i = 0; i < lines.length; i++) {
  51235. // if line is empty, ignore it.
  51236. // there is a case that a user forgot to delete `\n`.
  51237. var line = trim$1(lines[i]);
  51238. if (!line) {
  51239. continue;
  51240. }
  51241. var items = line.split(itemSplitRegex);
  51242. var name = '';
  51243. var value;
  51244. var hasName = false;
  51245. if (isNaN(items[0])) { // First item is name
  51246. hasName = true;
  51247. name = items[0];
  51248. items = items.slice(1);
  51249. data[i] = {
  51250. name: name,
  51251. value: []
  51252. };
  51253. value = data[i].value;
  51254. }
  51255. else {
  51256. value = data[i] = [];
  51257. }
  51258. for (var j = 0; j < items.length; j++) {
  51259. value.push(+items[j]);
  51260. }
  51261. if (value.length === 1) {
  51262. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  51263. }
  51264. }
  51265. return {
  51266. name: seriesName,
  51267. data: data
  51268. };
  51269. }
  51270. /**
  51271. * @param {string} str
  51272. * @param {Array.<Object>} blockMetaList
  51273. * @return {Object}
  51274. * @inner
  51275. */
  51276. function parseContents(str, blockMetaList) {
  51277. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  51278. var newOption = {
  51279. series: []
  51280. };
  51281. each$1(blocks, function (block, idx) {
  51282. if (isTSVFormat(block)) {
  51283. var result = parseTSVContents(block);
  51284. var blockMeta = blockMetaList[idx];
  51285. var axisKey = blockMeta.axisDim + 'Axis';
  51286. if (blockMeta) {
  51287. newOption[axisKey] = newOption[axisKey] || [];
  51288. newOption[axisKey][blockMeta.axisIndex] = {
  51289. data: result.categories
  51290. };
  51291. newOption.series = newOption.series.concat(result.series);
  51292. }
  51293. }
  51294. else {
  51295. var result = parseListContents(block);
  51296. newOption.series.push(result);
  51297. }
  51298. });
  51299. return newOption;
  51300. }
  51301. /**
  51302. * @alias {module:echarts/component/toolbox/feature/DataView}
  51303. * @constructor
  51304. * @param {module:echarts/model/Model} model
  51305. */
  51306. function DataView(model) {
  51307. this._dom = null;
  51308. this.model = model;
  51309. }
  51310. DataView.defaultOption = {
  51311. show: true,
  51312. readOnly: false,
  51313. optionToContent: null,
  51314. contentToOption: null,
  51315. 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',
  51316. title: clone(dataViewLang.title),
  51317. lang: clone(dataViewLang.lang),
  51318. backgroundColor: '#fff',
  51319. textColor: '#000',
  51320. textareaColor: '#fff',
  51321. textareaBorderColor: '#333',
  51322. buttonColor: '#c23531',
  51323. buttonTextColor: '#fff'
  51324. };
  51325. DataView.prototype.onclick = function (ecModel, api) {
  51326. var container = api.getDom();
  51327. var model = this.model;
  51328. if (this._dom) {
  51329. container.removeChild(this._dom);
  51330. }
  51331. var root = document.createElement('div');
  51332. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  51333. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  51334. // Create elements
  51335. var header = document.createElement('h4');
  51336. var lang$$1 = model.get('lang') || [];
  51337. header.innerHTML = lang$$1[0] || model.get('title');
  51338. header.style.cssText = 'margin: 10px 20px;';
  51339. header.style.color = model.get('textColor');
  51340. var viewMain = document.createElement('div');
  51341. var textarea = document.createElement('textarea');
  51342. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  51343. var optionToContent = model.get('optionToContent');
  51344. var contentToOption = model.get('contentToOption');
  51345. var result = getContentFromModel(ecModel);
  51346. if (typeof optionToContent === 'function') {
  51347. var htmlOrDom = optionToContent(api.getOption());
  51348. if (typeof htmlOrDom === 'string') {
  51349. viewMain.innerHTML = htmlOrDom;
  51350. }
  51351. else if (isDom(htmlOrDom)) {
  51352. viewMain.appendChild(htmlOrDom);
  51353. }
  51354. }
  51355. else {
  51356. // Use default textarea
  51357. viewMain.appendChild(textarea);
  51358. textarea.readOnly = model.get('readOnly');
  51359. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  51360. textarea.style.color = model.get('textColor');
  51361. textarea.style.borderColor = model.get('textareaBorderColor');
  51362. textarea.style.backgroundColor = model.get('textareaColor');
  51363. textarea.value = result.value;
  51364. }
  51365. var blockMetaList = result.meta;
  51366. var buttonContainer = document.createElement('div');
  51367. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  51368. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  51369. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  51370. var closeButton = document.createElement('div');
  51371. var refreshButton = document.createElement('div');
  51372. buttonStyle += ';background-color:' + model.get('buttonColor');
  51373. buttonStyle += ';color:' + model.get('buttonTextColor');
  51374. var self = this;
  51375. function close() {
  51376. container.removeChild(root);
  51377. self._dom = null;
  51378. }
  51379. addEventListener(closeButton, 'click', close);
  51380. addEventListener(refreshButton, 'click', function () {
  51381. var newOption;
  51382. try {
  51383. if (typeof contentToOption === 'function') {
  51384. newOption = contentToOption(viewMain, api.getOption());
  51385. }
  51386. else {
  51387. newOption = parseContents(textarea.value, blockMetaList);
  51388. }
  51389. }
  51390. catch (e) {
  51391. close();
  51392. throw new Error('Data view format error ' + e);
  51393. }
  51394. if (newOption) {
  51395. api.dispatchAction({
  51396. type: 'changeDataView',
  51397. newOption: newOption
  51398. });
  51399. }
  51400. close();
  51401. });
  51402. closeButton.innerHTML = lang$$1[1];
  51403. refreshButton.innerHTML = lang$$1[2];
  51404. refreshButton.style.cssText = buttonStyle;
  51405. closeButton.style.cssText = buttonStyle;
  51406. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  51407. buttonContainer.appendChild(closeButton);
  51408. root.appendChild(header);
  51409. root.appendChild(viewMain);
  51410. root.appendChild(buttonContainer);
  51411. viewMain.style.height = (container.clientHeight - 80) + 'px';
  51412. container.appendChild(root);
  51413. this._dom = root;
  51414. };
  51415. DataView.prototype.remove = function (ecModel, api) {
  51416. this._dom && api.getDom().removeChild(this._dom);
  51417. };
  51418. DataView.prototype.dispose = function (ecModel, api) {
  51419. this.remove(ecModel, api);
  51420. };
  51421. /**
  51422. * @inner
  51423. */
  51424. function tryMergeDataOption(newData, originalData) {
  51425. return map(newData, function (newVal, idx) {
  51426. var original = originalData && originalData[idx];
  51427. if (isObject$1(original) && !isArray(original)) {
  51428. var newValIsObject = isObject$1(newVal) && !isArray(newVal);
  51429. if (!newValIsObject) {
  51430. newVal = {
  51431. value: newVal
  51432. };
  51433. }
  51434. // original data has name but new data has no name
  51435. var shouldDeleteName = original.name != null && newVal.name == null;
  51436. // Original data has option
  51437. newVal = defaults(newVal, original);
  51438. shouldDeleteName && (delete newVal.name);
  51439. return newVal;
  51440. }
  51441. else {
  51442. return newVal;
  51443. }
  51444. });
  51445. }
  51446. register$2('dataView', DataView);
  51447. registerAction({
  51448. type: 'changeDataView',
  51449. event: 'dataViewChanged',
  51450. update: 'prepareAndUpdate'
  51451. }, function (payload, ecModel) {
  51452. var newSeriesOptList = [];
  51453. each$1(payload.newOption.series, function (seriesOpt) {
  51454. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  51455. if (!seriesModel) {
  51456. // New created series
  51457. // Geuss the series type
  51458. newSeriesOptList.push(extend({
  51459. // Default is scatter
  51460. type: 'scatter'
  51461. }, seriesOpt));
  51462. }
  51463. else {
  51464. var originalData = seriesModel.get('data');
  51465. newSeriesOptList.push({
  51466. name: seriesOpt.name,
  51467. data: tryMergeDataOption(seriesOpt.data, originalData)
  51468. });
  51469. }
  51470. });
  51471. ecModel.mergeOption(defaults({
  51472. series: newSeriesOptList
  51473. }, payload.newOption));
  51474. });
  51475. /*
  51476. * Licensed to the Apache Software Foundation (ASF) under one
  51477. * or more contributor license agreements. See the NOTICE file
  51478. * distributed with this work for additional information
  51479. * regarding copyright ownership. The ASF licenses this file
  51480. * to you under the Apache License, Version 2.0 (the
  51481. * "License"); you may not use this file except in compliance
  51482. * with the License. You may obtain a copy of the License at
  51483. *
  51484. * http://www.apache.org/licenses/LICENSE-2.0
  51485. *
  51486. * Unless required by applicable law or agreed to in writing,
  51487. * software distributed under the License is distributed on an
  51488. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51489. * KIND, either express or implied. See the License for the
  51490. * specific language governing permissions and limitations
  51491. * under the License.
  51492. */
  51493. var curry$5 = curry;
  51494. var each$16 = each$1;
  51495. var map$2 = map;
  51496. var mathMin$5 = Math.min;
  51497. var mathMax$5 = Math.max;
  51498. var mathPow$2 = Math.pow;
  51499. var COVER_Z = 10000;
  51500. var UNSELECT_THRESHOLD = 6;
  51501. var MIN_RESIZE_LINE_WIDTH = 6;
  51502. var MUTEX_RESOURCE_KEY = 'globalPan';
  51503. var DIRECTION_MAP = {
  51504. w: [0, 0],
  51505. e: [0, 1],
  51506. n: [1, 0],
  51507. s: [1, 1]
  51508. };
  51509. var CURSOR_MAP = {
  51510. w: 'ew',
  51511. e: 'ew',
  51512. n: 'ns',
  51513. s: 'ns',
  51514. ne: 'nesw',
  51515. sw: 'nesw',
  51516. nw: 'nwse',
  51517. se: 'nwse'
  51518. };
  51519. var DEFAULT_BRUSH_OPT = {
  51520. brushStyle: {
  51521. lineWidth: 2,
  51522. stroke: 'rgba(0,0,0,0.3)',
  51523. fill: 'rgba(0,0,0,0.1)'
  51524. },
  51525. transformable: true,
  51526. brushMode: 'single',
  51527. removeOnClick: false
  51528. };
  51529. var baseUID = 0;
  51530. /**
  51531. * @alias module:echarts/component/helper/BrushController
  51532. * @constructor
  51533. * @mixin {module:zrender/mixin/Eventful}
  51534. * @event module:echarts/component/helper/BrushController#brush
  51535. * params:
  51536. * areas: Array.<Array>, coord relates to container group,
  51537. * If no container specified, to global.
  51538. * opt {
  51539. * isEnd: boolean,
  51540. * removeOnClick: boolean
  51541. * }
  51542. *
  51543. * @param {module:zrender/zrender~ZRender} zr
  51544. */
  51545. function BrushController(zr) {
  51546. if (__DEV__) {
  51547. assert$1(zr);
  51548. }
  51549. Eventful.call(this);
  51550. /**
  51551. * @type {module:zrender/zrender~ZRender}
  51552. * @private
  51553. */
  51554. this._zr = zr;
  51555. /**
  51556. * @type {module:zrender/container/Group}
  51557. * @readOnly
  51558. */
  51559. this.group = new Group();
  51560. /**
  51561. * Only for drawing (after enabledBrush).
  51562. * 'line', 'rect', 'polygon' or false
  51563. * If passing false/null/undefined, disable brush.
  51564. * If passing 'auto', determined by panel.defaultBrushType
  51565. * @private
  51566. * @type {string}
  51567. */
  51568. this._brushType;
  51569. /**
  51570. * Only for drawing (after enabledBrush).
  51571. *
  51572. * @private
  51573. * @type {Object}
  51574. */
  51575. this._brushOption;
  51576. /**
  51577. * @private
  51578. * @type {Object}
  51579. */
  51580. this._panels;
  51581. /**
  51582. * @private
  51583. * @type {Array.<nubmer>}
  51584. */
  51585. this._track = [];
  51586. /**
  51587. * @private
  51588. * @type {boolean}
  51589. */
  51590. this._dragging;
  51591. /**
  51592. * @private
  51593. * @type {Array}
  51594. */
  51595. this._covers = [];
  51596. /**
  51597. * @private
  51598. * @type {moudule:zrender/container/Group}
  51599. */
  51600. this._creatingCover;
  51601. /**
  51602. * `true` means global panel
  51603. * @private
  51604. * @type {module:zrender/container/Group|boolean}
  51605. */
  51606. this._creatingPanel;
  51607. /**
  51608. * @private
  51609. * @type {boolean}
  51610. */
  51611. this._enableGlobalPan;
  51612. /**
  51613. * @private
  51614. * @type {boolean}
  51615. */
  51616. if (__DEV__) {
  51617. this._mounted;
  51618. }
  51619. /**
  51620. * @private
  51621. * @type {string}
  51622. */
  51623. this._uid = 'brushController_' + baseUID++;
  51624. /**
  51625. * @private
  51626. * @type {Object}
  51627. */
  51628. this._handlers = {};
  51629. each$16(pointerHandlers, function (handler, eventName) {
  51630. this._handlers[eventName] = bind(handler, this);
  51631. }, this);
  51632. }
  51633. BrushController.prototype = {
  51634. constructor: BrushController,
  51635. /**
  51636. * If set to null/undefined/false, select disabled.
  51637. * @param {Object} brushOption
  51638. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  51639. * If passing false/null/undefined, disable brush.
  51640. * If passing 'auto', determined by panel.defaultBrushType.
  51641. * ('auto' can not be used in global panel)
  51642. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  51643. * @param {boolean} [brushOption.transformable=true]
  51644. * @param {boolean} [brushOption.removeOnClick=false]
  51645. * @param {Object} [brushOption.brushStyle]
  51646. * @param {number} [brushOption.brushStyle.width]
  51647. * @param {number} [brushOption.brushStyle.lineWidth]
  51648. * @param {string} [brushOption.brushStyle.stroke]
  51649. * @param {string} [brushOption.brushStyle.fill]
  51650. * @param {number} [brushOption.z]
  51651. */
  51652. enableBrush: function (brushOption) {
  51653. if (__DEV__) {
  51654. assert$1(this._mounted);
  51655. }
  51656. this._brushType && doDisableBrush(this);
  51657. brushOption.brushType && doEnableBrush(this, brushOption);
  51658. return this;
  51659. },
  51660. /**
  51661. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  51662. * Each items: {
  51663. * panelId, // mandatory.
  51664. * clipPath, // mandatory. function.
  51665. * isTargetByCursor, // mandatory. function.
  51666. * defaultBrushType, // optional, only used when brushType is 'auto'.
  51667. * getLinearBrushOtherExtent, // optional. function.
  51668. * }
  51669. */
  51670. setPanels: function (panelOpts) {
  51671. if (panelOpts && panelOpts.length) {
  51672. var panels = this._panels = {};
  51673. each$1(panelOpts, function (panelOpts) {
  51674. panels[panelOpts.panelId] = clone(panelOpts);
  51675. });
  51676. }
  51677. else {
  51678. this._panels = null;
  51679. }
  51680. return this;
  51681. },
  51682. /**
  51683. * @param {Object} [opt]
  51684. * @return {boolean} [opt.enableGlobalPan=false]
  51685. */
  51686. mount: function (opt) {
  51687. opt = opt || {};
  51688. if (__DEV__) {
  51689. this._mounted = true; // should be at first.
  51690. }
  51691. this._enableGlobalPan = opt.enableGlobalPan;
  51692. var thisGroup = this.group;
  51693. this._zr.add(thisGroup);
  51694. thisGroup.attr({
  51695. position: opt.position || [0, 0],
  51696. rotation: opt.rotation || 0,
  51697. scale: opt.scale || [1, 1]
  51698. });
  51699. this._transform = thisGroup.getLocalTransform();
  51700. return this;
  51701. },
  51702. eachCover: function (cb, context) {
  51703. each$16(this._covers, cb, context);
  51704. },
  51705. /**
  51706. * Update covers.
  51707. * @param {Array.<Object>} brushOptionList Like:
  51708. * [
  51709. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  51710. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  51711. * ...
  51712. * ]
  51713. * `brushType` is required in each cover info. (can not be 'auto')
  51714. * `id` is not mandatory.
  51715. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  51716. * If brushOptionList is null/undefined, all covers removed.
  51717. */
  51718. updateCovers: function (brushOptionList) {
  51719. if (__DEV__) {
  51720. assert$1(this._mounted);
  51721. }
  51722. brushOptionList = map(brushOptionList, function (brushOption) {
  51723. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  51724. });
  51725. var tmpIdPrefix = '\0-brush-index-';
  51726. var oldCovers = this._covers;
  51727. var newCovers = this._covers = [];
  51728. var controller = this;
  51729. var creatingCover = this._creatingCover;
  51730. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  51731. .add(addOrUpdate)
  51732. .update(addOrUpdate)
  51733. .remove(remove)
  51734. .execute();
  51735. return this;
  51736. function getKey(brushOption, index) {
  51737. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  51738. + '-' + brushOption.brushType;
  51739. }
  51740. function oldGetKey(cover, index) {
  51741. return getKey(cover.__brushOption, index);
  51742. }
  51743. function addOrUpdate(newIndex, oldIndex) {
  51744. var newBrushOption = brushOptionList[newIndex];
  51745. // Consider setOption in event listener of brushSelect,
  51746. // where updating cover when creating should be forbiden.
  51747. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  51748. newCovers[newIndex] = oldCovers[oldIndex];
  51749. }
  51750. else {
  51751. var cover = newCovers[newIndex] = oldIndex != null
  51752. ? (
  51753. oldCovers[oldIndex].__brushOption = newBrushOption,
  51754. oldCovers[oldIndex]
  51755. )
  51756. : endCreating(controller, createCover(controller, newBrushOption));
  51757. updateCoverAfterCreation(controller, cover);
  51758. }
  51759. }
  51760. function remove(oldIndex) {
  51761. if (oldCovers[oldIndex] !== creatingCover) {
  51762. controller.group.remove(oldCovers[oldIndex]);
  51763. }
  51764. }
  51765. },
  51766. unmount: function () {
  51767. if (__DEV__) {
  51768. if (!this._mounted) {
  51769. return;
  51770. }
  51771. }
  51772. this.enableBrush(false);
  51773. // container may 'removeAll' outside.
  51774. clearCovers(this);
  51775. this._zr.remove(this.group);
  51776. if (__DEV__) {
  51777. this._mounted = false; // should be at last.
  51778. }
  51779. return this;
  51780. },
  51781. dispose: function () {
  51782. this.unmount();
  51783. this.off();
  51784. }
  51785. };
  51786. mixin(BrushController, Eventful);
  51787. function doEnableBrush(controller, brushOption) {
  51788. var zr = controller._zr;
  51789. // Consider roam, which takes globalPan too.
  51790. if (!controller._enableGlobalPan) {
  51791. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  51792. }
  51793. mountHandlers(zr, controller._handlers);
  51794. controller._brushType = brushOption.brushType;
  51795. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  51796. }
  51797. function doDisableBrush(controller) {
  51798. var zr = controller._zr;
  51799. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  51800. unmountHandlers(zr, controller._handlers);
  51801. controller._brushType = controller._brushOption = null;
  51802. }
  51803. function mountHandlers(zr, handlers) {
  51804. each$16(handlers, function (handler, eventName) {
  51805. zr.on(eventName, handler);
  51806. });
  51807. }
  51808. function unmountHandlers(zr, handlers) {
  51809. each$16(handlers, function (handler, eventName) {
  51810. zr.off(eventName, handler);
  51811. });
  51812. }
  51813. function createCover(controller, brushOption) {
  51814. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  51815. cover.__brushOption = brushOption;
  51816. updateZ$1(cover, brushOption);
  51817. controller.group.add(cover);
  51818. return cover;
  51819. }
  51820. function endCreating(controller, creatingCover) {
  51821. var coverRenderer = getCoverRenderer(creatingCover);
  51822. if (coverRenderer.endCreating) {
  51823. coverRenderer.endCreating(controller, creatingCover);
  51824. updateZ$1(creatingCover, creatingCover.__brushOption);
  51825. }
  51826. return creatingCover;
  51827. }
  51828. function updateCoverShape(controller, cover) {
  51829. var brushOption = cover.__brushOption;
  51830. getCoverRenderer(cover).updateCoverShape(
  51831. controller, cover, brushOption.range, brushOption
  51832. );
  51833. }
  51834. function updateZ$1(cover, brushOption) {
  51835. var z = brushOption.z;
  51836. z == null && (z = COVER_Z);
  51837. cover.traverse(function (el) {
  51838. el.z = z;
  51839. el.z2 = z; // Consider in given container.
  51840. });
  51841. }
  51842. function updateCoverAfterCreation(controller, cover) {
  51843. getCoverRenderer(cover).updateCommon(controller, cover);
  51844. updateCoverShape(controller, cover);
  51845. }
  51846. function getCoverRenderer(cover) {
  51847. return coverRenderers[cover.__brushOption.brushType];
  51848. }
  51849. // return target panel or `true` (means global panel)
  51850. function getPanelByPoint(controller, e, localCursorPoint) {
  51851. var panels = controller._panels;
  51852. if (!panels) {
  51853. return true; // Global panel
  51854. }
  51855. var panel;
  51856. var transform = controller._transform;
  51857. each$16(panels, function (pn) {
  51858. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  51859. });
  51860. return panel;
  51861. }
  51862. // Return a panel or true
  51863. function getPanelByCover(controller, cover) {
  51864. var panels = controller._panels;
  51865. if (!panels) {
  51866. return true; // Global panel
  51867. }
  51868. var panelId = cover.__brushOption.panelId;
  51869. // User may give cover without coord sys info,
  51870. // which is then treated as global panel.
  51871. return panelId != null ? panels[panelId] : true;
  51872. }
  51873. function clearCovers(controller) {
  51874. var covers = controller._covers;
  51875. var originalLength = covers.length;
  51876. each$16(covers, function (cover) {
  51877. controller.group.remove(cover);
  51878. }, controller);
  51879. covers.length = 0;
  51880. return !!originalLength;
  51881. }
  51882. function trigger$1(controller, opt) {
  51883. var areas = map$2(controller._covers, function (cover) {
  51884. var brushOption = cover.__brushOption;
  51885. var range = clone(brushOption.range);
  51886. return {
  51887. brushType: brushOption.brushType,
  51888. panelId: brushOption.panelId,
  51889. range: range
  51890. };
  51891. });
  51892. controller.trigger('brush', areas, {
  51893. isEnd: !!opt.isEnd,
  51894. removeOnClick: !!opt.removeOnClick
  51895. });
  51896. }
  51897. function shouldShowCover(controller) {
  51898. var track = controller._track;
  51899. if (!track.length) {
  51900. return false;
  51901. }
  51902. var p2 = track[track.length - 1];
  51903. var p1 = track[0];
  51904. var dx = p2[0] - p1[0];
  51905. var dy = p2[1] - p1[1];
  51906. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  51907. return dist > UNSELECT_THRESHOLD;
  51908. }
  51909. function getTrackEnds(track) {
  51910. var tail = track.length - 1;
  51911. tail < 0 && (tail = 0);
  51912. return [track[0], track[tail]];
  51913. }
  51914. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  51915. var cover = new Group();
  51916. cover.add(new Rect({
  51917. name: 'main',
  51918. style: makeStyle(brushOption),
  51919. silent: true,
  51920. draggable: true,
  51921. cursor: 'move',
  51922. drift: curry$5(doDrift, controller, cover, 'nswe'),
  51923. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51924. }));
  51925. each$16(
  51926. edgeNames,
  51927. function (name) {
  51928. cover.add(new Rect({
  51929. name: name,
  51930. style: {opacity: 0},
  51931. draggable: true,
  51932. silent: true,
  51933. invisible: true,
  51934. drift: curry$5(doDrift, controller, cover, name),
  51935. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51936. }));
  51937. }
  51938. );
  51939. return cover;
  51940. }
  51941. function updateBaseRect(controller, cover, localRange, brushOption) {
  51942. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  51943. var handleSize = mathMax$5(lineWidth, MIN_RESIZE_LINE_WIDTH);
  51944. var x = localRange[0][0];
  51945. var y = localRange[1][0];
  51946. var xa = x - lineWidth / 2;
  51947. var ya = y - lineWidth / 2;
  51948. var x2 = localRange[0][1];
  51949. var y2 = localRange[1][1];
  51950. var x2a = x2 - handleSize + lineWidth / 2;
  51951. var y2a = y2 - handleSize + lineWidth / 2;
  51952. var width = x2 - x;
  51953. var height = y2 - y;
  51954. var widtha = width + lineWidth;
  51955. var heighta = height + lineWidth;
  51956. updateRectShape(controller, cover, 'main', x, y, width, height);
  51957. if (brushOption.transformable) {
  51958. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  51959. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  51960. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  51961. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  51962. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  51963. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  51964. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  51965. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  51966. }
  51967. }
  51968. function updateCommon(controller, cover) {
  51969. var brushOption = cover.__brushOption;
  51970. var transformable = brushOption.transformable;
  51971. var mainEl = cover.childAt(0);
  51972. mainEl.useStyle(makeStyle(brushOption));
  51973. mainEl.attr({
  51974. silent: !transformable,
  51975. cursor: transformable ? 'move' : 'default'
  51976. });
  51977. each$16(
  51978. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  51979. function (name) {
  51980. var el = cover.childOfName(name);
  51981. var globalDir = getGlobalDirection(controller, name);
  51982. el && el.attr({
  51983. silent: !transformable,
  51984. invisible: !transformable,
  51985. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  51986. });
  51987. }
  51988. );
  51989. }
  51990. function updateRectShape(controller, cover, name, x, y, w, h) {
  51991. var el = cover.childOfName(name);
  51992. el && el.setShape(pointsToRect(
  51993. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  51994. ));
  51995. }
  51996. function makeStyle(brushOption) {
  51997. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  51998. }
  51999. function formatRectRange(x, y, x2, y2) {
  52000. var min = [mathMin$5(x, x2), mathMin$5(y, y2)];
  52001. var max = [mathMax$5(x, x2), mathMax$5(y, y2)];
  52002. return [
  52003. [min[0], max[0]], // x range
  52004. [min[1], max[1]] // y range
  52005. ];
  52006. }
  52007. function getTransform$1(controller) {
  52008. return getTransform(controller.group);
  52009. }
  52010. function getGlobalDirection(controller, localDirection) {
  52011. if (localDirection.length > 1) {
  52012. localDirection = localDirection.split('');
  52013. var globalDir = [
  52014. getGlobalDirection(controller, localDirection[0]),
  52015. getGlobalDirection(controller, localDirection[1])
  52016. ];
  52017. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  52018. return globalDir.join('');
  52019. }
  52020. else {
  52021. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  52022. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  52023. var globalDir = transformDirection(
  52024. map$$1[localDirection], getTransform$1(controller)
  52025. );
  52026. return inverseMap[globalDir];
  52027. }
  52028. }
  52029. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  52030. var brushOption = cover.__brushOption;
  52031. var rectRange = toRectRange(brushOption.range);
  52032. var localDelta = toLocalDelta(controller, dx, dy);
  52033. each$16(name.split(''), function (namePart) {
  52034. var ind = DIRECTION_MAP[namePart];
  52035. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  52036. });
  52037. brushOption.range = fromRectRange(formatRectRange(
  52038. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  52039. ));
  52040. updateCoverAfterCreation(controller, cover);
  52041. trigger$1(controller, {isEnd: false});
  52042. }
  52043. function driftPolygon(controller, cover, dx, dy, e) {
  52044. var range = cover.__brushOption.range;
  52045. var localDelta = toLocalDelta(controller, dx, dy);
  52046. each$16(range, function (point) {
  52047. point[0] += localDelta[0];
  52048. point[1] += localDelta[1];
  52049. });
  52050. updateCoverAfterCreation(controller, cover);
  52051. trigger$1(controller, {isEnd: false});
  52052. }
  52053. function toLocalDelta(controller, dx, dy) {
  52054. var thisGroup = controller.group;
  52055. var localD = thisGroup.transformCoordToLocal(dx, dy);
  52056. var localZero = thisGroup.transformCoordToLocal(0, 0);
  52057. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  52058. }
  52059. function clipByPanel(controller, cover, data) {
  52060. var panel = getPanelByCover(controller, cover);
  52061. return (panel && panel !== true)
  52062. ? panel.clipPath(data, controller._transform)
  52063. : clone(data);
  52064. }
  52065. function pointsToRect(points) {
  52066. var xmin = mathMin$5(points[0][0], points[1][0]);
  52067. var ymin = mathMin$5(points[0][1], points[1][1]);
  52068. var xmax = mathMax$5(points[0][0], points[1][0]);
  52069. var ymax = mathMax$5(points[0][1], points[1][1]);
  52070. return {
  52071. x: xmin,
  52072. y: ymin,
  52073. width: xmax - xmin,
  52074. height: ymax - ymin
  52075. };
  52076. }
  52077. function resetCursor(controller, e, localCursorPoint) {
  52078. if (
  52079. // Check active
  52080. !controller._brushType
  52081. // resetCursor should be always called when mouse is in zr area,
  52082. // but not called when mouse is out of zr area to avoid bad influence
  52083. // if `mousemove`, `mouseup` are triggered from `document` event.
  52084. || isOutsideZrArea(controller, e)
  52085. ) {
  52086. return;
  52087. }
  52088. var zr = controller._zr;
  52089. var covers = controller._covers;
  52090. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  52091. // Check whether in covers.
  52092. if (!controller._dragging) {
  52093. for (var i = 0; i < covers.length; i++) {
  52094. var brushOption = covers[i].__brushOption;
  52095. if (currPanel
  52096. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  52097. && coverRenderers[brushOption.brushType].contain(
  52098. covers[i], localCursorPoint[0], localCursorPoint[1]
  52099. )
  52100. ) {
  52101. // Use cursor style set on cover.
  52102. return;
  52103. }
  52104. }
  52105. }
  52106. currPanel && zr.setCursorStyle('crosshair');
  52107. }
  52108. function preventDefault(e) {
  52109. var rawE = e.event;
  52110. rawE.preventDefault && rawE.preventDefault();
  52111. }
  52112. function mainShapeContain(cover, x, y) {
  52113. return cover.childOfName('main').contain(x, y);
  52114. }
  52115. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  52116. var creatingCover = controller._creatingCover;
  52117. var panel = controller._creatingPanel;
  52118. var thisBrushOption = controller._brushOption;
  52119. var eventParams;
  52120. controller._track.push(localCursorPoint.slice());
  52121. if (shouldShowCover(controller) || creatingCover) {
  52122. if (panel && !creatingCover) {
  52123. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  52124. var brushOption = clone(thisBrushOption);
  52125. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  52126. brushOption.panelId = panel === true ? null : panel.panelId;
  52127. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  52128. controller._covers.push(creatingCover);
  52129. }
  52130. if (creatingCover) {
  52131. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  52132. var coverBrushOption = creatingCover.__brushOption;
  52133. coverBrushOption.range = coverRenderer.getCreatingRange(
  52134. clipByPanel(controller, creatingCover, controller._track)
  52135. );
  52136. if (isEnd) {
  52137. endCreating(controller, creatingCover);
  52138. coverRenderer.updateCommon(controller, creatingCover);
  52139. }
  52140. updateCoverShape(controller, creatingCover);
  52141. eventParams = {isEnd: isEnd};
  52142. }
  52143. }
  52144. else if (
  52145. isEnd
  52146. && thisBrushOption.brushMode === 'single'
  52147. && thisBrushOption.removeOnClick
  52148. ) {
  52149. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  52150. // But a single click do not clear covers, because user may have casual
  52151. // clicks (for example, click on other component and do not expect covers
  52152. // disappear).
  52153. // Only some cover removed, trigger action, but not every click trigger action.
  52154. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  52155. eventParams = {isEnd: isEnd, removeOnClick: true};
  52156. }
  52157. }
  52158. return eventParams;
  52159. }
  52160. function determineBrushType(brushType, panel) {
  52161. if (brushType === 'auto') {
  52162. if (__DEV__) {
  52163. assert$1(
  52164. panel && panel.defaultBrushType,
  52165. 'MUST have defaultBrushType when brushType is "atuo"'
  52166. );
  52167. }
  52168. return panel.defaultBrushType;
  52169. }
  52170. return brushType;
  52171. }
  52172. var pointerHandlers = {
  52173. mousedown: function (e) {
  52174. if (this._dragging) {
  52175. // In case some browser do not support globalOut,
  52176. // and release mose out side the browser.
  52177. handleDragEnd(this, e);
  52178. }
  52179. else if (!e.target || !e.target.draggable) {
  52180. preventDefault(e);
  52181. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  52182. this._creatingCover = null;
  52183. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  52184. if (panel) {
  52185. this._dragging = true;
  52186. this._track = [localCursorPoint.slice()];
  52187. }
  52188. }
  52189. },
  52190. mousemove: function (e) {
  52191. var x = e.offsetX;
  52192. var y = e.offsetY;
  52193. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  52194. resetCursor(this, e, localCursorPoint);
  52195. if (this._dragging) {
  52196. preventDefault(e);
  52197. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  52198. eventParams && trigger$1(this, eventParams);
  52199. }
  52200. },
  52201. mouseup: function (e) {
  52202. handleDragEnd(this, e);
  52203. }
  52204. };
  52205. function handleDragEnd(controller, e) {
  52206. if (controller._dragging) {
  52207. preventDefault(e);
  52208. var x = e.offsetX;
  52209. var y = e.offsetY;
  52210. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  52211. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  52212. controller._dragging = false;
  52213. controller._track = [];
  52214. controller._creatingCover = null;
  52215. // trigger event shoule be at final, after procedure will be nested.
  52216. eventParams && trigger$1(controller, eventParams);
  52217. }
  52218. }
  52219. function isOutsideZrArea(controller, x, y) {
  52220. var zr = controller._zr;
  52221. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  52222. }
  52223. /**
  52224. * key: brushType
  52225. * @type {Object}
  52226. */
  52227. var coverRenderers = {
  52228. lineX: getLineRenderer(0),
  52229. lineY: getLineRenderer(1),
  52230. rect: {
  52231. createCover: function (controller, brushOption) {
  52232. return createBaseRectCover(
  52233. curry$5(
  52234. driftRect,
  52235. function (range) {
  52236. return range;
  52237. },
  52238. function (range) {
  52239. return range;
  52240. }
  52241. ),
  52242. controller,
  52243. brushOption,
  52244. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  52245. );
  52246. },
  52247. getCreatingRange: function (localTrack) {
  52248. var ends = getTrackEnds(localTrack);
  52249. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  52250. },
  52251. updateCoverShape: function (controller, cover, localRange, brushOption) {
  52252. updateBaseRect(controller, cover, localRange, brushOption);
  52253. },
  52254. updateCommon: updateCommon,
  52255. contain: mainShapeContain
  52256. },
  52257. polygon: {
  52258. createCover: function (controller, brushOption) {
  52259. var cover = new Group();
  52260. // Do not use graphic.Polygon because graphic.Polyline do not close the
  52261. // border of the shape when drawing, which is a better experience for user.
  52262. cover.add(new Polyline({
  52263. name: 'main',
  52264. style: makeStyle(brushOption),
  52265. silent: true
  52266. }));
  52267. return cover;
  52268. },
  52269. getCreatingRange: function (localTrack) {
  52270. return localTrack;
  52271. },
  52272. endCreating: function (controller, cover) {
  52273. cover.remove(cover.childAt(0));
  52274. // Use graphic.Polygon close the shape.
  52275. cover.add(new Polygon({
  52276. name: 'main',
  52277. draggable: true,
  52278. drift: curry$5(driftPolygon, controller, cover),
  52279. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  52280. }));
  52281. },
  52282. updateCoverShape: function (controller, cover, localRange, brushOption) {
  52283. cover.childAt(0).setShape({
  52284. points: clipByPanel(controller, cover, localRange)
  52285. });
  52286. },
  52287. updateCommon: updateCommon,
  52288. contain: mainShapeContain
  52289. }
  52290. };
  52291. function getLineRenderer(xyIndex) {
  52292. return {
  52293. createCover: function (controller, brushOption) {
  52294. return createBaseRectCover(
  52295. curry$5(
  52296. driftRect,
  52297. function (range) {
  52298. var rectRange = [range, [0, 100]];
  52299. xyIndex && rectRange.reverse();
  52300. return rectRange;
  52301. },
  52302. function (rectRange) {
  52303. return rectRange[xyIndex];
  52304. }
  52305. ),
  52306. controller,
  52307. brushOption,
  52308. [['w', 'e'], ['n', 's']][xyIndex]
  52309. );
  52310. },
  52311. getCreatingRange: function (localTrack) {
  52312. var ends = getTrackEnds(localTrack);
  52313. var min = mathMin$5(ends[0][xyIndex], ends[1][xyIndex]);
  52314. var max = mathMax$5(ends[0][xyIndex], ends[1][xyIndex]);
  52315. return [min, max];
  52316. },
  52317. updateCoverShape: function (controller, cover, localRange, brushOption) {
  52318. var otherExtent;
  52319. // If brushWidth not specified, fit the panel.
  52320. var panel = getPanelByCover(controller, cover);
  52321. if (panel !== true && panel.getLinearBrushOtherExtent) {
  52322. otherExtent = panel.getLinearBrushOtherExtent(
  52323. xyIndex, controller._transform
  52324. );
  52325. }
  52326. else {
  52327. var zr = controller._zr;
  52328. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  52329. }
  52330. var rectRange = [localRange, otherExtent];
  52331. xyIndex && rectRange.reverse();
  52332. updateBaseRect(controller, cover, rectRange, brushOption);
  52333. },
  52334. updateCommon: updateCommon,
  52335. contain: mainShapeContain
  52336. };
  52337. }
  52338. /*
  52339. * Licensed to the Apache Software Foundation (ASF) under one
  52340. * or more contributor license agreements. See the NOTICE file
  52341. * distributed with this work for additional information
  52342. * regarding copyright ownership. The ASF licenses this file
  52343. * to you under the Apache License, Version 2.0 (the
  52344. * "License"); you may not use this file except in compliance
  52345. * with the License. You may obtain a copy of the License at
  52346. *
  52347. * http://www.apache.org/licenses/LICENSE-2.0
  52348. *
  52349. * Unless required by applicable law or agreed to in writing,
  52350. * software distributed under the License is distributed on an
  52351. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52352. * KIND, either express or implied. See the License for the
  52353. * specific language governing permissions and limitations
  52354. * under the License.
  52355. */
  52356. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  52357. /**
  52358. * Avoid that: mouse click on a elements that is over geo or graph,
  52359. * but roam is triggered.
  52360. */
  52361. function onIrrelevantElement(e, api, targetCoordSysModel) {
  52362. var model = api.getComponentByElement(e.topTarget);
  52363. // If model is axisModel, it works only if it is injected with coordinateSystem.
  52364. var coordSys = model && model.coordinateSystem;
  52365. return model
  52366. && model !== targetCoordSysModel
  52367. && !IRRELEVANT_EXCLUDES[model.mainType]
  52368. && (coordSys && coordSys.model !== targetCoordSysModel);
  52369. }
  52370. /*
  52371. * Licensed to the Apache Software Foundation (ASF) under one
  52372. * or more contributor license agreements. See the NOTICE file
  52373. * distributed with this work for additional information
  52374. * regarding copyright ownership. The ASF licenses this file
  52375. * to you under the Apache License, Version 2.0 (the
  52376. * "License"); you may not use this file except in compliance
  52377. * with the License. You may obtain a copy of the License at
  52378. *
  52379. * http://www.apache.org/licenses/LICENSE-2.0
  52380. *
  52381. * Unless required by applicable law or agreed to in writing,
  52382. * software distributed under the License is distributed on an
  52383. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52384. * KIND, either express or implied. See the License for the
  52385. * specific language governing permissions and limitations
  52386. * under the License.
  52387. */
  52388. function makeRectPanelClipPath(rect) {
  52389. rect = normalizeRect(rect);
  52390. return function (localPoints, transform) {
  52391. return clipPointsByRect(localPoints, rect);
  52392. };
  52393. }
  52394. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  52395. rect = normalizeRect(rect);
  52396. return function (xyIndex) {
  52397. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  52398. var brushWidth = idx ? rect.width : rect.height;
  52399. var base = idx ? rect.x : rect.y;
  52400. return [base, base + (brushWidth || 0)];
  52401. };
  52402. }
  52403. function makeRectIsTargetByCursor(rect, api, targetModel) {
  52404. rect = normalizeRect(rect);
  52405. return function (e, localCursorPoint, transform) {
  52406. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  52407. && !onIrrelevantElement(e, api, targetModel);
  52408. };
  52409. }
  52410. // Consider width/height is negative.
  52411. function normalizeRect(rect) {
  52412. return BoundingRect.create(rect);
  52413. }
  52414. /*
  52415. * Licensed to the Apache Software Foundation (ASF) under one
  52416. * or more contributor license agreements. See the NOTICE file
  52417. * distributed with this work for additional information
  52418. * regarding copyright ownership. The ASF licenses this file
  52419. * to you under the Apache License, Version 2.0 (the
  52420. * "License"); you may not use this file except in compliance
  52421. * with the License. You may obtain a copy of the License at
  52422. *
  52423. * http://www.apache.org/licenses/LICENSE-2.0
  52424. *
  52425. * Unless required by applicable law or agreed to in writing,
  52426. * software distributed under the License is distributed on an
  52427. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52428. * KIND, either express or implied. See the License for the
  52429. * specific language governing permissions and limitations
  52430. * under the License.
  52431. */
  52432. var each$17 = each$1;
  52433. var indexOf$2 = indexOf;
  52434. var curry$6 = curry;
  52435. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  52436. // FIXME
  52437. // how to genarialize to more coordinate systems.
  52438. var INCLUDE_FINDER_MAIN_TYPES = [
  52439. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  52440. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  52441. ];
  52442. /**
  52443. * [option in constructor]:
  52444. * {
  52445. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  52446. * }
  52447. *
  52448. *
  52449. * [targetInfo]:
  52450. *
  52451. * There can be multiple axes in a single targetInfo. Consider the case
  52452. * of `grid` component, a targetInfo represents a grid which contains one or more
  52453. * cartesian and one or more axes. And consider the case of parallel system,
  52454. * which has multiple axes in a coordinate system.
  52455. * Can be {
  52456. * panelId: ...,
  52457. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  52458. * coordSyses: all cartesians.
  52459. * gridModel: <grid component>
  52460. * xAxes: correspond to coordSyses on index
  52461. * yAxes: correspond to coordSyses on index
  52462. * }
  52463. * or {
  52464. * panelId: ...,
  52465. * coordSys: <geo coord sys>
  52466. * coordSyses: [<geo coord sys>]
  52467. * geoModel: <geo component>
  52468. * }
  52469. *
  52470. *
  52471. * [panelOpt]:
  52472. *
  52473. * Make from targetInfo. Input to BrushController.
  52474. * {
  52475. * panelId: ...,
  52476. * rect: ...
  52477. * }
  52478. *
  52479. *
  52480. * [area]:
  52481. *
  52482. * Generated by BrushController or user input.
  52483. * {
  52484. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  52485. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  52486. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  52487. * range: pixel range.
  52488. * coordRange: representitive coord range (the first one of coordRanges).
  52489. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  52490. * }
  52491. */
  52492. /**
  52493. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  52494. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  52495. * @param {module:echarts/model/Global} ecModel
  52496. * @param {Object} [opt]
  52497. * @param {Array.<string>} [opt.include] include coordinate system types.
  52498. */
  52499. function BrushTargetManager(option, ecModel, opt) {
  52500. /**
  52501. * @private
  52502. * @type {Array.<Object>}
  52503. */
  52504. var targetInfoList = this._targetInfoList = [];
  52505. var info = {};
  52506. var foundCpts = parseFinder$1(ecModel, option);
  52507. each$17(targetInfoBuilders, function (builder, type) {
  52508. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  52509. builder(foundCpts, targetInfoList, info);
  52510. }
  52511. });
  52512. }
  52513. var proto$5 = BrushTargetManager.prototype;
  52514. proto$5.setOutputRanges = function (areas, ecModel) {
  52515. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  52516. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  52517. // area.coordRange is the first of area.coordRanges
  52518. if (!area.coordRange) {
  52519. area.coordRange = coordRange;
  52520. // In 'category' axis, coord to pixel is not reversible, so we can not
  52521. // rebuild range by coordRange accrately, which may bring trouble when
  52522. // brushing only one item. So we use __rangeOffset to rebuilding range
  52523. // by coordRange. And this it only used in brush component so it is no
  52524. // need to be adapted to coordRanges.
  52525. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  52526. area.__rangeOffset = {
  52527. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  52528. xyMinMax: result.xyMinMax
  52529. };
  52530. }
  52531. });
  52532. };
  52533. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  52534. each$17(areas, function (area) {
  52535. var targetInfo = this.findTargetInfo(area, ecModel);
  52536. if (targetInfo && targetInfo !== true) {
  52537. each$1(
  52538. targetInfo.coordSyses,
  52539. function (coordSys) {
  52540. var result = coordConvert[area.brushType](1, coordSys, area.range);
  52541. cb(area, result.values, coordSys, ecModel);
  52542. }
  52543. );
  52544. }
  52545. }, this);
  52546. };
  52547. proto$5.setInputRanges = function (areas, ecModel) {
  52548. each$17(areas, function (area) {
  52549. var targetInfo = this.findTargetInfo(area, ecModel);
  52550. if (__DEV__) {
  52551. assert$1(
  52552. !targetInfo || targetInfo === true || area.coordRange,
  52553. 'coordRange must be specified when coord index specified.'
  52554. );
  52555. assert$1(
  52556. !targetInfo || targetInfo !== true || area.range,
  52557. 'range must be specified in global brush.'
  52558. );
  52559. }
  52560. area.range = area.range || [];
  52561. // convert coordRange to global range and set panelId.
  52562. if (targetInfo && targetInfo !== true) {
  52563. area.panelId = targetInfo.panelId;
  52564. // (1) area.range shoule always be calculate from coordRange but does
  52565. // not keep its original value, for the sake of the dataZoom scenario,
  52566. // where area.coordRange remains unchanged but area.range may be changed.
  52567. // (2) Only support converting one coordRange to pixel range in brush
  52568. // component. So do not consider `coordRanges`.
  52569. // (3) About __rangeOffset, see comment above.
  52570. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  52571. var rangeOffset = area.__rangeOffset;
  52572. area.range = rangeOffset
  52573. ? diffProcessor[area.brushType](
  52574. result.values,
  52575. rangeOffset.offset,
  52576. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  52577. )
  52578. : result.values;
  52579. }
  52580. }, this);
  52581. };
  52582. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  52583. return map(this._targetInfoList, function (targetInfo) {
  52584. var rect = targetInfo.getPanelRect();
  52585. return {
  52586. panelId: targetInfo.panelId,
  52587. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  52588. clipPath: makeRectPanelClipPath(rect),
  52589. isTargetByCursor: makeRectIsTargetByCursor(
  52590. rect, api, targetInfo.coordSysModel
  52591. ),
  52592. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  52593. };
  52594. });
  52595. };
  52596. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  52597. // Check whether area is bound in coord, and series do not belong to that coord.
  52598. // If do not do this check, some brush (like lineX) will controll all axes.
  52599. var targetInfo = this.findTargetInfo(area, ecModel);
  52600. return targetInfo === true || (
  52601. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  52602. );
  52603. };
  52604. /**
  52605. * If return Object, a coord found.
  52606. * If reutrn true, global found.
  52607. * Otherwise nothing found.
  52608. *
  52609. * @param {Object} area
  52610. * @param {Array} targetInfoList
  52611. * @return {Object|boolean}
  52612. */
  52613. proto$5.findTargetInfo = function (area, ecModel) {
  52614. var targetInfoList = this._targetInfoList;
  52615. var foundCpts = parseFinder$1(ecModel, area);
  52616. for (var i = 0; i < targetInfoList.length; i++) {
  52617. var targetInfo = targetInfoList[i];
  52618. var areaPanelId = area.panelId;
  52619. if (areaPanelId) {
  52620. if (targetInfo.panelId === areaPanelId) {
  52621. return targetInfo;
  52622. }
  52623. }
  52624. else {
  52625. for (var i = 0; i < targetInfoMatchers.length; i++) {
  52626. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  52627. return targetInfo;
  52628. }
  52629. }
  52630. }
  52631. }
  52632. return true;
  52633. };
  52634. function formatMinMax(minMax) {
  52635. minMax[0] > minMax[1] && minMax.reverse();
  52636. return minMax;
  52637. }
  52638. function parseFinder$1(ecModel, option) {
  52639. return parseFinder(
  52640. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  52641. );
  52642. }
  52643. var targetInfoBuilders = {
  52644. grid: function (foundCpts, targetInfoList) {
  52645. var xAxisModels = foundCpts.xAxisModels;
  52646. var yAxisModels = foundCpts.yAxisModels;
  52647. var gridModels = foundCpts.gridModels;
  52648. // Remove duplicated.
  52649. var gridModelMap = createHashMap();
  52650. var xAxesHas = {};
  52651. var yAxesHas = {};
  52652. if (!xAxisModels && !yAxisModels && !gridModels) {
  52653. return;
  52654. }
  52655. each$17(xAxisModels, function (axisModel) {
  52656. var gridModel = axisModel.axis.grid.model;
  52657. gridModelMap.set(gridModel.id, gridModel);
  52658. xAxesHas[gridModel.id] = true;
  52659. });
  52660. each$17(yAxisModels, function (axisModel) {
  52661. var gridModel = axisModel.axis.grid.model;
  52662. gridModelMap.set(gridModel.id, gridModel);
  52663. yAxesHas[gridModel.id] = true;
  52664. });
  52665. each$17(gridModels, function (gridModel) {
  52666. gridModelMap.set(gridModel.id, gridModel);
  52667. xAxesHas[gridModel.id] = true;
  52668. yAxesHas[gridModel.id] = true;
  52669. });
  52670. gridModelMap.each(function (gridModel) {
  52671. var grid = gridModel.coordinateSystem;
  52672. var cartesians = [];
  52673. each$17(grid.getCartesians(), function (cartesian, index) {
  52674. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  52675. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  52676. ) {
  52677. cartesians.push(cartesian);
  52678. }
  52679. });
  52680. targetInfoList.push({
  52681. panelId: 'grid--' + gridModel.id,
  52682. gridModel: gridModel,
  52683. coordSysModel: gridModel,
  52684. // Use the first one as the representitive coordSys.
  52685. coordSys: cartesians[0],
  52686. coordSyses: cartesians,
  52687. getPanelRect: panelRectBuilder.grid,
  52688. xAxisDeclared: xAxesHas[gridModel.id],
  52689. yAxisDeclared: yAxesHas[gridModel.id]
  52690. });
  52691. });
  52692. },
  52693. geo: function (foundCpts, targetInfoList) {
  52694. each$17(foundCpts.geoModels, function (geoModel) {
  52695. var coordSys = geoModel.coordinateSystem;
  52696. targetInfoList.push({
  52697. panelId: 'geo--' + geoModel.id,
  52698. geoModel: geoModel,
  52699. coordSysModel: geoModel,
  52700. coordSys: coordSys,
  52701. coordSyses: [coordSys],
  52702. getPanelRect: panelRectBuilder.geo
  52703. });
  52704. });
  52705. }
  52706. };
  52707. var targetInfoMatchers = [
  52708. // grid
  52709. function (foundCpts, targetInfo) {
  52710. var xAxisModel = foundCpts.xAxisModel;
  52711. var yAxisModel = foundCpts.yAxisModel;
  52712. var gridModel = foundCpts.gridModel;
  52713. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  52714. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  52715. return gridModel && gridModel === targetInfo.gridModel;
  52716. },
  52717. // geo
  52718. function (foundCpts, targetInfo) {
  52719. var geoModel = foundCpts.geoModel;
  52720. return geoModel && geoModel === targetInfo.geoModel;
  52721. }
  52722. ];
  52723. var panelRectBuilder = {
  52724. grid: function () {
  52725. // grid is not Transformable.
  52726. return this.coordSys.grid.getRect().clone();
  52727. },
  52728. geo: function () {
  52729. var coordSys = this.coordSys;
  52730. var rect = coordSys.getBoundingRect().clone();
  52731. // geo roam and zoom transform
  52732. rect.applyTransform(getTransform(coordSys));
  52733. return rect;
  52734. }
  52735. };
  52736. var coordConvert = {
  52737. lineX: curry$6(axisConvert, 0),
  52738. lineY: curry$6(axisConvert, 1),
  52739. rect: function (to, coordSys, rangeOrCoordRange) {
  52740. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  52741. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  52742. var values = [
  52743. formatMinMax([xminymin[0], xmaxymax[0]]),
  52744. formatMinMax([xminymin[1], xmaxymax[1]])
  52745. ];
  52746. return {values: values, xyMinMax: values};
  52747. },
  52748. polygon: function (to, coordSys, rangeOrCoordRange) {
  52749. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  52750. var values = map(rangeOrCoordRange, function (item) {
  52751. var p = coordSys[COORD_CONVERTS[to]](item);
  52752. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  52753. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  52754. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  52755. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  52756. return p;
  52757. });
  52758. return {values: values, xyMinMax: xyMinMax};
  52759. }
  52760. };
  52761. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  52762. if (__DEV__) {
  52763. assert$1(
  52764. coordSys.type === 'cartesian2d',
  52765. 'lineX/lineY brush is available only in cartesian2d.'
  52766. );
  52767. }
  52768. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  52769. var values = formatMinMax(map([0, 1], function (i) {
  52770. return to
  52771. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  52772. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  52773. }));
  52774. var xyMinMax = [];
  52775. xyMinMax[axisNameIndex] = values;
  52776. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  52777. return {values: values, xyMinMax: xyMinMax};
  52778. }
  52779. var diffProcessor = {
  52780. lineX: curry$6(axisDiffProcessor, 0),
  52781. lineY: curry$6(axisDiffProcessor, 1),
  52782. rect: function (values, refer, scales) {
  52783. return [
  52784. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  52785. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  52786. ];
  52787. },
  52788. polygon: function (values, refer, scales) {
  52789. return map(values, function (item, idx) {
  52790. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  52791. });
  52792. }
  52793. };
  52794. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  52795. return [
  52796. values[0] - scales[axisNameIndex] * refer[0],
  52797. values[1] - scales[axisNameIndex] * refer[1]
  52798. ];
  52799. }
  52800. // We have to process scale caused by dataZoom manually,
  52801. // although it might be not accurate.
  52802. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  52803. var sizeCurr = getSize(xyMinMaxCurr);
  52804. var sizeOrigin = getSize(xyMinMaxOrigin);
  52805. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  52806. isNaN(scales[0]) && (scales[0] = 1);
  52807. isNaN(scales[1]) && (scales[1] = 1);
  52808. return scales;
  52809. }
  52810. function getSize(xyMinMax) {
  52811. return xyMinMax
  52812. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  52813. : [NaN, NaN];
  52814. }
  52815. /*
  52816. * Licensed to the Apache Software Foundation (ASF) under one
  52817. * or more contributor license agreements. See the NOTICE file
  52818. * distributed with this work for additional information
  52819. * regarding copyright ownership. The ASF licenses this file
  52820. * to you under the Apache License, Version 2.0 (the
  52821. * "License"); you may not use this file except in compliance
  52822. * with the License. You may obtain a copy of the License at
  52823. *
  52824. * http://www.apache.org/licenses/LICENSE-2.0
  52825. *
  52826. * Unless required by applicable law or agreed to in writing,
  52827. * software distributed under the License is distributed on an
  52828. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52829. * KIND, either express or implied. See the License for the
  52830. * specific language governing permissions and limitations
  52831. * under the License.
  52832. */
  52833. var each$18 = each$1;
  52834. var ATTR$2 = '\0_ec_hist_store';
  52835. /**
  52836. * @param {module:echarts/model/Global} ecModel
  52837. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  52838. */
  52839. function push(ecModel, newSnapshot) {
  52840. var store = giveStore$1(ecModel);
  52841. // If previous dataZoom can not be found,
  52842. // complete an range with current range.
  52843. each$18(newSnapshot, function (batchItem, dataZoomId) {
  52844. var i = store.length - 1;
  52845. for (; i >= 0; i--) {
  52846. var snapshot = store[i];
  52847. if (snapshot[dataZoomId]) {
  52848. break;
  52849. }
  52850. }
  52851. if (i < 0) {
  52852. // No origin range set, create one by current range.
  52853. var dataZoomModel = ecModel.queryComponents(
  52854. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  52855. )[0];
  52856. if (dataZoomModel) {
  52857. var percentRange = dataZoomModel.getPercentRange();
  52858. store[0][dataZoomId] = {
  52859. dataZoomId: dataZoomId,
  52860. start: percentRange[0],
  52861. end: percentRange[1]
  52862. };
  52863. }
  52864. }
  52865. });
  52866. store.push(newSnapshot);
  52867. }
  52868. /**
  52869. * @param {module:echarts/model/Global} ecModel
  52870. * @return {Object} snapshot
  52871. */
  52872. function pop(ecModel) {
  52873. var store = giveStore$1(ecModel);
  52874. var head = store[store.length - 1];
  52875. store.length > 1 && store.pop();
  52876. // Find top for all dataZoom.
  52877. var snapshot = {};
  52878. each$18(head, function (batchItem, dataZoomId) {
  52879. for (var i = store.length - 1; i >= 0; i--) {
  52880. var batchItem = store[i][dataZoomId];
  52881. if (batchItem) {
  52882. snapshot[dataZoomId] = batchItem;
  52883. break;
  52884. }
  52885. }
  52886. });
  52887. return snapshot;
  52888. }
  52889. /**
  52890. * @param {module:echarts/model/Global} ecModel
  52891. */
  52892. function clear$1(ecModel) {
  52893. ecModel[ATTR$2] = null;
  52894. }
  52895. /**
  52896. * @param {module:echarts/model/Global} ecModel
  52897. * @return {number} records. always >= 1.
  52898. */
  52899. function count(ecModel) {
  52900. return giveStore$1(ecModel).length;
  52901. }
  52902. /**
  52903. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  52904. * History length of each dataZoom may be different.
  52905. * this._history[0] is used to store origin range.
  52906. * @type {Array.<Object>}
  52907. */
  52908. function giveStore$1(ecModel) {
  52909. var store = ecModel[ATTR$2];
  52910. if (!store) {
  52911. store = ecModel[ATTR$2] = [{}];
  52912. }
  52913. return store;
  52914. }
  52915. /*
  52916. * Licensed to the Apache Software Foundation (ASF) under one
  52917. * or more contributor license agreements. See the NOTICE file
  52918. * distributed with this work for additional information
  52919. * regarding copyright ownership. The ASF licenses this file
  52920. * to you under the Apache License, Version 2.0 (the
  52921. * "License"); you may not use this file except in compliance
  52922. * with the License. You may obtain a copy of the License at
  52923. *
  52924. * http://www.apache.org/licenses/LICENSE-2.0
  52925. *
  52926. * Unless required by applicable law or agreed to in writing,
  52927. * software distributed under the License is distributed on an
  52928. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52929. * KIND, either express or implied. See the License for the
  52930. * specific language governing permissions and limitations
  52931. * under the License.
  52932. */
  52933. DataZoomModel.extend({
  52934. type: 'dataZoom.select'
  52935. });
  52936. /*
  52937. * Licensed to the Apache Software Foundation (ASF) under one
  52938. * or more contributor license agreements. See the NOTICE file
  52939. * distributed with this work for additional information
  52940. * regarding copyright ownership. The ASF licenses this file
  52941. * to you under the Apache License, Version 2.0 (the
  52942. * "License"); you may not use this file except in compliance
  52943. * with the License. You may obtain a copy of the License at
  52944. *
  52945. * http://www.apache.org/licenses/LICENSE-2.0
  52946. *
  52947. * Unless required by applicable law or agreed to in writing,
  52948. * software distributed under the License is distributed on an
  52949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52950. * KIND, either express or implied. See the License for the
  52951. * specific language governing permissions and limitations
  52952. * under the License.
  52953. */
  52954. DataZoomView.extend({
  52955. type: 'dataZoom.select'
  52956. });
  52957. /*
  52958. * Licensed to the Apache Software Foundation (ASF) under one
  52959. * or more contributor license agreements. See the NOTICE file
  52960. * distributed with this work for additional information
  52961. * regarding copyright ownership. The ASF licenses this file
  52962. * to you under the Apache License, Version 2.0 (the
  52963. * "License"); you may not use this file except in compliance
  52964. * with the License. You may obtain a copy of the License at
  52965. *
  52966. * http://www.apache.org/licenses/LICENSE-2.0
  52967. *
  52968. * Unless required by applicable law or agreed to in writing,
  52969. * software distributed under the License is distributed on an
  52970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52971. * KIND, either express or implied. See the License for the
  52972. * specific language governing permissions and limitations
  52973. * under the License.
  52974. */
  52975. /**
  52976. * Only work for toolbox dataZoom. User
  52977. * MUST NOT import this module directly.
  52978. */
  52979. /*
  52980. * Licensed to the Apache Software Foundation (ASF) under one
  52981. * or more contributor license agreements. See the NOTICE file
  52982. * distributed with this work for additional information
  52983. * regarding copyright ownership. The ASF licenses this file
  52984. * to you under the Apache License, Version 2.0 (the
  52985. * "License"); you may not use this file except in compliance
  52986. * with the License. You may obtain a copy of the License at
  52987. *
  52988. * http://www.apache.org/licenses/LICENSE-2.0
  52989. *
  52990. * Unless required by applicable law or agreed to in writing,
  52991. * software distributed under the License is distributed on an
  52992. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52993. * KIND, either express or implied. See the License for the
  52994. * specific language governing permissions and limitations
  52995. * under the License.
  52996. */
  52997. // Use dataZoomSelect
  52998. var dataZoomLang = lang.toolbox.dataZoom;
  52999. var each$15 = each$1;
  53000. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  53001. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  53002. function DataZoom(model, ecModel, api) {
  53003. /**
  53004. * @private
  53005. * @type {module:echarts/component/helper/BrushController}
  53006. */
  53007. (this._brushController = new BrushController(api.getZr()))
  53008. .on('brush', bind(this._onBrush, this))
  53009. .mount();
  53010. /**
  53011. * @private
  53012. * @type {boolean}
  53013. */
  53014. this._isZoomActive;
  53015. }
  53016. DataZoom.defaultOption = {
  53017. show: true,
  53018. filterMode: 'filter',
  53019. // Icon group
  53020. icon: {
  53021. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  53022. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  53023. },
  53024. // `zoom`, `back`
  53025. title: clone(dataZoomLang.title),
  53026. brushStyle: {
  53027. borderWidth: 0,
  53028. color: 'rgba(0,0,0,0.2)'
  53029. }
  53030. };
  53031. var proto$4 = DataZoom.prototype;
  53032. proto$4.render = function (featureModel, ecModel, api, payload) {
  53033. this.model = featureModel;
  53034. this.ecModel = ecModel;
  53035. this.api = api;
  53036. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  53037. updateBackBtnStatus(featureModel, ecModel);
  53038. };
  53039. proto$4.onclick = function (ecModel, api, type) {
  53040. handlers[type].call(this);
  53041. };
  53042. proto$4.remove = function (ecModel, api) {
  53043. this._brushController.unmount();
  53044. };
  53045. proto$4.dispose = function (ecModel, api) {
  53046. this._brushController.dispose();
  53047. };
  53048. /**
  53049. * @private
  53050. */
  53051. var handlers = {
  53052. zoom: function () {
  53053. var nextActive = !this._isZoomActive;
  53054. this.api.dispatchAction({
  53055. type: 'takeGlobalCursor',
  53056. key: 'dataZoomSelect',
  53057. dataZoomSelectActive: nextActive
  53058. });
  53059. },
  53060. back: function () {
  53061. this._dispatchZoomAction(pop(this.ecModel));
  53062. }
  53063. };
  53064. /**
  53065. * @private
  53066. */
  53067. proto$4._onBrush = function (areas, opt) {
  53068. if (!opt.isEnd || !areas.length) {
  53069. return;
  53070. }
  53071. var snapshot = {};
  53072. var ecModel = this.ecModel;
  53073. this._brushController.updateCovers([]); // remove cover
  53074. var brushTargetManager = new BrushTargetManager(
  53075. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  53076. );
  53077. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  53078. if (coordSys.type !== 'cartesian2d') {
  53079. return;
  53080. }
  53081. var brushType = area.brushType;
  53082. if (brushType === 'rect') {
  53083. setBatch('x', coordSys, coordRange[0]);
  53084. setBatch('y', coordSys, coordRange[1]);
  53085. }
  53086. else {
  53087. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  53088. }
  53089. });
  53090. push(ecModel, snapshot);
  53091. this._dispatchZoomAction(snapshot);
  53092. function setBatch(dimName, coordSys, minMax) {
  53093. var axis = coordSys.getAxis(dimName);
  53094. var axisModel = axis.model;
  53095. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  53096. // Restrict range.
  53097. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  53098. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  53099. minMax = sliderMove(
  53100. 0, minMax.slice(), axis.scale.getExtent(), 0,
  53101. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  53102. );
  53103. }
  53104. dataZoomModel && (snapshot[dataZoomModel.id] = {
  53105. dataZoomId: dataZoomModel.id,
  53106. startValue: minMax[0],
  53107. endValue: minMax[1]
  53108. });
  53109. }
  53110. function findDataZoom(dimName, axisModel, ecModel) {
  53111. var found;
  53112. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  53113. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  53114. has && (found = dzModel);
  53115. });
  53116. return found;
  53117. }
  53118. };
  53119. /**
  53120. * @private
  53121. */
  53122. proto$4._dispatchZoomAction = function (snapshot) {
  53123. var batch = [];
  53124. // Convert from hash map to array.
  53125. each$15(snapshot, function (batchItem, dataZoomId) {
  53126. batch.push(clone(batchItem));
  53127. });
  53128. batch.length && this.api.dispatchAction({
  53129. type: 'dataZoom',
  53130. from: this.uid,
  53131. batch: batch
  53132. });
  53133. };
  53134. function retrieveAxisSetting(option) {
  53135. var setting = {};
  53136. // Compatible with previous setting: null => all axis, false => no axis.
  53137. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  53138. setting[name] = option[name];
  53139. setting[name] == null && (setting[name] = 'all');
  53140. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  53141. });
  53142. return setting;
  53143. }
  53144. function updateBackBtnStatus(featureModel, ecModel) {
  53145. featureModel.setIconStatus(
  53146. 'back',
  53147. count(ecModel) > 1 ? 'emphasis' : 'normal'
  53148. );
  53149. }
  53150. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  53151. var zoomActive = view._isZoomActive;
  53152. if (payload && payload.type === 'takeGlobalCursor') {
  53153. zoomActive = payload.key === 'dataZoomSelect'
  53154. ? payload.dataZoomSelectActive : false;
  53155. }
  53156. view._isZoomActive = zoomActive;
  53157. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  53158. var brushTargetManager = new BrushTargetManager(
  53159. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  53160. );
  53161. view._brushController
  53162. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  53163. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  53164. ? 'lineX'
  53165. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  53166. ? 'lineY'
  53167. : 'rect';
  53168. }))
  53169. .enableBrush(
  53170. zoomActive
  53171. ? {
  53172. brushType: 'auto',
  53173. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  53174. }
  53175. : false
  53176. );
  53177. }
  53178. register$2('dataZoom', DataZoom);
  53179. // Create special dataZoom option for select
  53180. // FIXME consider the case of merge option, where axes options are not exists.
  53181. registerPreprocessor(function (option) {
  53182. if (!option) {
  53183. return;
  53184. }
  53185. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  53186. if (!isArray(dataZoomOpts)) {
  53187. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  53188. }
  53189. var toolboxOpt = option.toolbox;
  53190. if (toolboxOpt) {
  53191. // Assume there is only one toolbox
  53192. if (isArray(toolboxOpt)) {
  53193. toolboxOpt = toolboxOpt[0];
  53194. }
  53195. if (toolboxOpt && toolboxOpt.feature) {
  53196. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  53197. // FIXME: If add dataZoom when setOption in merge mode,
  53198. // no axis info to be added. See `test/dataZoom-extreme.html`
  53199. addForAxis('xAxis', dataZoomOpt);
  53200. addForAxis('yAxis', dataZoomOpt);
  53201. }
  53202. }
  53203. function addForAxis(axisName, dataZoomOpt) {
  53204. if (!dataZoomOpt) {
  53205. return;
  53206. }
  53207. // Try not to modify model, because it is not merged yet.
  53208. var axisIndicesName = axisName + 'Index';
  53209. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  53210. if (givenAxisIndices != null
  53211. && givenAxisIndices !== 'all'
  53212. && !isArray(givenAxisIndices)
  53213. ) {
  53214. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  53215. }
  53216. forEachComponent(axisName, function (axisOpt, axisIndex) {
  53217. if (givenAxisIndices != null
  53218. && givenAxisIndices !== 'all'
  53219. && indexOf(givenAxisIndices, axisIndex) === -1
  53220. ) {
  53221. return;
  53222. }
  53223. var newOpt = {
  53224. type: 'select',
  53225. $fromToolbox: true,
  53226. // Default to be filter
  53227. filterMode: dataZoomOpt.filterMode || 'filter',
  53228. // Id for merge mapping.
  53229. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  53230. };
  53231. // FIXME
  53232. // Only support one axis now.
  53233. newOpt[axisIndicesName] = axisIndex;
  53234. dataZoomOpts.push(newOpt);
  53235. });
  53236. }
  53237. function forEachComponent(mainType, cb) {
  53238. var opts = option[mainType];
  53239. if (!isArray(opts)) {
  53240. opts = opts ? [opts] : [];
  53241. }
  53242. each$15(opts, cb);
  53243. }
  53244. });
  53245. /*
  53246. * Licensed to the Apache Software Foundation (ASF) under one
  53247. * or more contributor license agreements. See the NOTICE file
  53248. * distributed with this work for additional information
  53249. * regarding copyright ownership. The ASF licenses this file
  53250. * to you under the Apache License, Version 2.0 (the
  53251. * "License"); you may not use this file except in compliance
  53252. * with the License. You may obtain a copy of the License at
  53253. *
  53254. * http://www.apache.org/licenses/LICENSE-2.0
  53255. *
  53256. * Unless required by applicable law or agreed to in writing,
  53257. * software distributed under the License is distributed on an
  53258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53259. * KIND, either express or implied. See the License for the
  53260. * specific language governing permissions and limitations
  53261. * under the License.
  53262. */
  53263. var restoreLang = lang.toolbox.restore;
  53264. function Restore(model) {
  53265. this.model = model;
  53266. }
  53267. Restore.defaultOption = {
  53268. show: true,
  53269. /* eslint-disable */
  53270. 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',
  53271. /* eslint-enable */
  53272. title: restoreLang.title
  53273. };
  53274. var proto$6 = Restore.prototype;
  53275. proto$6.onclick = function (ecModel, api, type) {
  53276. clear$1(ecModel);
  53277. api.dispatchAction({
  53278. type: 'restore',
  53279. from: this.uid
  53280. });
  53281. };
  53282. register$2('restore', Restore);
  53283. registerAction(
  53284. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  53285. function (payload, ecModel) {
  53286. ecModel.resetOption('recreate');
  53287. }
  53288. );
  53289. /*
  53290. * Licensed to the Apache Software Foundation (ASF) under one
  53291. * or more contributor license agreements. See the NOTICE file
  53292. * distributed with this work for additional information
  53293. * regarding copyright ownership. The ASF licenses this file
  53294. * to you under the Apache License, Version 2.0 (the
  53295. * "License"); you may not use this file except in compliance
  53296. * with the License. You may obtain a copy of the License at
  53297. *
  53298. * http://www.apache.org/licenses/LICENSE-2.0
  53299. *
  53300. * Unless required by applicable law or agreed to in writing,
  53301. * software distributed under the License is distributed on an
  53302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53303. * KIND, either express or implied. See the License for the
  53304. * specific language governing permissions and limitations
  53305. * under the License.
  53306. */
  53307. var urn = 'urn:schemas-microsoft-com:vml';
  53308. var win = typeof window === 'undefined' ? null : window;
  53309. var vmlInited = false;
  53310. var doc = win && win.document;
  53311. function createNode(tagName) {
  53312. return doCreateNode(tagName);
  53313. }
  53314. // Avoid assign to an exported variable, for transforming to cjs.
  53315. var doCreateNode;
  53316. if (doc && !env$1.canvasSupported) {
  53317. try {
  53318. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  53319. doCreateNode = function (tagName) {
  53320. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  53321. };
  53322. }
  53323. catch (e) {
  53324. doCreateNode = function (tagName) {
  53325. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  53326. };
  53327. }
  53328. }
  53329. // From raphael
  53330. function initVML() {
  53331. if (vmlInited || !doc) {
  53332. return;
  53333. }
  53334. vmlInited = true;
  53335. var styleSheets = doc.styleSheets;
  53336. if (styleSheets.length < 31) {
  53337. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  53338. }
  53339. else {
  53340. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  53341. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  53342. }
  53343. }
  53344. // http://www.w3.org/TR/NOTE-VML
  53345. // TODO Use proxy like svg instead of overwrite brush methods
  53346. var CMD$3 = PathProxy.CMD;
  53347. var round$2 = Math.round;
  53348. var sqrt = Math.sqrt;
  53349. var abs$1 = Math.abs;
  53350. var cos = Math.cos;
  53351. var sin = Math.sin;
  53352. var mathMax$6 = Math.max;
  53353. if (!env$1.canvasSupported) {
  53354. var comma = ',';
  53355. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  53356. var Z = 21600;
  53357. var Z2 = Z / 2;
  53358. var ZLEVEL_BASE = 100000;
  53359. var Z_BASE = 1000;
  53360. var initRootElStyle = function (el) {
  53361. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  53362. el.coordsize = Z + ',' + Z;
  53363. el.coordorigin = '0,0';
  53364. };
  53365. var encodeHtmlAttribute = function (s) {
  53366. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  53367. };
  53368. var rgb2Str = function (r, g, b) {
  53369. return 'rgb(' + [r, g, b].join(',') + ')';
  53370. };
  53371. var append = function (parent, child) {
  53372. if (child && parent && child.parentNode !== parent) {
  53373. parent.appendChild(child);
  53374. }
  53375. };
  53376. var remove = function (parent, child) {
  53377. if (child && parent && child.parentNode === parent) {
  53378. parent.removeChild(child);
  53379. }
  53380. };
  53381. var getZIndex = function (zlevel, z, z2) {
  53382. // z 的取值范围为 [0, 1000]
  53383. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  53384. };
  53385. var parsePercent$3 = parsePercent;
  53386. /***************************************************
  53387. * PATH
  53388. **************************************************/
  53389. var setColorAndOpacity = function (el, color, opacity) {
  53390. var colorArr = parse(color);
  53391. opacity = +opacity;
  53392. if (isNaN(opacity)) {
  53393. opacity = 1;
  53394. }
  53395. if (colorArr) {
  53396. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  53397. el.opacity = opacity * colorArr[3];
  53398. }
  53399. };
  53400. var getColorAndAlpha = function (color) {
  53401. var colorArr = parse(color);
  53402. return [
  53403. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  53404. colorArr[3]
  53405. ];
  53406. };
  53407. var updateFillNode = function (el, style, zrEl) {
  53408. // TODO pattern
  53409. var fill = style.fill;
  53410. if (fill != null) {
  53411. // Modified from excanvas
  53412. if (fill instanceof Gradient) {
  53413. var gradientType;
  53414. var angle = 0;
  53415. var focus = [0, 0];
  53416. // additional offset
  53417. var shift = 0;
  53418. // scale factor for offset
  53419. var expansion = 1;
  53420. var rect = zrEl.getBoundingRect();
  53421. var rectWidth = rect.width;
  53422. var rectHeight = rect.height;
  53423. if (fill.type === 'linear') {
  53424. gradientType = 'gradient';
  53425. var transform = zrEl.transform;
  53426. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  53427. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  53428. if (transform) {
  53429. applyTransform(p0, p0, transform);
  53430. applyTransform(p1, p1, transform);
  53431. }
  53432. var dx = p1[0] - p0[0];
  53433. var dy = p1[1] - p0[1];
  53434. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  53435. // The angle should be a non-negative number.
  53436. if (angle < 0) {
  53437. angle += 360;
  53438. }
  53439. // Very small angles produce an unexpected result because they are
  53440. // converted to a scientific notation string.
  53441. if (angle < 1e-6) {
  53442. angle = 0;
  53443. }
  53444. }
  53445. else {
  53446. gradientType = 'gradientradial';
  53447. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  53448. var transform = zrEl.transform;
  53449. var scale$$1 = zrEl.scale;
  53450. var width = rectWidth;
  53451. var height = rectHeight;
  53452. focus = [
  53453. // Percent in bounding rect
  53454. (p0[0] - rect.x) / width,
  53455. (p0[1] - rect.y) / height
  53456. ];
  53457. if (transform) {
  53458. applyTransform(p0, p0, transform);
  53459. }
  53460. width /= scale$$1[0] * Z;
  53461. height /= scale$$1[1] * Z;
  53462. var dimension = mathMax$6(width, height);
  53463. shift = 2 * 0 / dimension;
  53464. expansion = 2 * fill.r / dimension - shift;
  53465. }
  53466. // We need to sort the color stops in ascending order by offset,
  53467. // otherwise IE won't interpret it correctly.
  53468. var stops = fill.colorStops.slice();
  53469. stops.sort(function (cs1, cs2) {
  53470. return cs1.offset - cs2.offset;
  53471. });
  53472. var length$$1 = stops.length;
  53473. // Color and alpha list of first and last stop
  53474. var colorAndAlphaList = [];
  53475. var colors = [];
  53476. for (var i = 0; i < length$$1; i++) {
  53477. var stop = stops[i];
  53478. var colorAndAlpha = getColorAndAlpha(stop.color);
  53479. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  53480. if (i === 0 || i === length$$1 - 1) {
  53481. colorAndAlphaList.push(colorAndAlpha);
  53482. }
  53483. }
  53484. if (length$$1 >= 2) {
  53485. var color1 = colorAndAlphaList[0][0];
  53486. var color2 = colorAndAlphaList[1][0];
  53487. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  53488. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  53489. el.type = gradientType;
  53490. el.method = 'none';
  53491. el.focus = '100%';
  53492. el.angle = angle;
  53493. el.color = color1;
  53494. el.color2 = color2;
  53495. el.colors = colors.join(',');
  53496. // When colors attribute is used, the meanings of opacity and o:opacity2
  53497. // are reversed.
  53498. el.opacity = opacity2;
  53499. // FIXME g_o_:opacity ?
  53500. el.opacity2 = opacity1;
  53501. }
  53502. if (gradientType === 'radial') {
  53503. el.focusposition = focus.join(',');
  53504. }
  53505. }
  53506. else {
  53507. // FIXME Change from Gradient fill to color fill
  53508. setColorAndOpacity(el, fill, style.opacity);
  53509. }
  53510. }
  53511. };
  53512. var updateStrokeNode = function (el, style) {
  53513. // if (style.lineJoin != null) {
  53514. // el.joinstyle = style.lineJoin;
  53515. // }
  53516. // if (style.miterLimit != null) {
  53517. // el.miterlimit = style.miterLimit * Z;
  53518. // }
  53519. // if (style.lineCap != null) {
  53520. // el.endcap = style.lineCap;
  53521. // }
  53522. if (style.lineDash) {
  53523. el.dashstyle = style.lineDash.join(' ');
  53524. }
  53525. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  53526. setColorAndOpacity(el, style.stroke, style.opacity);
  53527. }
  53528. };
  53529. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  53530. var isFill = type === 'fill';
  53531. var el = vmlEl.getElementsByTagName(type)[0];
  53532. // Stroke must have lineWidth
  53533. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  53534. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  53535. // FIXME Remove before updating, or set `colors` will throw error
  53536. if (style[type] instanceof Gradient) {
  53537. remove(vmlEl, el);
  53538. }
  53539. if (!el) {
  53540. el = createNode(type);
  53541. }
  53542. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  53543. append(vmlEl, el);
  53544. }
  53545. else {
  53546. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  53547. remove(vmlEl, el);
  53548. }
  53549. };
  53550. var points$1 = [[], [], []];
  53551. var pathDataToString = function (path, m) {
  53552. var M = CMD$3.M;
  53553. var C = CMD$3.C;
  53554. var L = CMD$3.L;
  53555. var A = CMD$3.A;
  53556. var Q = CMD$3.Q;
  53557. var str = [];
  53558. var nPoint;
  53559. var cmdStr;
  53560. var cmd;
  53561. var i;
  53562. var xi;
  53563. var yi;
  53564. var data = path.data;
  53565. var dataLength = path.len();
  53566. for (i = 0; i < dataLength;) {
  53567. cmd = data[i++];
  53568. cmdStr = '';
  53569. nPoint = 0;
  53570. switch (cmd) {
  53571. case M:
  53572. cmdStr = ' m ';
  53573. nPoint = 1;
  53574. xi = data[i++];
  53575. yi = data[i++];
  53576. points$1[0][0] = xi;
  53577. points$1[0][1] = yi;
  53578. break;
  53579. case L:
  53580. cmdStr = ' l ';
  53581. nPoint = 1;
  53582. xi = data[i++];
  53583. yi = data[i++];
  53584. points$1[0][0] = xi;
  53585. points$1[0][1] = yi;
  53586. break;
  53587. case Q:
  53588. case C:
  53589. cmdStr = ' c ';
  53590. nPoint = 3;
  53591. var x1 = data[i++];
  53592. var y1 = data[i++];
  53593. var x2 = data[i++];
  53594. var y2 = data[i++];
  53595. var x3;
  53596. var y3;
  53597. if (cmd === Q) {
  53598. // Convert quadratic to cubic using degree elevation
  53599. x3 = x2;
  53600. y3 = y2;
  53601. x2 = (x2 + 2 * x1) / 3;
  53602. y2 = (y2 + 2 * y1) / 3;
  53603. x1 = (xi + 2 * x1) / 3;
  53604. y1 = (yi + 2 * y1) / 3;
  53605. }
  53606. else {
  53607. x3 = data[i++];
  53608. y3 = data[i++];
  53609. }
  53610. points$1[0][0] = x1;
  53611. points$1[0][1] = y1;
  53612. points$1[1][0] = x2;
  53613. points$1[1][1] = y2;
  53614. points$1[2][0] = x3;
  53615. points$1[2][1] = y3;
  53616. xi = x3;
  53617. yi = y3;
  53618. break;
  53619. case A:
  53620. var x = 0;
  53621. var y = 0;
  53622. var sx = 1;
  53623. var sy = 1;
  53624. var angle = 0;
  53625. if (m) {
  53626. // Extract SRT from matrix
  53627. x = m[4];
  53628. y = m[5];
  53629. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  53630. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  53631. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  53632. }
  53633. var cx = data[i++];
  53634. var cy = data[i++];
  53635. var rx = data[i++];
  53636. var ry = data[i++];
  53637. var startAngle = data[i++] + angle;
  53638. var endAngle = data[i++] + startAngle + angle;
  53639. // FIXME
  53640. // var psi = data[i++];
  53641. i++;
  53642. var clockwise = data[i++];
  53643. var x0 = cx + cos(startAngle) * rx;
  53644. var y0 = cy + sin(startAngle) * ry;
  53645. var x1 = cx + cos(endAngle) * rx;
  53646. var y1 = cy + sin(endAngle) * ry;
  53647. var type = clockwise ? ' wa ' : ' at ';
  53648. if (Math.abs(x0 - x1) < 1e-4) {
  53649. // IE won't render arches drawn counter clockwise if x0 == x1.
  53650. if (Math.abs(endAngle - startAngle) > 1e-2) {
  53651. // Offset x0 by 1/80 of a pixel. Use something
  53652. // that can be represented in binary
  53653. if (clockwise) {
  53654. x0 += 270 / Z;
  53655. }
  53656. }
  53657. else {
  53658. // Avoid case draw full circle
  53659. if (Math.abs(y0 - cy) < 1e-4) {
  53660. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  53661. y1 -= 270 / Z;
  53662. }
  53663. else {
  53664. y1 += 270 / Z;
  53665. }
  53666. }
  53667. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  53668. x1 += 270 / Z;
  53669. }
  53670. else {
  53671. x1 -= 270 / Z;
  53672. }
  53673. }
  53674. }
  53675. str.push(
  53676. type,
  53677. round$2(((cx - rx) * sx + x) * Z - Z2), comma,
  53678. round$2(((cy - ry) * sy + y) * Z - Z2), comma,
  53679. round$2(((cx + rx) * sx + x) * Z - Z2), comma,
  53680. round$2(((cy + ry) * sy + y) * Z - Z2), comma,
  53681. round$2((x0 * sx + x) * Z - Z2), comma,
  53682. round$2((y0 * sy + y) * Z - Z2), comma,
  53683. round$2((x1 * sx + x) * Z - Z2), comma,
  53684. round$2((y1 * sy + y) * Z - Z2)
  53685. );
  53686. xi = x1;
  53687. yi = y1;
  53688. break;
  53689. case CMD$3.R:
  53690. var p0 = points$1[0];
  53691. var p1 = points$1[1];
  53692. // x0, y0
  53693. p0[0] = data[i++];
  53694. p0[1] = data[i++];
  53695. // x1, y1
  53696. p1[0] = p0[0] + data[i++];
  53697. p1[1] = p0[1] + data[i++];
  53698. if (m) {
  53699. applyTransform(p0, p0, m);
  53700. applyTransform(p1, p1, m);
  53701. }
  53702. p0[0] = round$2(p0[0] * Z - Z2);
  53703. p1[0] = round$2(p1[0] * Z - Z2);
  53704. p0[1] = round$2(p0[1] * Z - Z2);
  53705. p1[1] = round$2(p1[1] * Z - Z2);
  53706. str.push(
  53707. // x0, y0
  53708. ' m ', p0[0], comma, p0[1],
  53709. // x1, y0
  53710. ' l ', p1[0], comma, p0[1],
  53711. // x1, y1
  53712. ' l ', p1[0], comma, p1[1],
  53713. // x0, y1
  53714. ' l ', p0[0], comma, p1[1]
  53715. );
  53716. break;
  53717. case CMD$3.Z:
  53718. // FIXME Update xi, yi
  53719. str.push(' x ');
  53720. }
  53721. if (nPoint > 0) {
  53722. str.push(cmdStr);
  53723. for (var k = 0; k < nPoint; k++) {
  53724. var p = points$1[k];
  53725. m && applyTransform(p, p, m);
  53726. // 不 round 会非常慢
  53727. str.push(
  53728. round$2(p[0] * Z - Z2), comma, round$2(p[1] * Z - Z2),
  53729. k < nPoint - 1 ? comma : ''
  53730. );
  53731. }
  53732. }
  53733. }
  53734. return str.join('');
  53735. };
  53736. // Rewrite the original path method
  53737. Path.prototype.brushVML = function (vmlRoot) {
  53738. var style = this.style;
  53739. var vmlEl = this._vmlEl;
  53740. if (!vmlEl) {
  53741. vmlEl = createNode('shape');
  53742. initRootElStyle(vmlEl);
  53743. this._vmlEl = vmlEl;
  53744. }
  53745. updateFillAndStroke(vmlEl, 'fill', style, this);
  53746. updateFillAndStroke(vmlEl, 'stroke', style, this);
  53747. var m = this.transform;
  53748. var needTransform = m != null;
  53749. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  53750. if (strokeEl) {
  53751. var lineWidth = style.lineWidth;
  53752. // Get the line scale.
  53753. // Determinant of this.m_ means how much the area is enlarged by the
  53754. // transformation. So its square root can be used as a scale factor
  53755. // for width.
  53756. if (needTransform && !style.strokeNoScale) {
  53757. var det = m[0] * m[3] - m[1] * m[2];
  53758. lineWidth *= sqrt(abs$1(det));
  53759. }
  53760. strokeEl.weight = lineWidth + 'px';
  53761. }
  53762. var path = this.path || (this.path = new PathProxy());
  53763. if (this.__dirtyPath) {
  53764. path.beginPath();
  53765. path.subPixelOptimize = false;
  53766. this.buildPath(path, this.shape);
  53767. path.toStatic();
  53768. this.__dirtyPath = false;
  53769. }
  53770. vmlEl.path = pathDataToString(path, this.transform);
  53771. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53772. // Append to root
  53773. append(vmlRoot, vmlEl);
  53774. // Text
  53775. if (style.text != null) {
  53776. this.drawRectText(vmlRoot, this.getBoundingRect());
  53777. }
  53778. else {
  53779. this.removeRectText(vmlRoot);
  53780. }
  53781. };
  53782. Path.prototype.onRemove = function (vmlRoot) {
  53783. remove(vmlRoot, this._vmlEl);
  53784. this.removeRectText(vmlRoot);
  53785. };
  53786. Path.prototype.onAdd = function (vmlRoot) {
  53787. append(vmlRoot, this._vmlEl);
  53788. this.appendRectText(vmlRoot);
  53789. };
  53790. /***************************************************
  53791. * IMAGE
  53792. **************************************************/
  53793. var isImage = function (img) {
  53794. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  53795. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  53796. // return img instanceof Image;
  53797. };
  53798. // Rewrite the original path method
  53799. ZImage.prototype.brushVML = function (vmlRoot) {
  53800. var style = this.style;
  53801. var image = style.image;
  53802. // Image original width, height
  53803. var ow;
  53804. var oh;
  53805. if (isImage(image)) {
  53806. var src = image.src;
  53807. if (src === this._imageSrc) {
  53808. ow = this._imageWidth;
  53809. oh = this._imageHeight;
  53810. }
  53811. else {
  53812. var imageRuntimeStyle = image.runtimeStyle;
  53813. var oldRuntimeWidth = imageRuntimeStyle.width;
  53814. var oldRuntimeHeight = imageRuntimeStyle.height;
  53815. imageRuntimeStyle.width = 'auto';
  53816. imageRuntimeStyle.height = 'auto';
  53817. // get the original size
  53818. ow = image.width;
  53819. oh = image.height;
  53820. // and remove overides
  53821. imageRuntimeStyle.width = oldRuntimeWidth;
  53822. imageRuntimeStyle.height = oldRuntimeHeight;
  53823. // Caching image original width, height and src
  53824. this._imageSrc = src;
  53825. this._imageWidth = ow;
  53826. this._imageHeight = oh;
  53827. }
  53828. image = src;
  53829. }
  53830. else {
  53831. if (image === this._imageSrc) {
  53832. ow = this._imageWidth;
  53833. oh = this._imageHeight;
  53834. }
  53835. }
  53836. if (!image) {
  53837. return;
  53838. }
  53839. var x = style.x || 0;
  53840. var y = style.y || 0;
  53841. var dw = style.width;
  53842. var dh = style.height;
  53843. var sw = style.sWidth;
  53844. var sh = style.sHeight;
  53845. var sx = style.sx || 0;
  53846. var sy = style.sy || 0;
  53847. var hasCrop = sw && sh;
  53848. var vmlEl = this._vmlEl;
  53849. if (!vmlEl) {
  53850. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  53851. // vmlEl = vmlCore.createNode('group');
  53852. vmlEl = doc.createElement('div');
  53853. initRootElStyle(vmlEl);
  53854. this._vmlEl = vmlEl;
  53855. }
  53856. var vmlElStyle = vmlEl.style;
  53857. var hasRotation = false;
  53858. var m;
  53859. var scaleX = 1;
  53860. var scaleY = 1;
  53861. if (this.transform) {
  53862. m = this.transform;
  53863. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  53864. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  53865. hasRotation = m[1] || m[2];
  53866. }
  53867. if (hasRotation) {
  53868. // If filters are necessary (rotation exists), create them
  53869. // filters are bog-slow, so only create them if abbsolutely necessary
  53870. // The following check doesn't account for skews (which don't exist
  53871. // in the canvas spec (yet) anyway.
  53872. // From excanvas
  53873. var p0 = [x, y];
  53874. var p1 = [x + dw, y];
  53875. var p2 = [x, y + dh];
  53876. var p3 = [x + dw, y + dh];
  53877. applyTransform(p0, p0, m);
  53878. applyTransform(p1, p1, m);
  53879. applyTransform(p2, p2, m);
  53880. applyTransform(p3, p3, m);
  53881. var maxX = mathMax$6(p0[0], p1[0], p2[0], p3[0]);
  53882. var maxY = mathMax$6(p0[1], p1[1], p2[1], p3[1]);
  53883. var transformFilter = [];
  53884. transformFilter.push('M11=', m[0] / scaleX, comma,
  53885. 'M12=', m[2] / scaleY, comma,
  53886. 'M21=', m[1] / scaleX, comma,
  53887. 'M22=', m[3] / scaleY, comma,
  53888. 'Dx=', round$2(x * scaleX + m[4]), comma,
  53889. 'Dy=', round$2(y * scaleY + m[5]));
  53890. vmlElStyle.padding = '0 ' + round$2(maxX) + 'px ' + round$2(maxY) + 'px 0';
  53891. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  53892. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  53893. + transformFilter.join('') + ', SizingMethod=clip)';
  53894. }
  53895. else {
  53896. if (m) {
  53897. x = x * scaleX + m[4];
  53898. y = y * scaleY + m[5];
  53899. }
  53900. vmlElStyle.filter = '';
  53901. vmlElStyle.left = round$2(x) + 'px';
  53902. vmlElStyle.top = round$2(y) + 'px';
  53903. }
  53904. var imageEl = this._imageEl;
  53905. var cropEl = this._cropEl;
  53906. if (!imageEl) {
  53907. imageEl = doc.createElement('div');
  53908. this._imageEl = imageEl;
  53909. }
  53910. var imageELStyle = imageEl.style;
  53911. if (hasCrop) {
  53912. // Needs know image original width and height
  53913. if (!(ow && oh)) {
  53914. var tmpImage = new Image();
  53915. var self = this;
  53916. tmpImage.onload = function () {
  53917. tmpImage.onload = null;
  53918. ow = tmpImage.width;
  53919. oh = tmpImage.height;
  53920. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  53921. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  53922. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  53923. // Caching image original width, height and src
  53924. self._imageWidth = ow;
  53925. self._imageHeight = oh;
  53926. self._imageSrc = image;
  53927. };
  53928. tmpImage.src = image;
  53929. }
  53930. else {
  53931. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  53932. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  53933. }
  53934. if (!cropEl) {
  53935. cropEl = doc.createElement('div');
  53936. cropEl.style.overflow = 'hidden';
  53937. this._cropEl = cropEl;
  53938. }
  53939. var cropElStyle = cropEl.style;
  53940. cropElStyle.width = round$2((dw + sx * dw / sw) * scaleX);
  53941. cropElStyle.height = round$2((dh + sy * dh / sh) * scaleY);
  53942. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  53943. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  53944. if (!cropEl.parentNode) {
  53945. vmlEl.appendChild(cropEl);
  53946. }
  53947. if (imageEl.parentNode !== cropEl) {
  53948. cropEl.appendChild(imageEl);
  53949. }
  53950. }
  53951. else {
  53952. imageELStyle.width = round$2(scaleX * dw) + 'px';
  53953. imageELStyle.height = round$2(scaleY * dh) + 'px';
  53954. vmlEl.appendChild(imageEl);
  53955. if (cropEl && cropEl.parentNode) {
  53956. vmlEl.removeChild(cropEl);
  53957. this._cropEl = null;
  53958. }
  53959. }
  53960. var filterStr = '';
  53961. var alpha = style.opacity;
  53962. if (alpha < 1) {
  53963. filterStr += '.Alpha(opacity=' + round$2(alpha * 100) + ') ';
  53964. }
  53965. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  53966. imageELStyle.filter = filterStr;
  53967. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53968. // Append to root
  53969. append(vmlRoot, vmlEl);
  53970. // Text
  53971. if (style.text != null) {
  53972. this.drawRectText(vmlRoot, this.getBoundingRect());
  53973. }
  53974. };
  53975. ZImage.prototype.onRemove = function (vmlRoot) {
  53976. remove(vmlRoot, this._vmlEl);
  53977. this._vmlEl = null;
  53978. this._cropEl = null;
  53979. this._imageEl = null;
  53980. this.removeRectText(vmlRoot);
  53981. };
  53982. ZImage.prototype.onAdd = function (vmlRoot) {
  53983. append(vmlRoot, this._vmlEl);
  53984. this.appendRectText(vmlRoot);
  53985. };
  53986. /***************************************************
  53987. * TEXT
  53988. **************************************************/
  53989. var DEFAULT_STYLE_NORMAL = 'normal';
  53990. var fontStyleCache = {};
  53991. var fontStyleCacheCount = 0;
  53992. var MAX_FONT_CACHE_SIZE = 100;
  53993. var fontEl = document.createElement('div');
  53994. var getFontStyle = function (fontString) {
  53995. var fontStyle = fontStyleCache[fontString];
  53996. if (!fontStyle) {
  53997. // Clear cache
  53998. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  53999. fontStyleCacheCount = 0;
  54000. fontStyleCache = {};
  54001. }
  54002. var style = fontEl.style;
  54003. var fontFamily;
  54004. try {
  54005. style.font = fontString;
  54006. fontFamily = style.fontFamily.split(',')[0];
  54007. }
  54008. catch (e) {
  54009. }
  54010. fontStyle = {
  54011. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  54012. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  54013. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  54014. size: parseFloat(style.fontSize || 12) | 0,
  54015. family: fontFamily || 'Microsoft YaHei'
  54016. };
  54017. fontStyleCache[fontString] = fontStyle;
  54018. fontStyleCacheCount++;
  54019. }
  54020. return fontStyle;
  54021. };
  54022. var textMeasureEl;
  54023. // Overwrite measure text method
  54024. $override$1('measureText', function (text, textFont) {
  54025. var doc$$1 = doc;
  54026. if (!textMeasureEl) {
  54027. textMeasureEl = doc$$1.createElement('div');
  54028. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  54029. + 'padding:0;margin:0;border:none;white-space:pre;';
  54030. doc.body.appendChild(textMeasureEl);
  54031. }
  54032. try {
  54033. textMeasureEl.style.font = textFont;
  54034. }
  54035. catch (ex) {
  54036. // Ignore failures to set to invalid font.
  54037. }
  54038. textMeasureEl.innerHTML = '';
  54039. // Don't use innerHTML or innerText because they allow markup/whitespace.
  54040. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  54041. return {
  54042. width: textMeasureEl.offsetWidth
  54043. };
  54044. });
  54045. var tmpRect$2 = new BoundingRect();
  54046. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  54047. var style = this.style;
  54048. // Optimize, avoid normalize every time.
  54049. this.__dirty && normalizeTextStyle(style, true);
  54050. var text = style.text;
  54051. // Convert to string
  54052. text != null && (text += '');
  54053. if (!text) {
  54054. return;
  54055. }
  54056. // Convert rich text to plain text. Rich text is not supported in
  54057. // IE8-, but tags in rich text template will be removed.
  54058. if (style.rich) {
  54059. var contentBlock = parseRichText(text, style);
  54060. text = [];
  54061. for (var i = 0; i < contentBlock.lines.length; i++) {
  54062. var tokens = contentBlock.lines[i].tokens;
  54063. var textLine = [];
  54064. for (var j = 0; j < tokens.length; j++) {
  54065. textLine.push(tokens[j].text);
  54066. }
  54067. text.push(textLine.join(''));
  54068. }
  54069. text = text.join('\n');
  54070. }
  54071. var x;
  54072. var y;
  54073. var align = style.textAlign;
  54074. var verticalAlign = style.textVerticalAlign;
  54075. var fontStyle = getFontStyle(style.font);
  54076. // FIXME encodeHtmlAttribute ?
  54077. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  54078. + fontStyle.size + 'px "' + fontStyle.family + '"';
  54079. textRect = textRect || getBoundingRect(
  54080. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  54081. );
  54082. // Transform rect to view space
  54083. var m = this.transform;
  54084. // Ignore transform for text in other element
  54085. if (m && !fromTextEl) {
  54086. tmpRect$2.copy(rect);
  54087. tmpRect$2.applyTransform(m);
  54088. rect = tmpRect$2;
  54089. }
  54090. if (!fromTextEl) {
  54091. var textPosition = style.textPosition;
  54092. // Text position represented by coord
  54093. if (textPosition instanceof Array) {
  54094. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  54095. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  54096. align = align || 'left';
  54097. }
  54098. else {
  54099. var res = this.calculateTextPosition
  54100. ? this.calculateTextPosition({}, style, rect)
  54101. : calculateTextPosition({}, style, rect);
  54102. x = res.x;
  54103. y = res.y;
  54104. // Default align and baseline when has textPosition
  54105. align = align || res.textAlign;
  54106. verticalAlign = verticalAlign || res.textVerticalAlign;
  54107. }
  54108. }
  54109. else {
  54110. x = rect.x;
  54111. y = rect.y;
  54112. }
  54113. x = adjustTextX(x, textRect.width, align);
  54114. y = adjustTextY(y, textRect.height, verticalAlign);
  54115. // Force baseline 'middle'
  54116. y += textRect.height / 2;
  54117. // var fontSize = fontStyle.size;
  54118. // 1.75 is an arbitrary number, as there is no info about the text baseline
  54119. // switch (baseline) {
  54120. // case 'hanging':
  54121. // case 'top':
  54122. // y += fontSize / 1.75;
  54123. // break;
  54124. // case 'middle':
  54125. // break;
  54126. // default:
  54127. // // case null:
  54128. // // case 'alphabetic':
  54129. // // case 'ideographic':
  54130. // // case 'bottom':
  54131. // y -= fontSize / 2.25;
  54132. // break;
  54133. // }
  54134. // switch (align) {
  54135. // case 'left':
  54136. // break;
  54137. // case 'center':
  54138. // x -= textRect.width / 2;
  54139. // break;
  54140. // case 'right':
  54141. // x -= textRect.width;
  54142. // break;
  54143. // case 'end':
  54144. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  54145. // break;
  54146. // case 'start':
  54147. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  54148. // break;
  54149. // default:
  54150. // align = 'left';
  54151. // }
  54152. var createNode$$1 = createNode;
  54153. var textVmlEl = this._textVmlEl;
  54154. var pathEl;
  54155. var textPathEl;
  54156. var skewEl;
  54157. if (!textVmlEl) {
  54158. textVmlEl = createNode$$1('line');
  54159. pathEl = createNode$$1('path');
  54160. textPathEl = createNode$$1('textpath');
  54161. skewEl = createNode$$1('skew');
  54162. // FIXME Why here is not cammel case
  54163. // Align 'center' seems wrong
  54164. textPathEl.style['v-text-align'] = 'left';
  54165. initRootElStyle(textVmlEl);
  54166. pathEl.textpathok = true;
  54167. textPathEl.on = true;
  54168. textVmlEl.from = '0 0';
  54169. textVmlEl.to = '1000 0.05';
  54170. append(textVmlEl, skewEl);
  54171. append(textVmlEl, pathEl);
  54172. append(textVmlEl, textPathEl);
  54173. this._textVmlEl = textVmlEl;
  54174. }
  54175. else {
  54176. // 这里是在前面 appendChild 保证顺序的前提下
  54177. skewEl = textVmlEl.firstChild;
  54178. pathEl = skewEl.nextSibling;
  54179. textPathEl = pathEl.nextSibling;
  54180. }
  54181. var coords = [x, y];
  54182. var textVmlElStyle = textVmlEl.style;
  54183. // Ignore transform for text in other element
  54184. if (m && fromTextEl) {
  54185. applyTransform(coords, coords, m);
  54186. skewEl.on = true;
  54187. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  54188. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  54189. // Text position
  54190. skewEl.offset = (round$2(coords[0]) || 0) + ',' + (round$2(coords[1]) || 0);
  54191. // Left top point as origin
  54192. skewEl.origin = '0 0';
  54193. textVmlElStyle.left = '0px';
  54194. textVmlElStyle.top = '0px';
  54195. }
  54196. else {
  54197. skewEl.on = false;
  54198. textVmlElStyle.left = round$2(x) + 'px';
  54199. textVmlElStyle.top = round$2(y) + 'px';
  54200. }
  54201. textPathEl.string = encodeHtmlAttribute(text);
  54202. // TODO
  54203. try {
  54204. textPathEl.style.font = font;
  54205. }
  54206. // Error font format
  54207. catch (e) {}
  54208. updateFillAndStroke(textVmlEl, 'fill', {
  54209. fill: style.textFill,
  54210. opacity: style.opacity
  54211. }, this);
  54212. updateFillAndStroke(textVmlEl, 'stroke', {
  54213. stroke: style.textStroke,
  54214. opacity: style.opacity,
  54215. lineDash: style.lineDash || null // style.lineDash can be `false`.
  54216. }, this);
  54217. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  54218. // Attached to root
  54219. append(vmlRoot, textVmlEl);
  54220. };
  54221. var removeRectText = function (vmlRoot) {
  54222. remove(vmlRoot, this._textVmlEl);
  54223. this._textVmlEl = null;
  54224. };
  54225. var appendRectText = function (vmlRoot) {
  54226. append(vmlRoot, this._textVmlEl);
  54227. };
  54228. var list = [RectText, Displayable, ZImage, Path, Text];
  54229. // In case Displayable has been mixed in RectText
  54230. for (var i$1 = 0; i$1 < list.length; i$1++) {
  54231. var proto$7 = list[i$1].prototype;
  54232. proto$7.drawRectText = drawRectText;
  54233. proto$7.removeRectText = removeRectText;
  54234. proto$7.appendRectText = appendRectText;
  54235. }
  54236. Text.prototype.brushVML = function (vmlRoot) {
  54237. var style = this.style;
  54238. if (style.text != null) {
  54239. this.drawRectText(vmlRoot, {
  54240. x: style.x || 0, y: style.y || 0,
  54241. width: 0, height: 0
  54242. }, this.getBoundingRect(), true);
  54243. }
  54244. else {
  54245. this.removeRectText(vmlRoot);
  54246. }
  54247. };
  54248. Text.prototype.onRemove = function (vmlRoot) {
  54249. this.removeRectText(vmlRoot);
  54250. };
  54251. Text.prototype.onAdd = function (vmlRoot) {
  54252. this.appendRectText(vmlRoot);
  54253. };
  54254. }
  54255. /**
  54256. * VML Painter.
  54257. *
  54258. * @module zrender/vml/Painter
  54259. */
  54260. function parseInt10$1(val) {
  54261. return parseInt(val, 10);
  54262. }
  54263. /**
  54264. * @alias module:zrender/vml/Painter
  54265. */
  54266. function VMLPainter(root, storage) {
  54267. initVML();
  54268. this.root = root;
  54269. this.storage = storage;
  54270. var vmlViewport = document.createElement('div');
  54271. var vmlRoot = document.createElement('div');
  54272. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  54273. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  54274. root.appendChild(vmlViewport);
  54275. this._vmlRoot = vmlRoot;
  54276. this._vmlViewport = vmlViewport;
  54277. this.resize();
  54278. // Modify storage
  54279. var oldDelFromStorage = storage.delFromStorage;
  54280. var oldAddToStorage = storage.addToStorage;
  54281. storage.delFromStorage = function (el) {
  54282. oldDelFromStorage.call(storage, el);
  54283. if (el) {
  54284. el.onRemove && el.onRemove(vmlRoot);
  54285. }
  54286. };
  54287. storage.addToStorage = function (el) {
  54288. // Displayable already has a vml node
  54289. el.onAdd && el.onAdd(vmlRoot);
  54290. oldAddToStorage.call(storage, el);
  54291. };
  54292. this._firstPaint = true;
  54293. }
  54294. VMLPainter.prototype = {
  54295. constructor: VMLPainter,
  54296. getType: function () {
  54297. return 'vml';
  54298. },
  54299. /**
  54300. * @return {HTMLDivElement}
  54301. */
  54302. getViewportRoot: function () {
  54303. return this._vmlViewport;
  54304. },
  54305. getViewportRootOffset: function () {
  54306. var viewportRoot = this.getViewportRoot();
  54307. if (viewportRoot) {
  54308. return {
  54309. offsetLeft: viewportRoot.offsetLeft || 0,
  54310. offsetTop: viewportRoot.offsetTop || 0
  54311. };
  54312. }
  54313. },
  54314. /**
  54315. * 刷新
  54316. */
  54317. refresh: function () {
  54318. var list = this.storage.getDisplayList(true, true);
  54319. this._paintList(list);
  54320. },
  54321. _paintList: function (list) {
  54322. var vmlRoot = this._vmlRoot;
  54323. for (var i = 0; i < list.length; i++) {
  54324. var el = list[i];
  54325. if (el.invisible || el.ignore) {
  54326. if (!el.__alreadyNotVisible) {
  54327. el.onRemove(vmlRoot);
  54328. }
  54329. // Set as already invisible
  54330. el.__alreadyNotVisible = true;
  54331. }
  54332. else {
  54333. if (el.__alreadyNotVisible) {
  54334. el.onAdd(vmlRoot);
  54335. }
  54336. el.__alreadyNotVisible = false;
  54337. if (el.__dirty) {
  54338. el.beforeBrush && el.beforeBrush();
  54339. (el.brushVML || el.brush).call(el, vmlRoot);
  54340. el.afterBrush && el.afterBrush();
  54341. }
  54342. }
  54343. el.__dirty = false;
  54344. }
  54345. if (this._firstPaint) {
  54346. // Detached from document at first time
  54347. // to avoid page refreshing too many times
  54348. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  54349. this._vmlViewport.appendChild(vmlRoot);
  54350. this._firstPaint = false;
  54351. }
  54352. },
  54353. resize: function (width, height) {
  54354. var width = width == null ? this._getWidth() : width;
  54355. var height = height == null ? this._getHeight() : height;
  54356. if (this._width !== width || this._height !== height) {
  54357. this._width = width;
  54358. this._height = height;
  54359. var vmlViewportStyle = this._vmlViewport.style;
  54360. vmlViewportStyle.width = width + 'px';
  54361. vmlViewportStyle.height = height + 'px';
  54362. }
  54363. },
  54364. dispose: function () {
  54365. this.root.innerHTML = '';
  54366. this._vmlRoot =
  54367. this._vmlViewport =
  54368. this.storage = null;
  54369. },
  54370. getWidth: function () {
  54371. return this._width;
  54372. },
  54373. getHeight: function () {
  54374. return this._height;
  54375. },
  54376. clear: function () {
  54377. if (this._vmlViewport) {
  54378. this.root.removeChild(this._vmlViewport);
  54379. }
  54380. },
  54381. _getWidth: function () {
  54382. var root = this.root;
  54383. var stl = root.currentStyle;
  54384. return ((root.clientWidth || parseInt10$1(stl.width))
  54385. - parseInt10$1(stl.paddingLeft)
  54386. - parseInt10$1(stl.paddingRight)) | 0;
  54387. },
  54388. _getHeight: function () {
  54389. var root = this.root;
  54390. var stl = root.currentStyle;
  54391. return ((root.clientHeight || parseInt10$1(stl.height))
  54392. - parseInt10$1(stl.paddingTop)
  54393. - parseInt10$1(stl.paddingBottom)) | 0;
  54394. }
  54395. };
  54396. // Not supported methods
  54397. function createMethodNotSupport(method) {
  54398. return function () {
  54399. logError$1('In IE8.0 VML mode painter not support method "' + method + '"');
  54400. };
  54401. }
  54402. // Unsupported methods
  54403. each$1([
  54404. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  54405. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  54406. ], function (name) {
  54407. VMLPainter.prototype[name] = createMethodNotSupport(name);
  54408. });
  54409. registerPainter('vml', VMLPainter);
  54410. var svgURI = 'http://www.w3.org/2000/svg';
  54411. function createElement(name) {
  54412. return document.createElementNS(svgURI, name);
  54413. }
  54414. // TODO
  54415. // 1. shadow
  54416. // 2. Image: sx, sy, sw, sh
  54417. var CMD$4 = PathProxy.CMD;
  54418. var arrayJoin = Array.prototype.join;
  54419. var NONE = 'none';
  54420. var mathRound = Math.round;
  54421. var mathSin$3 = Math.sin;
  54422. var mathCos$3 = Math.cos;
  54423. var PI$3 = Math.PI;
  54424. var PI2$5 = Math.PI * 2;
  54425. var degree = 180 / PI$3;
  54426. var EPSILON$4 = 1e-4;
  54427. function round4(val) {
  54428. return mathRound(val * 1e4) / 1e4;
  54429. }
  54430. function isAroundZero$1(val) {
  54431. return val < EPSILON$4 && val > -EPSILON$4;
  54432. }
  54433. function pathHasFill(style, isText) {
  54434. var fill = isText ? style.textFill : style.fill;
  54435. return fill != null && fill !== NONE;
  54436. }
  54437. function pathHasStroke(style, isText) {
  54438. var stroke = isText ? style.textStroke : style.stroke;
  54439. return stroke != null && stroke !== NONE;
  54440. }
  54441. function setTransform(svgEl, m) {
  54442. if (m) {
  54443. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  54444. }
  54445. }
  54446. function attr(el, key, val) {
  54447. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  54448. // Don't set attribute for gradient, since it need new dom nodes
  54449. el.setAttribute(key, val);
  54450. }
  54451. }
  54452. function attrXLink(el, key, val) {
  54453. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  54454. }
  54455. function bindStyle(svgEl, style, isText, el) {
  54456. if (pathHasFill(style, isText)) {
  54457. var fill = isText ? style.textFill : style.fill;
  54458. fill = fill === 'transparent' ? NONE : fill;
  54459. attr(svgEl, 'fill', fill);
  54460. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  54461. }
  54462. else {
  54463. attr(svgEl, 'fill', NONE);
  54464. }
  54465. if (pathHasStroke(style, isText)) {
  54466. var stroke = isText ? style.textStroke : style.stroke;
  54467. stroke = stroke === 'transparent' ? NONE : stroke;
  54468. attr(svgEl, 'stroke', stroke);
  54469. var strokeWidth = isText
  54470. ? style.textStrokeWidth
  54471. : style.lineWidth;
  54472. var strokeScale = !isText && style.strokeNoScale
  54473. ? el.getLineScale()
  54474. : 1;
  54475. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  54476. // stroke then fill for text; fill then stroke for others
  54477. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  54478. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  54479. var lineDash = style.lineDash;
  54480. if (lineDash) {
  54481. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  54482. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  54483. }
  54484. else {
  54485. attr(svgEl, 'stroke-dasharray', '');
  54486. }
  54487. // PENDING
  54488. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  54489. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  54490. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  54491. }
  54492. else {
  54493. attr(svgEl, 'stroke', NONE);
  54494. }
  54495. }
  54496. /***************************************************
  54497. * PATH
  54498. **************************************************/
  54499. function pathDataToString$1(path) {
  54500. var str = [];
  54501. var data = path.data;
  54502. var dataLength = path.len();
  54503. for (var i = 0; i < dataLength;) {
  54504. var cmd = data[i++];
  54505. var cmdStr = '';
  54506. var nData = 0;
  54507. switch (cmd) {
  54508. case CMD$4.M:
  54509. cmdStr = 'M';
  54510. nData = 2;
  54511. break;
  54512. case CMD$4.L:
  54513. cmdStr = 'L';
  54514. nData = 2;
  54515. break;
  54516. case CMD$4.Q:
  54517. cmdStr = 'Q';
  54518. nData = 4;
  54519. break;
  54520. case CMD$4.C:
  54521. cmdStr = 'C';
  54522. nData = 6;
  54523. break;
  54524. case CMD$4.A:
  54525. var cx = data[i++];
  54526. var cy = data[i++];
  54527. var rx = data[i++];
  54528. var ry = data[i++];
  54529. var theta = data[i++];
  54530. var dTheta = data[i++];
  54531. var psi = data[i++];
  54532. var clockwise = data[i++];
  54533. var dThetaPositive = Math.abs(dTheta);
  54534. var isCircle = isAroundZero$1(dThetaPositive - PI2$5)
  54535. || (clockwise ? dTheta >= PI2$5 : -dTheta >= PI2$5);
  54536. // Mapping to 0~2PI
  54537. var unifiedTheta = dTheta > 0 ? dTheta % PI2$5 : (dTheta % PI2$5 + PI2$5);
  54538. var large = false;
  54539. if (isCircle) {
  54540. large = true;
  54541. }
  54542. else if (isAroundZero$1(dThetaPositive)) {
  54543. large = false;
  54544. }
  54545. else {
  54546. large = (unifiedTheta >= PI$3) === !!clockwise;
  54547. }
  54548. var x0 = round4(cx + rx * mathCos$3(theta));
  54549. var y0 = round4(cy + ry * mathSin$3(theta));
  54550. // It will not draw if start point and end point are exactly the same
  54551. // We need to shift the end point with a small value
  54552. // FIXME A better way to draw circle ?
  54553. if (isCircle) {
  54554. if (clockwise) {
  54555. dTheta = PI2$5 - 1e-4;
  54556. }
  54557. else {
  54558. dTheta = -PI2$5 + 1e-4;
  54559. }
  54560. large = true;
  54561. if (i === 9) {
  54562. // Move to (x0, y0) only when CMD.A comes at the
  54563. // first position of a shape.
  54564. // For instance, when drawing a ring, CMD.A comes
  54565. // after CMD.M, so it's unnecessary to move to
  54566. // (x0, y0).
  54567. str.push('M', x0, y0);
  54568. }
  54569. }
  54570. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  54571. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  54572. // FIXME Ellipse
  54573. str.push('A', round4(rx), round4(ry),
  54574. mathRound(psi * degree), +large, +clockwise, x, y);
  54575. break;
  54576. case CMD$4.Z:
  54577. cmdStr = 'Z';
  54578. break;
  54579. case CMD$4.R:
  54580. var x = round4(data[i++]);
  54581. var y = round4(data[i++]);
  54582. var w = round4(data[i++]);
  54583. var h = round4(data[i++]);
  54584. str.push(
  54585. 'M', x, y,
  54586. 'L', x + w, y,
  54587. 'L', x + w, y + h,
  54588. 'L', x, y + h,
  54589. 'L', x, y
  54590. );
  54591. break;
  54592. }
  54593. cmdStr && str.push(cmdStr);
  54594. for (var j = 0; j < nData; j++) {
  54595. // PENDING With scale
  54596. str.push(round4(data[i++]));
  54597. }
  54598. }
  54599. return str.join(' ');
  54600. }
  54601. var svgPath = {};
  54602. svgPath.brush = function (el) {
  54603. var style = el.style;
  54604. var svgEl = el.__svgEl;
  54605. if (!svgEl) {
  54606. svgEl = createElement('path');
  54607. el.__svgEl = svgEl;
  54608. }
  54609. if (!el.path) {
  54610. el.createPathProxy();
  54611. }
  54612. var path = el.path;
  54613. if (el.__dirtyPath) {
  54614. path.beginPath();
  54615. path.subPixelOptimize = false;
  54616. el.buildPath(path, el.shape);
  54617. el.__dirtyPath = false;
  54618. var pathStr = pathDataToString$1(path);
  54619. if (pathStr.indexOf('NaN') < 0) {
  54620. // Ignore illegal path, which may happen such in out-of-range
  54621. // data in Calendar series.
  54622. attr(svgEl, 'd', pathStr);
  54623. }
  54624. }
  54625. bindStyle(svgEl, style, false, el);
  54626. setTransform(svgEl, el.transform);
  54627. if (style.text != null) {
  54628. svgTextDrawRectText(el, el.getBoundingRect());
  54629. }
  54630. else {
  54631. removeOldTextNode(el);
  54632. }
  54633. };
  54634. /***************************************************
  54635. * IMAGE
  54636. **************************************************/
  54637. var svgImage = {};
  54638. svgImage.brush = function (el) {
  54639. var style = el.style;
  54640. var image = style.image;
  54641. if (image instanceof HTMLImageElement) {
  54642. var src = image.src;
  54643. image = src;
  54644. }
  54645. if (!image) {
  54646. return;
  54647. }
  54648. var x = style.x || 0;
  54649. var y = style.y || 0;
  54650. var dw = style.width;
  54651. var dh = style.height;
  54652. var svgEl = el.__svgEl;
  54653. if (!svgEl) {
  54654. svgEl = createElement('image');
  54655. el.__svgEl = svgEl;
  54656. }
  54657. if (image !== el.__imageSrc) {
  54658. attrXLink(svgEl, 'href', image);
  54659. // Caching image src
  54660. el.__imageSrc = image;
  54661. }
  54662. attr(svgEl, 'width', dw);
  54663. attr(svgEl, 'height', dh);
  54664. attr(svgEl, 'x', x);
  54665. attr(svgEl, 'y', y);
  54666. setTransform(svgEl, el.transform);
  54667. if (style.text != null) {
  54668. svgTextDrawRectText(el, el.getBoundingRect());
  54669. }
  54670. else {
  54671. removeOldTextNode(el);
  54672. }
  54673. };
  54674. /***************************************************
  54675. * TEXT
  54676. **************************************************/
  54677. var svgText = {};
  54678. var _tmpTextHostRect = new BoundingRect();
  54679. var _tmpTextBoxPos = {};
  54680. var _tmpTextTransform = [];
  54681. var TEXT_ALIGN_TO_ANCHRO = {
  54682. left: 'start',
  54683. right: 'end',
  54684. center: 'middle',
  54685. middle: 'middle'
  54686. };
  54687. /**
  54688. * @param {module:zrender/Element} el
  54689. * @param {Object|boolean} [hostRect] {x, y, width, height}
  54690. * If set false, rect text is not used.
  54691. */
  54692. var svgTextDrawRectText = function (el, hostRect) {
  54693. var style = el.style;
  54694. var elTransform = el.transform;
  54695. var needTransformTextByHostEl = el instanceof Text || style.transformText;
  54696. el.__dirty && normalizeTextStyle(style, true);
  54697. var text = style.text;
  54698. // Convert to string
  54699. text != null && (text += '');
  54700. if (!needDrawText(text, style)) {
  54701. return;
  54702. }
  54703. // render empty text for svg if no text but need draw text.
  54704. text == null && (text = '');
  54705. // Follow the setting in the canvas renderer, if not transform the
  54706. // text, transform the hostRect, by which the text is located.
  54707. if (!needTransformTextByHostEl && elTransform) {
  54708. _tmpTextHostRect.copy(hostRect);
  54709. _tmpTextHostRect.applyTransform(elTransform);
  54710. hostRect = _tmpTextHostRect;
  54711. }
  54712. var textSvgEl = el.__textSvgEl;
  54713. if (!textSvgEl) {
  54714. textSvgEl = createElement('text');
  54715. el.__textSvgEl = textSvgEl;
  54716. }
  54717. // style.font has been normalized by `normalizeTextStyle`.
  54718. var textSvgElStyle = textSvgEl.style;
  54719. var font = style.font || DEFAULT_FONT$1;
  54720. var computedFont = textSvgEl.__computedFont;
  54721. if (font !== textSvgEl.__styleFont) {
  54722. textSvgElStyle.font = textSvgEl.__styleFont = font;
  54723. // The computedFont might not be the orginal font if it is illegal font.
  54724. computedFont = textSvgEl.__computedFont = textSvgElStyle.font;
  54725. }
  54726. var textPadding = style.textPadding;
  54727. var textLineHeight = style.textLineHeight;
  54728. var contentBlock = el.__textCotentBlock;
  54729. if (!contentBlock || el.__dirtyText) {
  54730. contentBlock = el.__textCotentBlock = parsePlainText(
  54731. text, computedFont, textPadding, textLineHeight, style.truncate
  54732. );
  54733. }
  54734. var outerHeight = contentBlock.outerHeight;
  54735. var lineHeight = contentBlock.lineHeight;
  54736. getBoxPosition(_tmpTextBoxPos, el, style, hostRect);
  54737. var baseX = _tmpTextBoxPos.baseX;
  54738. var baseY = _tmpTextBoxPos.baseY;
  54739. var textAlign = _tmpTextBoxPos.textAlign || 'left';
  54740. var textVerticalAlign = _tmpTextBoxPos.textVerticalAlign;
  54741. setTextTransform(
  54742. textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY
  54743. );
  54744. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  54745. var textX = baseX;
  54746. var textY = boxY;
  54747. // TODO needDrawBg
  54748. if (textPadding) {
  54749. textX = getTextXForPadding$1(baseX, textAlign, textPadding);
  54750. textY += textPadding[0];
  54751. }
  54752. // `textBaseline` is set as 'middle'.
  54753. textY += lineHeight / 2;
  54754. bindStyle(textSvgEl, style, true, el);
  54755. // FIXME
  54756. // Add a <style> to reset all of the text font as inherit?
  54757. // otherwise the outer <style> may set the unexpected style.
  54758. // Font may affect position of each tspan elements
  54759. var canCacheByTextString = contentBlock.canCacheByTextString;
  54760. var tspanList = el.__tspanList || (el.__tspanList = []);
  54761. var tspanOriginLen = tspanList.length;
  54762. // Optimize for most cases, just compare text string to determine change.
  54763. if (canCacheByTextString && el.__canCacheByTextString && el.__text === text) {
  54764. if (el.__dirtyText && tspanOriginLen) {
  54765. for (var idx = 0; idx < tspanOriginLen; ++idx) {
  54766. updateTextLocation(tspanList[idx], textAlign, textX, textY + idx * lineHeight);
  54767. }
  54768. }
  54769. }
  54770. else {
  54771. el.__text = text;
  54772. el.__canCacheByTextString = canCacheByTextString;
  54773. var textLines = contentBlock.lines;
  54774. var nTextLines = textLines.length;
  54775. var idx = 0;
  54776. for (; idx < nTextLines; idx++) {
  54777. // Using cached tspan elements
  54778. var tspan = tspanList[idx];
  54779. var singleLineText = textLines[idx];
  54780. if (!tspan) {
  54781. tspan = tspanList[idx] = createElement('tspan');
  54782. textSvgEl.appendChild(tspan);
  54783. tspan.appendChild(document.createTextNode(singleLineText));
  54784. }
  54785. else if (tspan.__zrText !== singleLineText) {
  54786. tspan.innerHTML = '';
  54787. tspan.appendChild(document.createTextNode(singleLineText));
  54788. }
  54789. updateTextLocation(tspan, textAlign, textX, textY + idx * lineHeight);
  54790. }
  54791. // Remove unused tspan elements
  54792. if (tspanOriginLen > nTextLines) {
  54793. for (; idx < tspanOriginLen; idx++) {
  54794. textSvgEl.removeChild(tspanList[idx]);
  54795. }
  54796. tspanList.length = nTextLines;
  54797. }
  54798. }
  54799. };
  54800. function setTextTransform(textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY) {
  54801. identity(_tmpTextTransform);
  54802. if (needTransformTextByHostEl && elTransform) {
  54803. copy$1(_tmpTextTransform, elTransform);
  54804. }
  54805. // textRotation only apply in RectText.
  54806. var textRotation = style.textRotation;
  54807. if (hostRect && textRotation) {
  54808. var origin = style.textOrigin;
  54809. if (origin === 'center') {
  54810. baseX = hostRect.width / 2 + hostRect.x;
  54811. baseY = hostRect.height / 2 + hostRect.y;
  54812. }
  54813. else if (origin) {
  54814. baseX = origin[0] + hostRect.x;
  54815. baseY = origin[1] + hostRect.y;
  54816. }
  54817. _tmpTextTransform[4] -= baseX;
  54818. _tmpTextTransform[5] -= baseY;
  54819. // Positive: anticlockwise
  54820. rotate(_tmpTextTransform, _tmpTextTransform, textRotation);
  54821. _tmpTextTransform[4] += baseX;
  54822. _tmpTextTransform[5] += baseY;
  54823. }
  54824. // See the definition in `Style.js#textOrigin`, the default
  54825. // origin is from the result of `getBoxPosition`.
  54826. setTransform(textSvgEl, _tmpTextTransform);
  54827. }
  54828. // FIXME merge the same code with `helper/text.js#getTextXForPadding`;
  54829. function getTextXForPadding$1(x, textAlign, textPadding) {
  54830. return textAlign === 'right'
  54831. ? (x - textPadding[1])
  54832. : textAlign === 'center'
  54833. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  54834. : (x + textPadding[3]);
  54835. }
  54836. function updateTextLocation(tspan, textAlign, x, y) {
  54837. // Consider different font display differently in vertial align, we always
  54838. // set vertialAlign as 'middle', and use 'y' to locate text vertically.
  54839. attr(tspan, 'dominant-baseline', 'middle');
  54840. attr(tspan, 'text-anchor', TEXT_ALIGN_TO_ANCHRO[textAlign]);
  54841. attr(tspan, 'x', x);
  54842. attr(tspan, 'y', y);
  54843. }
  54844. function removeOldTextNode(el) {
  54845. if (el && el.__textSvgEl) {
  54846. // textSvgEl may has no parentNode if el has been removed temporary.
  54847. if (el.__textSvgEl.parentNode) {
  54848. el.__textSvgEl.parentNode.removeChild(el.__textSvgEl);
  54849. }
  54850. el.__textSvgEl = null;
  54851. el.__tspanList = [];
  54852. el.__text = null;
  54853. }
  54854. }
  54855. svgText.drawRectText = svgTextDrawRectText;
  54856. svgText.brush = function (el) {
  54857. var style = el.style;
  54858. if (style.text != null) {
  54859. svgTextDrawRectText(el, false);
  54860. }
  54861. else {
  54862. removeOldTextNode(el);
  54863. }
  54864. };
  54865. // Myers' Diff Algorithm
  54866. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  54867. function Diff() {}
  54868. Diff.prototype = {
  54869. diff: function (oldArr, newArr, equals) {
  54870. if (!equals) {
  54871. equals = function (a, b) {
  54872. return a === b;
  54873. };
  54874. }
  54875. this.equals = equals;
  54876. var self = this;
  54877. oldArr = oldArr.slice();
  54878. newArr = newArr.slice();
  54879. // Allow subclasses to massage the input prior to running
  54880. var newLen = newArr.length;
  54881. var oldLen = oldArr.length;
  54882. var editLength = 1;
  54883. var maxEditLength = newLen + oldLen;
  54884. var bestPath = [{ newPos: -1, components: [] }];
  54885. // Seed editLength = 0, i.e. the content starts with the same values
  54886. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  54887. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  54888. var indices = [];
  54889. for (var i = 0; i < newArr.length; i++) {
  54890. indices.push(i);
  54891. }
  54892. // Identity per the equality and tokenizer
  54893. return [{
  54894. indices: indices, count: newArr.length
  54895. }];
  54896. }
  54897. // Main worker method. checks all permutations of a given edit length for acceptance.
  54898. function execEditLength() {
  54899. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  54900. var basePath;
  54901. var addPath = bestPath[diagonalPath - 1];
  54902. var removePath = bestPath[diagonalPath + 1];
  54903. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  54904. if (addPath) {
  54905. // No one else is going to attempt to use this value, clear it
  54906. bestPath[diagonalPath - 1] = undefined;
  54907. }
  54908. var canAdd = addPath && addPath.newPos + 1 < newLen;
  54909. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  54910. if (!canAdd && !canRemove) {
  54911. // If this path is a terminal then prune
  54912. bestPath[diagonalPath] = undefined;
  54913. continue;
  54914. }
  54915. // Select the diagonal that we want to branch from. We select the prior
  54916. // path whose position in the new string is the farthest from the origin
  54917. // and does not pass the bounds of the diff graph
  54918. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  54919. basePath = clonePath(removePath);
  54920. self.pushComponent(basePath.components, undefined, true);
  54921. }
  54922. else {
  54923. basePath = addPath; // No need to clone, we've pulled it from the list
  54924. basePath.newPos++;
  54925. self.pushComponent(basePath.components, true, undefined);
  54926. }
  54927. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  54928. // If we have hit the end of both strings, then we are done
  54929. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  54930. return buildValues(self, basePath.components, newArr, oldArr);
  54931. }
  54932. else {
  54933. // Otherwise track this path as a potential candidate and continue.
  54934. bestPath[diagonalPath] = basePath;
  54935. }
  54936. }
  54937. editLength++;
  54938. }
  54939. while (editLength <= maxEditLength) {
  54940. var ret = execEditLength();
  54941. if (ret) {
  54942. return ret;
  54943. }
  54944. }
  54945. },
  54946. pushComponent: function (components, added, removed) {
  54947. var last = components[components.length - 1];
  54948. if (last && last.added === added && last.removed === removed) {
  54949. // We need to clone here as the component clone operation is just
  54950. // as shallow array clone
  54951. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  54952. }
  54953. else {
  54954. components.push({count: 1, added: added, removed: removed });
  54955. }
  54956. },
  54957. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  54958. var newLen = newArr.length;
  54959. var oldLen = oldArr.length;
  54960. var newPos = basePath.newPos;
  54961. var oldPos = newPos - diagonalPath;
  54962. var commonCount = 0;
  54963. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  54964. newPos++;
  54965. oldPos++;
  54966. commonCount++;
  54967. }
  54968. if (commonCount) {
  54969. basePath.components.push({count: commonCount});
  54970. }
  54971. basePath.newPos = newPos;
  54972. return oldPos;
  54973. },
  54974. tokenize: function (value) {
  54975. return value.slice();
  54976. },
  54977. join: function (value) {
  54978. return value.slice();
  54979. }
  54980. };
  54981. function buildValues(diff, components, newArr, oldArr) {
  54982. var componentPos = 0;
  54983. var componentLen = components.length;
  54984. var newPos = 0;
  54985. var oldPos = 0;
  54986. for (; componentPos < componentLen; componentPos++) {
  54987. var component = components[componentPos];
  54988. if (!component.removed) {
  54989. var indices = [];
  54990. for (var i = newPos; i < newPos + component.count; i++) {
  54991. indices.push(i);
  54992. }
  54993. component.indices = indices;
  54994. newPos += component.count;
  54995. // Common case
  54996. if (!component.added) {
  54997. oldPos += component.count;
  54998. }
  54999. }
  55000. else {
  55001. var indices = [];
  55002. for (var i = oldPos; i < oldPos + component.count; i++) {
  55003. indices.push(i);
  55004. }
  55005. component.indices = indices;
  55006. oldPos += component.count;
  55007. }
  55008. }
  55009. return components;
  55010. }
  55011. function clonePath(path) {
  55012. return { newPos: path.newPos, components: path.components.slice(0) };
  55013. }
  55014. var arrayDiff = new Diff();
  55015. var arrayDiff$1 = function (oldArr, newArr, callback) {
  55016. return arrayDiff.diff(oldArr, newArr, callback);
  55017. };
  55018. /**
  55019. * @file Manages elements that can be defined in <defs> in SVG,
  55020. * e.g., gradients, clip path, etc.
  55021. * @author Zhang Wenli
  55022. */
  55023. var MARK_UNUSED = '0';
  55024. var MARK_USED = '1';
  55025. /**
  55026. * Manages elements that can be defined in <defs> in SVG,
  55027. * e.g., gradients, clip path, etc.
  55028. *
  55029. * @class
  55030. * @param {number} zrId zrender instance id
  55031. * @param {SVGElement} svgRoot root of SVG document
  55032. * @param {string|string[]} tagNames possible tag names
  55033. * @param {string} markLabel label name to make if the element
  55034. * is used
  55035. */
  55036. function Definable(
  55037. zrId,
  55038. svgRoot,
  55039. tagNames,
  55040. markLabel,
  55041. domName
  55042. ) {
  55043. this._zrId = zrId;
  55044. this._svgRoot = svgRoot;
  55045. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  55046. this._markLabel = markLabel;
  55047. this._domName = domName || '_dom';
  55048. this.nextId = 0;
  55049. }
  55050. Definable.prototype.createElement = createElement;
  55051. /**
  55052. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  55053. *
  55054. * @param {boolean} isForceCreating if need to create when not exists
  55055. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  55056. * exist and isForceCreating is false
  55057. */
  55058. Definable.prototype.getDefs = function (isForceCreating) {
  55059. var svgRoot = this._svgRoot;
  55060. var defs = this._svgRoot.getElementsByTagName('defs');
  55061. if (defs.length === 0) {
  55062. // Not exist
  55063. if (isForceCreating) {
  55064. defs = svgRoot.insertBefore(
  55065. this.createElement('defs'), // Create new tag
  55066. svgRoot.firstChild // Insert in the front of svg
  55067. );
  55068. if (!defs.contains) {
  55069. // IE doesn't support contains method
  55070. defs.contains = function (el) {
  55071. var children = defs.children;
  55072. if (!children) {
  55073. return false;
  55074. }
  55075. for (var i = children.length - 1; i >= 0; --i) {
  55076. if (children[i] === el) {
  55077. return true;
  55078. }
  55079. }
  55080. return false;
  55081. };
  55082. }
  55083. return defs;
  55084. }
  55085. else {
  55086. return null;
  55087. }
  55088. }
  55089. else {
  55090. return defs[0];
  55091. }
  55092. };
  55093. /**
  55094. * Update DOM element if necessary.
  55095. *
  55096. * @param {Object|string} element style element. e.g., for gradient,
  55097. * it may be '#ccc' or {type: 'linear', ...}
  55098. * @param {Function|undefined} onUpdate update callback
  55099. */
  55100. Definable.prototype.update = function (element, onUpdate) {
  55101. if (!element) {
  55102. return;
  55103. }
  55104. var defs = this.getDefs(false);
  55105. if (element[this._domName] && defs.contains(element[this._domName])) {
  55106. // Update DOM
  55107. if (typeof onUpdate === 'function') {
  55108. onUpdate(element);
  55109. }
  55110. }
  55111. else {
  55112. // No previous dom, create new
  55113. var dom = this.add(element);
  55114. if (dom) {
  55115. element[this._domName] = dom;
  55116. }
  55117. }
  55118. };
  55119. /**
  55120. * Add gradient dom to defs
  55121. *
  55122. * @param {SVGElement} dom DOM to be added to <defs>
  55123. */
  55124. Definable.prototype.addDom = function (dom) {
  55125. var defs = this.getDefs(true);
  55126. defs.appendChild(dom);
  55127. };
  55128. /**
  55129. * Remove DOM of a given element.
  55130. *
  55131. * @param {SVGElement} element element to remove dom
  55132. */
  55133. Definable.prototype.removeDom = function (element) {
  55134. var defs = this.getDefs(false);
  55135. if (defs && element[this._domName]) {
  55136. defs.removeChild(element[this._domName]);
  55137. element[this._domName] = null;
  55138. }
  55139. };
  55140. /**
  55141. * Get DOMs of this element.
  55142. *
  55143. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  55144. */
  55145. Definable.prototype.getDoms = function () {
  55146. var defs = this.getDefs(false);
  55147. if (!defs) {
  55148. // No dom when defs is not defined
  55149. return [];
  55150. }
  55151. var doms = [];
  55152. each$1(this._tagNames, function (tagName) {
  55153. var tags = defs.getElementsByTagName(tagName);
  55154. // Note that tags is HTMLCollection, which is array-like
  55155. // rather than real array.
  55156. // So `doms.concat(tags)` add tags as one object.
  55157. doms = doms.concat([].slice.call(tags));
  55158. });
  55159. return doms;
  55160. };
  55161. /**
  55162. * Mark DOMs to be unused before painting, and clear unused ones at the end
  55163. * of the painting.
  55164. */
  55165. Definable.prototype.markAllUnused = function () {
  55166. var doms = this.getDoms();
  55167. var that = this;
  55168. each$1(doms, function (dom) {
  55169. dom[that._markLabel] = MARK_UNUSED;
  55170. });
  55171. };
  55172. /**
  55173. * Mark a single DOM to be used.
  55174. *
  55175. * @param {SVGElement} dom DOM to mark
  55176. */
  55177. Definable.prototype.markUsed = function (dom) {
  55178. if (dom) {
  55179. dom[this._markLabel] = MARK_USED;
  55180. }
  55181. };
  55182. /**
  55183. * Remove unused DOMs defined in <defs>
  55184. */
  55185. Definable.prototype.removeUnused = function () {
  55186. var defs = this.getDefs(false);
  55187. if (!defs) {
  55188. // Nothing to remove
  55189. return;
  55190. }
  55191. var doms = this.getDoms();
  55192. var that = this;
  55193. each$1(doms, function (dom) {
  55194. if (dom[that._markLabel] !== MARK_USED) {
  55195. // Remove gradient
  55196. defs.removeChild(dom);
  55197. }
  55198. });
  55199. };
  55200. /**
  55201. * Get SVG proxy.
  55202. *
  55203. * @param {Displayable} displayable displayable element
  55204. * @return {Path|Image|Text} svg proxy of given element
  55205. */
  55206. Definable.prototype.getSvgProxy = function (displayable) {
  55207. if (displayable instanceof Path) {
  55208. return svgPath;
  55209. }
  55210. else if (displayable instanceof ZImage) {
  55211. return svgImage;
  55212. }
  55213. else if (displayable instanceof Text) {
  55214. return svgText;
  55215. }
  55216. else {
  55217. return svgPath;
  55218. }
  55219. };
  55220. /**
  55221. * Get text SVG element.
  55222. *
  55223. * @param {Displayable} displayable displayable element
  55224. * @return {SVGElement} SVG element of text
  55225. */
  55226. Definable.prototype.getTextSvgElement = function (displayable) {
  55227. return displayable.__textSvgEl;
  55228. };
  55229. /**
  55230. * Get SVG element.
  55231. *
  55232. * @param {Displayable} displayable displayable element
  55233. * @return {SVGElement} SVG element
  55234. */
  55235. Definable.prototype.getSvgElement = function (displayable) {
  55236. return displayable.__svgEl;
  55237. };
  55238. /**
  55239. * @file Manages SVG gradient elements.
  55240. * @author Zhang Wenli
  55241. */
  55242. /**
  55243. * Manages SVG gradient elements.
  55244. *
  55245. * @class
  55246. * @extends Definable
  55247. * @param {number} zrId zrender instance id
  55248. * @param {SVGElement} svgRoot root of SVG document
  55249. */
  55250. function GradientManager(zrId, svgRoot) {
  55251. Definable.call(
  55252. this,
  55253. zrId,
  55254. svgRoot,
  55255. ['linearGradient', 'radialGradient'],
  55256. '__gradient_in_use__'
  55257. );
  55258. }
  55259. inherits(GradientManager, Definable);
  55260. /**
  55261. * Create new gradient DOM for fill or stroke if not exist,
  55262. * but will not update gradient if exists.
  55263. *
  55264. * @param {SvgElement} svgElement SVG element to paint
  55265. * @param {Displayable} displayable zrender displayable element
  55266. */
  55267. GradientManager.prototype.addWithoutUpdate = function (
  55268. svgElement,
  55269. displayable
  55270. ) {
  55271. if (displayable && displayable.style) {
  55272. var that = this;
  55273. each$1(['fill', 'stroke'], function (fillOrStroke) {
  55274. if (displayable.style[fillOrStroke]
  55275. && (displayable.style[fillOrStroke].type === 'linear'
  55276. || displayable.style[fillOrStroke].type === 'radial')
  55277. ) {
  55278. var gradient = displayable.style[fillOrStroke];
  55279. var defs = that.getDefs(true);
  55280. // Create dom in <defs> if not exists
  55281. var dom;
  55282. if (gradient._dom) {
  55283. // Gradient exists
  55284. dom = gradient._dom;
  55285. if (!defs.contains(gradient._dom)) {
  55286. // _dom is no longer in defs, recreate
  55287. that.addDom(dom);
  55288. }
  55289. }
  55290. else {
  55291. // New dom
  55292. dom = that.add(gradient);
  55293. }
  55294. that.markUsed(displayable);
  55295. var id = dom.getAttribute('id');
  55296. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  55297. }
  55298. });
  55299. }
  55300. };
  55301. /**
  55302. * Add a new gradient tag in <defs>
  55303. *
  55304. * @param {Gradient} gradient zr gradient instance
  55305. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  55306. * created DOM
  55307. */
  55308. GradientManager.prototype.add = function (gradient) {
  55309. var dom;
  55310. if (gradient.type === 'linear') {
  55311. dom = this.createElement('linearGradient');
  55312. }
  55313. else if (gradient.type === 'radial') {
  55314. dom = this.createElement('radialGradient');
  55315. }
  55316. else {
  55317. logError$1('Illegal gradient type.');
  55318. return null;
  55319. }
  55320. // Set dom id with gradient id, since each gradient instance
  55321. // will have no more than one dom element.
  55322. // id may exists before for those dirty elements, in which case
  55323. // id should remain the same, and other attributes should be
  55324. // updated.
  55325. gradient.id = gradient.id || this.nextId++;
  55326. dom.setAttribute('id', 'zr' + this._zrId
  55327. + '-gradient-' + gradient.id);
  55328. this.updateDom(gradient, dom);
  55329. this.addDom(dom);
  55330. return dom;
  55331. };
  55332. /**
  55333. * Update gradient.
  55334. *
  55335. * @param {Gradient} gradient zr gradient instance
  55336. */
  55337. GradientManager.prototype.update = function (gradient) {
  55338. var that = this;
  55339. Definable.prototype.update.call(this, gradient, function () {
  55340. var type = gradient.type;
  55341. var tagName = gradient._dom.tagName;
  55342. if (type === 'linear' && tagName === 'linearGradient'
  55343. || type === 'radial' && tagName === 'radialGradient'
  55344. ) {
  55345. // Gradient type is not changed, update gradient
  55346. that.updateDom(gradient, gradient._dom);
  55347. }
  55348. else {
  55349. // Remove and re-create if type is changed
  55350. that.removeDom(gradient);
  55351. that.add(gradient);
  55352. }
  55353. });
  55354. };
  55355. /**
  55356. * Update gradient dom
  55357. *
  55358. * @param {Gradient} gradient zr gradient instance
  55359. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  55360. * DOM to update
  55361. */
  55362. GradientManager.prototype.updateDom = function (gradient, dom) {
  55363. if (gradient.type === 'linear') {
  55364. dom.setAttribute('x1', gradient.x);
  55365. dom.setAttribute('y1', gradient.y);
  55366. dom.setAttribute('x2', gradient.x2);
  55367. dom.setAttribute('y2', gradient.y2);
  55368. }
  55369. else if (gradient.type === 'radial') {
  55370. dom.setAttribute('cx', gradient.x);
  55371. dom.setAttribute('cy', gradient.y);
  55372. dom.setAttribute('r', gradient.r);
  55373. }
  55374. else {
  55375. logError$1('Illegal gradient type.');
  55376. return;
  55377. }
  55378. if (gradient.global) {
  55379. // x1, x2, y1, y2 in range of 0 to canvas width or height
  55380. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  55381. }
  55382. else {
  55383. // x1, x2, y1, y2 in range of 0 to 1
  55384. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  55385. }
  55386. // Remove color stops if exists
  55387. dom.innerHTML = '';
  55388. // Add color stops
  55389. var colors = gradient.colorStops;
  55390. for (var i = 0, len = colors.length; i < len; ++i) {
  55391. var stop = this.createElement('stop');
  55392. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  55393. var color = colors[i].color;
  55394. if (color.indexOf('rgba') > -1) {
  55395. // Fix Safari bug that stop-color not recognizing alpha #9014
  55396. var opacity = parse(color)[3];
  55397. var hex = toHex(color);
  55398. // stop-color cannot be color, since:
  55399. // The opacity value used for the gradient calculation is the
  55400. // *product* of the value of stop-opacity and the opacity of the
  55401. // value of stop-color.
  55402. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  55403. stop.setAttribute('stop-color', '#' + hex);
  55404. stop.setAttribute('stop-opacity', opacity);
  55405. }
  55406. else {
  55407. stop.setAttribute('stop-color', colors[i].color);
  55408. }
  55409. dom.appendChild(stop);
  55410. }
  55411. // Store dom element in gradient, to avoid creating multiple
  55412. // dom instances for the same gradient element
  55413. gradient._dom = dom;
  55414. };
  55415. /**
  55416. * Mark a single gradient to be used
  55417. *
  55418. * @param {Displayable} displayable displayable element
  55419. */
  55420. GradientManager.prototype.markUsed = function (displayable) {
  55421. if (displayable.style) {
  55422. var gradient = displayable.style.fill;
  55423. if (gradient && gradient._dom) {
  55424. Definable.prototype.markUsed.call(this, gradient._dom);
  55425. }
  55426. gradient = displayable.style.stroke;
  55427. if (gradient && gradient._dom) {
  55428. Definable.prototype.markUsed.call(this, gradient._dom);
  55429. }
  55430. }
  55431. };
  55432. /**
  55433. * @file Manages SVG clipPath elements.
  55434. * @author Zhang Wenli
  55435. */
  55436. /**
  55437. * Manages SVG clipPath elements.
  55438. *
  55439. * @class
  55440. * @extends Definable
  55441. * @param {number} zrId zrender instance id
  55442. * @param {SVGElement} svgRoot root of SVG document
  55443. */
  55444. function ClippathManager(zrId, svgRoot) {
  55445. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  55446. }
  55447. inherits(ClippathManager, Definable);
  55448. /**
  55449. * Update clipPath.
  55450. *
  55451. * @param {Displayable} displayable displayable element
  55452. */
  55453. ClippathManager.prototype.update = function (displayable) {
  55454. var svgEl = this.getSvgElement(displayable);
  55455. if (svgEl) {
  55456. this.updateDom(svgEl, displayable.__clipPaths, false);
  55457. }
  55458. var textEl = this.getTextSvgElement(displayable);
  55459. if (textEl) {
  55460. // Make another clipPath for text, since it's transform
  55461. // matrix is not the same with svgElement
  55462. this.updateDom(textEl, displayable.__clipPaths, true);
  55463. }
  55464. this.markUsed(displayable);
  55465. };
  55466. /**
  55467. * Create an SVGElement of displayable and create a <clipPath> of its
  55468. * clipPath
  55469. *
  55470. * @param {Displayable} parentEl parent element
  55471. * @param {ClipPath[]} clipPaths clipPaths of parent element
  55472. * @param {boolean} isText if parent element is Text
  55473. */
  55474. ClippathManager.prototype.updateDom = function (
  55475. parentEl,
  55476. clipPaths,
  55477. isText
  55478. ) {
  55479. if (clipPaths && clipPaths.length > 0) {
  55480. // Has clipPath, create <clipPath> with the first clipPath
  55481. var defs = this.getDefs(true);
  55482. var clipPath = clipPaths[0];
  55483. var clipPathEl;
  55484. var id;
  55485. var dom = isText ? '_textDom' : '_dom';
  55486. if (clipPath[dom]) {
  55487. // Use a dom that is already in <defs>
  55488. id = clipPath[dom].getAttribute('id');
  55489. clipPathEl = clipPath[dom];
  55490. // Use a dom that is already in <defs>
  55491. if (!defs.contains(clipPathEl)) {
  55492. // This happens when set old clipPath that has
  55493. // been previously removed
  55494. defs.appendChild(clipPathEl);
  55495. }
  55496. }
  55497. else {
  55498. // New <clipPath>
  55499. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  55500. ++this.nextId;
  55501. clipPathEl = this.createElement('clipPath');
  55502. clipPathEl.setAttribute('id', id);
  55503. defs.appendChild(clipPathEl);
  55504. clipPath[dom] = clipPathEl;
  55505. }
  55506. // Build path and add to <clipPath>
  55507. var svgProxy = this.getSvgProxy(clipPath);
  55508. if (clipPath.transform
  55509. && clipPath.parent.invTransform
  55510. && !isText
  55511. ) {
  55512. /**
  55513. * If a clipPath has a parent with transform, the transform
  55514. * of parent should not be considered when setting transform
  55515. * of clipPath. So we need to transform back from parent's
  55516. * transform, which is done by multiplying parent's inverse
  55517. * transform.
  55518. */
  55519. // Store old transform
  55520. var transform = Array.prototype.slice.call(
  55521. clipPath.transform
  55522. );
  55523. // Transform back from parent, and brush path
  55524. mul$1(
  55525. clipPath.transform,
  55526. clipPath.parent.invTransform,
  55527. clipPath.transform
  55528. );
  55529. svgProxy.brush(clipPath);
  55530. // Set back transform of clipPath
  55531. clipPath.transform = transform;
  55532. }
  55533. else {
  55534. svgProxy.brush(clipPath);
  55535. }
  55536. var pathEl = this.getSvgElement(clipPath);
  55537. clipPathEl.innerHTML = '';
  55538. /**
  55539. * Use `cloneNode()` here to appendChild to multiple parents,
  55540. * which may happend when Text and other shapes are using the same
  55541. * clipPath. Since Text will create an extra clipPath DOM due to
  55542. * different transform rules.
  55543. */
  55544. clipPathEl.appendChild(pathEl.cloneNode());
  55545. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  55546. if (clipPaths.length > 1) {
  55547. // Make the other clipPaths recursively
  55548. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  55549. }
  55550. }
  55551. else {
  55552. // No clipPath
  55553. if (parentEl) {
  55554. parentEl.setAttribute('clip-path', 'none');
  55555. }
  55556. }
  55557. };
  55558. /**
  55559. * Mark a single clipPath to be used
  55560. *
  55561. * @param {Displayable} displayable displayable element
  55562. */
  55563. ClippathManager.prototype.markUsed = function (displayable) {
  55564. var that = this;
  55565. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  55566. if (displayable.__clipPaths) {
  55567. each$1(displayable.__clipPaths, function (clipPath) {
  55568. if (clipPath._dom) {
  55569. Definable.prototype.markUsed.call(that, clipPath._dom);
  55570. }
  55571. if (clipPath._textDom) {
  55572. Definable.prototype.markUsed.call(that, clipPath._textDom);
  55573. }
  55574. });
  55575. }
  55576. };
  55577. /**
  55578. * @file Manages SVG shadow elements.
  55579. * @author Zhang Wenli
  55580. */
  55581. /**
  55582. * Manages SVG shadow elements.
  55583. *
  55584. * @class
  55585. * @extends Definable
  55586. * @param {number} zrId zrender instance id
  55587. * @param {SVGElement} svgRoot root of SVG document
  55588. */
  55589. function ShadowManager(zrId, svgRoot) {
  55590. Definable.call(
  55591. this,
  55592. zrId,
  55593. svgRoot,
  55594. ['filter'],
  55595. '__filter_in_use__',
  55596. '_shadowDom'
  55597. );
  55598. }
  55599. inherits(ShadowManager, Definable);
  55600. /**
  55601. * Create new shadow DOM for fill or stroke if not exist,
  55602. * but will not update shadow if exists.
  55603. *
  55604. * @param {SvgElement} svgElement SVG element to paint
  55605. * @param {Displayable} displayable zrender displayable element
  55606. */
  55607. ShadowManager.prototype.addWithoutUpdate = function (
  55608. svgElement,
  55609. displayable
  55610. ) {
  55611. if (displayable && hasShadow(displayable.style)) {
  55612. // Create dom in <defs> if not exists
  55613. var dom;
  55614. if (displayable._shadowDom) {
  55615. // Gradient exists
  55616. dom = displayable._shadowDom;
  55617. var defs = this.getDefs(true);
  55618. if (!defs.contains(displayable._shadowDom)) {
  55619. // _shadowDom is no longer in defs, recreate
  55620. this.addDom(dom);
  55621. }
  55622. }
  55623. else {
  55624. // New dom
  55625. dom = this.add(displayable);
  55626. }
  55627. this.markUsed(displayable);
  55628. var id = dom.getAttribute('id');
  55629. svgElement.style.filter = 'url(#' + id + ')';
  55630. }
  55631. };
  55632. /**
  55633. * Add a new shadow tag in <defs>
  55634. *
  55635. * @param {Displayable} displayable zrender displayable element
  55636. * @return {SVGFilterElement} created DOM
  55637. */
  55638. ShadowManager.prototype.add = function (displayable) {
  55639. var dom = this.createElement('filter');
  55640. // Set dom id with shadow id, since each shadow instance
  55641. // will have no more than one dom element.
  55642. // id may exists before for those dirty elements, in which case
  55643. // id should remain the same, and other attributes should be
  55644. // updated.
  55645. displayable._shadowDomId = displayable._shadowDomId || this.nextId++;
  55646. dom.setAttribute('id', 'zr' + this._zrId
  55647. + '-shadow-' + displayable._shadowDomId);
  55648. this.updateDom(displayable, dom);
  55649. this.addDom(dom);
  55650. return dom;
  55651. };
  55652. /**
  55653. * Update shadow.
  55654. *
  55655. * @param {Displayable} displayable zrender displayable element
  55656. */
  55657. ShadowManager.prototype.update = function (svgElement, displayable) {
  55658. var style = displayable.style;
  55659. if (hasShadow(style)) {
  55660. var that = this;
  55661. Definable.prototype.update.call(this, displayable, function () {
  55662. that.updateDom(displayable, displayable._shadowDom);
  55663. });
  55664. }
  55665. else {
  55666. // Remove shadow
  55667. this.remove(svgElement, displayable);
  55668. }
  55669. };
  55670. /**
  55671. * Remove DOM and clear parent filter
  55672. */
  55673. ShadowManager.prototype.remove = function (svgElement, displayable) {
  55674. if (displayable._shadowDomId != null) {
  55675. this.removeDom(svgElement);
  55676. svgElement.style.filter = '';
  55677. }
  55678. };
  55679. /**
  55680. * Update shadow dom
  55681. *
  55682. * @param {Displayable} displayable zrender displayable element
  55683. * @param {SVGFilterElement} dom DOM to update
  55684. */
  55685. ShadowManager.prototype.updateDom = function (displayable, dom) {
  55686. var domChild = dom.getElementsByTagName('feDropShadow');
  55687. if (domChild.length === 0) {
  55688. domChild = this.createElement('feDropShadow');
  55689. }
  55690. else {
  55691. domChild = domChild[0];
  55692. }
  55693. var style = displayable.style;
  55694. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  55695. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  55696. // TODO: textBoxShadowBlur is not supported yet
  55697. var offsetX;
  55698. var offsetY;
  55699. var blur;
  55700. var color;
  55701. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  55702. offsetX = style.shadowOffsetX || 0;
  55703. offsetY = style.shadowOffsetY || 0;
  55704. blur = style.shadowBlur;
  55705. color = style.shadowColor;
  55706. }
  55707. else if (style.textShadowBlur) {
  55708. offsetX = style.textShadowOffsetX || 0;
  55709. offsetY = style.textShadowOffsetY || 0;
  55710. blur = style.textShadowBlur;
  55711. color = style.textShadowColor;
  55712. }
  55713. else {
  55714. // Remove shadow
  55715. this.removeDom(dom, style);
  55716. return;
  55717. }
  55718. domChild.setAttribute('dx', offsetX / scaleX);
  55719. domChild.setAttribute('dy', offsetY / scaleY);
  55720. domChild.setAttribute('flood-color', color);
  55721. // Divide by two here so that it looks the same as in canvas
  55722. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  55723. var stdDx = blur / 2 / scaleX;
  55724. var stdDy = blur / 2 / scaleY;
  55725. var stdDeviation = stdDx + ' ' + stdDy;
  55726. domChild.setAttribute('stdDeviation', stdDeviation);
  55727. // Fix filter clipping problem
  55728. dom.setAttribute('x', '-100%');
  55729. dom.setAttribute('y', '-100%');
  55730. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  55731. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  55732. dom.appendChild(domChild);
  55733. // Store dom element in shadow, to avoid creating multiple
  55734. // dom instances for the same shadow element
  55735. displayable._shadowDom = dom;
  55736. };
  55737. /**
  55738. * Mark a single shadow to be used
  55739. *
  55740. * @param {Displayable} displayable displayable element
  55741. */
  55742. ShadowManager.prototype.markUsed = function (displayable) {
  55743. if (displayable._shadowDom) {
  55744. Definable.prototype.markUsed.call(this, displayable._shadowDom);
  55745. }
  55746. };
  55747. function hasShadow(style) {
  55748. // TODO: textBoxShadowBlur is not supported yet
  55749. return style
  55750. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  55751. || style.textShadowBlur || style.textShadowOffsetX
  55752. || style.textShadowOffsetY);
  55753. }
  55754. /**
  55755. * SVG Painter
  55756. * @module zrender/svg/Painter
  55757. */
  55758. function parseInt10$2(val) {
  55759. return parseInt(val, 10);
  55760. }
  55761. function getSvgProxy(el) {
  55762. if (el instanceof Path) {
  55763. return svgPath;
  55764. }
  55765. else if (el instanceof ZImage) {
  55766. return svgImage;
  55767. }
  55768. else if (el instanceof Text) {
  55769. return svgText;
  55770. }
  55771. else {
  55772. return svgPath;
  55773. }
  55774. }
  55775. function checkParentAvailable(parent, child) {
  55776. return child && parent && child.parentNode !== parent;
  55777. }
  55778. function insertAfter(parent, child, prevSibling) {
  55779. if (checkParentAvailable(parent, child) && prevSibling) {
  55780. var nextSibling = prevSibling.nextSibling;
  55781. nextSibling ? parent.insertBefore(child, nextSibling)
  55782. : parent.appendChild(child);
  55783. }
  55784. }
  55785. function prepend(parent, child) {
  55786. if (checkParentAvailable(parent, child)) {
  55787. var firstChild = parent.firstChild;
  55788. firstChild ? parent.insertBefore(child, firstChild)
  55789. : parent.appendChild(child);
  55790. }
  55791. }
  55792. // function append(parent, child) {
  55793. // if (checkParentAvailable(parent, child)) {
  55794. // parent.appendChild(child);
  55795. // }
  55796. // }
  55797. function remove$1(parent, child) {
  55798. if (child && parent && child.parentNode === parent) {
  55799. parent.removeChild(child);
  55800. }
  55801. }
  55802. function getTextSvgElement(displayable) {
  55803. return displayable.__textSvgEl;
  55804. }
  55805. function getSvgElement(displayable) {
  55806. return displayable.__svgEl;
  55807. }
  55808. /**
  55809. * @alias module:zrender/svg/Painter
  55810. * @constructor
  55811. * @param {HTMLElement} root 绘图容器
  55812. * @param {module:zrender/Storage} storage
  55813. * @param {Object} opts
  55814. */
  55815. var SVGPainter = function (root, storage, opts, zrId) {
  55816. this.root = root;
  55817. this.storage = storage;
  55818. this._opts = opts = extend({}, opts || {});
  55819. var svgDom = createElement('svg');
  55820. svgDom.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  55821. svgDom.setAttribute('version', '1.1');
  55822. svgDom.setAttribute('baseProfile', 'full');
  55823. svgDom.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  55824. var bgRoot = createElement('g');
  55825. svgDom.appendChild(bgRoot);
  55826. var svgRoot = createElement('g');
  55827. svgDom.appendChild(svgRoot);
  55828. this.gradientManager = new GradientManager(zrId, svgRoot);
  55829. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  55830. this.shadowManager = new ShadowManager(zrId, svgRoot);
  55831. var viewport = document.createElement('div');
  55832. viewport.style.cssText = 'overflow:hidden;position:relative';
  55833. this._svgDom = svgDom;
  55834. this._svgRoot = svgRoot;
  55835. this._backgroundRoot = bgRoot;
  55836. this._viewport = viewport;
  55837. root.appendChild(viewport);
  55838. viewport.appendChild(svgDom);
  55839. this.resize(opts.width, opts.height);
  55840. this._visibleList = [];
  55841. };
  55842. SVGPainter.prototype = {
  55843. constructor: SVGPainter,
  55844. getType: function () {
  55845. return 'svg';
  55846. },
  55847. getViewportRoot: function () {
  55848. return this._viewport;
  55849. },
  55850. getSvgDom: function () {
  55851. return this._svgDom;
  55852. },
  55853. getSvgRoot: function () {
  55854. return this._svgRoot;
  55855. },
  55856. getViewportRootOffset: function () {
  55857. var viewportRoot = this.getViewportRoot();
  55858. if (viewportRoot) {
  55859. return {
  55860. offsetLeft: viewportRoot.offsetLeft || 0,
  55861. offsetTop: viewportRoot.offsetTop || 0
  55862. };
  55863. }
  55864. },
  55865. refresh: function () {
  55866. var list = this.storage.getDisplayList(true);
  55867. this._paintList(list);
  55868. },
  55869. setBackgroundColor: function (backgroundColor) {
  55870. // TODO gradient
  55871. // Insert a bg rect instead of setting background to viewport.
  55872. // Otherwise, the exported SVG don't have background.
  55873. if (this._backgroundRoot && this._backgroundNode) {
  55874. this._backgroundRoot.removeChild(this._backgroundNode);
  55875. }
  55876. var bgNode = createElement('rect');
  55877. bgNode.setAttribute('width', this.getWidth());
  55878. bgNode.setAttribute('height', this.getHeight());
  55879. bgNode.setAttribute('x', 0);
  55880. bgNode.setAttribute('y', 0);
  55881. bgNode.setAttribute('id', 0);
  55882. bgNode.style.fill = backgroundColor;
  55883. this._backgroundRoot.appendChild(bgNode);
  55884. this._backgroundNode = bgNode;
  55885. },
  55886. _paintList: function (list) {
  55887. this.gradientManager.markAllUnused();
  55888. this.clipPathManager.markAllUnused();
  55889. this.shadowManager.markAllUnused();
  55890. var svgRoot = this._svgRoot;
  55891. var visibleList = this._visibleList;
  55892. var listLen = list.length;
  55893. var newVisibleList = [];
  55894. var i;
  55895. for (i = 0; i < listLen; i++) {
  55896. var displayable = list[i];
  55897. var svgProxy = getSvgProxy(displayable);
  55898. var svgElement = getSvgElement(displayable)
  55899. || getTextSvgElement(displayable);
  55900. if (!displayable.invisible) {
  55901. if (displayable.__dirty) {
  55902. svgProxy && svgProxy.brush(displayable);
  55903. // Update clipPath
  55904. this.clipPathManager.update(displayable);
  55905. // Update gradient and shadow
  55906. if (displayable.style) {
  55907. this.gradientManager
  55908. .update(displayable.style.fill);
  55909. this.gradientManager
  55910. .update(displayable.style.stroke);
  55911. this.shadowManager
  55912. .update(svgElement, displayable);
  55913. }
  55914. displayable.__dirty = false;
  55915. }
  55916. newVisibleList.push(displayable);
  55917. }
  55918. }
  55919. var diff = arrayDiff$1(visibleList, newVisibleList);
  55920. var prevSvgElement;
  55921. // First do remove, in case element moved to the head and do remove
  55922. // after add
  55923. for (i = 0; i < diff.length; i++) {
  55924. var item = diff[i];
  55925. if (item.removed) {
  55926. for (var k = 0; k < item.count; k++) {
  55927. var displayable = visibleList[item.indices[k]];
  55928. var svgElement = getSvgElement(displayable);
  55929. var textSvgElement = getTextSvgElement(displayable);
  55930. remove$1(svgRoot, svgElement);
  55931. remove$1(svgRoot, textSvgElement);
  55932. }
  55933. }
  55934. }
  55935. for (i = 0; i < diff.length; i++) {
  55936. var item = diff[i];
  55937. if (item.added) {
  55938. for (var k = 0; k < item.count; k++) {
  55939. var displayable = newVisibleList[item.indices[k]];
  55940. var svgElement = getSvgElement(displayable);
  55941. var textSvgElement = getTextSvgElement(displayable);
  55942. prevSvgElement
  55943. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  55944. : prepend(svgRoot, svgElement);
  55945. if (svgElement) {
  55946. insertAfter(svgRoot, textSvgElement, svgElement);
  55947. }
  55948. else if (prevSvgElement) {
  55949. insertAfter(
  55950. svgRoot, textSvgElement, prevSvgElement
  55951. );
  55952. }
  55953. else {
  55954. prepend(svgRoot, textSvgElement);
  55955. }
  55956. // Insert text
  55957. insertAfter(svgRoot, textSvgElement, svgElement);
  55958. prevSvgElement = textSvgElement || svgElement
  55959. || prevSvgElement;
  55960. // zrender.Text only create textSvgElement.
  55961. this.gradientManager
  55962. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55963. this.shadowManager
  55964. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55965. this.clipPathManager.markUsed(displayable);
  55966. }
  55967. }
  55968. else if (!item.removed) {
  55969. for (var k = 0; k < item.count; k++) {
  55970. var displayable = newVisibleList[item.indices[k]];
  55971. var svgElement = getSvgElement(displayable);
  55972. var textSvgElement = getTextSvgElement(displayable);
  55973. var svgElement = getSvgElement(displayable);
  55974. var textSvgElement = getTextSvgElement(displayable);
  55975. this.gradientManager.markUsed(displayable);
  55976. this.gradientManager
  55977. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55978. this.shadowManager.markUsed(displayable);
  55979. this.shadowManager
  55980. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55981. this.clipPathManager.markUsed(displayable);
  55982. if (textSvgElement) { // Insert text.
  55983. insertAfter(svgRoot, textSvgElement, svgElement);
  55984. }
  55985. prevSvgElement = svgElement
  55986. || textSvgElement || prevSvgElement;
  55987. }
  55988. }
  55989. }
  55990. this.gradientManager.removeUnused();
  55991. this.clipPathManager.removeUnused();
  55992. this.shadowManager.removeUnused();
  55993. this._visibleList = newVisibleList;
  55994. },
  55995. _getDefs: function (isForceCreating) {
  55996. var svgRoot = this._svgDom;
  55997. var defs = svgRoot.getElementsByTagName('defs');
  55998. if (defs.length === 0) {
  55999. // Not exist
  56000. if (isForceCreating) {
  56001. var defs = svgRoot.insertBefore(
  56002. createElement('defs'), // Create new tag
  56003. svgRoot.firstChild // Insert in the front of svg
  56004. );
  56005. if (!defs.contains) {
  56006. // IE doesn't support contains method
  56007. defs.contains = function (el) {
  56008. var children = defs.children;
  56009. if (!children) {
  56010. return false;
  56011. }
  56012. for (var i = children.length - 1; i >= 0; --i) {
  56013. if (children[i] === el) {
  56014. return true;
  56015. }
  56016. }
  56017. return false;
  56018. };
  56019. }
  56020. return defs;
  56021. }
  56022. else {
  56023. return null;
  56024. }
  56025. }
  56026. else {
  56027. return defs[0];
  56028. }
  56029. },
  56030. resize: function (width, height) {
  56031. var viewport = this._viewport;
  56032. // FIXME Why ?
  56033. viewport.style.display = 'none';
  56034. // Save input w/h
  56035. var opts = this._opts;
  56036. width != null && (opts.width = width);
  56037. height != null && (opts.height = height);
  56038. width = this._getSize(0);
  56039. height = this._getSize(1);
  56040. viewport.style.display = '';
  56041. if (this._width !== width || this._height !== height) {
  56042. this._width = width;
  56043. this._height = height;
  56044. var viewportStyle = viewport.style;
  56045. viewportStyle.width = width + 'px';
  56046. viewportStyle.height = height + 'px';
  56047. var svgRoot = this._svgDom;
  56048. // Set width by 'svgRoot.width = width' is invalid
  56049. svgRoot.setAttribute('width', width);
  56050. svgRoot.setAttribute('height', height);
  56051. }
  56052. if (this._backgroundNode) {
  56053. this._backgroundNode.setAttribute('width', width);
  56054. this._backgroundNode.setAttribute('height', height);
  56055. }
  56056. },
  56057. /**
  56058. * 获取绘图区域宽度
  56059. */
  56060. getWidth: function () {
  56061. return this._width;
  56062. },
  56063. /**
  56064. * 获取绘图区域高度
  56065. */
  56066. getHeight: function () {
  56067. return this._height;
  56068. },
  56069. _getSize: function (whIdx) {
  56070. var opts = this._opts;
  56071. var wh = ['width', 'height'][whIdx];
  56072. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  56073. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  56074. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  56075. if (opts[wh] != null && opts[wh] !== 'auto') {
  56076. return parseFloat(opts[wh]);
  56077. }
  56078. var root = this.root;
  56079. // IE8 does not support getComputedStyle, but it use VML.
  56080. var stl = document.defaultView.getComputedStyle(root);
  56081. return (
  56082. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  56083. - (parseInt10$2(stl[plt]) || 0)
  56084. - (parseInt10$2(stl[prb]) || 0)
  56085. ) | 0;
  56086. },
  56087. dispose: function () {
  56088. this.root.innerHTML = '';
  56089. this._svgRoot
  56090. = this._backgroundRoot
  56091. = this._svgDom
  56092. = this._backgroundNode
  56093. = this._viewport
  56094. = this.storage
  56095. = null;
  56096. },
  56097. clear: function () {
  56098. if (this._viewport) {
  56099. this.root.removeChild(this._viewport);
  56100. }
  56101. },
  56102. toDataURL: function () {
  56103. this.refresh();
  56104. var html = encodeURIComponent(this._svgDom.outerHTML.replace(/></g, '>\n\r<'));
  56105. return 'data:image/svg+xml;charset=UTF-8,' + html;
  56106. }
  56107. };
  56108. // Not supported methods
  56109. function createMethodNotSupport$1(method) {
  56110. return function () {
  56111. logError$1('In SVG mode painter not support method "' + method + '"');
  56112. };
  56113. }
  56114. // Unsuppoted methods
  56115. each$1([
  56116. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  56117. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  56118. 'pathToImage'
  56119. ], function (name) {
  56120. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  56121. });
  56122. registerPainter('svg', SVGPainter);
  56123. /*
  56124. * Licensed to the Apache Software Foundation (ASF) under one
  56125. * or more contributor license agreements. See the NOTICE file
  56126. * distributed with this work for additional information
  56127. * regarding copyright ownership. The ASF licenses this file
  56128. * to you under the Apache License, Version 2.0 (the
  56129. * "License"); you may not use this file except in compliance
  56130. * with the License. You may obtain a copy of the License at
  56131. *
  56132. * http://www.apache.org/licenses/LICENSE-2.0
  56133. *
  56134. * Unless required by applicable law or agreed to in writing,
  56135. * software distributed under the License is distributed on an
  56136. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56137. * KIND, either express or implied. See the License for the
  56138. * specific language governing permissions and limitations
  56139. * under the License.
  56140. */
  56141. exports.version = version;
  56142. exports.dependencies = dependencies;
  56143. exports.PRIORITY = PRIORITY;
  56144. exports.init = init;
  56145. exports.connect = connect;
  56146. exports.disConnect = disConnect;
  56147. exports.disconnect = disconnect;
  56148. exports.dispose = dispose;
  56149. exports.getInstanceByDom = getInstanceByDom;
  56150. exports.getInstanceById = getInstanceById;
  56151. exports.registerTheme = registerTheme;
  56152. exports.registerPreprocessor = registerPreprocessor;
  56153. exports.registerProcessor = registerProcessor;
  56154. exports.registerPostUpdate = registerPostUpdate;
  56155. exports.registerAction = registerAction;
  56156. exports.registerCoordinateSystem = registerCoordinateSystem;
  56157. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  56158. exports.registerLayout = registerLayout;
  56159. exports.registerVisual = registerVisual;
  56160. exports.registerLoading = registerLoading;
  56161. exports.extendComponentModel = extendComponentModel;
  56162. exports.extendComponentView = extendComponentView;
  56163. exports.extendSeriesModel = extendSeriesModel;
  56164. exports.extendChartView = extendChartView;
  56165. exports.setCanvasCreator = setCanvasCreator;
  56166. exports.registerMap = registerMap;
  56167. exports.getMap = getMap;
  56168. exports.dataTool = dataTool;
  56169. exports.zrender = zrender;
  56170. exports.number = number;
  56171. exports.format = format;
  56172. exports.throttle = throttle;
  56173. exports.helper = helper;
  56174. exports.matrix = matrix;
  56175. exports.vector = vector;
  56176. exports.color = color;
  56177. exports.parseGeoJSON = parseGeoJSON;
  56178. exports.parseGeoJson = parseGeoJson;
  56179. exports.util = ecUtil;
  56180. exports.graphic = graphic$1;
  56181. exports.List = List;
  56182. exports.Model = Model;
  56183. exports.Axis = Axis;
  56184. exports.env = env$1;
  56185. })));