echarts-en.common.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937
  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. if (draggingTarget && draggingTarget.draggable) {
  1168. this._draggingTarget = draggingTarget;
  1169. draggingTarget.dragging = true;
  1170. this._x = e.offsetX;
  1171. this._y = e.offsetY;
  1172. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1173. }
  1174. },
  1175. _drag: function (e) {
  1176. var draggingTarget = this._draggingTarget;
  1177. if (draggingTarget) {
  1178. var x = e.offsetX;
  1179. var y = e.offsetY;
  1180. var dx = x - this._x;
  1181. var dy = y - this._y;
  1182. this._x = x;
  1183. this._y = y;
  1184. draggingTarget.drift(dx, dy, e);
  1185. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1186. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1187. var lastDropTarget = this._dropTarget;
  1188. this._dropTarget = dropTarget;
  1189. if (draggingTarget !== dropTarget) {
  1190. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1191. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1192. }
  1193. if (dropTarget && dropTarget !== lastDropTarget) {
  1194. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1195. }
  1196. }
  1197. }
  1198. },
  1199. _dragEnd: function (e) {
  1200. var draggingTarget = this._draggingTarget;
  1201. if (draggingTarget) {
  1202. draggingTarget.dragging = false;
  1203. }
  1204. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1205. if (this._dropTarget) {
  1206. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1207. }
  1208. this._draggingTarget = null;
  1209. this._dropTarget = null;
  1210. }
  1211. };
  1212. function param(target, e) {
  1213. return {target: target, topTarget: e && e.topTarget};
  1214. }
  1215. /**
  1216. * Event Mixin
  1217. * @module zrender/mixin/Eventful
  1218. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1219. * pissang (https://www.github.com/pissang)
  1220. */
  1221. var arrySlice = Array.prototype.slice;
  1222. /**
  1223. * Event dispatcher.
  1224. *
  1225. * @alias module:zrender/mixin/Eventful
  1226. * @constructor
  1227. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1228. * `eventProcessor.xxx` called.
  1229. * @param {Function} [eventProcessor.normalizeQuery]
  1230. * param: {string|Object} Raw query.
  1231. * return: {string|Object} Normalized query.
  1232. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1233. * if it returns `true`.
  1234. * param: {string} eventType
  1235. * param: {string|Object} query
  1236. * return: {boolean}
  1237. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1238. * param: {string} eventType
  1239. */
  1240. var Eventful = function (eventProcessor) {
  1241. this._$handlers = {};
  1242. this._$eventProcessor = eventProcessor;
  1243. };
  1244. Eventful.prototype = {
  1245. constructor: Eventful,
  1246. /**
  1247. * The handler can only be triggered once, then removed.
  1248. *
  1249. * @param {string} event The event name.
  1250. * @param {string|Object} [query] Condition used on event filter.
  1251. * @param {Function} handler The event handler.
  1252. * @param {Object} context
  1253. */
  1254. one: function (event, query, handler, context) {
  1255. return on(this, event, query, handler, context, true);
  1256. },
  1257. /**
  1258. * Bind a handler.
  1259. *
  1260. * @param {string} event The event name.
  1261. * @param {string|Object} [query] Condition used on event filter.
  1262. * @param {Function} handler The event handler.
  1263. * @param {Object} [context]
  1264. */
  1265. on: function (event, query, handler, context) {
  1266. return on(this, event, query, handler, context, false);
  1267. },
  1268. /**
  1269. * Whether any handler has bound.
  1270. *
  1271. * @param {string} event
  1272. * @return {boolean}
  1273. */
  1274. isSilent: function (event) {
  1275. var _h = this._$handlers;
  1276. return !_h[event] || !_h[event].length;
  1277. },
  1278. /**
  1279. * Unbind a event.
  1280. *
  1281. * @param {string} [event] The event name.
  1282. * If no `event` input, "off" all listeners.
  1283. * @param {Function} [handler] The event handler.
  1284. * If no `handler` input, "off" all listeners of the `event`.
  1285. */
  1286. off: function (event, handler) {
  1287. var _h = this._$handlers;
  1288. if (!event) {
  1289. this._$handlers = {};
  1290. return this;
  1291. }
  1292. if (handler) {
  1293. if (_h[event]) {
  1294. var newList = [];
  1295. for (var i = 0, l = _h[event].length; i < l; i++) {
  1296. if (_h[event][i].h !== handler) {
  1297. newList.push(_h[event][i]);
  1298. }
  1299. }
  1300. _h[event] = newList;
  1301. }
  1302. if (_h[event] && _h[event].length === 0) {
  1303. delete _h[event];
  1304. }
  1305. }
  1306. else {
  1307. delete _h[event];
  1308. }
  1309. return this;
  1310. },
  1311. /**
  1312. * Dispatch a event.
  1313. *
  1314. * @param {string} type The event name.
  1315. */
  1316. trigger: function (type) {
  1317. var _h = this._$handlers[type];
  1318. var eventProcessor = this._$eventProcessor;
  1319. if (_h) {
  1320. var args = arguments;
  1321. var argLen = args.length;
  1322. if (argLen > 3) {
  1323. args = arrySlice.call(args, 1);
  1324. }
  1325. var len = _h.length;
  1326. for (var i = 0; i < len;) {
  1327. var hItem = _h[i];
  1328. if (eventProcessor
  1329. && eventProcessor.filter
  1330. && hItem.query != null
  1331. && !eventProcessor.filter(type, hItem.query)
  1332. ) {
  1333. i++;
  1334. continue;
  1335. }
  1336. // Optimize advise from backbone
  1337. switch (argLen) {
  1338. case 1:
  1339. hItem.h.call(hItem.ctx);
  1340. break;
  1341. case 2:
  1342. hItem.h.call(hItem.ctx, args[1]);
  1343. break;
  1344. case 3:
  1345. hItem.h.call(hItem.ctx, args[1], args[2]);
  1346. break;
  1347. default:
  1348. // have more than 2 given arguments
  1349. hItem.h.apply(hItem.ctx, args);
  1350. break;
  1351. }
  1352. if (hItem.one) {
  1353. _h.splice(i, 1);
  1354. len--;
  1355. }
  1356. else {
  1357. i++;
  1358. }
  1359. }
  1360. }
  1361. eventProcessor && eventProcessor.afterTrigger
  1362. && eventProcessor.afterTrigger(type);
  1363. return this;
  1364. },
  1365. /**
  1366. * Dispatch a event with context, which is specified at the last parameter.
  1367. *
  1368. * @param {string} type The event name.
  1369. */
  1370. triggerWithContext: function (type) {
  1371. var _h = this._$handlers[type];
  1372. var eventProcessor = this._$eventProcessor;
  1373. if (_h) {
  1374. var args = arguments;
  1375. var argLen = args.length;
  1376. if (argLen > 4) {
  1377. args = arrySlice.call(args, 1, args.length - 1);
  1378. }
  1379. var ctx = args[args.length - 1];
  1380. var len = _h.length;
  1381. for (var i = 0; i < len;) {
  1382. var hItem = _h[i];
  1383. if (eventProcessor
  1384. && eventProcessor.filter
  1385. && hItem.query != null
  1386. && !eventProcessor.filter(type, hItem.query)
  1387. ) {
  1388. i++;
  1389. continue;
  1390. }
  1391. // Optimize advise from backbone
  1392. switch (argLen) {
  1393. case 1:
  1394. hItem.h.call(ctx);
  1395. break;
  1396. case 2:
  1397. hItem.h.call(ctx, args[1]);
  1398. break;
  1399. case 3:
  1400. hItem.h.call(ctx, args[1], args[2]);
  1401. break;
  1402. default:
  1403. // have more than 2 given arguments
  1404. hItem.h.apply(ctx, args);
  1405. break;
  1406. }
  1407. if (hItem.one) {
  1408. _h.splice(i, 1);
  1409. len--;
  1410. }
  1411. else {
  1412. i++;
  1413. }
  1414. }
  1415. }
  1416. eventProcessor && eventProcessor.afterTrigger
  1417. && eventProcessor.afterTrigger(type);
  1418. return this;
  1419. }
  1420. };
  1421. function normalizeQuery(host, query) {
  1422. var eventProcessor = host._$eventProcessor;
  1423. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1424. query = eventProcessor.normalizeQuery(query);
  1425. }
  1426. return query;
  1427. }
  1428. function on(eventful, event, query, handler, context, isOnce) {
  1429. var _h = eventful._$handlers;
  1430. if (typeof query === 'function') {
  1431. context = handler;
  1432. handler = query;
  1433. query = null;
  1434. }
  1435. if (!handler || !event) {
  1436. return eventful;
  1437. }
  1438. query = normalizeQuery(eventful, query);
  1439. if (!_h[event]) {
  1440. _h[event] = [];
  1441. }
  1442. for (var i = 0; i < _h[event].length; i++) {
  1443. if (_h[event][i].h === handler) {
  1444. return eventful;
  1445. }
  1446. }
  1447. var wrap = {
  1448. h: handler,
  1449. one: isOnce,
  1450. query: query,
  1451. ctx: context || eventful,
  1452. // FIXME
  1453. // Do not publish this feature util it is proved that it makes sense.
  1454. callAtLast: handler.zrEventfulCallAtLast
  1455. };
  1456. var lastIndex = _h[event].length - 1;
  1457. var lastWrap = _h[event][lastIndex];
  1458. (lastWrap && lastWrap.callAtLast)
  1459. ? _h[event].splice(lastIndex, 0, wrap)
  1460. : _h[event].push(wrap);
  1461. return eventful;
  1462. }
  1463. /**
  1464. * The algoritm is learnt from
  1465. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1466. * And we made some optimization for matrix inversion.
  1467. * Other similar approaches:
  1468. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1469. */
  1470. var LN2 = Math.log(2);
  1471. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1472. var cacheKey = rowMask + '-' + colMask;
  1473. var fullRank = rows.length;
  1474. if (detCache.hasOwnProperty(cacheKey)) {
  1475. return detCache[cacheKey];
  1476. }
  1477. if (rank === 1) {
  1478. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1479. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1480. return rows[rowStart][colStart];
  1481. }
  1482. var subRowMask = rowMask | (1 << rowStart);
  1483. var subRowStart = rowStart + 1;
  1484. while (rowMask & (1 << subRowStart)) {
  1485. subRowStart++;
  1486. }
  1487. var sum = 0;
  1488. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1489. var colTag = 1 << j;
  1490. if (!(colTag & colMask)) {
  1491. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1492. // det(subMatrix(0, j))
  1493. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1494. colLocalIdx++;
  1495. }
  1496. }
  1497. detCache[cacheKey] = sum;
  1498. return sum;
  1499. }
  1500. /**
  1501. * Usage:
  1502. * ```js
  1503. * var transformer = buildTransformer(
  1504. * [10, 44, 100, 44, 100, 300, 10, 300],
  1505. * [50, 54, 130, 14, 140, 330, 14, 220]
  1506. * );
  1507. * var out = [];
  1508. * transformer && transformer([11, 33], out);
  1509. * ```
  1510. *
  1511. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1512. *
  1513. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1514. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1515. * @return {Function} transformer If fail, return null/undefined.
  1516. */
  1517. function buildTransformer(src, dest) {
  1518. var mA = [
  1519. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1520. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1521. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1522. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1523. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1524. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1525. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1526. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1527. ];
  1528. var detCache = {};
  1529. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1530. if (det === 0) {
  1531. return;
  1532. }
  1533. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1534. var vh = [];
  1535. for (var i = 0; i < 8; i++) {
  1536. for (var j = 0; j < 8; j++) {
  1537. vh[j] == null && (vh[j] = 0);
  1538. vh[j] += ((i + j) % 2 ? -1 : 1)
  1539. // det(subMatrix(i, j))
  1540. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1541. / det * dest[i];
  1542. }
  1543. }
  1544. return function (out, srcPointX, srcPointY) {
  1545. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1546. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1547. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1548. };
  1549. }
  1550. /**
  1551. * Utilities for mouse or touch events.
  1552. */
  1553. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1554. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1555. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1556. var _calcOut = [];
  1557. /**
  1558. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1559. * the input `el`.
  1560. * CSS transform (2D & 3D) is supported.
  1561. *
  1562. * The strategy to fetch the coords:
  1563. * + If `calculate` is not set as `true`, users of this method should
  1564. * ensure that `el` is the same or the same size & location as `e.target`.
  1565. * Otherwise the result coords are probably not expected. Because we
  1566. * firstly try to get coords from e.offsetX/e.offsetY.
  1567. * + If `calculate` is set as `true`, the input `el` can be any element
  1568. * and we force to calculate the coords based on `el`.
  1569. * + The input `el` should be positionable (not position:static).
  1570. *
  1571. * The force `calculate` can be used in case like:
  1572. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1573. *
  1574. * @param {HTMLElement} el DOM element.
  1575. * @param {Event} e Mouse event or touch event.
  1576. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1577. * @param {boolean} [calculate=false] Whether to force calculate
  1578. * the coordinates but not use ones provided by browser.
  1579. */
  1580. function clientToLocal(el, e, out, calculate) {
  1581. out = out || {};
  1582. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1583. // to the padding edge of the target element. The only browser using this convention
  1584. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1585. // not support the properties.
  1586. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1587. // In zr painter.dom, padding edge equals to border edge.
  1588. if (calculate || !env$1.canvasSupported) {
  1589. calculateZrXY(el, e, out);
  1590. }
  1591. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1592. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1593. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1594. // zoom-factor, overflow / opacity layers, transforms ...)
  1595. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1596. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1597. // BTW3, In ff, offsetX/offsetY is always 0.
  1598. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1599. out.zrX = e.layerX;
  1600. out.zrY = e.layerY;
  1601. }
  1602. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1603. else if (e.offsetX != null) {
  1604. out.zrX = e.offsetX;
  1605. out.zrY = e.offsetY;
  1606. }
  1607. // For some other device, e.g., IOS safari.
  1608. else {
  1609. calculateZrXY(el, e, out);
  1610. }
  1611. return out;
  1612. }
  1613. function calculateZrXY(el, e, out) {
  1614. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1615. if (el.getBoundingClientRect && env$1.domSupported) {
  1616. var ex = e.clientX;
  1617. var ey = e.clientY;
  1618. if (el.nodeName.toUpperCase() === 'CANVAS') {
  1619. // Original approach, which do not support CSS transform.
  1620. // marker can not be locationed in a canvas container
  1621. // (getBoundingClientRect is always 0). We do not support
  1622. // that input a pre-created canvas to zr while using css
  1623. // transform in iOS.
  1624. var box = el.getBoundingClientRect();
  1625. out.zrX = ex - box.left;
  1626. out.zrY = ey - box.top;
  1627. return;
  1628. }
  1629. else {
  1630. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1631. var transformer = preparePointerTransformer(prepareCoordMarkers(el, saved), saved);
  1632. if (transformer) {
  1633. transformer(_calcOut, ex, ey);
  1634. out.zrX = _calcOut[0];
  1635. out.zrY = _calcOut[1];
  1636. return;
  1637. }
  1638. }
  1639. }
  1640. out.zrX = out.zrY = 0;
  1641. }
  1642. function prepareCoordMarkers(el, saved) {
  1643. var markers = saved.markers;
  1644. if (markers) {
  1645. return markers;
  1646. }
  1647. markers = saved.markers = [];
  1648. var propLR = ['left', 'right'];
  1649. var propTB = ['top', 'bottom'];
  1650. for (var i = 0; i < 4; i++) {
  1651. var marker = document.createElement('div');
  1652. var stl = marker.style;
  1653. var idxLR = i % 2;
  1654. var idxTB = (i >> 1) % 2;
  1655. stl.cssText = [
  1656. 'position:absolute',
  1657. 'visibility: hidden',
  1658. 'padding: 0',
  1659. 'margin: 0',
  1660. 'border-width: 0',
  1661. 'width:0',
  1662. 'height:0',
  1663. // 'width: 5px',
  1664. // 'height: 5px',
  1665. propLR[idxLR] + ':0',
  1666. propTB[idxTB] + ':0',
  1667. propLR[1 - idxLR] + ':auto',
  1668. propTB[1 - idxTB] + ':auto',
  1669. ''
  1670. ].join('!important;');
  1671. el.appendChild(marker);
  1672. markers.push(marker);
  1673. }
  1674. return markers;
  1675. }
  1676. function preparePointerTransformer(markers, saved) {
  1677. var transformer = saved.transformer;
  1678. var oldSrcCoords = saved.srcCoords;
  1679. var useOld = true;
  1680. var srcCoords = [];
  1681. var destCoords = [];
  1682. for (var i = 0; i < 4; i++) {
  1683. var rect = markers[i].getBoundingClientRect();
  1684. var ii = 2 * i;
  1685. var x = rect.left;
  1686. var y = rect.top;
  1687. srcCoords.push(x, y);
  1688. useOld &= oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1689. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1690. }
  1691. // Cache to avoid time consuming of `buildTransformer`.
  1692. return useOld
  1693. ? transformer
  1694. : (
  1695. saved.srcCoords = srcCoords,
  1696. saved.transformer = buildTransformer(srcCoords, destCoords)
  1697. );
  1698. }
  1699. /**
  1700. * Find native event compat for legency IE.
  1701. * Should be called at the begining of a native event listener.
  1702. *
  1703. * @param {Event} [e] Mouse event or touch event or pointer event.
  1704. * For lagency IE, we use `window.event` is used.
  1705. * @return {Event} The native event.
  1706. */
  1707. function getNativeEvent(e) {
  1708. return e || window.event;
  1709. }
  1710. /**
  1711. * Normalize the coordinates of the input event.
  1712. *
  1713. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1714. * the input `el`.
  1715. * Get `e.zrDelta` if using mouse wheel.
  1716. * Get `e.which`, see the comment inside this function.
  1717. *
  1718. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1719. *
  1720. * Notice: see comments in `clientToLocal`. check the relationship
  1721. * between the result coords and the parameters `el` and `calculate`.
  1722. *
  1723. * @param {HTMLElement} el DOM element.
  1724. * @param {Event} [e] See `getNativeEvent`.
  1725. * @param {boolean} [calculate=false] Whether to force calculate
  1726. * the coordinates but not use ones provided by browser.
  1727. * @return {UIEvent} The normalized native UIEvent.
  1728. */
  1729. function normalizeEvent(el, e, calculate) {
  1730. e = getNativeEvent(e);
  1731. if (e.zrX != null) {
  1732. return e;
  1733. }
  1734. var eventType = e.type;
  1735. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1736. if (!isTouch) {
  1737. clientToLocal(el, e, e, calculate);
  1738. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1739. }
  1740. else {
  1741. var touch = eventType !== 'touchend'
  1742. ? e.targetTouches[0]
  1743. : e.changedTouches[0];
  1744. touch && clientToLocal(el, touch, e, calculate);
  1745. }
  1746. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1747. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1748. // If e.which has been defined, it may be readonly,
  1749. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1750. var button = e.button;
  1751. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1752. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1753. }
  1754. // [Caution]: `e.which` from browser is not always reliable. For example,
  1755. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1756. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1757. // `mousedown (pointerdown)` is the same as Chrome does.
  1758. return e;
  1759. }
  1760. /**
  1761. * @param {HTMLElement} el
  1762. * @param {string} name
  1763. * @param {Function} handler
  1764. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1765. * @param {boolean} [opt.capture=false]
  1766. * @param {boolean} [opt.passive=false]
  1767. */
  1768. function addEventListener(el, name, handler, opt) {
  1769. if (isDomLevel2) {
  1770. // Reproduct the console warning:
  1771. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1772. // Consider marking event handler as 'passive' to make the page more responsive.
  1773. // Just set console log level: verbose in chrome dev tool.
  1774. // then the warning log will be printed when addEventListener called.
  1775. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1776. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1777. // listener delegate all of the upper events of element. Some of those events need
  1778. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1779. // Before passive can be adopted, these issues should be considered:
  1780. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1781. // passive or not.
  1782. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1783. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1784. // compatibility should be handled.
  1785. // var opts = (env.passiveSupported && name === 'mousewheel')
  1786. // ? {passive: true}
  1787. // // By default, the third param of el.addEventListener is `capture: false`.
  1788. // : void 0;
  1789. // el.addEventListener(name, handler /* , opts */);
  1790. el.addEventListener(name, handler, opt);
  1791. }
  1792. else {
  1793. // For simplicity, do not implement `setCapture` for IE9-.
  1794. el.attachEvent('on' + name, handler);
  1795. }
  1796. }
  1797. /**
  1798. * Parameter are the same as `addEventListener`.
  1799. *
  1800. * Notice that if a listener is registered twice, one with capture and one without,
  1801. * remove each one separately. Removal of a capturing listener does not affect a
  1802. * non-capturing version of the same listener, and vice versa.
  1803. */
  1804. function removeEventListener(el, name, handler, opt) {
  1805. if (isDomLevel2) {
  1806. el.removeEventListener(name, handler, opt);
  1807. }
  1808. else {
  1809. el.detachEvent('on' + name, handler);
  1810. }
  1811. }
  1812. /**
  1813. * preventDefault and stopPropagation.
  1814. * Notice: do not use this method in zrender. It can only be
  1815. * used by upper applications if necessary.
  1816. *
  1817. * @param {Event} e A mouse or touch event.
  1818. */
  1819. var stop = isDomLevel2
  1820. ? function (e) {
  1821. e.preventDefault();
  1822. e.stopPropagation();
  1823. e.cancelBubble = true;
  1824. }
  1825. : function (e) {
  1826. e.returnValue = false;
  1827. e.cancelBubble = true;
  1828. };
  1829. /**
  1830. * This method only works for mouseup and mousedown. The functionality is restricted
  1831. * for fault tolerance, See the `e.which` compatibility above.
  1832. *
  1833. * @param {MouseEvent} e
  1834. * @return {boolean}
  1835. */
  1836. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1837. return e.which === 2 || e.which === 3;
  1838. }
  1839. /**
  1840. * To be removed.
  1841. * @deprecated
  1842. */
  1843. /**
  1844. * Only implements needed gestures for mobile.
  1845. */
  1846. var GestureMgr = function () {
  1847. /**
  1848. * @private
  1849. * @type {Array.<Object>}
  1850. */
  1851. this._track = [];
  1852. };
  1853. GestureMgr.prototype = {
  1854. constructor: GestureMgr,
  1855. recognize: function (event, target, root) {
  1856. this._doTrack(event, target, root);
  1857. return this._recognize(event);
  1858. },
  1859. clear: function () {
  1860. this._track.length = 0;
  1861. return this;
  1862. },
  1863. _doTrack: function (event, target, root) {
  1864. var touches = event.touches;
  1865. if (!touches) {
  1866. return;
  1867. }
  1868. var trackItem = {
  1869. points: [],
  1870. touches: [],
  1871. target: target,
  1872. event: event
  1873. };
  1874. for (var i = 0, len = touches.length; i < len; i++) {
  1875. var touch = touches[i];
  1876. var pos = clientToLocal(root, touch, {});
  1877. trackItem.points.push([pos.zrX, pos.zrY]);
  1878. trackItem.touches.push(touch);
  1879. }
  1880. this._track.push(trackItem);
  1881. },
  1882. _recognize: function (event) {
  1883. for (var eventName in recognizers) {
  1884. if (recognizers.hasOwnProperty(eventName)) {
  1885. var gestureInfo = recognizers[eventName](this._track, event);
  1886. if (gestureInfo) {
  1887. return gestureInfo;
  1888. }
  1889. }
  1890. }
  1891. }
  1892. };
  1893. function dist$1(pointPair) {
  1894. var dx = pointPair[1][0] - pointPair[0][0];
  1895. var dy = pointPair[1][1] - pointPair[0][1];
  1896. return Math.sqrt(dx * dx + dy * dy);
  1897. }
  1898. function center(pointPair) {
  1899. return [
  1900. (pointPair[0][0] + pointPair[1][0]) / 2,
  1901. (pointPair[0][1] + pointPair[1][1]) / 2
  1902. ];
  1903. }
  1904. var recognizers = {
  1905. pinch: function (track, event) {
  1906. var trackLen = track.length;
  1907. if (!trackLen) {
  1908. return;
  1909. }
  1910. var pinchEnd = (track[trackLen - 1] || {}).points;
  1911. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1912. if (pinchPre
  1913. && pinchPre.length > 1
  1914. && pinchEnd
  1915. && pinchEnd.length > 1
  1916. ) {
  1917. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1918. !isFinite(pinchScale) && (pinchScale = 1);
  1919. event.pinchScale = pinchScale;
  1920. var pinchCenter = center(pinchEnd);
  1921. event.pinchX = pinchCenter[0];
  1922. event.pinchY = pinchCenter[1];
  1923. return {
  1924. type: 'pinch',
  1925. target: track[0].target,
  1926. event: event
  1927. };
  1928. }
  1929. }
  1930. // Only pinch currently.
  1931. };
  1932. /**
  1933. * [The interface between `Handler` and `HandlerProxy`]:
  1934. *
  1935. * The default `HandlerProxy` only support the common standard web environment
  1936. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  1937. * But `HandlerProxy` can be replaced to support more non-standard environment
  1938. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  1939. * not provided (like echarts-gl did).
  1940. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  1941. * make break changes util inevitable. The interface include the public methods
  1942. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  1943. * drives `Handler`.
  1944. */
  1945. /**
  1946. * [Drag outside]:
  1947. *
  1948. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  1949. * zrender area when dragging. That is important for the improvement of the user experience
  1950. * when dragging something near the boundary without being terminated unexpectedly.
  1951. *
  1952. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  1953. * to resolve this issue. But some drawbacks of it is described in
  1954. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  1955. *
  1956. * Instead, we referenced the specifications:
  1957. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  1958. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  1959. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  1960. * operation and the pointer has left the boundary. (for the mouse event, browsers
  1961. * only do it on `document` and when the pointer has left the boundary of the browser.)
  1962. *
  1963. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  1964. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  1965. * to fire until release the pointer. That is implemented by listen to those event on
  1966. * `document`.
  1967. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  1968. * The touch event support this feature by default.
  1969. *
  1970. * Note:
  1971. * There might be some cases that the mouse event can not be
  1972. * received on `document`. For example,
  1973. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  1974. * of zr dom throw Error .
  1975. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  1976. * zr dom call `stopPropagation`.
  1977. * In these cases, the `mousemove` event might be keep triggered event
  1978. * if the mouse is released. We try to reduce the side-effect in those cases.
  1979. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  1980. *
  1981. * Note:
  1982. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  1983. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  1984. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  1985. * `document` capture phase to prevent the propagation to any listener of the webpage.
  1986. * But they are needed to work when the pointer inside the zrender dom.
  1987. */
  1988. var SILENT = 'silent';
  1989. function makeEventPacket(eveType, targetInfo, event) {
  1990. return {
  1991. type: eveType,
  1992. event: event,
  1993. // target can only be an element that is not silent.
  1994. target: targetInfo.target,
  1995. // topTarget can be a silent element.
  1996. topTarget: targetInfo.topTarget,
  1997. cancelBubble: false,
  1998. offsetX: event.zrX,
  1999. offsetY: event.zrY,
  2000. gestureEvent: event.gestureEvent,
  2001. pinchX: event.pinchX,
  2002. pinchY: event.pinchY,
  2003. pinchScale: event.pinchScale,
  2004. wheelDelta: event.zrDelta,
  2005. zrByTouch: event.zrByTouch,
  2006. which: event.which,
  2007. stop: stopEvent
  2008. };
  2009. }
  2010. function stopEvent() {
  2011. stop(this.event);
  2012. }
  2013. function EmptyProxy() {}
  2014. EmptyProxy.prototype.dispose = function () {};
  2015. var handlerNames = [
  2016. 'click', 'dblclick', 'mousewheel', 'mouseout',
  2017. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  2018. ];
  2019. /**
  2020. * @alias module:zrender/Handler
  2021. * @constructor
  2022. * @extends module:zrender/mixin/Eventful
  2023. * @param {module:zrender/Storage} storage Storage instance.
  2024. * @param {module:zrender/Painter} painter Painter instance.
  2025. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  2026. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  2027. */
  2028. var Handler = function (storage, painter, proxy, painterRoot) {
  2029. Eventful.call(this);
  2030. this.storage = storage;
  2031. this.painter = painter;
  2032. this.painterRoot = painterRoot;
  2033. proxy = proxy || new EmptyProxy();
  2034. /**
  2035. * Proxy of event. can be Dom, WebGLSurface, etc.
  2036. */
  2037. this.proxy = null;
  2038. /**
  2039. * {target, topTarget, x, y}
  2040. * @private
  2041. * @type {Object}
  2042. */
  2043. this._hovered = {};
  2044. /**
  2045. * @private
  2046. * @type {Date}
  2047. */
  2048. this._lastTouchMoment;
  2049. /**
  2050. * @private
  2051. * @type {number}
  2052. */
  2053. this._lastX;
  2054. /**
  2055. * @private
  2056. * @type {number}
  2057. */
  2058. this._lastY;
  2059. /**
  2060. * @private
  2061. * @type {module:zrender/core/GestureMgr}
  2062. */
  2063. this._gestureMgr;
  2064. Draggable.call(this);
  2065. this.setHandlerProxy(proxy);
  2066. };
  2067. Handler.prototype = {
  2068. constructor: Handler,
  2069. setHandlerProxy: function (proxy) {
  2070. if (this.proxy) {
  2071. this.proxy.dispose();
  2072. }
  2073. if (proxy) {
  2074. each$1(handlerNames, function (name) {
  2075. proxy.on && proxy.on(name, this[name], this);
  2076. }, this);
  2077. // Attach handler
  2078. proxy.handler = this;
  2079. }
  2080. this.proxy = proxy;
  2081. },
  2082. mousemove: function (event) {
  2083. var x = event.zrX;
  2084. var y = event.zrY;
  2085. var isOutside = isOutsideBoundary(this, x, y);
  2086. var lastHovered = this._hovered;
  2087. var lastHoveredTarget = lastHovered.target;
  2088. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2089. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2090. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2091. // See #6198.
  2092. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2093. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2094. lastHoveredTarget = lastHovered.target;
  2095. }
  2096. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  2097. var hoveredTarget = hovered.target;
  2098. var proxy = this.proxy;
  2099. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2100. // Mouse out on previous hovered element
  2101. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2102. this.dispatchToElement(lastHovered, 'mouseout', event);
  2103. }
  2104. // Mouse moving on one element
  2105. this.dispatchToElement(hovered, 'mousemove', event);
  2106. // Mouse over on a new element
  2107. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2108. this.dispatchToElement(hovered, 'mouseover', event);
  2109. }
  2110. },
  2111. mouseout: function (event) {
  2112. var eventControl = event.zrEventControl;
  2113. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2114. if (eventControl !== 'only_globalout') {
  2115. this.dispatchToElement(this._hovered, 'mouseout', event);
  2116. }
  2117. if (eventControl !== 'no_globalout') {
  2118. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2119. // the `globalout` should have been triggered. But currently not.
  2120. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2121. }
  2122. },
  2123. /**
  2124. * Resize
  2125. */
  2126. resize: function (event) {
  2127. this._hovered = {};
  2128. },
  2129. /**
  2130. * Dispatch event
  2131. * @param {string} eventName
  2132. * @param {event=} eventArgs
  2133. */
  2134. dispatch: function (eventName, eventArgs) {
  2135. var handler = this[eventName];
  2136. handler && handler.call(this, eventArgs);
  2137. },
  2138. /**
  2139. * Dispose
  2140. */
  2141. dispose: function () {
  2142. this.proxy.dispose();
  2143. this.storage =
  2144. this.proxy =
  2145. this.painter = null;
  2146. },
  2147. /**
  2148. * 设置默认的cursor style
  2149. * @param {string} [cursorStyle='default'] 例如 crosshair
  2150. */
  2151. setCursorStyle: function (cursorStyle) {
  2152. var proxy = this.proxy;
  2153. proxy.setCursor && proxy.setCursor(cursorStyle);
  2154. },
  2155. /**
  2156. * 事件分发代理
  2157. *
  2158. * @private
  2159. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2160. * @param {string} eventName 事件名称
  2161. * @param {Object} event 事件对象
  2162. */
  2163. dispatchToElement: function (targetInfo, eventName, event) {
  2164. targetInfo = targetInfo || {};
  2165. var el = targetInfo.target;
  2166. if (el && el.silent) {
  2167. return;
  2168. }
  2169. var eventHandler = 'on' + eventName;
  2170. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2171. while (el) {
  2172. el[eventHandler]
  2173. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2174. el.trigger(eventName, eventPacket);
  2175. el = el.parent;
  2176. if (eventPacket.cancelBubble) {
  2177. break;
  2178. }
  2179. }
  2180. if (!eventPacket.cancelBubble) {
  2181. // 冒泡到顶级 zrender 对象
  2182. this.trigger(eventName, eventPacket);
  2183. // 分发事件到用户自定义层
  2184. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2185. this.painter && this.painter.eachOtherLayer(function (layer) {
  2186. if (typeof (layer[eventHandler]) === 'function') {
  2187. layer[eventHandler].call(layer, eventPacket);
  2188. }
  2189. if (layer.trigger) {
  2190. layer.trigger(eventName, eventPacket);
  2191. }
  2192. });
  2193. }
  2194. },
  2195. /**
  2196. * @private
  2197. * @param {number} x
  2198. * @param {number} y
  2199. * @param {module:zrender/graphic/Displayable} exclude
  2200. * @return {model:zrender/Element}
  2201. * @method
  2202. */
  2203. findHover: function (x, y, exclude) {
  2204. var list = this.storage.getDisplayList();
  2205. var out = {x: x, y: y};
  2206. for (var i = list.length - 1; i >= 0; i--) {
  2207. var hoverCheckResult;
  2208. if (list[i] !== exclude
  2209. // getDisplayList may include ignored item in VML mode
  2210. && !list[i].ignore
  2211. && (hoverCheckResult = isHover(list[i], x, y))
  2212. ) {
  2213. !out.topTarget && (out.topTarget = list[i]);
  2214. if (hoverCheckResult !== SILENT) {
  2215. out.target = list[i];
  2216. break;
  2217. }
  2218. }
  2219. }
  2220. return out;
  2221. },
  2222. processGesture: function (event, stage) {
  2223. if (!this._gestureMgr) {
  2224. this._gestureMgr = new GestureMgr();
  2225. }
  2226. var gestureMgr = this._gestureMgr;
  2227. stage === 'start' && gestureMgr.clear();
  2228. var gestureInfo = gestureMgr.recognize(
  2229. event,
  2230. this.findHover(event.zrX, event.zrY, null).target,
  2231. this.proxy.dom
  2232. );
  2233. stage === 'end' && gestureMgr.clear();
  2234. // Do not do any preventDefault here. Upper application do that if necessary.
  2235. if (gestureInfo) {
  2236. var type = gestureInfo.type;
  2237. event.gestureEvent = type;
  2238. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2239. }
  2240. }
  2241. };
  2242. // Common handlers
  2243. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2244. Handler.prototype[name] = function (event) {
  2245. var x = event.zrX;
  2246. var y = event.zrY;
  2247. var isOutside = isOutsideBoundary(this, x, y);
  2248. var hovered;
  2249. var hoveredTarget;
  2250. if (name !== 'mouseup' || !isOutside) {
  2251. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2252. hovered = this.findHover(x, y);
  2253. hoveredTarget = hovered.target;
  2254. }
  2255. if (name === 'mousedown') {
  2256. this._downEl = hoveredTarget;
  2257. this._downPoint = [event.zrX, event.zrY];
  2258. // In case click triggered before mouseup
  2259. this._upEl = hoveredTarget;
  2260. }
  2261. else if (name === 'mouseup') {
  2262. this._upEl = hoveredTarget;
  2263. }
  2264. else if (name === 'click') {
  2265. if (this._downEl !== this._upEl
  2266. // Original click event is triggered on the whole canvas element,
  2267. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2268. // which should be filtered, otherwise it will bring trouble to
  2269. // pan and zoom.
  2270. || !this._downPoint
  2271. // Arbitrary value
  2272. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2273. ) {
  2274. return;
  2275. }
  2276. this._downPoint = null;
  2277. }
  2278. this.dispatchToElement(hovered, name, event);
  2279. };
  2280. });
  2281. function isHover(displayable, x, y) {
  2282. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2283. var el = displayable;
  2284. var isSilent;
  2285. while (el) {
  2286. // If clipped by ancestor.
  2287. // FIXME: If clipPath has neither stroke nor fill,
  2288. // el.clipPath.contain(x, y) will always return false.
  2289. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2290. return false;
  2291. }
  2292. if (el.silent) {
  2293. isSilent = true;
  2294. }
  2295. el = el.parent;
  2296. }
  2297. return isSilent ? SILENT : true;
  2298. }
  2299. return false;
  2300. }
  2301. /**
  2302. * See [Drag outside].
  2303. */
  2304. function isOutsideBoundary(handlerInstance, x, y) {
  2305. var painter = handlerInstance.painter;
  2306. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2307. }
  2308. mixin(Handler, Eventful);
  2309. mixin(Handler, Draggable);
  2310. /**
  2311. * 3x2矩阵操作类
  2312. * @exports zrender/tool/matrix
  2313. */
  2314. /* global Float32Array */
  2315. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2316. ? Array
  2317. : Float32Array;
  2318. /**
  2319. * Create a identity matrix.
  2320. * @return {Float32Array|Array.<number>}
  2321. */
  2322. function create$1() {
  2323. var out = new ArrayCtor$1(6);
  2324. identity(out);
  2325. return out;
  2326. }
  2327. /**
  2328. * 设置矩阵为单位矩阵
  2329. * @param {Float32Array|Array.<number>} out
  2330. */
  2331. function identity(out) {
  2332. out[0] = 1;
  2333. out[1] = 0;
  2334. out[2] = 0;
  2335. out[3] = 1;
  2336. out[4] = 0;
  2337. out[5] = 0;
  2338. return out;
  2339. }
  2340. /**
  2341. * 复制矩阵
  2342. * @param {Float32Array|Array.<number>} out
  2343. * @param {Float32Array|Array.<number>} m
  2344. */
  2345. function copy$1(out, m) {
  2346. out[0] = m[0];
  2347. out[1] = m[1];
  2348. out[2] = m[2];
  2349. out[3] = m[3];
  2350. out[4] = m[4];
  2351. out[5] = m[5];
  2352. return out;
  2353. }
  2354. /**
  2355. * 矩阵相乘
  2356. * @param {Float32Array|Array.<number>} out
  2357. * @param {Float32Array|Array.<number>} m1
  2358. * @param {Float32Array|Array.<number>} m2
  2359. */
  2360. function mul$1(out, m1, m2) {
  2361. // Consider matrix.mul(m, m2, m);
  2362. // where out is the same as m2.
  2363. // So use temp variable to escape error.
  2364. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2365. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2366. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2367. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2368. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2369. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2370. out[0] = out0;
  2371. out[1] = out1;
  2372. out[2] = out2;
  2373. out[3] = out3;
  2374. out[4] = out4;
  2375. out[5] = out5;
  2376. return out;
  2377. }
  2378. /**
  2379. * 平移变换
  2380. * @param {Float32Array|Array.<number>} out
  2381. * @param {Float32Array|Array.<number>} a
  2382. * @param {Float32Array|Array.<number>} v
  2383. */
  2384. function translate(out, a, v) {
  2385. out[0] = a[0];
  2386. out[1] = a[1];
  2387. out[2] = a[2];
  2388. out[3] = a[3];
  2389. out[4] = a[4] + v[0];
  2390. out[5] = a[5] + v[1];
  2391. return out;
  2392. }
  2393. /**
  2394. * 旋转变换
  2395. * @param {Float32Array|Array.<number>} out
  2396. * @param {Float32Array|Array.<number>} a
  2397. * @param {number} rad
  2398. */
  2399. function rotate(out, a, rad) {
  2400. var aa = a[0];
  2401. var ac = a[2];
  2402. var atx = a[4];
  2403. var ab = a[1];
  2404. var ad = a[3];
  2405. var aty = a[5];
  2406. var st = Math.sin(rad);
  2407. var ct = Math.cos(rad);
  2408. out[0] = aa * ct + ab * st;
  2409. out[1] = -aa * st + ab * ct;
  2410. out[2] = ac * ct + ad * st;
  2411. out[3] = -ac * st + ct * ad;
  2412. out[4] = ct * atx + st * aty;
  2413. out[5] = ct * aty - st * atx;
  2414. return out;
  2415. }
  2416. /**
  2417. * 缩放变换
  2418. * @param {Float32Array|Array.<number>} out
  2419. * @param {Float32Array|Array.<number>} a
  2420. * @param {Float32Array|Array.<number>} v
  2421. */
  2422. function scale$1(out, a, v) {
  2423. var vx = v[0];
  2424. var vy = v[1];
  2425. out[0] = a[0] * vx;
  2426. out[1] = a[1] * vy;
  2427. out[2] = a[2] * vx;
  2428. out[3] = a[3] * vy;
  2429. out[4] = a[4] * vx;
  2430. out[5] = a[5] * vy;
  2431. return out;
  2432. }
  2433. /**
  2434. * 求逆矩阵
  2435. * @param {Float32Array|Array.<number>} out
  2436. * @param {Float32Array|Array.<number>} a
  2437. */
  2438. function invert(out, a) {
  2439. var aa = a[0];
  2440. var ac = a[2];
  2441. var atx = a[4];
  2442. var ab = a[1];
  2443. var ad = a[3];
  2444. var aty = a[5];
  2445. var det = aa * ad - ab * ac;
  2446. if (!det) {
  2447. return null;
  2448. }
  2449. det = 1.0 / det;
  2450. out[0] = ad * det;
  2451. out[1] = -ab * det;
  2452. out[2] = -ac * det;
  2453. out[3] = aa * det;
  2454. out[4] = (ac * aty - ad * atx) * det;
  2455. out[5] = (ab * atx - aa * aty) * det;
  2456. return out;
  2457. }
  2458. /**
  2459. * Clone a new matrix.
  2460. * @param {Float32Array|Array.<number>} a
  2461. */
  2462. function clone$2(a) {
  2463. var b = create$1();
  2464. copy$1(b, a);
  2465. return b;
  2466. }
  2467. var matrix = (Object.freeze || Object)({
  2468. create: create$1,
  2469. identity: identity,
  2470. copy: copy$1,
  2471. mul: mul$1,
  2472. translate: translate,
  2473. rotate: rotate,
  2474. scale: scale$1,
  2475. invert: invert,
  2476. clone: clone$2
  2477. });
  2478. /**
  2479. * 提供变换扩展
  2480. * @module zrender/mixin/Transformable
  2481. * @author pissang (https://www.github.com/pissang)
  2482. */
  2483. var mIdentity = identity;
  2484. var EPSILON = 5e-5;
  2485. function isNotAroundZero(val) {
  2486. return val > EPSILON || val < -EPSILON;
  2487. }
  2488. /**
  2489. * @alias module:zrender/mixin/Transformable
  2490. * @constructor
  2491. */
  2492. var Transformable = function (opts) {
  2493. opts = opts || {};
  2494. // If there are no given position, rotation, scale
  2495. if (!opts.position) {
  2496. /**
  2497. * 平移
  2498. * @type {Array.<number>}
  2499. * @default [0, 0]
  2500. */
  2501. this.position = [0, 0];
  2502. }
  2503. if (opts.rotation == null) {
  2504. /**
  2505. * 旋转
  2506. * @type {Array.<number>}
  2507. * @default 0
  2508. */
  2509. this.rotation = 0;
  2510. }
  2511. if (!opts.scale) {
  2512. /**
  2513. * 缩放
  2514. * @type {Array.<number>}
  2515. * @default [1, 1]
  2516. */
  2517. this.scale = [1, 1];
  2518. }
  2519. /**
  2520. * 旋转和缩放的原点
  2521. * @type {Array.<number>}
  2522. * @default null
  2523. */
  2524. this.origin = this.origin || null;
  2525. };
  2526. var transformableProto = Transformable.prototype;
  2527. transformableProto.transform = null;
  2528. /**
  2529. * 判断是否需要有坐标变换
  2530. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2531. */
  2532. transformableProto.needLocalTransform = function () {
  2533. return isNotAroundZero(this.rotation)
  2534. || isNotAroundZero(this.position[0])
  2535. || isNotAroundZero(this.position[1])
  2536. || isNotAroundZero(this.scale[0] - 1)
  2537. || isNotAroundZero(this.scale[1] - 1);
  2538. };
  2539. var scaleTmp = [];
  2540. transformableProto.updateTransform = function () {
  2541. var parent = this.parent;
  2542. var parentHasTransform = parent && parent.transform;
  2543. var needLocalTransform = this.needLocalTransform();
  2544. var m = this.transform;
  2545. if (!(needLocalTransform || parentHasTransform)) {
  2546. m && mIdentity(m);
  2547. return;
  2548. }
  2549. m = m || create$1();
  2550. if (needLocalTransform) {
  2551. this.getLocalTransform(m);
  2552. }
  2553. else {
  2554. mIdentity(m);
  2555. }
  2556. // 应用父节点变换
  2557. if (parentHasTransform) {
  2558. if (needLocalTransform) {
  2559. mul$1(m, parent.transform, m);
  2560. }
  2561. else {
  2562. copy$1(m, parent.transform);
  2563. }
  2564. }
  2565. // 保存这个变换矩阵
  2566. this.transform = m;
  2567. var globalScaleRatio = this.globalScaleRatio;
  2568. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2569. this.getGlobalScale(scaleTmp);
  2570. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2571. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2572. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2573. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2574. m[0] *= sx;
  2575. m[1] *= sx;
  2576. m[2] *= sy;
  2577. m[3] *= sy;
  2578. }
  2579. this.invTransform = this.invTransform || create$1();
  2580. invert(this.invTransform, m);
  2581. };
  2582. transformableProto.getLocalTransform = function (m) {
  2583. return Transformable.getLocalTransform(this, m);
  2584. };
  2585. /**
  2586. * 将自己的transform应用到context上
  2587. * @param {CanvasRenderingContext2D} ctx
  2588. */
  2589. transformableProto.setTransform = function (ctx) {
  2590. var m = this.transform;
  2591. var dpr = ctx.dpr || 1;
  2592. if (m) {
  2593. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2594. }
  2595. else {
  2596. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2597. }
  2598. };
  2599. transformableProto.restoreTransform = function (ctx) {
  2600. var dpr = ctx.dpr || 1;
  2601. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2602. };
  2603. var tmpTransform = [];
  2604. var originTransform = create$1();
  2605. transformableProto.setLocalTransform = function (m) {
  2606. if (!m) {
  2607. // TODO return or set identity?
  2608. return;
  2609. }
  2610. var sx = m[0] * m[0] + m[1] * m[1];
  2611. var sy = m[2] * m[2] + m[3] * m[3];
  2612. var position = this.position;
  2613. var scale$$1 = this.scale;
  2614. if (isNotAroundZero(sx - 1)) {
  2615. sx = Math.sqrt(sx);
  2616. }
  2617. if (isNotAroundZero(sy - 1)) {
  2618. sy = Math.sqrt(sy);
  2619. }
  2620. if (m[0] < 0) {
  2621. sx = -sx;
  2622. }
  2623. if (m[3] < 0) {
  2624. sy = -sy;
  2625. }
  2626. position[0] = m[4];
  2627. position[1] = m[5];
  2628. scale$$1[0] = sx;
  2629. scale$$1[1] = sy;
  2630. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2631. };
  2632. /**
  2633. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2634. */
  2635. transformableProto.decomposeTransform = function () {
  2636. if (!this.transform) {
  2637. return;
  2638. }
  2639. var parent = this.parent;
  2640. var m = this.transform;
  2641. if (parent && parent.transform) {
  2642. // Get local transform and decompose them to position, scale, rotation
  2643. mul$1(tmpTransform, parent.invTransform, m);
  2644. m = tmpTransform;
  2645. }
  2646. var origin = this.origin;
  2647. if (origin && (origin[0] || origin[1])) {
  2648. originTransform[4] = origin[0];
  2649. originTransform[5] = origin[1];
  2650. mul$1(tmpTransform, m, originTransform);
  2651. tmpTransform[4] -= origin[0];
  2652. tmpTransform[5] -= origin[1];
  2653. m = tmpTransform;
  2654. }
  2655. this.setLocalTransform(m);
  2656. };
  2657. /**
  2658. * Get global scale
  2659. * @return {Array.<number>}
  2660. */
  2661. transformableProto.getGlobalScale = function (out) {
  2662. var m = this.transform;
  2663. out = out || [];
  2664. if (!m) {
  2665. out[0] = 1;
  2666. out[1] = 1;
  2667. return out;
  2668. }
  2669. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2670. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2671. if (m[0] < 0) {
  2672. out[0] = -out[0];
  2673. }
  2674. if (m[3] < 0) {
  2675. out[1] = -out[1];
  2676. }
  2677. return out;
  2678. };
  2679. /**
  2680. * 变换坐标位置到 shape 的局部坐标空间
  2681. * @method
  2682. * @param {number} x
  2683. * @param {number} y
  2684. * @return {Array.<number>}
  2685. */
  2686. transformableProto.transformCoordToLocal = function (x, y) {
  2687. var v2 = [x, y];
  2688. var invTransform = this.invTransform;
  2689. if (invTransform) {
  2690. applyTransform(v2, v2, invTransform);
  2691. }
  2692. return v2;
  2693. };
  2694. /**
  2695. * 变换局部坐标位置到全局坐标空间
  2696. * @method
  2697. * @param {number} x
  2698. * @param {number} y
  2699. * @return {Array.<number>}
  2700. */
  2701. transformableProto.transformCoordToGlobal = function (x, y) {
  2702. var v2 = [x, y];
  2703. var transform = this.transform;
  2704. if (transform) {
  2705. applyTransform(v2, v2, transform);
  2706. }
  2707. return v2;
  2708. };
  2709. /**
  2710. * @static
  2711. * @param {Object} target
  2712. * @param {Array.<number>} target.origin
  2713. * @param {number} target.rotation
  2714. * @param {Array.<number>} target.position
  2715. * @param {Array.<number>} [m]
  2716. */
  2717. Transformable.getLocalTransform = function (target, m) {
  2718. m = m || [];
  2719. mIdentity(m);
  2720. var origin = target.origin;
  2721. var scale$$1 = target.scale || [1, 1];
  2722. var rotation = target.rotation || 0;
  2723. var position = target.position || [0, 0];
  2724. if (origin) {
  2725. // Translate to origin
  2726. m[4] -= origin[0];
  2727. m[5] -= origin[1];
  2728. }
  2729. scale$1(m, m, scale$$1);
  2730. if (rotation) {
  2731. rotate(m, m, rotation);
  2732. }
  2733. if (origin) {
  2734. // Translate back from origin
  2735. m[4] += origin[0];
  2736. m[5] += origin[1];
  2737. }
  2738. m[4] += position[0];
  2739. m[5] += position[1];
  2740. return m;
  2741. };
  2742. /**
  2743. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2744. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2745. * @exports zrender/animation/easing
  2746. */
  2747. var easing = {
  2748. /**
  2749. * @param {number} k
  2750. * @return {number}
  2751. */
  2752. linear: function (k) {
  2753. return k;
  2754. },
  2755. /**
  2756. * @param {number} k
  2757. * @return {number}
  2758. */
  2759. quadraticIn: function (k) {
  2760. return k * k;
  2761. },
  2762. /**
  2763. * @param {number} k
  2764. * @return {number}
  2765. */
  2766. quadraticOut: function (k) {
  2767. return k * (2 - k);
  2768. },
  2769. /**
  2770. * @param {number} k
  2771. * @return {number}
  2772. */
  2773. quadraticInOut: function (k) {
  2774. if ((k *= 2) < 1) {
  2775. return 0.5 * k * k;
  2776. }
  2777. return -0.5 * (--k * (k - 2) - 1);
  2778. },
  2779. // 三次方的缓动(t^3)
  2780. /**
  2781. * @param {number} k
  2782. * @return {number}
  2783. */
  2784. cubicIn: function (k) {
  2785. return k * k * k;
  2786. },
  2787. /**
  2788. * @param {number} k
  2789. * @return {number}
  2790. */
  2791. cubicOut: function (k) {
  2792. return --k * k * k + 1;
  2793. },
  2794. /**
  2795. * @param {number} k
  2796. * @return {number}
  2797. */
  2798. cubicInOut: function (k) {
  2799. if ((k *= 2) < 1) {
  2800. return 0.5 * k * k * k;
  2801. }
  2802. return 0.5 * ((k -= 2) * k * k + 2);
  2803. },
  2804. // 四次方的缓动(t^4)
  2805. /**
  2806. * @param {number} k
  2807. * @return {number}
  2808. */
  2809. quarticIn: function (k) {
  2810. return k * k * k * k;
  2811. },
  2812. /**
  2813. * @param {number} k
  2814. * @return {number}
  2815. */
  2816. quarticOut: function (k) {
  2817. return 1 - (--k * k * k * k);
  2818. },
  2819. /**
  2820. * @param {number} k
  2821. * @return {number}
  2822. */
  2823. quarticInOut: function (k) {
  2824. if ((k *= 2) < 1) {
  2825. return 0.5 * k * k * k * k;
  2826. }
  2827. return -0.5 * ((k -= 2) * k * k * k - 2);
  2828. },
  2829. // 五次方的缓动(t^5)
  2830. /**
  2831. * @param {number} k
  2832. * @return {number}
  2833. */
  2834. quinticIn: function (k) {
  2835. return k * k * k * k * k;
  2836. },
  2837. /**
  2838. * @param {number} k
  2839. * @return {number}
  2840. */
  2841. quinticOut: function (k) {
  2842. return --k * k * k * k * k + 1;
  2843. },
  2844. /**
  2845. * @param {number} k
  2846. * @return {number}
  2847. */
  2848. quinticInOut: function (k) {
  2849. if ((k *= 2) < 1) {
  2850. return 0.5 * k * k * k * k * k;
  2851. }
  2852. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2853. },
  2854. // 正弦曲线的缓动(sin(t))
  2855. /**
  2856. * @param {number} k
  2857. * @return {number}
  2858. */
  2859. sinusoidalIn: function (k) {
  2860. return 1 - Math.cos(k * Math.PI / 2);
  2861. },
  2862. /**
  2863. * @param {number} k
  2864. * @return {number}
  2865. */
  2866. sinusoidalOut: function (k) {
  2867. return Math.sin(k * Math.PI / 2);
  2868. },
  2869. /**
  2870. * @param {number} k
  2871. * @return {number}
  2872. */
  2873. sinusoidalInOut: function (k) {
  2874. return 0.5 * (1 - Math.cos(Math.PI * k));
  2875. },
  2876. // 指数曲线的缓动(2^t)
  2877. /**
  2878. * @param {number} k
  2879. * @return {number}
  2880. */
  2881. exponentialIn: function (k) {
  2882. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2883. },
  2884. /**
  2885. * @param {number} k
  2886. * @return {number}
  2887. */
  2888. exponentialOut: function (k) {
  2889. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2890. },
  2891. /**
  2892. * @param {number} k
  2893. * @return {number}
  2894. */
  2895. exponentialInOut: function (k) {
  2896. if (k === 0) {
  2897. return 0;
  2898. }
  2899. if (k === 1) {
  2900. return 1;
  2901. }
  2902. if ((k *= 2) < 1) {
  2903. return 0.5 * Math.pow(1024, k - 1);
  2904. }
  2905. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2906. },
  2907. // 圆形曲线的缓动(sqrt(1-t^2))
  2908. /**
  2909. * @param {number} k
  2910. * @return {number}
  2911. */
  2912. circularIn: function (k) {
  2913. return 1 - Math.sqrt(1 - k * k);
  2914. },
  2915. /**
  2916. * @param {number} k
  2917. * @return {number}
  2918. */
  2919. circularOut: function (k) {
  2920. return Math.sqrt(1 - (--k * k));
  2921. },
  2922. /**
  2923. * @param {number} k
  2924. * @return {number}
  2925. */
  2926. circularInOut: function (k) {
  2927. if ((k *= 2) < 1) {
  2928. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2929. }
  2930. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2931. },
  2932. // 创建类似于弹簧在停止前来回振荡的动画
  2933. /**
  2934. * @param {number} k
  2935. * @return {number}
  2936. */
  2937. elasticIn: function (k) {
  2938. var s;
  2939. var a = 0.1;
  2940. var p = 0.4;
  2941. if (k === 0) {
  2942. return 0;
  2943. }
  2944. if (k === 1) {
  2945. return 1;
  2946. }
  2947. if (!a || a < 1) {
  2948. a = 1;
  2949. s = p / 4;
  2950. }
  2951. else {
  2952. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2953. }
  2954. return -(a * Math.pow(2, 10 * (k -= 1))
  2955. * Math.sin((k - s) * (2 * Math.PI) / p));
  2956. },
  2957. /**
  2958. * @param {number} k
  2959. * @return {number}
  2960. */
  2961. elasticOut: function (k) {
  2962. var s;
  2963. var a = 0.1;
  2964. var p = 0.4;
  2965. if (k === 0) {
  2966. return 0;
  2967. }
  2968. if (k === 1) {
  2969. return 1;
  2970. }
  2971. if (!a || a < 1) {
  2972. a = 1;
  2973. s = p / 4;
  2974. }
  2975. else {
  2976. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2977. }
  2978. return (a * Math.pow(2, -10 * k)
  2979. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2980. },
  2981. /**
  2982. * @param {number} k
  2983. * @return {number}
  2984. */
  2985. elasticInOut: function (k) {
  2986. var s;
  2987. var a = 0.1;
  2988. var p = 0.4;
  2989. if (k === 0) {
  2990. return 0;
  2991. }
  2992. if (k === 1) {
  2993. return 1;
  2994. }
  2995. if (!a || a < 1) {
  2996. a = 1;
  2997. s = p / 4;
  2998. }
  2999. else {
  3000. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3001. }
  3002. if ((k *= 2) < 1) {
  3003. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3004. * Math.sin((k - s) * (2 * Math.PI) / p));
  3005. }
  3006. return a * Math.pow(2, -10 * (k -= 1))
  3007. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3008. },
  3009. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  3010. /**
  3011. * @param {number} k
  3012. * @return {number}
  3013. */
  3014. backIn: function (k) {
  3015. var s = 1.70158;
  3016. return k * k * ((s + 1) * k - s);
  3017. },
  3018. /**
  3019. * @param {number} k
  3020. * @return {number}
  3021. */
  3022. backOut: function (k) {
  3023. var s = 1.70158;
  3024. return --k * k * ((s + 1) * k + s) + 1;
  3025. },
  3026. /**
  3027. * @param {number} k
  3028. * @return {number}
  3029. */
  3030. backInOut: function (k) {
  3031. var s = 1.70158 * 1.525;
  3032. if ((k *= 2) < 1) {
  3033. return 0.5 * (k * k * ((s + 1) * k - s));
  3034. }
  3035. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3036. },
  3037. // 创建弹跳效果
  3038. /**
  3039. * @param {number} k
  3040. * @return {number}
  3041. */
  3042. bounceIn: function (k) {
  3043. return 1 - easing.bounceOut(1 - k);
  3044. },
  3045. /**
  3046. * @param {number} k
  3047. * @return {number}
  3048. */
  3049. bounceOut: function (k) {
  3050. if (k < (1 / 2.75)) {
  3051. return 7.5625 * k * k;
  3052. }
  3053. else if (k < (2 / 2.75)) {
  3054. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3055. }
  3056. else if (k < (2.5 / 2.75)) {
  3057. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3058. }
  3059. else {
  3060. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3061. }
  3062. },
  3063. /**
  3064. * @param {number} k
  3065. * @return {number}
  3066. */
  3067. bounceInOut: function (k) {
  3068. if (k < 0.5) {
  3069. return easing.bounceIn(k * 2) * 0.5;
  3070. }
  3071. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3072. }
  3073. };
  3074. /**
  3075. * 动画主控制器
  3076. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  3077. * @config life(1000) 动画时长
  3078. * @config delay(0) 动画延迟时间
  3079. * @config loop(true)
  3080. * @config gap(0) 循环的间隔时间
  3081. * @config onframe
  3082. * @config easing(optional)
  3083. * @config ondestroy(optional)
  3084. * @config onrestart(optional)
  3085. *
  3086. * TODO pause
  3087. */
  3088. function Clip(options) {
  3089. this._target = options.target;
  3090. // 生命周期
  3091. this._life = options.life || 1000;
  3092. // 延时
  3093. this._delay = options.delay || 0;
  3094. // 开始时间
  3095. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  3096. this._initialized = false;
  3097. // 是否循环
  3098. this.loop = options.loop == null ? false : options.loop;
  3099. this.gap = options.gap || 0;
  3100. this.easing = options.easing || 'Linear';
  3101. this.onframe = options.onframe;
  3102. this.ondestroy = options.ondestroy;
  3103. this.onrestart = options.onrestart;
  3104. this._pausedTime = 0;
  3105. this._paused = false;
  3106. }
  3107. Clip.prototype = {
  3108. constructor: Clip,
  3109. step: function (globalTime, deltaTime) {
  3110. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3111. // PENDING
  3112. if (!this._initialized) {
  3113. this._startTime = globalTime + this._delay;
  3114. this._initialized = true;
  3115. }
  3116. if (this._paused) {
  3117. this._pausedTime += deltaTime;
  3118. return;
  3119. }
  3120. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  3121. // 还没开始
  3122. if (percent < 0) {
  3123. return;
  3124. }
  3125. percent = Math.min(percent, 1);
  3126. var easing$$1 = this.easing;
  3127. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3128. var schedule = typeof easingFunc === 'function'
  3129. ? easingFunc(percent)
  3130. : percent;
  3131. this.fire('frame', schedule);
  3132. // 结束
  3133. if (percent === 1) {
  3134. if (this.loop) {
  3135. this.restart(globalTime);
  3136. // 重新开始周期
  3137. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3138. return 'restart';
  3139. }
  3140. // 动画完成将这个控制器标识为待删除
  3141. // 在Animation.update中进行批量删除
  3142. this._needsRemove = true;
  3143. return 'destroy';
  3144. }
  3145. return null;
  3146. },
  3147. restart: function (globalTime) {
  3148. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3149. this._startTime = globalTime - remainder + this.gap;
  3150. this._pausedTime = 0;
  3151. this._needsRemove = false;
  3152. },
  3153. fire: function (eventType, arg) {
  3154. eventType = 'on' + eventType;
  3155. if (this[eventType]) {
  3156. this[eventType](this._target, arg);
  3157. }
  3158. },
  3159. pause: function () {
  3160. this._paused = true;
  3161. },
  3162. resume: function () {
  3163. this._paused = false;
  3164. }
  3165. };
  3166. // Simple LRU cache use doubly linked list
  3167. // @module zrender/core/LRU
  3168. /**
  3169. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3170. * @constructor
  3171. */
  3172. var LinkedList = function () {
  3173. /**
  3174. * @type {module:zrender/core/LRU~Entry}
  3175. */
  3176. this.head = null;
  3177. /**
  3178. * @type {module:zrender/core/LRU~Entry}
  3179. */
  3180. this.tail = null;
  3181. this._len = 0;
  3182. };
  3183. var linkedListProto = LinkedList.prototype;
  3184. /**
  3185. * Insert a new value at the tail
  3186. * @param {} val
  3187. * @return {module:zrender/core/LRU~Entry}
  3188. */
  3189. linkedListProto.insert = function (val) {
  3190. var entry = new Entry(val);
  3191. this.insertEntry(entry);
  3192. return entry;
  3193. };
  3194. /**
  3195. * Insert an entry at the tail
  3196. * @param {module:zrender/core/LRU~Entry} entry
  3197. */
  3198. linkedListProto.insertEntry = function (entry) {
  3199. if (!this.head) {
  3200. this.head = this.tail = entry;
  3201. }
  3202. else {
  3203. this.tail.next = entry;
  3204. entry.prev = this.tail;
  3205. entry.next = null;
  3206. this.tail = entry;
  3207. }
  3208. this._len++;
  3209. };
  3210. /**
  3211. * Remove entry.
  3212. * @param {module:zrender/core/LRU~Entry} entry
  3213. */
  3214. linkedListProto.remove = function (entry) {
  3215. var prev = entry.prev;
  3216. var next = entry.next;
  3217. if (prev) {
  3218. prev.next = next;
  3219. }
  3220. else {
  3221. // Is head
  3222. this.head = next;
  3223. }
  3224. if (next) {
  3225. next.prev = prev;
  3226. }
  3227. else {
  3228. // Is tail
  3229. this.tail = prev;
  3230. }
  3231. entry.next = entry.prev = null;
  3232. this._len--;
  3233. };
  3234. /**
  3235. * @return {number}
  3236. */
  3237. linkedListProto.len = function () {
  3238. return this._len;
  3239. };
  3240. /**
  3241. * Clear list
  3242. */
  3243. linkedListProto.clear = function () {
  3244. this.head = this.tail = null;
  3245. this._len = 0;
  3246. };
  3247. /**
  3248. * @constructor
  3249. * @param {} val
  3250. */
  3251. var Entry = function (val) {
  3252. /**
  3253. * @type {}
  3254. */
  3255. this.value = val;
  3256. /**
  3257. * @type {module:zrender/core/LRU~Entry}
  3258. */
  3259. this.next;
  3260. /**
  3261. * @type {module:zrender/core/LRU~Entry}
  3262. */
  3263. this.prev;
  3264. };
  3265. /**
  3266. * LRU Cache
  3267. * @constructor
  3268. * @alias module:zrender/core/LRU
  3269. */
  3270. var LRU = function (maxSize) {
  3271. this._list = new LinkedList();
  3272. this._map = {};
  3273. this._maxSize = maxSize || 10;
  3274. this._lastRemovedEntry = null;
  3275. };
  3276. var LRUProto = LRU.prototype;
  3277. /**
  3278. * @param {string} key
  3279. * @param {} value
  3280. * @return {} Removed value
  3281. */
  3282. LRUProto.put = function (key, value) {
  3283. var list = this._list;
  3284. var map = this._map;
  3285. var removed = null;
  3286. if (map[key] == null) {
  3287. var len = list.len();
  3288. // Reuse last removed entry
  3289. var entry = this._lastRemovedEntry;
  3290. if (len >= this._maxSize && len > 0) {
  3291. // Remove the least recently used
  3292. var leastUsedEntry = list.head;
  3293. list.remove(leastUsedEntry);
  3294. delete map[leastUsedEntry.key];
  3295. removed = leastUsedEntry.value;
  3296. this._lastRemovedEntry = leastUsedEntry;
  3297. }
  3298. if (entry) {
  3299. entry.value = value;
  3300. }
  3301. else {
  3302. entry = new Entry(value);
  3303. }
  3304. entry.key = key;
  3305. list.insertEntry(entry);
  3306. map[key] = entry;
  3307. }
  3308. return removed;
  3309. };
  3310. /**
  3311. * @param {string} key
  3312. * @return {}
  3313. */
  3314. LRUProto.get = function (key) {
  3315. var entry = this._map[key];
  3316. var list = this._list;
  3317. if (entry != null) {
  3318. // Put the latest used entry in the tail
  3319. if (entry !== list.tail) {
  3320. list.remove(entry);
  3321. list.insertEntry(entry);
  3322. }
  3323. return entry.value;
  3324. }
  3325. };
  3326. /**
  3327. * Clear the cache
  3328. */
  3329. LRUProto.clear = function () {
  3330. this._list.clear();
  3331. this._map = {};
  3332. };
  3333. var kCSSColorTable = {
  3334. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3335. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3336. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3337. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3338. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3339. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3340. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3341. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3342. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3343. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3344. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3345. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3346. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3347. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3348. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3349. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3350. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3351. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3352. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3353. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3354. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3355. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3356. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3357. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3358. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3359. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3360. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3361. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3362. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3363. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3364. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3365. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3366. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3367. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3368. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3369. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3370. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3371. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3372. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3373. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3374. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3375. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3376. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3377. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3378. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3379. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3380. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3381. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3382. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3383. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3384. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3385. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3386. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3387. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3388. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3389. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3390. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3391. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3392. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3393. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3394. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3395. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3396. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3397. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3398. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3399. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3400. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3401. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3402. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3403. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3404. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3405. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3406. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3407. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3408. };
  3409. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3410. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3411. return i < 0 ? 0 : i > 255 ? 255 : i;
  3412. }
  3413. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  3414. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3415. return i < 0 ? 0 : i > 360 ? 360 : i;
  3416. }
  3417. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3418. return f < 0 ? 0 : f > 1 ? 1 : f;
  3419. }
  3420. function parseCssInt(str) { // int or percentage.
  3421. if (str.length && str.charAt(str.length - 1) === '%') {
  3422. return clampCssByte(parseFloat(str) / 100 * 255);
  3423. }
  3424. return clampCssByte(parseInt(str, 10));
  3425. }
  3426. function parseCssFloat(str) { // float or percentage.
  3427. if (str.length && str.charAt(str.length - 1) === '%') {
  3428. return clampCssFloat(parseFloat(str) / 100);
  3429. }
  3430. return clampCssFloat(parseFloat(str));
  3431. }
  3432. function cssHueToRgb(m1, m2, h) {
  3433. if (h < 0) {
  3434. h += 1;
  3435. }
  3436. else if (h > 1) {
  3437. h -= 1;
  3438. }
  3439. if (h * 6 < 1) {
  3440. return m1 + (m2 - m1) * h * 6;
  3441. }
  3442. if (h * 2 < 1) {
  3443. return m2;
  3444. }
  3445. if (h * 3 < 2) {
  3446. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3447. }
  3448. return m1;
  3449. }
  3450. function lerpNumber(a, b, p) {
  3451. return a + (b - a) * p;
  3452. }
  3453. function setRgba(out, r, g, b, a) {
  3454. out[0] = r;
  3455. out[1] = g;
  3456. out[2] = b;
  3457. out[3] = a;
  3458. return out;
  3459. }
  3460. function copyRgba(out, a) {
  3461. out[0] = a[0];
  3462. out[1] = a[1];
  3463. out[2] = a[2];
  3464. out[3] = a[3];
  3465. return out;
  3466. }
  3467. var colorCache = new LRU(20);
  3468. var lastRemovedArr = null;
  3469. function putToCache(colorStr, rgbaArr) {
  3470. // Reuse removed array
  3471. if (lastRemovedArr) {
  3472. copyRgba(lastRemovedArr, rgbaArr);
  3473. }
  3474. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3475. }
  3476. /**
  3477. * @param {string} colorStr
  3478. * @param {Array.<number>} out
  3479. * @return {Array.<number>}
  3480. * @memberOf module:zrender/util/color
  3481. */
  3482. function parse(colorStr, rgbaArr) {
  3483. if (!colorStr) {
  3484. return;
  3485. }
  3486. rgbaArr = rgbaArr || [];
  3487. var cached = colorCache.get(colorStr);
  3488. if (cached) {
  3489. return copyRgba(rgbaArr, cached);
  3490. }
  3491. // colorStr may be not string
  3492. colorStr = colorStr + '';
  3493. // Remove all whitespace, not compliant, but should just be more accepting.
  3494. var str = colorStr.replace(/ /g, '').toLowerCase();
  3495. // Color keywords (and transparent) lookup.
  3496. if (str in kCSSColorTable) {
  3497. copyRgba(rgbaArr, kCSSColorTable[str]);
  3498. putToCache(colorStr, rgbaArr);
  3499. return rgbaArr;
  3500. }
  3501. // #abc and #abc123 syntax.
  3502. if (str.charAt(0) === '#') {
  3503. if (str.length === 4) {
  3504. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3505. if (!(iv >= 0 && iv <= 0xfff)) {
  3506. setRgba(rgbaArr, 0, 0, 0, 1);
  3507. return; // Covers NaN.
  3508. }
  3509. setRgba(rgbaArr,
  3510. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3511. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3512. (iv & 0xf) | ((iv & 0xf) << 4),
  3513. 1
  3514. );
  3515. putToCache(colorStr, rgbaArr);
  3516. return rgbaArr;
  3517. }
  3518. else if (str.length === 7) {
  3519. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3520. if (!(iv >= 0 && iv <= 0xffffff)) {
  3521. setRgba(rgbaArr, 0, 0, 0, 1);
  3522. return; // Covers NaN.
  3523. }
  3524. setRgba(rgbaArr,
  3525. (iv & 0xff0000) >> 16,
  3526. (iv & 0xff00) >> 8,
  3527. iv & 0xff,
  3528. 1
  3529. );
  3530. putToCache(colorStr, rgbaArr);
  3531. return rgbaArr;
  3532. }
  3533. return;
  3534. }
  3535. var op = str.indexOf('(');
  3536. var ep = str.indexOf(')');
  3537. if (op !== -1 && ep + 1 === str.length) {
  3538. var fname = str.substr(0, op);
  3539. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3540. var alpha = 1; // To allow case fallthrough.
  3541. switch (fname) {
  3542. case 'rgba':
  3543. if (params.length !== 4) {
  3544. setRgba(rgbaArr, 0, 0, 0, 1);
  3545. return;
  3546. }
  3547. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3548. // Fall through.
  3549. case 'rgb':
  3550. if (params.length !== 3) {
  3551. setRgba(rgbaArr, 0, 0, 0, 1);
  3552. return;
  3553. }
  3554. setRgba(rgbaArr,
  3555. parseCssInt(params[0]),
  3556. parseCssInt(params[1]),
  3557. parseCssInt(params[2]),
  3558. alpha
  3559. );
  3560. putToCache(colorStr, rgbaArr);
  3561. return rgbaArr;
  3562. case 'hsla':
  3563. if (params.length !== 4) {
  3564. setRgba(rgbaArr, 0, 0, 0, 1);
  3565. return;
  3566. }
  3567. params[3] = parseCssFloat(params[3]);
  3568. hsla2rgba(params, rgbaArr);
  3569. putToCache(colorStr, rgbaArr);
  3570. return rgbaArr;
  3571. case 'hsl':
  3572. if (params.length !== 3) {
  3573. setRgba(rgbaArr, 0, 0, 0, 1);
  3574. return;
  3575. }
  3576. hsla2rgba(params, rgbaArr);
  3577. putToCache(colorStr, rgbaArr);
  3578. return rgbaArr;
  3579. default:
  3580. return;
  3581. }
  3582. }
  3583. setRgba(rgbaArr, 0, 0, 0, 1);
  3584. return;
  3585. }
  3586. /**
  3587. * @param {Array.<number>} hsla
  3588. * @param {Array.<number>} rgba
  3589. * @return {Array.<number>} rgba
  3590. */
  3591. function hsla2rgba(hsla, rgba) {
  3592. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3593. // NOTE(deanm): According to the CSS spec s/l should only be
  3594. // percentages, but we don't bother and let float or percentage.
  3595. var s = parseCssFloat(hsla[1]);
  3596. var l = parseCssFloat(hsla[2]);
  3597. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3598. var m1 = l * 2 - m2;
  3599. rgba = rgba || [];
  3600. setRgba(rgba,
  3601. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3602. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3603. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3604. 1
  3605. );
  3606. if (hsla.length === 4) {
  3607. rgba[3] = hsla[3];
  3608. }
  3609. return rgba;
  3610. }
  3611. /**
  3612. * @param {Array.<number>} rgba
  3613. * @return {Array.<number>} hsla
  3614. */
  3615. function rgba2hsla(rgba) {
  3616. if (!rgba) {
  3617. return;
  3618. }
  3619. // RGB from 0 to 255
  3620. var R = rgba[0] / 255;
  3621. var G = rgba[1] / 255;
  3622. var B = rgba[2] / 255;
  3623. var vMin = Math.min(R, G, B); // Min. value of RGB
  3624. var vMax = Math.max(R, G, B); // Max. value of RGB
  3625. var delta = vMax - vMin; // Delta RGB value
  3626. var L = (vMax + vMin) / 2;
  3627. var H;
  3628. var S;
  3629. // HSL results from 0 to 1
  3630. if (delta === 0) {
  3631. H = 0;
  3632. S = 0;
  3633. }
  3634. else {
  3635. if (L < 0.5) {
  3636. S = delta / (vMax + vMin);
  3637. }
  3638. else {
  3639. S = delta / (2 - vMax - vMin);
  3640. }
  3641. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3642. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3643. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3644. if (R === vMax) {
  3645. H = deltaB - deltaG;
  3646. }
  3647. else if (G === vMax) {
  3648. H = (1 / 3) + deltaR - deltaB;
  3649. }
  3650. else if (B === vMax) {
  3651. H = (2 / 3) + deltaG - deltaR;
  3652. }
  3653. if (H < 0) {
  3654. H += 1;
  3655. }
  3656. if (H > 1) {
  3657. H -= 1;
  3658. }
  3659. }
  3660. var hsla = [H * 360, S, L];
  3661. if (rgba[3] != null) {
  3662. hsla.push(rgba[3]);
  3663. }
  3664. return hsla;
  3665. }
  3666. /**
  3667. * @param {string} color
  3668. * @param {number} level
  3669. * @return {string}
  3670. * @memberOf module:zrender/util/color
  3671. */
  3672. function lift(color, level) {
  3673. var colorArr = parse(color);
  3674. if (colorArr) {
  3675. for (var i = 0; i < 3; i++) {
  3676. if (level < 0) {
  3677. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3678. }
  3679. else {
  3680. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3681. }
  3682. if (colorArr[i] > 255) {
  3683. colorArr[i] = 255;
  3684. }
  3685. else if (color[i] < 0) {
  3686. colorArr[i] = 0;
  3687. }
  3688. }
  3689. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3690. }
  3691. }
  3692. /**
  3693. * @param {string} color
  3694. * @return {string}
  3695. * @memberOf module:zrender/util/color
  3696. */
  3697. function toHex(color) {
  3698. var colorArr = parse(color);
  3699. if (colorArr) {
  3700. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3701. }
  3702. }
  3703. /**
  3704. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3705. * @param {number} normalizedValue A float between 0 and 1.
  3706. * @param {Array.<Array.<number>>} colors List of rgba color array
  3707. * @param {Array.<number>} [out] Mapped gba color array
  3708. * @return {Array.<number>} will be null/undefined if input illegal.
  3709. */
  3710. function fastLerp(normalizedValue, colors, out) {
  3711. if (!(colors && colors.length)
  3712. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3713. ) {
  3714. return;
  3715. }
  3716. out = out || [];
  3717. var value = normalizedValue * (colors.length - 1);
  3718. var leftIndex = Math.floor(value);
  3719. var rightIndex = Math.ceil(value);
  3720. var leftColor = colors[leftIndex];
  3721. var rightColor = colors[rightIndex];
  3722. var dv = value - leftIndex;
  3723. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3724. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3725. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3726. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3727. return out;
  3728. }
  3729. /**
  3730. * @deprecated
  3731. */
  3732. var fastMapToColor = fastLerp;
  3733. /**
  3734. * @param {number} normalizedValue A float between 0 and 1.
  3735. * @param {Array.<string>} colors Color list.
  3736. * @param {boolean=} fullOutput Default false.
  3737. * @return {(string|Object)} Result color. If fullOutput,
  3738. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3739. * @memberOf module:zrender/util/color
  3740. */
  3741. function lerp$1(normalizedValue, colors, fullOutput) {
  3742. if (!(colors && colors.length)
  3743. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3744. ) {
  3745. return;
  3746. }
  3747. var value = normalizedValue * (colors.length - 1);
  3748. var leftIndex = Math.floor(value);
  3749. var rightIndex = Math.ceil(value);
  3750. var leftColor = parse(colors[leftIndex]);
  3751. var rightColor = parse(colors[rightIndex]);
  3752. var dv = value - leftIndex;
  3753. var color = stringify(
  3754. [
  3755. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3756. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3757. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3758. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3759. ],
  3760. 'rgba'
  3761. );
  3762. return fullOutput
  3763. ? {
  3764. color: color,
  3765. leftIndex: leftIndex,
  3766. rightIndex: rightIndex,
  3767. value: value
  3768. }
  3769. : color;
  3770. }
  3771. /**
  3772. * @deprecated
  3773. */
  3774. var mapToColor = lerp$1;
  3775. /**
  3776. * @param {string} color
  3777. * @param {number=} h 0 ~ 360, ignore when null.
  3778. * @param {number=} s 0 ~ 1, ignore when null.
  3779. * @param {number=} l 0 ~ 1, ignore when null.
  3780. * @return {string} Color string in rgba format.
  3781. * @memberOf module:zrender/util/color
  3782. */
  3783. function modifyHSL(color, h, s, l) {
  3784. color = parse(color);
  3785. if (color) {
  3786. color = rgba2hsla(color);
  3787. h != null && (color[0] = clampCssAngle(h));
  3788. s != null && (color[1] = parseCssFloat(s));
  3789. l != null && (color[2] = parseCssFloat(l));
  3790. return stringify(hsla2rgba(color), 'rgba');
  3791. }
  3792. }
  3793. /**
  3794. * @param {string} color
  3795. * @param {number=} alpha 0 ~ 1
  3796. * @return {string} Color string in rgba format.
  3797. * @memberOf module:zrender/util/color
  3798. */
  3799. function modifyAlpha(color, alpha) {
  3800. color = parse(color);
  3801. if (color && alpha != null) {
  3802. color[3] = clampCssFloat(alpha);
  3803. return stringify(color, 'rgba');
  3804. }
  3805. }
  3806. /**
  3807. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3808. * @param {string} type 'rgba', 'hsva', ...
  3809. * @return {string} Result color. (If input illegal, return undefined).
  3810. */
  3811. function stringify(arrColor, type) {
  3812. if (!arrColor || !arrColor.length) {
  3813. return;
  3814. }
  3815. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3816. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3817. colorStr += ',' + arrColor[3];
  3818. }
  3819. return type + '(' + colorStr + ')';
  3820. }
  3821. var color = (Object.freeze || Object)({
  3822. parse: parse,
  3823. lift: lift,
  3824. toHex: toHex,
  3825. fastLerp: fastLerp,
  3826. fastMapToColor: fastMapToColor,
  3827. lerp: lerp$1,
  3828. mapToColor: mapToColor,
  3829. modifyHSL: modifyHSL,
  3830. modifyAlpha: modifyAlpha,
  3831. stringify: stringify
  3832. });
  3833. /**
  3834. * @module echarts/animation/Animator
  3835. */
  3836. var arraySlice = Array.prototype.slice;
  3837. function defaultGetter(target, key) {
  3838. return target[key];
  3839. }
  3840. function defaultSetter(target, key, value) {
  3841. target[key] = value;
  3842. }
  3843. /**
  3844. * @param {number} p0
  3845. * @param {number} p1
  3846. * @param {number} percent
  3847. * @return {number}
  3848. */
  3849. function interpolateNumber(p0, p1, percent) {
  3850. return (p1 - p0) * percent + p0;
  3851. }
  3852. /**
  3853. * @param {string} p0
  3854. * @param {string} p1
  3855. * @param {number} percent
  3856. * @return {string}
  3857. */
  3858. function interpolateString(p0, p1, percent) {
  3859. return percent > 0.5 ? p1 : p0;
  3860. }
  3861. /**
  3862. * @param {Array} p0
  3863. * @param {Array} p1
  3864. * @param {number} percent
  3865. * @param {Array} out
  3866. * @param {number} arrDim
  3867. */
  3868. function interpolateArray(p0, p1, percent, out, arrDim) {
  3869. var len = p0.length;
  3870. if (arrDim === 1) {
  3871. for (var i = 0; i < len; i++) {
  3872. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3873. }
  3874. }
  3875. else {
  3876. var len2 = len && p0[0].length;
  3877. for (var i = 0; i < len; i++) {
  3878. for (var j = 0; j < len2; j++) {
  3879. out[i][j] = interpolateNumber(
  3880. p0[i][j], p1[i][j], percent
  3881. );
  3882. }
  3883. }
  3884. }
  3885. }
  3886. // arr0 is source array, arr1 is target array.
  3887. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3888. function fillArr(arr0, arr1, arrDim) {
  3889. var arr0Len = arr0.length;
  3890. var arr1Len = arr1.length;
  3891. if (arr0Len !== arr1Len) {
  3892. // FIXME Not work for TypedArray
  3893. var isPreviousLarger = arr0Len > arr1Len;
  3894. if (isPreviousLarger) {
  3895. // Cut the previous
  3896. arr0.length = arr1Len;
  3897. }
  3898. else {
  3899. // Fill the previous
  3900. for (var i = arr0Len; i < arr1Len; i++) {
  3901. arr0.push(
  3902. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3903. );
  3904. }
  3905. }
  3906. }
  3907. // Handling NaN value
  3908. var len2 = arr0[0] && arr0[0].length;
  3909. for (var i = 0; i < arr0.length; i++) {
  3910. if (arrDim === 1) {
  3911. if (isNaN(arr0[i])) {
  3912. arr0[i] = arr1[i];
  3913. }
  3914. }
  3915. else {
  3916. for (var j = 0; j < len2; j++) {
  3917. if (isNaN(arr0[i][j])) {
  3918. arr0[i][j] = arr1[i][j];
  3919. }
  3920. }
  3921. }
  3922. }
  3923. }
  3924. /**
  3925. * @param {Array} arr0
  3926. * @param {Array} arr1
  3927. * @param {number} arrDim
  3928. * @return {boolean}
  3929. */
  3930. function isArraySame(arr0, arr1, arrDim) {
  3931. if (arr0 === arr1) {
  3932. return true;
  3933. }
  3934. var len = arr0.length;
  3935. if (len !== arr1.length) {
  3936. return false;
  3937. }
  3938. if (arrDim === 1) {
  3939. for (var i = 0; i < len; i++) {
  3940. if (arr0[i] !== arr1[i]) {
  3941. return false;
  3942. }
  3943. }
  3944. }
  3945. else {
  3946. var len2 = arr0[0].length;
  3947. for (var i = 0; i < len; i++) {
  3948. for (var j = 0; j < len2; j++) {
  3949. if (arr0[i][j] !== arr1[i][j]) {
  3950. return false;
  3951. }
  3952. }
  3953. }
  3954. }
  3955. return true;
  3956. }
  3957. /**
  3958. * Catmull Rom interpolate array
  3959. * @param {Array} p0
  3960. * @param {Array} p1
  3961. * @param {Array} p2
  3962. * @param {Array} p3
  3963. * @param {number} t
  3964. * @param {number} t2
  3965. * @param {number} t3
  3966. * @param {Array} out
  3967. * @param {number} arrDim
  3968. */
  3969. function catmullRomInterpolateArray(
  3970. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3971. ) {
  3972. var len = p0.length;
  3973. if (arrDim === 1) {
  3974. for (var i = 0; i < len; i++) {
  3975. out[i] = catmullRomInterpolate(
  3976. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3977. );
  3978. }
  3979. }
  3980. else {
  3981. var len2 = p0[0].length;
  3982. for (var i = 0; i < len; i++) {
  3983. for (var j = 0; j < len2; j++) {
  3984. out[i][j] = catmullRomInterpolate(
  3985. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3986. t, t2, t3
  3987. );
  3988. }
  3989. }
  3990. }
  3991. }
  3992. /**
  3993. * Catmull Rom interpolate number
  3994. * @param {number} p0
  3995. * @param {number} p1
  3996. * @param {number} p2
  3997. * @param {number} p3
  3998. * @param {number} t
  3999. * @param {number} t2
  4000. * @param {number} t3
  4001. * @return {number}
  4002. */
  4003. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  4004. var v0 = (p2 - p0) * 0.5;
  4005. var v1 = (p3 - p1) * 0.5;
  4006. return (2 * (p1 - p2) + v0 + v1) * t3
  4007. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  4008. + v0 * t + p1;
  4009. }
  4010. function cloneValue(value) {
  4011. if (isArrayLike(value)) {
  4012. var len = value.length;
  4013. if (isArrayLike(value[0])) {
  4014. var ret = [];
  4015. for (var i = 0; i < len; i++) {
  4016. ret.push(arraySlice.call(value[i]));
  4017. }
  4018. return ret;
  4019. }
  4020. return arraySlice.call(value);
  4021. }
  4022. return value;
  4023. }
  4024. function rgba2String(rgba) {
  4025. rgba[0] = Math.floor(rgba[0]);
  4026. rgba[1] = Math.floor(rgba[1]);
  4027. rgba[2] = Math.floor(rgba[2]);
  4028. return 'rgba(' + rgba.join(',') + ')';
  4029. }
  4030. function getArrayDim(keyframes) {
  4031. var lastValue = keyframes[keyframes.length - 1].value;
  4032. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  4033. }
  4034. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  4035. var getter = animator._getter;
  4036. var setter = animator._setter;
  4037. var useSpline = easing === 'spline';
  4038. var trackLen = keyframes.length;
  4039. if (!trackLen) {
  4040. return;
  4041. }
  4042. // Guess data type
  4043. var firstVal = keyframes[0].value;
  4044. var isValueArray = isArrayLike(firstVal);
  4045. var isValueColor = false;
  4046. var isValueString = false;
  4047. // For vertices morphing
  4048. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  4049. var trackMaxTime;
  4050. // Sort keyframe as ascending
  4051. keyframes.sort(function (a, b) {
  4052. return a.time - b.time;
  4053. });
  4054. trackMaxTime = keyframes[trackLen - 1].time;
  4055. // Percents of each keyframe
  4056. var kfPercents = [];
  4057. // Value of each keyframe
  4058. var kfValues = [];
  4059. var prevValue = keyframes[0].value;
  4060. var isAllValueEqual = true;
  4061. for (var i = 0; i < trackLen; i++) {
  4062. kfPercents.push(keyframes[i].time / trackMaxTime);
  4063. // Assume value is a color when it is a string
  4064. var value = keyframes[i].value;
  4065. // Check if value is equal, deep check if value is array
  4066. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  4067. || (!isValueArray && value === prevValue))) {
  4068. isAllValueEqual = false;
  4069. }
  4070. prevValue = value;
  4071. // Try converting a string to a color array
  4072. if (typeof value === 'string') {
  4073. var colorArray = parse(value);
  4074. if (colorArray) {
  4075. value = colorArray;
  4076. isValueColor = true;
  4077. }
  4078. else {
  4079. isValueString = true;
  4080. }
  4081. }
  4082. kfValues.push(value);
  4083. }
  4084. if (!forceAnimate && isAllValueEqual) {
  4085. return;
  4086. }
  4087. var lastValue = kfValues[trackLen - 1];
  4088. // Polyfill array and NaN value
  4089. for (var i = 0; i < trackLen - 1; i++) {
  4090. if (isValueArray) {
  4091. fillArr(kfValues[i], lastValue, arrDim);
  4092. }
  4093. else {
  4094. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  4095. kfValues[i] = lastValue;
  4096. }
  4097. }
  4098. }
  4099. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  4100. // Cache the key of last frame to speed up when
  4101. // animation playback is sequency
  4102. var lastFrame = 0;
  4103. var lastFramePercent = 0;
  4104. var start;
  4105. var w;
  4106. var p0;
  4107. var p1;
  4108. var p2;
  4109. var p3;
  4110. if (isValueColor) {
  4111. var rgba = [0, 0, 0, 0];
  4112. }
  4113. var onframe = function (target, percent) {
  4114. // Find the range keyframes
  4115. // kf1-----kf2---------current--------kf3
  4116. // find kf2 and kf3 and do interpolation
  4117. var frame;
  4118. // In the easing function like elasticOut, percent may less than 0
  4119. if (percent < 0) {
  4120. frame = 0;
  4121. }
  4122. else if (percent < lastFramePercent) {
  4123. // Start from next key
  4124. // PENDING start from lastFrame ?
  4125. start = Math.min(lastFrame + 1, trackLen - 1);
  4126. for (frame = start; frame >= 0; frame--) {
  4127. if (kfPercents[frame] <= percent) {
  4128. break;
  4129. }
  4130. }
  4131. // PENDING really need to do this ?
  4132. frame = Math.min(frame, trackLen - 2);
  4133. }
  4134. else {
  4135. for (frame = lastFrame; frame < trackLen; frame++) {
  4136. if (kfPercents[frame] > percent) {
  4137. break;
  4138. }
  4139. }
  4140. frame = Math.min(frame - 1, trackLen - 2);
  4141. }
  4142. lastFrame = frame;
  4143. lastFramePercent = percent;
  4144. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  4145. if (range === 0) {
  4146. return;
  4147. }
  4148. else {
  4149. w = (percent - kfPercents[frame]) / range;
  4150. }
  4151. if (useSpline) {
  4152. p1 = kfValues[frame];
  4153. p0 = kfValues[frame === 0 ? frame : frame - 1];
  4154. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  4155. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  4156. if (isValueArray) {
  4157. catmullRomInterpolateArray(
  4158. p0, p1, p2, p3, w, w * w, w * w * w,
  4159. getter(target, propName),
  4160. arrDim
  4161. );
  4162. }
  4163. else {
  4164. var value;
  4165. if (isValueColor) {
  4166. value = catmullRomInterpolateArray(
  4167. p0, p1, p2, p3, w, w * w, w * w * w,
  4168. rgba, 1
  4169. );
  4170. value = rgba2String(rgba);
  4171. }
  4172. else if (isValueString) {
  4173. // String is step(0.5)
  4174. return interpolateString(p1, p2, w);
  4175. }
  4176. else {
  4177. value = catmullRomInterpolate(
  4178. p0, p1, p2, p3, w, w * w, w * w * w
  4179. );
  4180. }
  4181. setter(
  4182. target,
  4183. propName,
  4184. value
  4185. );
  4186. }
  4187. }
  4188. else {
  4189. if (isValueArray) {
  4190. interpolateArray(
  4191. kfValues[frame], kfValues[frame + 1], w,
  4192. getter(target, propName),
  4193. arrDim
  4194. );
  4195. }
  4196. else {
  4197. var value;
  4198. if (isValueColor) {
  4199. interpolateArray(
  4200. kfValues[frame], kfValues[frame + 1], w,
  4201. rgba, 1
  4202. );
  4203. value = rgba2String(rgba);
  4204. }
  4205. else if (isValueString) {
  4206. // String is step(0.5)
  4207. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4208. }
  4209. else {
  4210. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4211. }
  4212. setter(
  4213. target,
  4214. propName,
  4215. value
  4216. );
  4217. }
  4218. }
  4219. };
  4220. var clip = new Clip({
  4221. target: animator._target,
  4222. life: trackMaxTime,
  4223. loop: animator._loop,
  4224. delay: animator._delay,
  4225. onframe: onframe,
  4226. ondestroy: oneTrackDone
  4227. });
  4228. if (easing && easing !== 'spline') {
  4229. clip.easing = easing;
  4230. }
  4231. return clip;
  4232. }
  4233. /**
  4234. * @alias module:zrender/animation/Animator
  4235. * @constructor
  4236. * @param {Object} target
  4237. * @param {boolean} loop
  4238. * @param {Function} getter
  4239. * @param {Function} setter
  4240. */
  4241. var Animator = function (target, loop, getter, setter) {
  4242. this._tracks = {};
  4243. this._target = target;
  4244. this._loop = loop || false;
  4245. this._getter = getter || defaultGetter;
  4246. this._setter = setter || defaultSetter;
  4247. this._clipCount = 0;
  4248. this._delay = 0;
  4249. this._doneList = [];
  4250. this._onframeList = [];
  4251. this._clipList = [];
  4252. };
  4253. Animator.prototype = {
  4254. /**
  4255. * 设置动画关键帧
  4256. * @param {number} time 关键帧时间,单位是ms
  4257. * @param {Object} props 关键帧的属性值,key-value表示
  4258. * @return {module:zrender/animation/Animator}
  4259. */
  4260. when: function (time /* ms */, props) {
  4261. var tracks = this._tracks;
  4262. for (var propName in props) {
  4263. if (!props.hasOwnProperty(propName)) {
  4264. continue;
  4265. }
  4266. if (!tracks[propName]) {
  4267. tracks[propName] = [];
  4268. // Invalid value
  4269. var value = this._getter(this._target, propName);
  4270. if (value == null) {
  4271. // zrLog('Invalid property ' + propName);
  4272. continue;
  4273. }
  4274. // If time is 0
  4275. // Then props is given initialize value
  4276. // Else
  4277. // Initialize value from current prop value
  4278. if (time !== 0) {
  4279. tracks[propName].push({
  4280. time: 0,
  4281. value: cloneValue(value)
  4282. });
  4283. }
  4284. }
  4285. tracks[propName].push({
  4286. time: time,
  4287. value: props[propName]
  4288. });
  4289. }
  4290. return this;
  4291. },
  4292. /**
  4293. * 添加动画每一帧的回调函数
  4294. * @param {Function} callback
  4295. * @return {module:zrender/animation/Animator}
  4296. */
  4297. during: function (callback) {
  4298. this._onframeList.push(callback);
  4299. return this;
  4300. },
  4301. pause: function () {
  4302. for (var i = 0; i < this._clipList.length; i++) {
  4303. this._clipList[i].pause();
  4304. }
  4305. this._paused = true;
  4306. },
  4307. resume: function () {
  4308. for (var i = 0; i < this._clipList.length; i++) {
  4309. this._clipList[i].resume();
  4310. }
  4311. this._paused = false;
  4312. },
  4313. isPaused: function () {
  4314. return !!this._paused;
  4315. },
  4316. _doneCallback: function () {
  4317. // Clear all tracks
  4318. this._tracks = {};
  4319. // Clear all clips
  4320. this._clipList.length = 0;
  4321. var doneList = this._doneList;
  4322. var len = doneList.length;
  4323. for (var i = 0; i < len; i++) {
  4324. doneList[i].call(this);
  4325. }
  4326. },
  4327. /**
  4328. * 开始执行动画
  4329. * @param {string|Function} [easing]
  4330. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4331. * @param {boolean} forceAnimate
  4332. * @return {module:zrender/animation/Animator}
  4333. */
  4334. start: function (easing, forceAnimate) {
  4335. var self = this;
  4336. var clipCount = 0;
  4337. var oneTrackDone = function () {
  4338. clipCount--;
  4339. if (!clipCount) {
  4340. self._doneCallback();
  4341. }
  4342. };
  4343. var lastClip;
  4344. for (var propName in this._tracks) {
  4345. if (!this._tracks.hasOwnProperty(propName)) {
  4346. continue;
  4347. }
  4348. var clip = createTrackClip(
  4349. this, easing, oneTrackDone,
  4350. this._tracks[propName], propName, forceAnimate
  4351. );
  4352. if (clip) {
  4353. this._clipList.push(clip);
  4354. clipCount++;
  4355. // If start after added to animation
  4356. if (this.animation) {
  4357. this.animation.addClip(clip);
  4358. }
  4359. lastClip = clip;
  4360. }
  4361. }
  4362. // Add during callback on the last clip
  4363. if (lastClip) {
  4364. var oldOnFrame = lastClip.onframe;
  4365. lastClip.onframe = function (target, percent) {
  4366. oldOnFrame(target, percent);
  4367. for (var i = 0; i < self._onframeList.length; i++) {
  4368. self._onframeList[i](target, percent);
  4369. }
  4370. };
  4371. }
  4372. // This optimization will help the case that in the upper application
  4373. // the view may be refreshed frequently, where animation will be
  4374. // called repeatly but nothing changed.
  4375. if (!clipCount) {
  4376. this._doneCallback();
  4377. }
  4378. return this;
  4379. },
  4380. /**
  4381. * 停止动画
  4382. * @param {boolean} forwardToLast If move to last frame before stop
  4383. */
  4384. stop: function (forwardToLast) {
  4385. var clipList = this._clipList;
  4386. var animation = this.animation;
  4387. for (var i = 0; i < clipList.length; i++) {
  4388. var clip = clipList[i];
  4389. if (forwardToLast) {
  4390. // Move to last frame before stop
  4391. clip.onframe(this._target, 1);
  4392. }
  4393. animation && animation.removeClip(clip);
  4394. }
  4395. clipList.length = 0;
  4396. },
  4397. /**
  4398. * 设置动画延迟开始的时间
  4399. * @param {number} time 单位ms
  4400. * @return {module:zrender/animation/Animator}
  4401. */
  4402. delay: function (time) {
  4403. this._delay = time;
  4404. return this;
  4405. },
  4406. /**
  4407. * 添加动画结束的回调
  4408. * @param {Function} cb
  4409. * @return {module:zrender/animation/Animator}
  4410. */
  4411. done: function (cb) {
  4412. if (cb) {
  4413. this._doneList.push(cb);
  4414. }
  4415. return this;
  4416. },
  4417. /**
  4418. * @return {Array.<module:zrender/animation/Clip>}
  4419. */
  4420. getClips: function () {
  4421. return this._clipList;
  4422. }
  4423. };
  4424. var dpr = 1;
  4425. // If in browser environment
  4426. if (typeof window !== 'undefined') {
  4427. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4428. }
  4429. /**
  4430. * config默认配置项
  4431. * @exports zrender/config
  4432. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4433. */
  4434. /**
  4435. * Debug log mode:
  4436. * 0: Do nothing, for release.
  4437. * 1: console.error, for debug.
  4438. */
  4439. var debugMode = 0;
  4440. // retina 屏幕优化
  4441. var devicePixelRatio = dpr;
  4442. var logError = function () {
  4443. };
  4444. if (debugMode === 1) {
  4445. logError = console.error;
  4446. }
  4447. var logError$1 = logError;
  4448. /**
  4449. * @alias modue:zrender/mixin/Animatable
  4450. * @constructor
  4451. */
  4452. var Animatable = function () {
  4453. /**
  4454. * @type {Array.<module:zrender/animation/Animator>}
  4455. * @readOnly
  4456. */
  4457. this.animators = [];
  4458. };
  4459. Animatable.prototype = {
  4460. constructor: Animatable,
  4461. /**
  4462. * 动画
  4463. *
  4464. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4465. * @param {boolean} [loop] Whether to loop animation.
  4466. * @return {module:zrender/animation/Animator}
  4467. * @example:
  4468. * el.animate('style', false)
  4469. * .when(1000, {x: 10} )
  4470. * .done(function(){ // Animation done })
  4471. * .start()
  4472. */
  4473. animate: function (path, loop) {
  4474. var target;
  4475. var animatingShape = false;
  4476. var el = this;
  4477. var zr = this.__zr;
  4478. if (path) {
  4479. var pathSplitted = path.split('.');
  4480. var prop = el;
  4481. // If animating shape
  4482. animatingShape = pathSplitted[0] === 'shape';
  4483. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4484. if (!prop) {
  4485. continue;
  4486. }
  4487. prop = prop[pathSplitted[i]];
  4488. }
  4489. if (prop) {
  4490. target = prop;
  4491. }
  4492. }
  4493. else {
  4494. target = el;
  4495. }
  4496. if (!target) {
  4497. logError$1(
  4498. 'Property "'
  4499. + path
  4500. + '" is not existed in element '
  4501. + el.id
  4502. );
  4503. return;
  4504. }
  4505. var animators = el.animators;
  4506. var animator = new Animator(target, loop);
  4507. animator.during(function (target) {
  4508. el.dirty(animatingShape);
  4509. })
  4510. .done(function () {
  4511. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4512. animators.splice(indexOf(animators, animator), 1);
  4513. });
  4514. animators.push(animator);
  4515. // If animate after added to the zrender
  4516. if (zr) {
  4517. zr.animation.addAnimator(animator);
  4518. }
  4519. return animator;
  4520. },
  4521. /**
  4522. * 停止动画
  4523. * @param {boolean} forwardToLast If move to last frame before stop
  4524. */
  4525. stopAnimation: function (forwardToLast) {
  4526. var animators = this.animators;
  4527. var len = animators.length;
  4528. for (var i = 0; i < len; i++) {
  4529. animators[i].stop(forwardToLast);
  4530. }
  4531. animators.length = 0;
  4532. return this;
  4533. },
  4534. /**
  4535. * Caution: this method will stop previous animation.
  4536. * So do not use this method to one element twice before
  4537. * animation starts, unless you know what you are doing.
  4538. * @param {Object} target
  4539. * @param {number} [time=500] Time in ms
  4540. * @param {string} [easing='linear']
  4541. * @param {number} [delay=0]
  4542. * @param {Function} [callback]
  4543. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4544. * immediently when target values are the same as current values.
  4545. *
  4546. * @example
  4547. * // Animate position
  4548. * el.animateTo({
  4549. * position: [10, 10]
  4550. * }, function () { // done })
  4551. *
  4552. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4553. * el.animateTo({
  4554. * shape: {
  4555. * width: 500
  4556. * },
  4557. * style: {
  4558. * fill: 'red'
  4559. * }
  4560. * position: [10, 10]
  4561. * }, 100, 100, 'cubicOut', function () { // done })
  4562. */
  4563. // TODO Return animation key
  4564. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4565. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4566. },
  4567. /**
  4568. * Animate from the target state to current state.
  4569. * The params and the return value are the same as `this.animateTo`.
  4570. */
  4571. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4572. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4573. }
  4574. };
  4575. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4576. // animateTo(target, time, easing, callback);
  4577. if (isString(delay)) {
  4578. callback = easing;
  4579. easing = delay;
  4580. delay = 0;
  4581. }
  4582. // animateTo(target, time, delay, callback);
  4583. else if (isFunction$1(easing)) {
  4584. callback = easing;
  4585. easing = 'linear';
  4586. delay = 0;
  4587. }
  4588. // animateTo(target, time, callback);
  4589. else if (isFunction$1(delay)) {
  4590. callback = delay;
  4591. delay = 0;
  4592. }
  4593. // animateTo(target, callback)
  4594. else if (isFunction$1(time)) {
  4595. callback = time;
  4596. time = 500;
  4597. }
  4598. // animateTo(target)
  4599. else if (!time) {
  4600. time = 500;
  4601. }
  4602. // Stop all previous animations
  4603. animatable.stopAnimation();
  4604. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4605. // Animators may be removed immediately after start
  4606. // if there is nothing to animate
  4607. var animators = animatable.animators.slice();
  4608. var count = animators.length;
  4609. function done() {
  4610. count--;
  4611. if (!count) {
  4612. callback && callback();
  4613. }
  4614. }
  4615. // No animators. This should be checked before animators[i].start(),
  4616. // because 'done' may be executed immediately if no need to animate.
  4617. if (!count) {
  4618. callback && callback();
  4619. }
  4620. // Start after all animators created
  4621. // Incase any animator is done immediately when all animation properties are not changed
  4622. for (var i = 0; i < animators.length; i++) {
  4623. animators[i]
  4624. .done(done)
  4625. .start(easing, forceAnimate);
  4626. }
  4627. }
  4628. /**
  4629. * @param {string} path=''
  4630. * @param {Object} source=animatable
  4631. * @param {Object} target
  4632. * @param {number} [time=500]
  4633. * @param {number} [delay=0]
  4634. * @param {boolean} [reverse] If `true`, animate
  4635. * from the `target` to current state.
  4636. *
  4637. * @example
  4638. * // Animate position
  4639. * el._animateToShallow({
  4640. * position: [10, 10]
  4641. * })
  4642. *
  4643. * // Animate shape, style and position in 100ms, delayed 100ms
  4644. * el._animateToShallow({
  4645. * shape: {
  4646. * width: 500
  4647. * },
  4648. * style: {
  4649. * fill: 'red'
  4650. * }
  4651. * position: [10, 10]
  4652. * }, 100, 100)
  4653. */
  4654. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4655. var objShallow = {};
  4656. var propertyCount = 0;
  4657. for (var name in target) {
  4658. if (!target.hasOwnProperty(name)) {
  4659. continue;
  4660. }
  4661. if (source[name] != null) {
  4662. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4663. animateToShallow(
  4664. animatable,
  4665. path ? path + '.' + name : name,
  4666. source[name],
  4667. target[name],
  4668. time,
  4669. delay,
  4670. reverse
  4671. );
  4672. }
  4673. else {
  4674. if (reverse) {
  4675. objShallow[name] = source[name];
  4676. setAttrByPath(animatable, path, name, target[name]);
  4677. }
  4678. else {
  4679. objShallow[name] = target[name];
  4680. }
  4681. propertyCount++;
  4682. }
  4683. }
  4684. else if (target[name] != null && !reverse) {
  4685. setAttrByPath(animatable, path, name, target[name]);
  4686. }
  4687. }
  4688. if (propertyCount > 0) {
  4689. animatable.animate(path, false)
  4690. .when(time == null ? 500 : time, objShallow)
  4691. .delay(delay || 0);
  4692. }
  4693. }
  4694. function setAttrByPath(el, path, name, value) {
  4695. // Attr directly if not has property
  4696. // FIXME, if some property not needed for element ?
  4697. if (!path) {
  4698. el.attr(name, value);
  4699. }
  4700. else {
  4701. // Only support set shape or style
  4702. var props = {};
  4703. props[path] = {};
  4704. props[path][name] = value;
  4705. el.attr(props);
  4706. }
  4707. }
  4708. /**
  4709. * @alias module:zrender/Element
  4710. * @constructor
  4711. * @extends {module:zrender/mixin/Animatable}
  4712. * @extends {module:zrender/mixin/Transformable}
  4713. * @extends {module:zrender/mixin/Eventful}
  4714. */
  4715. var Element = function (opts) { // jshint ignore:line
  4716. Transformable.call(this, opts);
  4717. Eventful.call(this, opts);
  4718. Animatable.call(this, opts);
  4719. /**
  4720. * 画布元素ID
  4721. * @type {string}
  4722. */
  4723. this.id = opts.id || guid();
  4724. };
  4725. Element.prototype = {
  4726. /**
  4727. * 元素类型
  4728. * Element type
  4729. * @type {string}
  4730. */
  4731. type: 'element',
  4732. /**
  4733. * 元素名字
  4734. * Element name
  4735. * @type {string}
  4736. */
  4737. name: '',
  4738. /**
  4739. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4740. * ZRender instance will be assigned when element is associated with zrender
  4741. * @name module:/zrender/Element#__zr
  4742. * @type {module:zrender/ZRender}
  4743. */
  4744. __zr: null,
  4745. /**
  4746. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4747. * If ignore drawing and events of the element object
  4748. * @name module:/zrender/Element#ignore
  4749. * @type {boolean}
  4750. * @default false
  4751. */
  4752. ignore: false,
  4753. /**
  4754. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4755. * 该路径会继承被裁减对象的变换
  4756. * @type {module:zrender/graphic/Path}
  4757. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4758. * @readOnly
  4759. */
  4760. clipPath: null,
  4761. /**
  4762. * 是否是 Group
  4763. * @type {boolean}
  4764. */
  4765. isGroup: false,
  4766. /**
  4767. * Drift element
  4768. * @param {number} dx dx on the global space
  4769. * @param {number} dy dy on the global space
  4770. */
  4771. drift: function (dx, dy) {
  4772. switch (this.draggable) {
  4773. case 'horizontal':
  4774. dy = 0;
  4775. break;
  4776. case 'vertical':
  4777. dx = 0;
  4778. break;
  4779. }
  4780. var m = this.transform;
  4781. if (!m) {
  4782. m = this.transform = [1, 0, 0, 1, 0, 0];
  4783. }
  4784. m[4] += dx;
  4785. m[5] += dy;
  4786. this.decomposeTransform();
  4787. this.dirty(false);
  4788. },
  4789. /**
  4790. * Hook before update
  4791. */
  4792. beforeUpdate: function () {},
  4793. /**
  4794. * Hook after update
  4795. */
  4796. afterUpdate: function () {},
  4797. /**
  4798. * Update each frame
  4799. */
  4800. update: function () {
  4801. this.updateTransform();
  4802. },
  4803. /**
  4804. * @param {Function} cb
  4805. * @param {} context
  4806. */
  4807. traverse: function (cb, context) {},
  4808. /**
  4809. * @protected
  4810. */
  4811. attrKV: function (key, value) {
  4812. if (key === 'position' || key === 'scale' || key === 'origin') {
  4813. // Copy the array
  4814. if (value) {
  4815. var target = this[key];
  4816. if (!target) {
  4817. target = this[key] = [];
  4818. }
  4819. target[0] = value[0];
  4820. target[1] = value[1];
  4821. }
  4822. }
  4823. else {
  4824. this[key] = value;
  4825. }
  4826. },
  4827. /**
  4828. * Hide the element
  4829. */
  4830. hide: function () {
  4831. this.ignore = true;
  4832. this.__zr && this.__zr.refresh();
  4833. },
  4834. /**
  4835. * Show the element
  4836. */
  4837. show: function () {
  4838. this.ignore = false;
  4839. this.__zr && this.__zr.refresh();
  4840. },
  4841. /**
  4842. * @param {string|Object} key
  4843. * @param {*} value
  4844. */
  4845. attr: function (key, value) {
  4846. if (typeof key === 'string') {
  4847. this.attrKV(key, value);
  4848. }
  4849. else if (isObject$1(key)) {
  4850. for (var name in key) {
  4851. if (key.hasOwnProperty(name)) {
  4852. this.attrKV(name, key[name]);
  4853. }
  4854. }
  4855. }
  4856. this.dirty(false);
  4857. return this;
  4858. },
  4859. /**
  4860. * @param {module:zrender/graphic/Path} clipPath
  4861. */
  4862. setClipPath: function (clipPath) {
  4863. var zr = this.__zr;
  4864. if (zr) {
  4865. clipPath.addSelfToZr(zr);
  4866. }
  4867. // Remove previous clip path
  4868. if (this.clipPath && this.clipPath !== clipPath) {
  4869. this.removeClipPath();
  4870. }
  4871. this.clipPath = clipPath;
  4872. clipPath.__zr = zr;
  4873. clipPath.__clipTarget = this;
  4874. this.dirty(false);
  4875. },
  4876. /**
  4877. */
  4878. removeClipPath: function () {
  4879. var clipPath = this.clipPath;
  4880. if (clipPath) {
  4881. if (clipPath.__zr) {
  4882. clipPath.removeSelfFromZr(clipPath.__zr);
  4883. }
  4884. clipPath.__zr = null;
  4885. clipPath.__clipTarget = null;
  4886. this.clipPath = null;
  4887. this.dirty(false);
  4888. }
  4889. },
  4890. /**
  4891. * Add self from zrender instance.
  4892. * Not recursively because it will be invoked when element added to storage.
  4893. * @param {module:zrender/ZRender} zr
  4894. */
  4895. addSelfToZr: function (zr) {
  4896. this.__zr = zr;
  4897. // 添加动画
  4898. var animators = this.animators;
  4899. if (animators) {
  4900. for (var i = 0; i < animators.length; i++) {
  4901. zr.animation.addAnimator(animators[i]);
  4902. }
  4903. }
  4904. if (this.clipPath) {
  4905. this.clipPath.addSelfToZr(zr);
  4906. }
  4907. },
  4908. /**
  4909. * Remove self from zrender instance.
  4910. * Not recursively because it will be invoked when element added to storage.
  4911. * @param {module:zrender/ZRender} zr
  4912. */
  4913. removeSelfFromZr: function (zr) {
  4914. this.__zr = null;
  4915. // 移除动画
  4916. var animators = this.animators;
  4917. if (animators) {
  4918. for (var i = 0; i < animators.length; i++) {
  4919. zr.animation.removeAnimator(animators[i]);
  4920. }
  4921. }
  4922. if (this.clipPath) {
  4923. this.clipPath.removeSelfFromZr(zr);
  4924. }
  4925. }
  4926. };
  4927. mixin(Element, Animatable);
  4928. mixin(Element, Transformable);
  4929. mixin(Element, Eventful);
  4930. /**
  4931. * @module echarts/core/BoundingRect
  4932. */
  4933. var v2ApplyTransform = applyTransform;
  4934. var mathMin = Math.min;
  4935. var mathMax = Math.max;
  4936. /**
  4937. * @alias module:echarts/core/BoundingRect
  4938. */
  4939. function BoundingRect(x, y, width, height) {
  4940. if (width < 0) {
  4941. x = x + width;
  4942. width = -width;
  4943. }
  4944. if (height < 0) {
  4945. y = y + height;
  4946. height = -height;
  4947. }
  4948. /**
  4949. * @type {number}
  4950. */
  4951. this.x = x;
  4952. /**
  4953. * @type {number}
  4954. */
  4955. this.y = y;
  4956. /**
  4957. * @type {number}
  4958. */
  4959. this.width = width;
  4960. /**
  4961. * @type {number}
  4962. */
  4963. this.height = height;
  4964. }
  4965. BoundingRect.prototype = {
  4966. constructor: BoundingRect,
  4967. /**
  4968. * @param {module:echarts/core/BoundingRect} other
  4969. */
  4970. union: function (other) {
  4971. var x = mathMin(other.x, this.x);
  4972. var y = mathMin(other.y, this.y);
  4973. this.width = mathMax(
  4974. other.x + other.width,
  4975. this.x + this.width
  4976. ) - x;
  4977. this.height = mathMax(
  4978. other.y + other.height,
  4979. this.y + this.height
  4980. ) - y;
  4981. this.x = x;
  4982. this.y = y;
  4983. },
  4984. /**
  4985. * @param {Array.<number>} m
  4986. * @methods
  4987. */
  4988. applyTransform: (function () {
  4989. var lt = [];
  4990. var rb = [];
  4991. var lb = [];
  4992. var rt = [];
  4993. return function (m) {
  4994. // In case usage like this
  4995. // el.getBoundingRect().applyTransform(el.transform)
  4996. // And element has no transform
  4997. if (!m) {
  4998. return;
  4999. }
  5000. lt[0] = lb[0] = this.x;
  5001. lt[1] = rt[1] = this.y;
  5002. rb[0] = rt[0] = this.x + this.width;
  5003. rb[1] = lb[1] = this.y + this.height;
  5004. v2ApplyTransform(lt, lt, m);
  5005. v2ApplyTransform(rb, rb, m);
  5006. v2ApplyTransform(lb, lb, m);
  5007. v2ApplyTransform(rt, rt, m);
  5008. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  5009. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  5010. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  5011. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  5012. this.width = maxX - this.x;
  5013. this.height = maxY - this.y;
  5014. };
  5015. })(),
  5016. /**
  5017. * Calculate matrix of transforming from self to target rect
  5018. * @param {module:zrender/core/BoundingRect} b
  5019. * @return {Array.<number>}
  5020. */
  5021. calculateTransform: function (b) {
  5022. var a = this;
  5023. var sx = b.width / a.width;
  5024. var sy = b.height / a.height;
  5025. var m = create$1();
  5026. // 矩阵右乘
  5027. translate(m, m, [-a.x, -a.y]);
  5028. scale$1(m, m, [sx, sy]);
  5029. translate(m, m, [b.x, b.y]);
  5030. return m;
  5031. },
  5032. /**
  5033. * @param {(module:echarts/core/BoundingRect|Object)} b
  5034. * @return {boolean}
  5035. */
  5036. intersect: function (b) {
  5037. if (!b) {
  5038. return false;
  5039. }
  5040. if (!(b instanceof BoundingRect)) {
  5041. // Normalize negative width/height.
  5042. b = BoundingRect.create(b);
  5043. }
  5044. var a = this;
  5045. var ax0 = a.x;
  5046. var ax1 = a.x + a.width;
  5047. var ay0 = a.y;
  5048. var ay1 = a.y + a.height;
  5049. var bx0 = b.x;
  5050. var bx1 = b.x + b.width;
  5051. var by0 = b.y;
  5052. var by1 = b.y + b.height;
  5053. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  5054. },
  5055. contain: function (x, y) {
  5056. var rect = this;
  5057. return x >= rect.x
  5058. && x <= (rect.x + rect.width)
  5059. && y >= rect.y
  5060. && y <= (rect.y + rect.height);
  5061. },
  5062. /**
  5063. * @return {module:echarts/core/BoundingRect}
  5064. */
  5065. clone: function () {
  5066. return new BoundingRect(this.x, this.y, this.width, this.height);
  5067. },
  5068. /**
  5069. * Copy from another rect
  5070. */
  5071. copy: function (other) {
  5072. this.x = other.x;
  5073. this.y = other.y;
  5074. this.width = other.width;
  5075. this.height = other.height;
  5076. },
  5077. plain: function () {
  5078. return {
  5079. x: this.x,
  5080. y: this.y,
  5081. width: this.width,
  5082. height: this.height
  5083. };
  5084. }
  5085. };
  5086. /**
  5087. * @param {Object|module:zrender/core/BoundingRect} rect
  5088. * @param {number} rect.x
  5089. * @param {number} rect.y
  5090. * @param {number} rect.width
  5091. * @param {number} rect.height
  5092. * @return {module:zrender/core/BoundingRect}
  5093. */
  5094. BoundingRect.create = function (rect) {
  5095. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  5096. };
  5097. /**
  5098. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  5099. * @module zrender/graphic/Group
  5100. * @example
  5101. * var Group = require('zrender/container/Group');
  5102. * var Circle = require('zrender/graphic/shape/Circle');
  5103. * var g = new Group();
  5104. * g.position[0] = 100;
  5105. * g.position[1] = 100;
  5106. * g.add(new Circle({
  5107. * style: {
  5108. * x: 100,
  5109. * y: 100,
  5110. * r: 20,
  5111. * }
  5112. * }));
  5113. * zr.add(g);
  5114. */
  5115. /**
  5116. * @alias module:zrender/graphic/Group
  5117. * @constructor
  5118. * @extends module:zrender/mixin/Transformable
  5119. * @extends module:zrender/mixin/Eventful
  5120. */
  5121. var Group = function (opts) {
  5122. opts = opts || {};
  5123. Element.call(this, opts);
  5124. for (var key in opts) {
  5125. if (opts.hasOwnProperty(key)) {
  5126. this[key] = opts[key];
  5127. }
  5128. }
  5129. this._children = [];
  5130. this.__storage = null;
  5131. this.__dirty = true;
  5132. };
  5133. Group.prototype = {
  5134. constructor: Group,
  5135. isGroup: true,
  5136. /**
  5137. * @type {string}
  5138. */
  5139. type: 'group',
  5140. /**
  5141. * 所有子孙元素是否响应鼠标事件
  5142. * @name module:/zrender/container/Group#silent
  5143. * @type {boolean}
  5144. * @default false
  5145. */
  5146. silent: false,
  5147. /**
  5148. * @return {Array.<module:zrender/Element>}
  5149. */
  5150. children: function () {
  5151. return this._children.slice();
  5152. },
  5153. /**
  5154. * 获取指定 index 的儿子节点
  5155. * @param {number} idx
  5156. * @return {module:zrender/Element}
  5157. */
  5158. childAt: function (idx) {
  5159. return this._children[idx];
  5160. },
  5161. /**
  5162. * 获取指定名字的儿子节点
  5163. * @param {string} name
  5164. * @return {module:zrender/Element}
  5165. */
  5166. childOfName: function (name) {
  5167. var children = this._children;
  5168. for (var i = 0; i < children.length; i++) {
  5169. if (children[i].name === name) {
  5170. return children[i];
  5171. }
  5172. }
  5173. },
  5174. /**
  5175. * @return {number}
  5176. */
  5177. childCount: function () {
  5178. return this._children.length;
  5179. },
  5180. /**
  5181. * 添加子节点到最后
  5182. * @param {module:zrender/Element} child
  5183. */
  5184. add: function (child) {
  5185. if (child && child !== this && child.parent !== this) {
  5186. this._children.push(child);
  5187. this._doAdd(child);
  5188. }
  5189. return this;
  5190. },
  5191. /**
  5192. * 添加子节点在 nextSibling 之前
  5193. * @param {module:zrender/Element} child
  5194. * @param {module:zrender/Element} nextSibling
  5195. */
  5196. addBefore: function (child, nextSibling) {
  5197. if (child && child !== this && child.parent !== this
  5198. && nextSibling && nextSibling.parent === this) {
  5199. var children = this._children;
  5200. var idx = children.indexOf(nextSibling);
  5201. if (idx >= 0) {
  5202. children.splice(idx, 0, child);
  5203. this._doAdd(child);
  5204. }
  5205. }
  5206. return this;
  5207. },
  5208. _doAdd: function (child) {
  5209. if (child.parent) {
  5210. child.parent.remove(child);
  5211. }
  5212. child.parent = this;
  5213. var storage = this.__storage;
  5214. var zr = this.__zr;
  5215. if (storage && storage !== child.__storage) {
  5216. storage.addToStorage(child);
  5217. if (child instanceof Group) {
  5218. child.addChildrenToStorage(storage);
  5219. }
  5220. }
  5221. zr && zr.refresh();
  5222. },
  5223. /**
  5224. * 移除子节点
  5225. * @param {module:zrender/Element} child
  5226. */
  5227. remove: function (child) {
  5228. var zr = this.__zr;
  5229. var storage = this.__storage;
  5230. var children = this._children;
  5231. var idx = indexOf(children, child);
  5232. if (idx < 0) {
  5233. return this;
  5234. }
  5235. children.splice(idx, 1);
  5236. child.parent = null;
  5237. if (storage) {
  5238. storage.delFromStorage(child);
  5239. if (child instanceof Group) {
  5240. child.delChildrenFromStorage(storage);
  5241. }
  5242. }
  5243. zr && zr.refresh();
  5244. return this;
  5245. },
  5246. /**
  5247. * 移除所有子节点
  5248. */
  5249. removeAll: function () {
  5250. var children = this._children;
  5251. var storage = this.__storage;
  5252. var child;
  5253. var i;
  5254. for (i = 0; i < children.length; i++) {
  5255. child = children[i];
  5256. if (storage) {
  5257. storage.delFromStorage(child);
  5258. if (child instanceof Group) {
  5259. child.delChildrenFromStorage(storage);
  5260. }
  5261. }
  5262. child.parent = null;
  5263. }
  5264. children.length = 0;
  5265. return this;
  5266. },
  5267. /**
  5268. * 遍历所有子节点
  5269. * @param {Function} cb
  5270. * @param {} context
  5271. */
  5272. eachChild: function (cb, context) {
  5273. var children = this._children;
  5274. for (var i = 0; i < children.length; i++) {
  5275. var child = children[i];
  5276. cb.call(context, child, i);
  5277. }
  5278. return this;
  5279. },
  5280. /**
  5281. * 深度优先遍历所有子孙节点
  5282. * @param {Function} cb
  5283. * @param {} context
  5284. */
  5285. traverse: function (cb, context) {
  5286. for (var i = 0; i < this._children.length; i++) {
  5287. var child = this._children[i];
  5288. cb.call(context, child);
  5289. if (child.type === 'group') {
  5290. child.traverse(cb, context);
  5291. }
  5292. }
  5293. return this;
  5294. },
  5295. addChildrenToStorage: function (storage) {
  5296. for (var i = 0; i < this._children.length; i++) {
  5297. var child = this._children[i];
  5298. storage.addToStorage(child);
  5299. if (child instanceof Group) {
  5300. child.addChildrenToStorage(storage);
  5301. }
  5302. }
  5303. },
  5304. delChildrenFromStorage: function (storage) {
  5305. for (var i = 0; i < this._children.length; i++) {
  5306. var child = this._children[i];
  5307. storage.delFromStorage(child);
  5308. if (child instanceof Group) {
  5309. child.delChildrenFromStorage(storage);
  5310. }
  5311. }
  5312. },
  5313. dirty: function () {
  5314. this.__dirty = true;
  5315. this.__zr && this.__zr.refresh();
  5316. return this;
  5317. },
  5318. /**
  5319. * @return {module:zrender/core/BoundingRect}
  5320. */
  5321. getBoundingRect: function (includeChildren) {
  5322. // TODO Caching
  5323. var rect = null;
  5324. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5325. var children = includeChildren || this._children;
  5326. var tmpMat = [];
  5327. for (var i = 0; i < children.length; i++) {
  5328. var child = children[i];
  5329. if (child.ignore || child.invisible) {
  5330. continue;
  5331. }
  5332. var childRect = child.getBoundingRect();
  5333. var transform = child.getLocalTransform(tmpMat);
  5334. // TODO
  5335. // The boundingRect cacluated by transforming original
  5336. // rect may be bigger than the actual bundingRect when rotation
  5337. // is used. (Consider a circle rotated aginst its center, where
  5338. // the actual boundingRect should be the same as that not be
  5339. // rotated.) But we can not find better approach to calculate
  5340. // actual boundingRect yet, considering performance.
  5341. if (transform) {
  5342. tmpRect.copy(childRect);
  5343. tmpRect.applyTransform(transform);
  5344. rect = rect || tmpRect.clone();
  5345. rect.union(tmpRect);
  5346. }
  5347. else {
  5348. rect = rect || childRect.clone();
  5349. rect.union(childRect);
  5350. }
  5351. }
  5352. return rect || tmpRect;
  5353. }
  5354. };
  5355. inherits(Group, Element);
  5356. // https://github.com/mziccard/node-timsort
  5357. var DEFAULT_MIN_MERGE = 32;
  5358. var DEFAULT_MIN_GALLOPING = 7;
  5359. function minRunLength(n) {
  5360. var r = 0;
  5361. while (n >= DEFAULT_MIN_MERGE) {
  5362. r |= n & 1;
  5363. n >>= 1;
  5364. }
  5365. return n + r;
  5366. }
  5367. function makeAscendingRun(array, lo, hi, compare) {
  5368. var runHi = lo + 1;
  5369. if (runHi === hi) {
  5370. return 1;
  5371. }
  5372. if (compare(array[runHi++], array[lo]) < 0) {
  5373. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5374. runHi++;
  5375. }
  5376. reverseRun(array, lo, runHi);
  5377. }
  5378. else {
  5379. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5380. runHi++;
  5381. }
  5382. }
  5383. return runHi - lo;
  5384. }
  5385. function reverseRun(array, lo, hi) {
  5386. hi--;
  5387. while (lo < hi) {
  5388. var t = array[lo];
  5389. array[lo++] = array[hi];
  5390. array[hi--] = t;
  5391. }
  5392. }
  5393. function binaryInsertionSort(array, lo, hi, start, compare) {
  5394. if (start === lo) {
  5395. start++;
  5396. }
  5397. for (; start < hi; start++) {
  5398. var pivot = array[start];
  5399. var left = lo;
  5400. var right = start;
  5401. var mid;
  5402. while (left < right) {
  5403. mid = left + right >>> 1;
  5404. if (compare(pivot, array[mid]) < 0) {
  5405. right = mid;
  5406. }
  5407. else {
  5408. left = mid + 1;
  5409. }
  5410. }
  5411. var n = start - left;
  5412. switch (n) {
  5413. case 3:
  5414. array[left + 3] = array[left + 2];
  5415. case 2:
  5416. array[left + 2] = array[left + 1];
  5417. case 1:
  5418. array[left + 1] = array[left];
  5419. break;
  5420. default:
  5421. while (n > 0) {
  5422. array[left + n] = array[left + n - 1];
  5423. n--;
  5424. }
  5425. }
  5426. array[left] = pivot;
  5427. }
  5428. }
  5429. function gallopLeft(value, array, start, length, hint, compare) {
  5430. var lastOffset = 0;
  5431. var maxOffset = 0;
  5432. var offset = 1;
  5433. if (compare(value, array[start + hint]) > 0) {
  5434. maxOffset = length - hint;
  5435. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5436. lastOffset = offset;
  5437. offset = (offset << 1) + 1;
  5438. if (offset <= 0) {
  5439. offset = maxOffset;
  5440. }
  5441. }
  5442. if (offset > maxOffset) {
  5443. offset = maxOffset;
  5444. }
  5445. lastOffset += hint;
  5446. offset += hint;
  5447. }
  5448. else {
  5449. maxOffset = hint + 1;
  5450. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5451. lastOffset = offset;
  5452. offset = (offset << 1) + 1;
  5453. if (offset <= 0) {
  5454. offset = maxOffset;
  5455. }
  5456. }
  5457. if (offset > maxOffset) {
  5458. offset = maxOffset;
  5459. }
  5460. var tmp = lastOffset;
  5461. lastOffset = hint - offset;
  5462. offset = hint - tmp;
  5463. }
  5464. lastOffset++;
  5465. while (lastOffset < offset) {
  5466. var m = lastOffset + (offset - lastOffset >>> 1);
  5467. if (compare(value, array[start + m]) > 0) {
  5468. lastOffset = m + 1;
  5469. }
  5470. else {
  5471. offset = m;
  5472. }
  5473. }
  5474. return offset;
  5475. }
  5476. function gallopRight(value, array, start, length, hint, compare) {
  5477. var lastOffset = 0;
  5478. var maxOffset = 0;
  5479. var offset = 1;
  5480. if (compare(value, array[start + hint]) < 0) {
  5481. maxOffset = hint + 1;
  5482. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5483. lastOffset = offset;
  5484. offset = (offset << 1) + 1;
  5485. if (offset <= 0) {
  5486. offset = maxOffset;
  5487. }
  5488. }
  5489. if (offset > maxOffset) {
  5490. offset = maxOffset;
  5491. }
  5492. var tmp = lastOffset;
  5493. lastOffset = hint - offset;
  5494. offset = hint - tmp;
  5495. }
  5496. else {
  5497. maxOffset = length - hint;
  5498. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5499. lastOffset = offset;
  5500. offset = (offset << 1) + 1;
  5501. if (offset <= 0) {
  5502. offset = maxOffset;
  5503. }
  5504. }
  5505. if (offset > maxOffset) {
  5506. offset = maxOffset;
  5507. }
  5508. lastOffset += hint;
  5509. offset += hint;
  5510. }
  5511. lastOffset++;
  5512. while (lastOffset < offset) {
  5513. var m = lastOffset + (offset - lastOffset >>> 1);
  5514. if (compare(value, array[start + m]) < 0) {
  5515. offset = m;
  5516. }
  5517. else {
  5518. lastOffset = m + 1;
  5519. }
  5520. }
  5521. return offset;
  5522. }
  5523. function TimSort(array, compare) {
  5524. var minGallop = DEFAULT_MIN_GALLOPING;
  5525. var runStart;
  5526. var runLength;
  5527. var stackSize = 0;
  5528. var tmp = [];
  5529. runStart = [];
  5530. runLength = [];
  5531. function pushRun(_runStart, _runLength) {
  5532. runStart[stackSize] = _runStart;
  5533. runLength[stackSize] = _runLength;
  5534. stackSize += 1;
  5535. }
  5536. function mergeRuns() {
  5537. while (stackSize > 1) {
  5538. var n = stackSize - 2;
  5539. if (
  5540. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5541. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5542. ) {
  5543. if (runLength[n - 1] < runLength[n + 1]) {
  5544. n--;
  5545. }
  5546. }
  5547. else if (runLength[n] > runLength[n + 1]) {
  5548. break;
  5549. }
  5550. mergeAt(n);
  5551. }
  5552. }
  5553. function forceMergeRuns() {
  5554. while (stackSize > 1) {
  5555. var n = stackSize - 2;
  5556. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5557. n--;
  5558. }
  5559. mergeAt(n);
  5560. }
  5561. }
  5562. function mergeAt(i) {
  5563. var start1 = runStart[i];
  5564. var length1 = runLength[i];
  5565. var start2 = runStart[i + 1];
  5566. var length2 = runLength[i + 1];
  5567. runLength[i] = length1 + length2;
  5568. if (i === stackSize - 3) {
  5569. runStart[i + 1] = runStart[i + 2];
  5570. runLength[i + 1] = runLength[i + 2];
  5571. }
  5572. stackSize--;
  5573. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5574. start1 += k;
  5575. length1 -= k;
  5576. if (length1 === 0) {
  5577. return;
  5578. }
  5579. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5580. if (length2 === 0) {
  5581. return;
  5582. }
  5583. if (length1 <= length2) {
  5584. mergeLow(start1, length1, start2, length2);
  5585. }
  5586. else {
  5587. mergeHigh(start1, length1, start2, length2);
  5588. }
  5589. }
  5590. function mergeLow(start1, length1, start2, length2) {
  5591. var i = 0;
  5592. for (i = 0; i < length1; i++) {
  5593. tmp[i] = array[start1 + i];
  5594. }
  5595. var cursor1 = 0;
  5596. var cursor2 = start2;
  5597. var dest = start1;
  5598. array[dest++] = array[cursor2++];
  5599. if (--length2 === 0) {
  5600. for (i = 0; i < length1; i++) {
  5601. array[dest + i] = tmp[cursor1 + i];
  5602. }
  5603. return;
  5604. }
  5605. if (length1 === 1) {
  5606. for (i = 0; i < length2; i++) {
  5607. array[dest + i] = array[cursor2 + i];
  5608. }
  5609. array[dest + length2] = tmp[cursor1];
  5610. return;
  5611. }
  5612. var _minGallop = minGallop;
  5613. var count1;
  5614. var count2;
  5615. var exit;
  5616. while (1) {
  5617. count1 = 0;
  5618. count2 = 0;
  5619. exit = false;
  5620. do {
  5621. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5622. array[dest++] = array[cursor2++];
  5623. count2++;
  5624. count1 = 0;
  5625. if (--length2 === 0) {
  5626. exit = true;
  5627. break;
  5628. }
  5629. }
  5630. else {
  5631. array[dest++] = tmp[cursor1++];
  5632. count1++;
  5633. count2 = 0;
  5634. if (--length1 === 1) {
  5635. exit = true;
  5636. break;
  5637. }
  5638. }
  5639. } while ((count1 | count2) < _minGallop);
  5640. if (exit) {
  5641. break;
  5642. }
  5643. do {
  5644. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5645. if (count1 !== 0) {
  5646. for (i = 0; i < count1; i++) {
  5647. array[dest + i] = tmp[cursor1 + i];
  5648. }
  5649. dest += count1;
  5650. cursor1 += count1;
  5651. length1 -= count1;
  5652. if (length1 <= 1) {
  5653. exit = true;
  5654. break;
  5655. }
  5656. }
  5657. array[dest++] = array[cursor2++];
  5658. if (--length2 === 0) {
  5659. exit = true;
  5660. break;
  5661. }
  5662. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5663. if (count2 !== 0) {
  5664. for (i = 0; i < count2; i++) {
  5665. array[dest + i] = array[cursor2 + i];
  5666. }
  5667. dest += count2;
  5668. cursor2 += count2;
  5669. length2 -= count2;
  5670. if (length2 === 0) {
  5671. exit = true;
  5672. break;
  5673. }
  5674. }
  5675. array[dest++] = tmp[cursor1++];
  5676. if (--length1 === 1) {
  5677. exit = true;
  5678. break;
  5679. }
  5680. _minGallop--;
  5681. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5682. if (exit) {
  5683. break;
  5684. }
  5685. if (_minGallop < 0) {
  5686. _minGallop = 0;
  5687. }
  5688. _minGallop += 2;
  5689. }
  5690. minGallop = _minGallop;
  5691. minGallop < 1 && (minGallop = 1);
  5692. if (length1 === 1) {
  5693. for (i = 0; i < length2; i++) {
  5694. array[dest + i] = array[cursor2 + i];
  5695. }
  5696. array[dest + length2] = tmp[cursor1];
  5697. }
  5698. else if (length1 === 0) {
  5699. throw new Error();
  5700. // throw new Error('mergeLow preconditions were not respected');
  5701. }
  5702. else {
  5703. for (i = 0; i < length1; i++) {
  5704. array[dest + i] = tmp[cursor1 + i];
  5705. }
  5706. }
  5707. }
  5708. function mergeHigh(start1, length1, start2, length2) {
  5709. var i = 0;
  5710. for (i = 0; i < length2; i++) {
  5711. tmp[i] = array[start2 + i];
  5712. }
  5713. var cursor1 = start1 + length1 - 1;
  5714. var cursor2 = length2 - 1;
  5715. var dest = start2 + length2 - 1;
  5716. var customCursor = 0;
  5717. var customDest = 0;
  5718. array[dest--] = array[cursor1--];
  5719. if (--length1 === 0) {
  5720. customCursor = dest - (length2 - 1);
  5721. for (i = 0; i < length2; i++) {
  5722. array[customCursor + i] = tmp[i];
  5723. }
  5724. return;
  5725. }
  5726. if (length2 === 1) {
  5727. dest -= length1;
  5728. cursor1 -= length1;
  5729. customDest = dest + 1;
  5730. customCursor = cursor1 + 1;
  5731. for (i = length1 - 1; i >= 0; i--) {
  5732. array[customDest + i] = array[customCursor + i];
  5733. }
  5734. array[dest] = tmp[cursor2];
  5735. return;
  5736. }
  5737. var _minGallop = minGallop;
  5738. while (true) {
  5739. var count1 = 0;
  5740. var count2 = 0;
  5741. var exit = false;
  5742. do {
  5743. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5744. array[dest--] = array[cursor1--];
  5745. count1++;
  5746. count2 = 0;
  5747. if (--length1 === 0) {
  5748. exit = true;
  5749. break;
  5750. }
  5751. }
  5752. else {
  5753. array[dest--] = tmp[cursor2--];
  5754. count2++;
  5755. count1 = 0;
  5756. if (--length2 === 1) {
  5757. exit = true;
  5758. break;
  5759. }
  5760. }
  5761. } while ((count1 | count2) < _minGallop);
  5762. if (exit) {
  5763. break;
  5764. }
  5765. do {
  5766. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5767. if (count1 !== 0) {
  5768. dest -= count1;
  5769. cursor1 -= count1;
  5770. length1 -= count1;
  5771. customDest = dest + 1;
  5772. customCursor = cursor1 + 1;
  5773. for (i = count1 - 1; i >= 0; i--) {
  5774. array[customDest + i] = array[customCursor + i];
  5775. }
  5776. if (length1 === 0) {
  5777. exit = true;
  5778. break;
  5779. }
  5780. }
  5781. array[dest--] = tmp[cursor2--];
  5782. if (--length2 === 1) {
  5783. exit = true;
  5784. break;
  5785. }
  5786. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5787. if (count2 !== 0) {
  5788. dest -= count2;
  5789. cursor2 -= count2;
  5790. length2 -= count2;
  5791. customDest = dest + 1;
  5792. customCursor = cursor2 + 1;
  5793. for (i = 0; i < count2; i++) {
  5794. array[customDest + i] = tmp[customCursor + i];
  5795. }
  5796. if (length2 <= 1) {
  5797. exit = true;
  5798. break;
  5799. }
  5800. }
  5801. array[dest--] = array[cursor1--];
  5802. if (--length1 === 0) {
  5803. exit = true;
  5804. break;
  5805. }
  5806. _minGallop--;
  5807. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5808. if (exit) {
  5809. break;
  5810. }
  5811. if (_minGallop < 0) {
  5812. _minGallop = 0;
  5813. }
  5814. _minGallop += 2;
  5815. }
  5816. minGallop = _minGallop;
  5817. if (minGallop < 1) {
  5818. minGallop = 1;
  5819. }
  5820. if (length2 === 1) {
  5821. dest -= length1;
  5822. cursor1 -= length1;
  5823. customDest = dest + 1;
  5824. customCursor = cursor1 + 1;
  5825. for (i = length1 - 1; i >= 0; i--) {
  5826. array[customDest + i] = array[customCursor + i];
  5827. }
  5828. array[dest] = tmp[cursor2];
  5829. }
  5830. else if (length2 === 0) {
  5831. throw new Error();
  5832. // throw new Error('mergeHigh preconditions were not respected');
  5833. }
  5834. else {
  5835. customCursor = dest - (length2 - 1);
  5836. for (i = 0; i < length2; i++) {
  5837. array[customCursor + i] = tmp[i];
  5838. }
  5839. }
  5840. }
  5841. this.mergeRuns = mergeRuns;
  5842. this.forceMergeRuns = forceMergeRuns;
  5843. this.pushRun = pushRun;
  5844. }
  5845. function sort(array, compare, lo, hi) {
  5846. if (!lo) {
  5847. lo = 0;
  5848. }
  5849. if (!hi) {
  5850. hi = array.length;
  5851. }
  5852. var remaining = hi - lo;
  5853. if (remaining < 2) {
  5854. return;
  5855. }
  5856. var runLength = 0;
  5857. if (remaining < DEFAULT_MIN_MERGE) {
  5858. runLength = makeAscendingRun(array, lo, hi, compare);
  5859. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5860. return;
  5861. }
  5862. var ts = new TimSort(array, compare);
  5863. var minRun = minRunLength(remaining);
  5864. do {
  5865. runLength = makeAscendingRun(array, lo, hi, compare);
  5866. if (runLength < minRun) {
  5867. var force = remaining;
  5868. if (force > minRun) {
  5869. force = minRun;
  5870. }
  5871. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5872. runLength = force;
  5873. }
  5874. ts.pushRun(lo, runLength);
  5875. ts.mergeRuns();
  5876. remaining -= runLength;
  5877. lo += runLength;
  5878. } while (remaining !== 0);
  5879. ts.forceMergeRuns();
  5880. }
  5881. // Use timsort because in most case elements are partially sorted
  5882. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5883. function shapeCompareFunc(a, b) {
  5884. if (a.zlevel === b.zlevel) {
  5885. if (a.z === b.z) {
  5886. // if (a.z2 === b.z2) {
  5887. // // FIXME Slow has renderidx compare
  5888. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5889. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5890. // return a.__renderidx - b.__renderidx;
  5891. // }
  5892. return a.z2 - b.z2;
  5893. }
  5894. return a.z - b.z;
  5895. }
  5896. return a.zlevel - b.zlevel;
  5897. }
  5898. /**
  5899. * 内容仓库 (M)
  5900. * @alias module:zrender/Storage
  5901. * @constructor
  5902. */
  5903. var Storage = function () { // jshint ignore:line
  5904. this._roots = [];
  5905. this._displayList = [];
  5906. this._displayListLen = 0;
  5907. };
  5908. Storage.prototype = {
  5909. constructor: Storage,
  5910. /**
  5911. * @param {Function} cb
  5912. *
  5913. */
  5914. traverse: function (cb, context) {
  5915. for (var i = 0; i < this._roots.length; i++) {
  5916. this._roots[i].traverse(cb, context);
  5917. }
  5918. },
  5919. /**
  5920. * 返回所有图形的绘制队列
  5921. * @param {boolean} [update=false] 是否在返回前更新该数组
  5922. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5923. *
  5924. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5925. * @return {Array.<module:zrender/graphic/Displayable>}
  5926. */
  5927. getDisplayList: function (update, includeIgnore) {
  5928. includeIgnore = includeIgnore || false;
  5929. if (update) {
  5930. this.updateDisplayList(includeIgnore);
  5931. }
  5932. return this._displayList;
  5933. },
  5934. /**
  5935. * 更新图形的绘制队列。
  5936. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5937. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5938. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5939. */
  5940. updateDisplayList: function (includeIgnore) {
  5941. this._displayListLen = 0;
  5942. var roots = this._roots;
  5943. var displayList = this._displayList;
  5944. for (var i = 0, len = roots.length; i < len; i++) {
  5945. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5946. }
  5947. displayList.length = this._displayListLen;
  5948. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5949. },
  5950. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5951. if (el.ignore && !includeIgnore) {
  5952. return;
  5953. }
  5954. el.beforeUpdate();
  5955. if (el.__dirty) {
  5956. el.update();
  5957. }
  5958. el.afterUpdate();
  5959. var userSetClipPath = el.clipPath;
  5960. if (userSetClipPath) {
  5961. // FIXME 效率影响
  5962. if (clipPaths) {
  5963. clipPaths = clipPaths.slice();
  5964. }
  5965. else {
  5966. clipPaths = [];
  5967. }
  5968. var currentClipPath = userSetClipPath;
  5969. var parentClipPath = el;
  5970. // Recursively add clip path
  5971. while (currentClipPath) {
  5972. // clipPath 的变换是基于使用这个 clipPath 的元素
  5973. currentClipPath.parent = parentClipPath;
  5974. currentClipPath.updateTransform();
  5975. clipPaths.push(currentClipPath);
  5976. parentClipPath = currentClipPath;
  5977. currentClipPath = currentClipPath.clipPath;
  5978. }
  5979. }
  5980. if (el.isGroup) {
  5981. var children = el._children;
  5982. for (var i = 0; i < children.length; i++) {
  5983. var child = children[i];
  5984. // Force to mark as dirty if group is dirty
  5985. // FIXME __dirtyPath ?
  5986. if (el.__dirty) {
  5987. child.__dirty = true;
  5988. }
  5989. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5990. }
  5991. // Mark group clean here
  5992. el.__dirty = false;
  5993. }
  5994. else {
  5995. el.__clipPaths = clipPaths;
  5996. this._displayList[this._displayListLen++] = el;
  5997. }
  5998. },
  5999. /**
  6000. * 添加图形(Shape)或者组(Group)到根节点
  6001. * @param {module:zrender/Element} el
  6002. */
  6003. addRoot: function (el) {
  6004. if (el.__storage === this) {
  6005. return;
  6006. }
  6007. if (el instanceof Group) {
  6008. el.addChildrenToStorage(this);
  6009. }
  6010. this.addToStorage(el);
  6011. this._roots.push(el);
  6012. },
  6013. /**
  6014. * 删除指定的图形(Shape)或者组(Group)
  6015. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  6016. */
  6017. delRoot: function (el) {
  6018. if (el == null) {
  6019. // 不指定el清空
  6020. for (var i = 0; i < this._roots.length; i++) {
  6021. var root = this._roots[i];
  6022. if (root instanceof Group) {
  6023. root.delChildrenFromStorage(this);
  6024. }
  6025. }
  6026. this._roots = [];
  6027. this._displayList = [];
  6028. this._displayListLen = 0;
  6029. return;
  6030. }
  6031. if (el instanceof Array) {
  6032. for (var i = 0, l = el.length; i < l; i++) {
  6033. this.delRoot(el[i]);
  6034. }
  6035. return;
  6036. }
  6037. var idx = indexOf(this._roots, el);
  6038. if (idx >= 0) {
  6039. this.delFromStorage(el);
  6040. this._roots.splice(idx, 1);
  6041. if (el instanceof Group) {
  6042. el.delChildrenFromStorage(this);
  6043. }
  6044. }
  6045. },
  6046. addToStorage: function (el) {
  6047. if (el) {
  6048. el.__storage = this;
  6049. el.dirty(false);
  6050. }
  6051. return this;
  6052. },
  6053. delFromStorage: function (el) {
  6054. if (el) {
  6055. el.__storage = null;
  6056. }
  6057. return this;
  6058. },
  6059. /**
  6060. * 清空并且释放Storage
  6061. */
  6062. dispose: function () {
  6063. this._renderList =
  6064. this._roots = null;
  6065. },
  6066. displayableSortFunc: shapeCompareFunc
  6067. };
  6068. var SHADOW_PROPS = {
  6069. 'shadowBlur': 1,
  6070. 'shadowOffsetX': 1,
  6071. 'shadowOffsetY': 1,
  6072. 'textShadowBlur': 1,
  6073. 'textShadowOffsetX': 1,
  6074. 'textShadowOffsetY': 1,
  6075. 'textBoxShadowBlur': 1,
  6076. 'textBoxShadowOffsetX': 1,
  6077. 'textBoxShadowOffsetY': 1
  6078. };
  6079. var fixShadow = function (ctx, propName, value) {
  6080. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  6081. return value *= ctx.dpr;
  6082. }
  6083. return value;
  6084. };
  6085. var ContextCachedBy = {
  6086. NONE: 0,
  6087. STYLE_BIND: 1,
  6088. PLAIN_TEXT: 2
  6089. };
  6090. // Avoid confused with 0/false.
  6091. var WILL_BE_RESTORED = 9;
  6092. var STYLE_COMMON_PROPS = [
  6093. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  6094. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  6095. ];
  6096. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  6097. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  6098. var Style = function (opts) {
  6099. this.extendFrom(opts, false);
  6100. };
  6101. function createLinearGradient(ctx, obj, rect) {
  6102. var x = obj.x == null ? 0 : obj.x;
  6103. var x2 = obj.x2 == null ? 1 : obj.x2;
  6104. var y = obj.y == null ? 0 : obj.y;
  6105. var y2 = obj.y2 == null ? 0 : obj.y2;
  6106. if (!obj.global) {
  6107. x = x * rect.width + rect.x;
  6108. x2 = x2 * rect.width + rect.x;
  6109. y = y * rect.height + rect.y;
  6110. y2 = y2 * rect.height + rect.y;
  6111. }
  6112. // Fix NaN when rect is Infinity
  6113. x = isNaN(x) ? 0 : x;
  6114. x2 = isNaN(x2) ? 1 : x2;
  6115. y = isNaN(y) ? 0 : y;
  6116. y2 = isNaN(y2) ? 0 : y2;
  6117. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  6118. return canvasGradient;
  6119. }
  6120. function createRadialGradient(ctx, obj, rect) {
  6121. var width = rect.width;
  6122. var height = rect.height;
  6123. var min = Math.min(width, height);
  6124. var x = obj.x == null ? 0.5 : obj.x;
  6125. var y = obj.y == null ? 0.5 : obj.y;
  6126. var r = obj.r == null ? 0.5 : obj.r;
  6127. if (!obj.global) {
  6128. x = x * width + rect.x;
  6129. y = y * height + rect.y;
  6130. r = r * min;
  6131. }
  6132. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  6133. return canvasGradient;
  6134. }
  6135. Style.prototype = {
  6136. constructor: Style,
  6137. /**
  6138. * @type {string}
  6139. */
  6140. fill: '#000',
  6141. /**
  6142. * @type {string}
  6143. */
  6144. stroke: null,
  6145. /**
  6146. * @type {number}
  6147. */
  6148. opacity: 1,
  6149. /**
  6150. * @type {number}
  6151. */
  6152. fillOpacity: null,
  6153. /**
  6154. * @type {number}
  6155. */
  6156. strokeOpacity: null,
  6157. /**
  6158. * `true` is not supported.
  6159. * `false`/`null`/`undefined` are the same.
  6160. * `false` is used to remove lineDash in some
  6161. * case that `null`/`undefined` can not be set.
  6162. * (e.g., emphasis.lineStyle in echarts)
  6163. * @type {Array.<number>|boolean}
  6164. */
  6165. lineDash: null,
  6166. /**
  6167. * @type {number}
  6168. */
  6169. lineDashOffset: 0,
  6170. /**
  6171. * @type {number}
  6172. */
  6173. shadowBlur: 0,
  6174. /**
  6175. * @type {number}
  6176. */
  6177. shadowOffsetX: 0,
  6178. /**
  6179. * @type {number}
  6180. */
  6181. shadowOffsetY: 0,
  6182. /**
  6183. * @type {number}
  6184. */
  6185. lineWidth: 1,
  6186. /**
  6187. * If stroke ignore scale
  6188. * @type {Boolean}
  6189. */
  6190. strokeNoScale: false,
  6191. // Bounding rect text configuration
  6192. // Not affected by element transform
  6193. /**
  6194. * @type {string}
  6195. */
  6196. text: null,
  6197. /**
  6198. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  6199. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  6200. * So do not visit it directly in upper application (like echarts),
  6201. * but use `contain/text#makeFont` instead.
  6202. * @type {string}
  6203. */
  6204. font: null,
  6205. /**
  6206. * The same as font. Use font please.
  6207. * @deprecated
  6208. * @type {string}
  6209. */
  6210. textFont: null,
  6211. /**
  6212. * It helps merging respectively, rather than parsing an entire font string.
  6213. * @type {string}
  6214. */
  6215. fontStyle: null,
  6216. /**
  6217. * It helps merging respectively, rather than parsing an entire font string.
  6218. * @type {string}
  6219. */
  6220. fontWeight: null,
  6221. /**
  6222. * It helps merging respectively, rather than parsing an entire font string.
  6223. * Should be 12 but not '12px'.
  6224. * @type {number}
  6225. */
  6226. fontSize: null,
  6227. /**
  6228. * It helps merging respectively, rather than parsing an entire font string.
  6229. * @type {string}
  6230. */
  6231. fontFamily: null,
  6232. /**
  6233. * Reserved for special functinality, like 'hr'.
  6234. * @type {string}
  6235. */
  6236. textTag: null,
  6237. /**
  6238. * @type {string}
  6239. */
  6240. textFill: '#000',
  6241. /**
  6242. * @type {string}
  6243. */
  6244. textStroke: null,
  6245. /**
  6246. * @type {number}
  6247. */
  6248. textWidth: null,
  6249. /**
  6250. * Only for textBackground.
  6251. * @type {number}
  6252. */
  6253. textHeight: null,
  6254. /**
  6255. * textStroke may be set as some color as a default
  6256. * value in upper applicaion, where the default value
  6257. * of textStrokeWidth should be 0 to make sure that
  6258. * user can choose to do not use text stroke.
  6259. * @type {number}
  6260. */
  6261. textStrokeWidth: 0,
  6262. /**
  6263. * @type {number}
  6264. */
  6265. textLineHeight: null,
  6266. /**
  6267. * 'inside', 'left', 'right', 'top', 'bottom'
  6268. * [x, y]
  6269. * Based on x, y of rect.
  6270. * @type {string|Array.<number>}
  6271. * @default 'inside'
  6272. */
  6273. textPosition: 'inside',
  6274. /**
  6275. * If not specified, use the boundingRect of a `displayable`.
  6276. * @type {Object}
  6277. */
  6278. textRect: null,
  6279. /**
  6280. * [x, y]
  6281. * @type {Array.<number>}
  6282. */
  6283. textOffset: null,
  6284. /**
  6285. * @type {string}
  6286. */
  6287. textAlign: null,
  6288. /**
  6289. * @type {string}
  6290. */
  6291. textVerticalAlign: null,
  6292. /**
  6293. * @type {number}
  6294. */
  6295. textDistance: 5,
  6296. /**
  6297. * @type {string}
  6298. */
  6299. textShadowColor: 'transparent',
  6300. /**
  6301. * @type {number}
  6302. */
  6303. textShadowBlur: 0,
  6304. /**
  6305. * @type {number}
  6306. */
  6307. textShadowOffsetX: 0,
  6308. /**
  6309. * @type {number}
  6310. */
  6311. textShadowOffsetY: 0,
  6312. /**
  6313. * @type {string}
  6314. */
  6315. textBoxShadowColor: 'transparent',
  6316. /**
  6317. * @type {number}
  6318. */
  6319. textBoxShadowBlur: 0,
  6320. /**
  6321. * @type {number}
  6322. */
  6323. textBoxShadowOffsetX: 0,
  6324. /**
  6325. * @type {number}
  6326. */
  6327. textBoxShadowOffsetY: 0,
  6328. /**
  6329. * Whether transform text.
  6330. * Only available in Path and Image element,
  6331. * where the text is called as `RectText`.
  6332. * @type {boolean}
  6333. */
  6334. transformText: false,
  6335. /**
  6336. * Text rotate around position of Path or Image.
  6337. * The origin of the rotation can be specified by `textOrigin`.
  6338. * Only available in Path and Image element,
  6339. * where the text is called as `RectText`.
  6340. */
  6341. textRotation: 0,
  6342. /**
  6343. * Text origin of text rotation.
  6344. * Useful in the case like label rotation of circular symbol.
  6345. * Only available in Path and Image element, where the text is called
  6346. * as `RectText` and the element is called as "host element".
  6347. * The value can be:
  6348. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6349. * base on the left-top corner of the rect of its host element.
  6350. * + If specified as a string `center`, it is the center of the rect of
  6351. * its host element.
  6352. * + By default, this origin is the `textPosition`.
  6353. * @type {string|Array.<number>}
  6354. */
  6355. textOrigin: null,
  6356. /**
  6357. * @type {string}
  6358. */
  6359. textBackgroundColor: null,
  6360. /**
  6361. * @type {string}
  6362. */
  6363. textBorderColor: null,
  6364. /**
  6365. * @type {number}
  6366. */
  6367. textBorderWidth: 0,
  6368. /**
  6369. * @type {number}
  6370. */
  6371. textBorderRadius: 0,
  6372. /**
  6373. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6374. * @type {number|Array.<number>}
  6375. */
  6376. textPadding: null,
  6377. /**
  6378. * Text styles for rich text.
  6379. * @type {Object}
  6380. */
  6381. rich: null,
  6382. /**
  6383. * {outerWidth, outerHeight, ellipsis, placeholder}
  6384. * @type {Object}
  6385. */
  6386. truncate: null,
  6387. /**
  6388. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6389. * @type {string}
  6390. */
  6391. blend: null,
  6392. /**
  6393. * @param {CanvasRenderingContext2D} ctx
  6394. */
  6395. bind: function (ctx, el, prevEl) {
  6396. var style = this;
  6397. var prevStyle = prevEl && prevEl.style;
  6398. // If no prevStyle, it means first draw.
  6399. // Only apply cache if the last time cachced by this function.
  6400. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6401. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6402. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6403. var prop = STYLE_COMMON_PROPS[i];
  6404. var styleName = prop[0];
  6405. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6406. // FIXME Invalid property value will cause style leak from previous element.
  6407. ctx[styleName] =
  6408. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6409. }
  6410. }
  6411. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6412. ctx.fillStyle = style.fill;
  6413. }
  6414. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6415. ctx.strokeStyle = style.stroke;
  6416. }
  6417. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6418. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6419. }
  6420. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6421. ctx.globalCompositeOperation = style.blend || 'source-over';
  6422. }
  6423. if (this.hasStroke()) {
  6424. var lineWidth = style.lineWidth;
  6425. ctx.lineWidth = lineWidth / (
  6426. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6427. );
  6428. }
  6429. },
  6430. hasFill: function () {
  6431. var fill = this.fill;
  6432. return fill != null && fill !== 'none';
  6433. },
  6434. hasStroke: function () {
  6435. var stroke = this.stroke;
  6436. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6437. },
  6438. /**
  6439. * Extend from other style
  6440. * @param {zrender/graphic/Style} otherStyle
  6441. * @param {boolean} overwrite true: overwrirte any way.
  6442. * false: overwrite only when !target.hasOwnProperty
  6443. * others: overwrite when property is not null/undefined.
  6444. */
  6445. extendFrom: function (otherStyle, overwrite) {
  6446. if (otherStyle) {
  6447. for (var name in otherStyle) {
  6448. if (otherStyle.hasOwnProperty(name)
  6449. && (overwrite === true
  6450. || (
  6451. overwrite === false
  6452. ? !this.hasOwnProperty(name)
  6453. : otherStyle[name] != null
  6454. )
  6455. )
  6456. ) {
  6457. this[name] = otherStyle[name];
  6458. }
  6459. }
  6460. }
  6461. },
  6462. /**
  6463. * Batch setting style with a given object
  6464. * @param {Object|string} obj
  6465. * @param {*} [obj]
  6466. */
  6467. set: function (obj, value) {
  6468. if (typeof obj === 'string') {
  6469. this[obj] = value;
  6470. }
  6471. else {
  6472. this.extendFrom(obj, true);
  6473. }
  6474. },
  6475. /**
  6476. * Clone
  6477. * @return {zrender/graphic/Style} [description]
  6478. */
  6479. clone: function () {
  6480. var newStyle = new this.constructor();
  6481. newStyle.extendFrom(this, true);
  6482. return newStyle;
  6483. },
  6484. getGradient: function (ctx, obj, rect) {
  6485. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6486. var canvasGradient = method(ctx, obj, rect);
  6487. var colorStops = obj.colorStops;
  6488. for (var i = 0; i < colorStops.length; i++) {
  6489. canvasGradient.addColorStop(
  6490. colorStops[i].offset, colorStops[i].color
  6491. );
  6492. }
  6493. return canvasGradient;
  6494. }
  6495. };
  6496. var styleProto = Style.prototype;
  6497. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6498. var prop = STYLE_COMMON_PROPS[i];
  6499. if (!(prop[0] in styleProto)) {
  6500. styleProto[prop[0]] = prop[1];
  6501. }
  6502. }
  6503. // Provide for others
  6504. Style.getGradient = styleProto.getGradient;
  6505. var Pattern = function (image, repeat) {
  6506. // Should do nothing more in this constructor. Because gradient can be
  6507. // declard by `color: {image: ...}`, where this constructor will not be called.
  6508. this.image = image;
  6509. this.repeat = repeat;
  6510. // Can be cloned
  6511. this.type = 'pattern';
  6512. };
  6513. Pattern.prototype.getCanvasPattern = function (ctx) {
  6514. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6515. };
  6516. /**
  6517. * @module zrender/Layer
  6518. * @author pissang(https://www.github.com/pissang)
  6519. */
  6520. function returnFalse() {
  6521. return false;
  6522. }
  6523. /**
  6524. * 创建dom
  6525. *
  6526. * @inner
  6527. * @param {string} id dom id 待用
  6528. * @param {Painter} painter painter instance
  6529. * @param {number} number
  6530. */
  6531. function createDom(id, painter, dpr) {
  6532. var newDom = createCanvas();
  6533. var width = painter.getWidth();
  6534. var height = painter.getHeight();
  6535. var newDomStyle = newDom.style;
  6536. if (newDomStyle) { // In node or some other non-browser environment
  6537. newDomStyle.position = 'absolute';
  6538. newDomStyle.left = 0;
  6539. newDomStyle.top = 0;
  6540. newDomStyle.width = width + 'px';
  6541. newDomStyle.height = height + 'px';
  6542. newDom.setAttribute('data-zr-dom-id', id);
  6543. }
  6544. newDom.width = width * dpr;
  6545. newDom.height = height * dpr;
  6546. return newDom;
  6547. }
  6548. /**
  6549. * @alias module:zrender/Layer
  6550. * @constructor
  6551. * @extends module:zrender/mixin/Transformable
  6552. * @param {string} id
  6553. * @param {module:zrender/Painter} painter
  6554. * @param {number} [dpr]
  6555. */
  6556. var Layer = function (id, painter, dpr) {
  6557. var dom;
  6558. dpr = dpr || devicePixelRatio;
  6559. if (typeof id === 'string') {
  6560. dom = createDom(id, painter, dpr);
  6561. }
  6562. // Not using isDom because in node it will return false
  6563. else if (isObject$1(id)) {
  6564. dom = id;
  6565. id = dom.id;
  6566. }
  6567. this.id = id;
  6568. this.dom = dom;
  6569. var domStyle = dom.style;
  6570. if (domStyle) { // Not in node
  6571. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6572. domStyle['-webkit-user-select'] = 'none';
  6573. domStyle['user-select'] = 'none';
  6574. domStyle['-webkit-touch-callout'] = 'none';
  6575. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6576. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6577. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6578. domStyle['border-width'] = 0;
  6579. }
  6580. this.domBack = null;
  6581. this.ctxBack = null;
  6582. this.painter = painter;
  6583. this.config = null;
  6584. // Configs
  6585. /**
  6586. * 每次清空画布的颜色
  6587. * @type {string}
  6588. * @default 0
  6589. */
  6590. this.clearColor = 0;
  6591. /**
  6592. * 是否开启动态模糊
  6593. * @type {boolean}
  6594. * @default false
  6595. */
  6596. this.motionBlur = false;
  6597. /**
  6598. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6599. * @type {number}
  6600. * @default 0.7
  6601. */
  6602. this.lastFrameAlpha = 0.7;
  6603. /**
  6604. * Layer dpr
  6605. * @type {number}
  6606. */
  6607. this.dpr = dpr;
  6608. };
  6609. Layer.prototype = {
  6610. constructor: Layer,
  6611. __dirty: true,
  6612. __used: false,
  6613. __drawIndex: 0,
  6614. __startIndex: 0,
  6615. __endIndex: 0,
  6616. incremental: false,
  6617. getElementCount: function () {
  6618. return this.__endIndex - this.__startIndex;
  6619. },
  6620. initContext: function () {
  6621. this.ctx = this.dom.getContext('2d');
  6622. this.ctx.dpr = this.dpr;
  6623. },
  6624. createBackBuffer: function () {
  6625. var dpr = this.dpr;
  6626. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6627. this.ctxBack = this.domBack.getContext('2d');
  6628. if (dpr !== 1) {
  6629. this.ctxBack.scale(dpr, dpr);
  6630. }
  6631. },
  6632. /**
  6633. * @param {number} width
  6634. * @param {number} height
  6635. */
  6636. resize: function (width, height) {
  6637. var dpr = this.dpr;
  6638. var dom = this.dom;
  6639. var domStyle = dom.style;
  6640. var domBack = this.domBack;
  6641. if (domStyle) {
  6642. domStyle.width = width + 'px';
  6643. domStyle.height = height + 'px';
  6644. }
  6645. dom.width = width * dpr;
  6646. dom.height = height * dpr;
  6647. if (domBack) {
  6648. domBack.width = width * dpr;
  6649. domBack.height = height * dpr;
  6650. if (dpr !== 1) {
  6651. this.ctxBack.scale(dpr, dpr);
  6652. }
  6653. }
  6654. },
  6655. /**
  6656. * 清空该层画布
  6657. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6658. * @param {Color} [clearColor]
  6659. */
  6660. clear: function (clearAll, clearColor) {
  6661. var dom = this.dom;
  6662. var ctx = this.ctx;
  6663. var width = dom.width;
  6664. var height = dom.height;
  6665. var clearColor = clearColor || this.clearColor;
  6666. var haveMotionBLur = this.motionBlur && !clearAll;
  6667. var lastFrameAlpha = this.lastFrameAlpha;
  6668. var dpr = this.dpr;
  6669. if (haveMotionBLur) {
  6670. if (!this.domBack) {
  6671. this.createBackBuffer();
  6672. }
  6673. this.ctxBack.globalCompositeOperation = 'copy';
  6674. this.ctxBack.drawImage(
  6675. dom, 0, 0,
  6676. width / dpr,
  6677. height / dpr
  6678. );
  6679. }
  6680. ctx.clearRect(0, 0, width, height);
  6681. if (clearColor && clearColor !== 'transparent') {
  6682. var clearColorGradientOrPattern;
  6683. // Gradient
  6684. if (clearColor.colorStops) {
  6685. // Cache canvas gradient
  6686. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6687. x: 0,
  6688. y: 0,
  6689. width: width,
  6690. height: height
  6691. });
  6692. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6693. }
  6694. // Pattern
  6695. else if (clearColor.image) {
  6696. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6697. }
  6698. ctx.save();
  6699. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6700. ctx.fillRect(0, 0, width, height);
  6701. ctx.restore();
  6702. }
  6703. if (haveMotionBLur) {
  6704. var domBack = this.domBack;
  6705. ctx.save();
  6706. ctx.globalAlpha = lastFrameAlpha;
  6707. ctx.drawImage(domBack, 0, 0, width, height);
  6708. ctx.restore();
  6709. }
  6710. }
  6711. };
  6712. var requestAnimationFrame = (
  6713. typeof window !== 'undefined'
  6714. && (
  6715. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6716. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6717. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6718. || window.mozRequestAnimationFrame
  6719. || window.webkitRequestAnimationFrame
  6720. )
  6721. ) || function (func) {
  6722. setTimeout(func, 16);
  6723. };
  6724. var globalImageCache = new LRU(50);
  6725. /**
  6726. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6727. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6728. */
  6729. function findExistImage(newImageOrSrc) {
  6730. if (typeof newImageOrSrc === 'string') {
  6731. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6732. return cachedImgObj && cachedImgObj.image;
  6733. }
  6734. else {
  6735. return newImageOrSrc;
  6736. }
  6737. }
  6738. /**
  6739. * Caution: User should cache loaded images, but not just count on LRU.
  6740. * Consider if required images more than LRU size, will dead loop occur?
  6741. *
  6742. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6743. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6744. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6745. * @param {Function} [cb] params: (image, cbPayload)
  6746. * @param {Object} [cbPayload] Payload on cb calling.
  6747. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6748. */
  6749. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6750. if (!newImageOrSrc) {
  6751. return image;
  6752. }
  6753. else if (typeof newImageOrSrc === 'string') {
  6754. // Image should not be loaded repeatly.
  6755. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6756. return image;
  6757. }
  6758. // Only when there is no existent image or existent image src
  6759. // is different, this method is responsible for load.
  6760. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6761. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6762. if (cachedImgObj) {
  6763. image = cachedImgObj.image;
  6764. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6765. }
  6766. else {
  6767. image = new Image();
  6768. image.onload = image.onerror = imageOnLoad;
  6769. globalImageCache.put(
  6770. newImageOrSrc,
  6771. image.__cachedImgObj = {
  6772. image: image,
  6773. pending: [pendingWrap]
  6774. }
  6775. );
  6776. image.src = image.__zrImageSrc = newImageOrSrc;
  6777. }
  6778. return image;
  6779. }
  6780. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6781. else {
  6782. return newImageOrSrc;
  6783. }
  6784. }
  6785. function imageOnLoad() {
  6786. var cachedImgObj = this.__cachedImgObj;
  6787. this.onload = this.onerror = this.__cachedImgObj = null;
  6788. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6789. var pendingWrap = cachedImgObj.pending[i];
  6790. var cb = pendingWrap.cb;
  6791. cb && cb(this, pendingWrap.cbPayload);
  6792. pendingWrap.hostEl.dirty();
  6793. }
  6794. cachedImgObj.pending.length = 0;
  6795. }
  6796. function isImageReady(image) {
  6797. return image && image.width && image.height;
  6798. }
  6799. var textWidthCache = {};
  6800. var textWidthCacheCounter = 0;
  6801. var TEXT_CACHE_MAX = 5000;
  6802. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6803. var DEFAULT_FONT$1 = '12px sans-serif';
  6804. // Avoid assign to an exported variable, for transforming to cjs.
  6805. var methods$1 = {};
  6806. function $override$1(name, fn) {
  6807. methods$1[name] = fn;
  6808. }
  6809. /**
  6810. * @public
  6811. * @param {string} text
  6812. * @param {string} font
  6813. * @return {number} width
  6814. */
  6815. function getWidth(text, font) {
  6816. font = font || DEFAULT_FONT$1;
  6817. var key = text + ':' + font;
  6818. if (textWidthCache[key]) {
  6819. return textWidthCache[key];
  6820. }
  6821. var textLines = (text + '').split('\n');
  6822. var width = 0;
  6823. for (var i = 0, l = textLines.length; i < l; i++) {
  6824. // textContain.measureText may be overrided in SVG or VML
  6825. width = Math.max(measureText(textLines[i], font).width, width);
  6826. }
  6827. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6828. textWidthCacheCounter = 0;
  6829. textWidthCache = {};
  6830. }
  6831. textWidthCacheCounter++;
  6832. textWidthCache[key] = width;
  6833. return width;
  6834. }
  6835. /**
  6836. * @public
  6837. * @param {string} text
  6838. * @param {string} font
  6839. * @param {string} [textAlign='left']
  6840. * @param {string} [textVerticalAlign='top']
  6841. * @param {Array.<number>} [textPadding]
  6842. * @param {Object} [rich]
  6843. * @param {Object} [truncate]
  6844. * @return {Object} {x, y, width, height, lineHeight}
  6845. */
  6846. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6847. return rich
  6848. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6849. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6850. }
  6851. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6852. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6853. var outerWidth = getWidth(text, font);
  6854. if (textPadding) {
  6855. outerWidth += textPadding[1] + textPadding[3];
  6856. }
  6857. var outerHeight = contentBlock.outerHeight;
  6858. var x = adjustTextX(0, outerWidth, textAlign);
  6859. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6860. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6861. rect.lineHeight = contentBlock.lineHeight;
  6862. return rect;
  6863. }
  6864. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6865. var contentBlock = parseRichText(text, {
  6866. rich: rich,
  6867. truncate: truncate,
  6868. font: font,
  6869. textAlign: textAlign,
  6870. textPadding: textPadding,
  6871. textLineHeight: textLineHeight
  6872. });
  6873. var outerWidth = contentBlock.outerWidth;
  6874. var outerHeight = contentBlock.outerHeight;
  6875. var x = adjustTextX(0, outerWidth, textAlign);
  6876. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6877. return new BoundingRect(x, y, outerWidth, outerHeight);
  6878. }
  6879. /**
  6880. * @public
  6881. * @param {number} x
  6882. * @param {number} width
  6883. * @param {string} [textAlign='left']
  6884. * @return {number} Adjusted x.
  6885. */
  6886. function adjustTextX(x, width, textAlign) {
  6887. // FIXME Right to left language
  6888. if (textAlign === 'right') {
  6889. x -= width;
  6890. }
  6891. else if (textAlign === 'center') {
  6892. x -= width / 2;
  6893. }
  6894. return x;
  6895. }
  6896. /**
  6897. * @public
  6898. * @param {number} y
  6899. * @param {number} height
  6900. * @param {string} [textVerticalAlign='top']
  6901. * @return {number} Adjusted y.
  6902. */
  6903. function adjustTextY(y, height, textVerticalAlign) {
  6904. if (textVerticalAlign === 'middle') {
  6905. y -= height / 2;
  6906. }
  6907. else if (textVerticalAlign === 'bottom') {
  6908. y -= height;
  6909. }
  6910. return y;
  6911. }
  6912. /**
  6913. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6914. * @public
  6915. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6916. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6917. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  6918. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  6919. */
  6920. function calculateTextPosition(out, style, rect) {
  6921. var textPosition = style.textPosition;
  6922. var distance = style.textDistance;
  6923. var x = rect.x;
  6924. var y = rect.y;
  6925. distance = distance || 0;
  6926. var height = rect.height;
  6927. var width = rect.width;
  6928. var halfHeight = height / 2;
  6929. var textAlign = 'left';
  6930. var textVerticalAlign = 'top';
  6931. switch (textPosition) {
  6932. case 'left':
  6933. x -= distance;
  6934. y += halfHeight;
  6935. textAlign = 'right';
  6936. textVerticalAlign = 'middle';
  6937. break;
  6938. case 'right':
  6939. x += distance + width;
  6940. y += halfHeight;
  6941. textVerticalAlign = 'middle';
  6942. break;
  6943. case 'top':
  6944. x += width / 2;
  6945. y -= distance;
  6946. textAlign = 'center';
  6947. textVerticalAlign = 'bottom';
  6948. break;
  6949. case 'bottom':
  6950. x += width / 2;
  6951. y += height + distance;
  6952. textAlign = 'center';
  6953. break;
  6954. case 'inside':
  6955. x += width / 2;
  6956. y += halfHeight;
  6957. textAlign = 'center';
  6958. textVerticalAlign = 'middle';
  6959. break;
  6960. case 'insideLeft':
  6961. x += distance;
  6962. y += halfHeight;
  6963. textVerticalAlign = 'middle';
  6964. break;
  6965. case 'insideRight':
  6966. x += width - distance;
  6967. y += halfHeight;
  6968. textAlign = 'right';
  6969. textVerticalAlign = 'middle';
  6970. break;
  6971. case 'insideTop':
  6972. x += width / 2;
  6973. y += distance;
  6974. textAlign = 'center';
  6975. break;
  6976. case 'insideBottom':
  6977. x += width / 2;
  6978. y += height - distance;
  6979. textAlign = 'center';
  6980. textVerticalAlign = 'bottom';
  6981. break;
  6982. case 'insideTopLeft':
  6983. x += distance;
  6984. y += distance;
  6985. break;
  6986. case 'insideTopRight':
  6987. x += width - distance;
  6988. y += distance;
  6989. textAlign = 'right';
  6990. break;
  6991. case 'insideBottomLeft':
  6992. x += distance;
  6993. y += height - distance;
  6994. textVerticalAlign = 'bottom';
  6995. break;
  6996. case 'insideBottomRight':
  6997. x += width - distance;
  6998. y += height - distance;
  6999. textAlign = 'right';
  7000. textVerticalAlign = 'bottom';
  7001. break;
  7002. }
  7003. out = out || {};
  7004. out.x = x;
  7005. out.y = y;
  7006. out.textAlign = textAlign;
  7007. out.textVerticalAlign = textVerticalAlign;
  7008. return out;
  7009. }
  7010. /**
  7011. * To be removed. But still do not remove in case that some one has imported it.
  7012. * @deprecated
  7013. * @public
  7014. * @param {stirng} textPosition
  7015. * @param {Object} rect {x, y, width, height}
  7016. * @param {number} distance
  7017. * @return {Object} {x, y, textAlign, textVerticalAlign}
  7018. */
  7019. /**
  7020. * Show ellipsis if overflow.
  7021. *
  7022. * @public
  7023. * @param {string} text
  7024. * @param {string} containerWidth
  7025. * @param {string} font
  7026. * @param {number} [ellipsis='...']
  7027. * @param {Object} [options]
  7028. * @param {number} [options.maxIterations=3]
  7029. * @param {number} [options.minChar=0] If truncate result are less
  7030. * then minChar, ellipsis will not show, which is
  7031. * better for user hint in some cases.
  7032. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  7033. * @return {string}
  7034. */
  7035. function truncateText(text, containerWidth, font, ellipsis, options) {
  7036. if (!containerWidth) {
  7037. return '';
  7038. }
  7039. var textLines = (text + '').split('\n');
  7040. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  7041. // FIXME
  7042. // It is not appropriate that every line has '...' when truncate multiple lines.
  7043. for (var i = 0, len = textLines.length; i < len; i++) {
  7044. textLines[i] = truncateSingleLine(textLines[i], options);
  7045. }
  7046. return textLines.join('\n');
  7047. }
  7048. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  7049. options = extend({}, options);
  7050. options.font = font;
  7051. var ellipsis = retrieve2(ellipsis, '...');
  7052. options.maxIterations = retrieve2(options.maxIterations, 2);
  7053. var minChar = options.minChar = retrieve2(options.minChar, 0);
  7054. // FIXME
  7055. // Other languages?
  7056. options.cnCharWidth = getWidth('国', font);
  7057. // FIXME
  7058. // Consider proportional font?
  7059. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  7060. options.placeholder = retrieve2(options.placeholder, '');
  7061. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  7062. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  7063. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  7064. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  7065. contentWidth -= ascCharWidth;
  7066. }
  7067. var ellipsisWidth = getWidth(ellipsis, font);
  7068. if (ellipsisWidth > contentWidth) {
  7069. ellipsis = '';
  7070. ellipsisWidth = 0;
  7071. }
  7072. contentWidth = containerWidth - ellipsisWidth;
  7073. options.ellipsis = ellipsis;
  7074. options.ellipsisWidth = ellipsisWidth;
  7075. options.contentWidth = contentWidth;
  7076. options.containerWidth = containerWidth;
  7077. return options;
  7078. }
  7079. function truncateSingleLine(textLine, options) {
  7080. var containerWidth = options.containerWidth;
  7081. var font = options.font;
  7082. var contentWidth = options.contentWidth;
  7083. if (!containerWidth) {
  7084. return '';
  7085. }
  7086. var lineWidth = getWidth(textLine, font);
  7087. if (lineWidth <= containerWidth) {
  7088. return textLine;
  7089. }
  7090. for (var j = 0; ; j++) {
  7091. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  7092. textLine += options.ellipsis;
  7093. break;
  7094. }
  7095. var subLength = j === 0
  7096. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  7097. : lineWidth > 0
  7098. ? Math.floor(textLine.length * contentWidth / lineWidth)
  7099. : 0;
  7100. textLine = textLine.substr(0, subLength);
  7101. lineWidth = getWidth(textLine, font);
  7102. }
  7103. if (textLine === '') {
  7104. textLine = options.placeholder;
  7105. }
  7106. return textLine;
  7107. }
  7108. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  7109. var width = 0;
  7110. var i = 0;
  7111. for (var len = text.length; i < len && width < contentWidth; i++) {
  7112. var charCode = text.charCodeAt(i);
  7113. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  7114. }
  7115. return i;
  7116. }
  7117. /**
  7118. * @public
  7119. * @param {string} font
  7120. * @return {number} line height
  7121. */
  7122. function getLineHeight(font) {
  7123. // FIXME A rough approach.
  7124. return getWidth('国', font);
  7125. }
  7126. /**
  7127. * @public
  7128. * @param {string} text
  7129. * @param {string} font
  7130. * @return {Object} width
  7131. */
  7132. function measureText(text, font) {
  7133. return methods$1.measureText(text, font);
  7134. }
  7135. // Avoid assign to an exported variable, for transforming to cjs.
  7136. methods$1.measureText = function (text, font) {
  7137. var ctx = getContext();
  7138. ctx.font = font || DEFAULT_FONT$1;
  7139. return ctx.measureText(text);
  7140. };
  7141. /**
  7142. * @public
  7143. * @param {string} text
  7144. * @param {string} font
  7145. * @param {Object} [truncate]
  7146. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  7147. * Notice: for performance, do not calculate outerWidth util needed.
  7148. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  7149. * Thus we can simply comparing the `input` text to determin whether the result changed,
  7150. * without travel the result `lines`.
  7151. */
  7152. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  7153. text != null && (text += '');
  7154. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  7155. var lines = text ? text.split('\n') : [];
  7156. var height = lines.length * lineHeight;
  7157. var outerHeight = height;
  7158. var canCacheByTextString = true;
  7159. if (padding) {
  7160. outerHeight += padding[0] + padding[2];
  7161. }
  7162. if (text && truncate) {
  7163. canCacheByTextString = false;
  7164. var truncOuterHeight = truncate.outerHeight;
  7165. var truncOuterWidth = truncate.outerWidth;
  7166. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  7167. text = '';
  7168. lines = [];
  7169. }
  7170. else if (truncOuterWidth != null) {
  7171. var options = prepareTruncateOptions(
  7172. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  7173. font,
  7174. truncate.ellipsis,
  7175. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  7176. );
  7177. // FIXME
  7178. // It is not appropriate that every line has '...' when truncate multiple lines.
  7179. for (var i = 0, len = lines.length; i < len; i++) {
  7180. lines[i] = truncateSingleLine(lines[i], options);
  7181. }
  7182. }
  7183. }
  7184. return {
  7185. lines: lines,
  7186. height: height,
  7187. outerHeight: outerHeight,
  7188. lineHeight: lineHeight,
  7189. canCacheByTextString: canCacheByTextString
  7190. };
  7191. }
  7192. /**
  7193. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  7194. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  7195. *
  7196. * @public
  7197. * @param {string} text
  7198. * @param {Object} style
  7199. * @return {Object} block
  7200. * {
  7201. * width,
  7202. * height,
  7203. * lines: [{
  7204. * lineHeight,
  7205. * width,
  7206. * tokens: [[{
  7207. * styleName,
  7208. * text,
  7209. * width, // include textPadding
  7210. * height, // include textPadding
  7211. * textWidth, // pure text width
  7212. * textHeight, // pure text height
  7213. * lineHeihgt,
  7214. * font,
  7215. * textAlign,
  7216. * textVerticalAlign
  7217. * }], [...], ...]
  7218. * }, ...]
  7219. * }
  7220. * If styleName is undefined, it is plain text.
  7221. */
  7222. function parseRichText(text, style) {
  7223. var contentBlock = {lines: [], width: 0, height: 0};
  7224. text != null && (text += '');
  7225. if (!text) {
  7226. return contentBlock;
  7227. }
  7228. var lastIndex = STYLE_REG.lastIndex = 0;
  7229. var result;
  7230. while ((result = STYLE_REG.exec(text)) != null) {
  7231. var matchedIndex = result.index;
  7232. if (matchedIndex > lastIndex) {
  7233. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  7234. }
  7235. pushTokens(contentBlock, result[2], result[1]);
  7236. lastIndex = STYLE_REG.lastIndex;
  7237. }
  7238. if (lastIndex < text.length) {
  7239. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  7240. }
  7241. var lines = contentBlock.lines;
  7242. var contentHeight = 0;
  7243. var contentWidth = 0;
  7244. // For `textWidth: 100%`
  7245. var pendingList = [];
  7246. var stlPadding = style.textPadding;
  7247. var truncate = style.truncate;
  7248. var truncateWidth = truncate && truncate.outerWidth;
  7249. var truncateHeight = truncate && truncate.outerHeight;
  7250. if (stlPadding) {
  7251. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  7252. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  7253. }
  7254. // Calculate layout info of tokens.
  7255. for (var i = 0; i < lines.length; i++) {
  7256. var line = lines[i];
  7257. var lineHeight = 0;
  7258. var lineWidth = 0;
  7259. for (var j = 0; j < line.tokens.length; j++) {
  7260. var token = line.tokens[j];
  7261. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  7262. // textPadding should not inherit from style.
  7263. var textPadding = token.textPadding = tokenStyle.textPadding;
  7264. // textFont has been asigned to font by `normalizeStyle`.
  7265. var font = token.font = tokenStyle.font || style.font;
  7266. // textHeight can be used when textVerticalAlign is specified in token.
  7267. var tokenHeight = token.textHeight = retrieve2(
  7268. // textHeight should not be inherited, consider it can be specified
  7269. // as box height of the block.
  7270. tokenStyle.textHeight, getLineHeight(font)
  7271. );
  7272. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  7273. token.height = tokenHeight;
  7274. token.lineHeight = retrieve3(
  7275. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  7276. );
  7277. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  7278. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  7279. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  7280. return {lines: [], width: 0, height: 0};
  7281. }
  7282. token.textWidth = getWidth(token.text, font);
  7283. var tokenWidth = tokenStyle.textWidth;
  7284. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  7285. // Percent width, can be `100%`, can be used in drawing separate
  7286. // line when box width is needed to be auto.
  7287. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7288. token.percentWidth = tokenWidth;
  7289. pendingList.push(token);
  7290. tokenWidth = 0;
  7291. // Do not truncate in this case, because there is no user case
  7292. // and it is too complicated.
  7293. }
  7294. else {
  7295. if (tokenWidthNotSpecified) {
  7296. tokenWidth = token.textWidth;
  7297. // FIXME: If image is not loaded and textWidth is not specified, calling
  7298. // `getBoundingRect()` will not get correct result.
  7299. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7300. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7301. // Use cases:
  7302. // (1) If image is not loaded, it will be loaded at render phase and call
  7303. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7304. // image, and then the right size will be calculated here at the next tick.
  7305. // See `graphic/helper/text.js`.
  7306. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7307. // use `imageHelper.findExistImage` to find cached image.
  7308. // `imageHelper.findExistImage` will always be called here before
  7309. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7310. // which ensures that image will not be rendered before correct size calcualted.
  7311. if (bgImg) {
  7312. bgImg = findExistImage(bgImg);
  7313. if (isImageReady(bgImg)) {
  7314. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7315. }
  7316. }
  7317. }
  7318. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7319. tokenWidth += paddingW;
  7320. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7321. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7322. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7323. token.text = '';
  7324. token.textWidth = tokenWidth = 0;
  7325. }
  7326. else {
  7327. token.text = truncateText(
  7328. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7329. {minChar: truncate.minChar}
  7330. );
  7331. token.textWidth = getWidth(token.text, font);
  7332. tokenWidth = token.textWidth + paddingW;
  7333. }
  7334. }
  7335. }
  7336. lineWidth += (token.width = tokenWidth);
  7337. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7338. }
  7339. line.width = lineWidth;
  7340. line.lineHeight = lineHeight;
  7341. contentHeight += lineHeight;
  7342. contentWidth = Math.max(contentWidth, lineWidth);
  7343. }
  7344. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7345. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7346. if (stlPadding) {
  7347. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7348. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7349. }
  7350. for (var i = 0; i < pendingList.length; i++) {
  7351. var token = pendingList[i];
  7352. var percentWidth = token.percentWidth;
  7353. // Should not base on outerWidth, because token can not be placed out of padding.
  7354. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7355. }
  7356. return contentBlock;
  7357. }
  7358. function pushTokens(block, str, styleName) {
  7359. var isEmptyStr = str === '';
  7360. var strs = str.split('\n');
  7361. var lines = block.lines;
  7362. for (var i = 0; i < strs.length; i++) {
  7363. var text = strs[i];
  7364. var token = {
  7365. styleName: styleName,
  7366. text: text,
  7367. isLineHolder: !text && !isEmptyStr
  7368. };
  7369. // The first token should be appended to the last line.
  7370. if (!i) {
  7371. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7372. // Consider cases:
  7373. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7374. // (which is a placeholder) should be replaced by new token.
  7375. // (2) A image backage, where token likes {a|}.
  7376. // (3) A redundant '' will affect textAlign in line.
  7377. // (4) tokens with the same tplName should not be merged, because
  7378. // they should be displayed in different box (with border and padding).
  7379. var tokensLen = tokens.length;
  7380. (tokensLen === 1 && tokens[0].isLineHolder)
  7381. ? (tokens[0] = token)
  7382. // Consider text is '', only insert when it is the "lineHolder" or
  7383. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7384. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7385. }
  7386. // Other tokens always start a new line.
  7387. else {
  7388. // If there is '', insert it as a placeholder.
  7389. lines.push({tokens: [token]});
  7390. }
  7391. }
  7392. }
  7393. function makeFont(style) {
  7394. // FIXME in node-canvas fontWeight is before fontStyle
  7395. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7396. var font = (style.fontSize || style.fontFamily) && [
  7397. style.fontStyle,
  7398. style.fontWeight,
  7399. (style.fontSize || 12) + 'px',
  7400. // If font properties are defined, `fontFamily` should not be ignored.
  7401. style.fontFamily || 'sans-serif'
  7402. ].join(' ');
  7403. return font && trim(font) || style.textFont || style.font;
  7404. }
  7405. /**
  7406. * @param {Object} ctx
  7407. * @param {Object} shape
  7408. * @param {number} shape.x
  7409. * @param {number} shape.y
  7410. * @param {number} shape.width
  7411. * @param {number} shape.height
  7412. * @param {number} shape.r
  7413. */
  7414. function buildPath(ctx, shape) {
  7415. var x = shape.x;
  7416. var y = shape.y;
  7417. var width = shape.width;
  7418. var height = shape.height;
  7419. var r = shape.r;
  7420. var r1;
  7421. var r2;
  7422. var r3;
  7423. var r4;
  7424. // Convert width and height to positive for better borderRadius
  7425. if (width < 0) {
  7426. x = x + width;
  7427. width = -width;
  7428. }
  7429. if (height < 0) {
  7430. y = y + height;
  7431. height = -height;
  7432. }
  7433. if (typeof r === 'number') {
  7434. r1 = r2 = r3 = r4 = r;
  7435. }
  7436. else if (r instanceof Array) {
  7437. if (r.length === 1) {
  7438. r1 = r2 = r3 = r4 = r[0];
  7439. }
  7440. else if (r.length === 2) {
  7441. r1 = r3 = r[0];
  7442. r2 = r4 = r[1];
  7443. }
  7444. else if (r.length === 3) {
  7445. r1 = r[0];
  7446. r2 = r4 = r[1];
  7447. r3 = r[2];
  7448. }
  7449. else {
  7450. r1 = r[0];
  7451. r2 = r[1];
  7452. r3 = r[2];
  7453. r4 = r[3];
  7454. }
  7455. }
  7456. else {
  7457. r1 = r2 = r3 = r4 = 0;
  7458. }
  7459. var total;
  7460. if (r1 + r2 > width) {
  7461. total = r1 + r2;
  7462. r1 *= width / total;
  7463. r2 *= width / total;
  7464. }
  7465. if (r3 + r4 > width) {
  7466. total = r3 + r4;
  7467. r3 *= width / total;
  7468. r4 *= width / total;
  7469. }
  7470. if (r2 + r3 > height) {
  7471. total = r2 + r3;
  7472. r2 *= height / total;
  7473. r3 *= height / total;
  7474. }
  7475. if (r1 + r4 > height) {
  7476. total = r1 + r4;
  7477. r1 *= height / total;
  7478. r4 *= height / total;
  7479. }
  7480. ctx.moveTo(x + r1, y);
  7481. ctx.lineTo(x + width - r2, y);
  7482. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7483. ctx.lineTo(x + width, y + height - r3);
  7484. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7485. ctx.lineTo(x + r4, y + height);
  7486. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7487. ctx.lineTo(x, y + r1);
  7488. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7489. }
  7490. var DEFAULT_FONT = DEFAULT_FONT$1;
  7491. // TODO: Have not support 'start', 'end' yet.
  7492. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7493. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7494. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7495. // the default value of shadowColor is `'transparent'`.
  7496. var SHADOW_STYLE_COMMON_PROPS = [
  7497. ['textShadowBlur', 'shadowBlur', 0],
  7498. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7499. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7500. ['textShadowColor', 'shadowColor', 'transparent']
  7501. ];
  7502. var _tmpTextPositionResult = {};
  7503. var _tmpBoxPositionResult = {};
  7504. /**
  7505. * @param {module:zrender/graphic/Style} style
  7506. * @return {module:zrender/graphic/Style} The input style.
  7507. */
  7508. function normalizeTextStyle(style) {
  7509. normalizeStyle(style);
  7510. each$1(style.rich, normalizeStyle);
  7511. return style;
  7512. }
  7513. function normalizeStyle(style) {
  7514. if (style) {
  7515. style.font = makeFont(style);
  7516. var textAlign = style.textAlign;
  7517. textAlign === 'middle' && (textAlign = 'center');
  7518. style.textAlign = (
  7519. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7520. ) ? textAlign : 'left';
  7521. // Compatible with textBaseline.
  7522. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7523. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7524. style.textVerticalAlign = (
  7525. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7526. ) ? textVerticalAlign : 'top';
  7527. var textPadding = style.textPadding;
  7528. if (textPadding) {
  7529. style.textPadding = normalizeCssArray(style.textPadding);
  7530. }
  7531. }
  7532. }
  7533. /**
  7534. * @param {CanvasRenderingContext2D} ctx
  7535. * @param {string} text
  7536. * @param {module:zrender/graphic/Style} style
  7537. * @param {Object|boolean} [rect] {x, y, width, height}
  7538. * If set false, rect text is not used.
  7539. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7540. */
  7541. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7542. style.rich
  7543. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7544. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7545. }
  7546. // Avoid setting to ctx according to prevEl if possible for
  7547. // performance in scenarios of large amount text.
  7548. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7549. 'use strict';
  7550. var needDrawBg = needDrawBackground(style);
  7551. var prevStyle;
  7552. var checkCache = false;
  7553. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7554. // Only take and check cache for `Text` el, but not RectText.
  7555. if (prevEl !== WILL_BE_RESTORED) {
  7556. if (prevEl) {
  7557. prevStyle = prevEl.style;
  7558. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7559. }
  7560. // Prevent from using cache in `Style::bind`, because of the case:
  7561. // ctx property is modified by other properties than `Style::bind`
  7562. // used, and Style::bind is called next.
  7563. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7564. }
  7565. // Since this will be restored, prevent from using these props to check cache in the next
  7566. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7567. else if (cachedByMe) {
  7568. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7569. }
  7570. var styleFont = style.font || DEFAULT_FONT;
  7571. // PENDING
  7572. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7573. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7574. // But layer save/restore needed to be considered.
  7575. // if (styleFont !== ctx.__fontCache) {
  7576. // ctx.font = styleFont;
  7577. // if (prevEl !== WILL_BE_RESTORED) {
  7578. // ctx.__fontCache = styleFont;
  7579. // }
  7580. // }
  7581. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7582. ctx.font = styleFont;
  7583. }
  7584. // Use the final font from context-2d, because the final
  7585. // font might not be the style.font when it is illegal.
  7586. // But get `ctx.font` might be time consuming.
  7587. var computedFont = hostEl.__computedFont;
  7588. if (hostEl.__styleFont !== styleFont) {
  7589. hostEl.__styleFont = styleFont;
  7590. computedFont = hostEl.__computedFont = ctx.font;
  7591. }
  7592. var textPadding = style.textPadding;
  7593. var textLineHeight = style.textLineHeight;
  7594. var contentBlock = hostEl.__textCotentBlock;
  7595. if (!contentBlock || hostEl.__dirtyText) {
  7596. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7597. text, computedFont, textPadding, textLineHeight, style.truncate
  7598. );
  7599. }
  7600. var outerHeight = contentBlock.outerHeight;
  7601. var textLines = contentBlock.lines;
  7602. var lineHeight = contentBlock.lineHeight;
  7603. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7604. var baseX = boxPos.baseX;
  7605. var baseY = boxPos.baseY;
  7606. var textAlign = boxPos.textAlign || 'left';
  7607. var textVerticalAlign = boxPos.textVerticalAlign;
  7608. // Origin of textRotation should be the base point of text drawing.
  7609. applyTextRotation(ctx, style, rect, baseX, baseY);
  7610. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7611. var textX = baseX;
  7612. var textY = boxY;
  7613. if (needDrawBg || textPadding) {
  7614. // Consider performance, do not call getTextWidth util necessary.
  7615. var textWidth = getWidth(text, computedFont);
  7616. var outerWidth = textWidth;
  7617. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7618. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7619. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7620. if (textPadding) {
  7621. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7622. textY += textPadding[0];
  7623. }
  7624. }
  7625. // Always set textAlign and textBase line, because it is difficute to calculate
  7626. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7627. // font set happened.
  7628. ctx.textAlign = textAlign;
  7629. // Force baseline to be "middle". Otherwise, if using "top", the
  7630. // text will offset downward a little bit in font "Microsoft YaHei".
  7631. ctx.textBaseline = 'middle';
  7632. // Set text opacity
  7633. ctx.globalAlpha = style.opacity || 1;
  7634. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7635. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7636. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7637. var styleProp = propItem[0];
  7638. var ctxProp = propItem[1];
  7639. var val = style[styleProp];
  7640. if (!checkCache || val !== prevStyle[styleProp]) {
  7641. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7642. }
  7643. }
  7644. // `textBaseline` is set as 'middle'.
  7645. textY += lineHeight / 2;
  7646. var textStrokeWidth = style.textStrokeWidth;
  7647. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7648. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7649. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7650. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7651. var textFill = getFill(style.textFill);
  7652. if (textStroke) {
  7653. if (strokeWidthChanged) {
  7654. ctx.lineWidth = textStrokeWidth;
  7655. }
  7656. if (strokeChanged) {
  7657. ctx.strokeStyle = textStroke;
  7658. }
  7659. }
  7660. if (textFill) {
  7661. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7662. ctx.fillStyle = textFill;
  7663. }
  7664. }
  7665. // Optimize simply, in most cases only one line exists.
  7666. if (textLines.length === 1) {
  7667. // Fill after stroke so the outline will not cover the main part.
  7668. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7669. textFill && ctx.fillText(textLines[0], textX, textY);
  7670. }
  7671. else {
  7672. for (var i = 0; i < textLines.length; i++) {
  7673. // Fill after stroke so the outline will not cover the main part.
  7674. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7675. textFill && ctx.fillText(textLines[i], textX, textY);
  7676. textY += lineHeight;
  7677. }
  7678. }
  7679. }
  7680. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7681. // Do not do cache for rich text because of the complexity.
  7682. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7683. if (prevEl !== WILL_BE_RESTORED) {
  7684. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7685. }
  7686. var contentBlock = hostEl.__textCotentBlock;
  7687. if (!contentBlock || hostEl.__dirtyText) {
  7688. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7689. }
  7690. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7691. }
  7692. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7693. var contentWidth = contentBlock.width;
  7694. var outerWidth = contentBlock.outerWidth;
  7695. var outerHeight = contentBlock.outerHeight;
  7696. var textPadding = style.textPadding;
  7697. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7698. var baseX = boxPos.baseX;
  7699. var baseY = boxPos.baseY;
  7700. var textAlign = boxPos.textAlign;
  7701. var textVerticalAlign = boxPos.textVerticalAlign;
  7702. // Origin of textRotation should be the base point of text drawing.
  7703. applyTextRotation(ctx, style, rect, baseX, baseY);
  7704. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7705. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7706. var xLeft = boxX;
  7707. var lineTop = boxY;
  7708. if (textPadding) {
  7709. xLeft += textPadding[3];
  7710. lineTop += textPadding[0];
  7711. }
  7712. var xRight = xLeft + contentWidth;
  7713. needDrawBackground(style) && drawBackground(
  7714. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7715. );
  7716. for (var i = 0; i < contentBlock.lines.length; i++) {
  7717. var line = contentBlock.lines[i];
  7718. var tokens = line.tokens;
  7719. var tokenCount = tokens.length;
  7720. var lineHeight = line.lineHeight;
  7721. var usedWidth = line.width;
  7722. var leftIndex = 0;
  7723. var lineXLeft = xLeft;
  7724. var lineXRight = xRight;
  7725. var rightIndex = tokenCount - 1;
  7726. var token;
  7727. while (
  7728. leftIndex < tokenCount
  7729. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7730. ) {
  7731. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7732. usedWidth -= token.width;
  7733. lineXLeft += token.width;
  7734. leftIndex++;
  7735. }
  7736. while (
  7737. rightIndex >= 0
  7738. && (token = tokens[rightIndex], token.textAlign === 'right')
  7739. ) {
  7740. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7741. usedWidth -= token.width;
  7742. lineXRight -= token.width;
  7743. rightIndex--;
  7744. }
  7745. // The other tokens are placed as textAlign 'center' if there is enough space.
  7746. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7747. while (leftIndex <= rightIndex) {
  7748. token = tokens[leftIndex];
  7749. // Consider width specified by user, use 'center' rather than 'left'.
  7750. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7751. lineXLeft += token.width;
  7752. leftIndex++;
  7753. }
  7754. lineTop += lineHeight;
  7755. }
  7756. }
  7757. function applyTextRotation(ctx, style, rect, x, y) {
  7758. // textRotation only apply in RectText.
  7759. if (rect && style.textRotation) {
  7760. var origin = style.textOrigin;
  7761. if (origin === 'center') {
  7762. x = rect.width / 2 + rect.x;
  7763. y = rect.height / 2 + rect.y;
  7764. }
  7765. else if (origin) {
  7766. x = origin[0] + rect.x;
  7767. y = origin[1] + rect.y;
  7768. }
  7769. ctx.translate(x, y);
  7770. // Positive: anticlockwise
  7771. ctx.rotate(-style.textRotation);
  7772. ctx.translate(-x, -y);
  7773. }
  7774. }
  7775. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7776. var tokenStyle = style.rich[token.styleName] || {};
  7777. tokenStyle.text = token.text;
  7778. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7779. // the bias of "Microsoft YaHei".
  7780. var textVerticalAlign = token.textVerticalAlign;
  7781. var y = lineTop + lineHeight / 2;
  7782. if (textVerticalAlign === 'top') {
  7783. y = lineTop + token.height / 2;
  7784. }
  7785. else if (textVerticalAlign === 'bottom') {
  7786. y = lineTop + lineHeight - token.height / 2;
  7787. }
  7788. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7789. hostEl,
  7790. ctx,
  7791. tokenStyle,
  7792. textAlign === 'right'
  7793. ? x - token.width
  7794. : textAlign === 'center'
  7795. ? x - token.width / 2
  7796. : x,
  7797. y - token.height / 2,
  7798. token.width,
  7799. token.height
  7800. );
  7801. var textPadding = token.textPadding;
  7802. if (textPadding) {
  7803. x = getTextXForPadding(x, textAlign, textPadding);
  7804. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7805. }
  7806. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7807. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7808. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7809. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7810. setCtx(ctx, 'textAlign', textAlign);
  7811. // Force baseline to be "middle". Otherwise, if using "top", the
  7812. // text will offset downward a little bit in font "Microsoft YaHei".
  7813. setCtx(ctx, 'textBaseline', 'middle');
  7814. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7815. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7816. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7817. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7818. // Fill after stroke so the outline will not cover the main part.
  7819. if (textStroke) {
  7820. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7821. setCtx(ctx, 'strokeStyle', textStroke);
  7822. ctx.strokeText(token.text, x, y);
  7823. }
  7824. if (textFill) {
  7825. setCtx(ctx, 'fillStyle', textFill);
  7826. ctx.fillText(token.text, x, y);
  7827. }
  7828. }
  7829. function needDrawBackground(style) {
  7830. return !!(
  7831. style.textBackgroundColor
  7832. || (style.textBorderWidth && style.textBorderColor)
  7833. );
  7834. }
  7835. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7836. // shape: {x, y, width, height}
  7837. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7838. var textBackgroundColor = style.textBackgroundColor;
  7839. var textBorderWidth = style.textBorderWidth;
  7840. var textBorderColor = style.textBorderColor;
  7841. var isPlainBg = isString(textBackgroundColor);
  7842. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7843. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7844. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7845. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7846. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7847. ctx.beginPath();
  7848. var textBorderRadius = style.textBorderRadius;
  7849. if (!textBorderRadius) {
  7850. ctx.rect(x, y, width, height);
  7851. }
  7852. else {
  7853. buildPath(ctx, {
  7854. x: x, y: y, width: width, height: height, r: textBorderRadius
  7855. });
  7856. }
  7857. ctx.closePath();
  7858. }
  7859. if (isPlainBg) {
  7860. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7861. if (style.fillOpacity != null) {
  7862. var originalGlobalAlpha = ctx.globalAlpha;
  7863. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7864. ctx.fill();
  7865. ctx.globalAlpha = originalGlobalAlpha;
  7866. }
  7867. else {
  7868. ctx.fill();
  7869. }
  7870. }
  7871. else if (isObject$1(textBackgroundColor)) {
  7872. var image = textBackgroundColor.image;
  7873. image = createOrUpdateImage(
  7874. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7875. );
  7876. if (image && isImageReady(image)) {
  7877. ctx.drawImage(image, x, y, width, height);
  7878. }
  7879. }
  7880. if (textBorderWidth && textBorderColor) {
  7881. setCtx(ctx, 'lineWidth', textBorderWidth);
  7882. setCtx(ctx, 'strokeStyle', textBorderColor);
  7883. if (style.strokeOpacity != null) {
  7884. var originalGlobalAlpha = ctx.globalAlpha;
  7885. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7886. ctx.stroke();
  7887. ctx.globalAlpha = originalGlobalAlpha;
  7888. }
  7889. else {
  7890. ctx.stroke();
  7891. }
  7892. }
  7893. }
  7894. function onBgImageLoaded(image, textBackgroundColor) {
  7895. // Replace image, so that `contain/text.js#parseRichText`
  7896. // will get correct result in next tick.
  7897. textBackgroundColor.image = image;
  7898. }
  7899. function getBoxPosition(out, hostEl, style, rect) {
  7900. var baseX = style.x || 0;
  7901. var baseY = style.y || 0;
  7902. var textAlign = style.textAlign;
  7903. var textVerticalAlign = style.textVerticalAlign;
  7904. // Text position represented by coord
  7905. if (rect) {
  7906. var textPosition = style.textPosition;
  7907. if (textPosition instanceof Array) {
  7908. // Percent
  7909. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7910. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7911. }
  7912. else {
  7913. var res = (hostEl && hostEl.calculateTextPosition)
  7914. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7915. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7916. baseX = res.x;
  7917. baseY = res.y;
  7918. // Default align and baseline when has textPosition
  7919. textAlign = textAlign || res.textAlign;
  7920. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7921. }
  7922. // textOffset is only support in RectText, otherwise
  7923. // we have to adjust boundingRect for textOffset.
  7924. var textOffset = style.textOffset;
  7925. if (textOffset) {
  7926. baseX += textOffset[0];
  7927. baseY += textOffset[1];
  7928. }
  7929. }
  7930. out = out || {};
  7931. out.baseX = baseX;
  7932. out.baseY = baseY;
  7933. out.textAlign = textAlign;
  7934. out.textVerticalAlign = textVerticalAlign;
  7935. return out;
  7936. }
  7937. function setCtx(ctx, prop, value) {
  7938. ctx[prop] = fixShadow(ctx, prop, value);
  7939. return ctx[prop];
  7940. }
  7941. /**
  7942. * @param {string} [stroke] If specified, do not check style.textStroke.
  7943. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7944. * @param {number} style
  7945. */
  7946. function getStroke(stroke, lineWidth) {
  7947. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7948. ? null
  7949. // TODO pattern and gradient?
  7950. : (stroke.image || stroke.colorStops)
  7951. ? '#000'
  7952. : stroke;
  7953. }
  7954. function getFill(fill) {
  7955. return (fill == null || fill === 'none')
  7956. ? null
  7957. // TODO pattern and gradient?
  7958. : (fill.image || fill.colorStops)
  7959. ? '#000'
  7960. : fill;
  7961. }
  7962. function parsePercent(value, maxValue) {
  7963. if (typeof value === 'string') {
  7964. if (value.lastIndexOf('%') >= 0) {
  7965. return parseFloat(value) / 100 * maxValue;
  7966. }
  7967. return parseFloat(value);
  7968. }
  7969. return value;
  7970. }
  7971. function getTextXForPadding(x, textAlign, textPadding) {
  7972. return textAlign === 'right'
  7973. ? (x - textPadding[1])
  7974. : textAlign === 'center'
  7975. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7976. : (x + textPadding[3]);
  7977. }
  7978. /**
  7979. * @param {string} text
  7980. * @param {module:zrender/Style} style
  7981. * @return {boolean}
  7982. */
  7983. function needDrawText(text, style) {
  7984. return text != null
  7985. && (text
  7986. || style.textBackgroundColor
  7987. || (style.textBorderWidth && style.textBorderColor)
  7988. || style.textPadding
  7989. );
  7990. }
  7991. /**
  7992. * Mixin for drawing text in a element bounding rect
  7993. * @module zrender/mixin/RectText
  7994. */
  7995. var tmpRect$1 = new BoundingRect();
  7996. var RectText = function () {};
  7997. RectText.prototype = {
  7998. constructor: RectText,
  7999. /**
  8000. * Draw text in a rect with specified position.
  8001. * @param {CanvasRenderingContext2D} ctx
  8002. * @param {Object} rect Displayable rect
  8003. */
  8004. drawRectText: function (ctx, rect) {
  8005. var style = this.style;
  8006. rect = style.textRect || rect;
  8007. // Optimize, avoid normalize every time.
  8008. this.__dirty && normalizeTextStyle(style, true);
  8009. var text = style.text;
  8010. // Convert to string
  8011. text != null && (text += '');
  8012. if (!needDrawText(text, style)) {
  8013. return;
  8014. }
  8015. // FIXME
  8016. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  8017. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  8018. // text propably break the cache for its host elements.
  8019. ctx.save();
  8020. // Transform rect to view space
  8021. var transform = this.transform;
  8022. if (!style.transformText) {
  8023. if (transform) {
  8024. tmpRect$1.copy(rect);
  8025. tmpRect$1.applyTransform(transform);
  8026. rect = tmpRect$1;
  8027. }
  8028. }
  8029. else {
  8030. this.setTransform(ctx);
  8031. }
  8032. // transformText and textRotation can not be used at the same time.
  8033. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  8034. ctx.restore();
  8035. }
  8036. };
  8037. /**
  8038. * Base class of all displayable graphic objects
  8039. * @module zrender/graphic/Displayable
  8040. */
  8041. /**
  8042. * @alias module:zrender/graphic/Displayable
  8043. * @extends module:zrender/Element
  8044. * @extends module:zrender/graphic/mixin/RectText
  8045. */
  8046. function Displayable(opts) {
  8047. opts = opts || {};
  8048. Element.call(this, opts);
  8049. // Extend properties
  8050. for (var name in opts) {
  8051. if (
  8052. opts.hasOwnProperty(name)
  8053. && name !== 'style'
  8054. ) {
  8055. this[name] = opts[name];
  8056. }
  8057. }
  8058. /**
  8059. * @type {module:zrender/graphic/Style}
  8060. */
  8061. this.style = new Style(opts.style, this);
  8062. this._rect = null;
  8063. // Shapes for cascade clipping.
  8064. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  8065. // because it is easy to only using null to check whether clipPaths changed.
  8066. this.__clipPaths = null;
  8067. // FIXME Stateful must be mixined after style is setted
  8068. // Stateful.call(this, opts);
  8069. }
  8070. Displayable.prototype = {
  8071. constructor: Displayable,
  8072. type: 'displayable',
  8073. /**
  8074. * Dirty flag. From which painter will determine if this displayable object needs brush.
  8075. * @name module:zrender/graphic/Displayable#__dirty
  8076. * @type {boolean}
  8077. */
  8078. __dirty: true,
  8079. /**
  8080. * Whether the displayable object is visible. when it is true, the displayable object
  8081. * is not drawn, but the mouse event can still trigger the object.
  8082. * @name module:/zrender/graphic/Displayable#invisible
  8083. * @type {boolean}
  8084. * @default false
  8085. */
  8086. invisible: false,
  8087. /**
  8088. * @name module:/zrender/graphic/Displayable#z
  8089. * @type {number}
  8090. * @default 0
  8091. */
  8092. z: 0,
  8093. /**
  8094. * @name module:/zrender/graphic/Displayable#z
  8095. * @type {number}
  8096. * @default 0
  8097. */
  8098. z2: 0,
  8099. /**
  8100. * The z level determines the displayable object can be drawn in which layer canvas.
  8101. * @name module:/zrender/graphic/Displayable#zlevel
  8102. * @type {number}
  8103. * @default 0
  8104. */
  8105. zlevel: 0,
  8106. /**
  8107. * Whether it can be dragged.
  8108. * @name module:/zrender/graphic/Displayable#draggable
  8109. * @type {boolean}
  8110. * @default false
  8111. */
  8112. draggable: false,
  8113. /**
  8114. * Whether is it dragging.
  8115. * @name module:/zrender/graphic/Displayable#draggable
  8116. * @type {boolean}
  8117. * @default false
  8118. */
  8119. dragging: false,
  8120. /**
  8121. * Whether to respond to mouse events.
  8122. * @name module:/zrender/graphic/Displayable#silent
  8123. * @type {boolean}
  8124. * @default false
  8125. */
  8126. silent: false,
  8127. /**
  8128. * If enable culling
  8129. * @type {boolean}
  8130. * @default false
  8131. */
  8132. culling: false,
  8133. /**
  8134. * Mouse cursor when hovered
  8135. * @name module:/zrender/graphic/Displayable#cursor
  8136. * @type {string}
  8137. */
  8138. cursor: 'pointer',
  8139. /**
  8140. * If hover area is bounding rect
  8141. * @name module:/zrender/graphic/Displayable#rectHover
  8142. * @type {string}
  8143. */
  8144. rectHover: false,
  8145. /**
  8146. * Render the element progressively when the value >= 0,
  8147. * usefull for large data.
  8148. * @type {boolean}
  8149. */
  8150. progressive: false,
  8151. /**
  8152. * @type {boolean}
  8153. */
  8154. incremental: false,
  8155. /**
  8156. * Scale ratio for global scale.
  8157. * @type {boolean}
  8158. */
  8159. globalScaleRatio: 1,
  8160. beforeBrush: function (ctx) {},
  8161. afterBrush: function (ctx) {},
  8162. /**
  8163. * Graphic drawing method.
  8164. * @param {CanvasRenderingContext2D} ctx
  8165. */
  8166. // Interface
  8167. brush: function (ctx, prevEl) {},
  8168. /**
  8169. * Get the minimum bounding box.
  8170. * @return {module:zrender/core/BoundingRect}
  8171. */
  8172. // Interface
  8173. getBoundingRect: function () {},
  8174. /**
  8175. * If displayable element contain coord x, y
  8176. * @param {number} x
  8177. * @param {number} y
  8178. * @return {boolean}
  8179. */
  8180. contain: function (x, y) {
  8181. return this.rectContain(x, y);
  8182. },
  8183. /**
  8184. * @param {Function} cb
  8185. * @param {} context
  8186. */
  8187. traverse: function (cb, context) {
  8188. cb.call(context, this);
  8189. },
  8190. /**
  8191. * If bounding rect of element contain coord x, y
  8192. * @param {number} x
  8193. * @param {number} y
  8194. * @return {boolean}
  8195. */
  8196. rectContain: function (x, y) {
  8197. var coord = this.transformCoordToLocal(x, y);
  8198. var rect = this.getBoundingRect();
  8199. return rect.contain(coord[0], coord[1]);
  8200. },
  8201. /**
  8202. * Mark displayable element dirty and refresh next frame
  8203. */
  8204. dirty: function () {
  8205. this.__dirty = this.__dirtyText = true;
  8206. this._rect = null;
  8207. this.__zr && this.__zr.refresh();
  8208. },
  8209. /**
  8210. * If displayable object binded any event
  8211. * @return {boolean}
  8212. */
  8213. // TODO, events bound by bind
  8214. // isSilent: function () {
  8215. // return !(
  8216. // this.hoverable || this.draggable
  8217. // || this.onmousemove || this.onmouseover || this.onmouseout
  8218. // || this.onmousedown || this.onmouseup || this.onclick
  8219. // || this.ondragenter || this.ondragover || this.ondragleave
  8220. // || this.ondrop
  8221. // );
  8222. // },
  8223. /**
  8224. * Alias for animate('style')
  8225. * @param {boolean} loop
  8226. */
  8227. animateStyle: function (loop) {
  8228. return this.animate('style', loop);
  8229. },
  8230. attrKV: function (key, value) {
  8231. if (key !== 'style') {
  8232. Element.prototype.attrKV.call(this, key, value);
  8233. }
  8234. else {
  8235. this.style.set(value);
  8236. }
  8237. },
  8238. /**
  8239. * @param {Object|string} key
  8240. * @param {*} value
  8241. */
  8242. setStyle: function (key, value) {
  8243. this.style.set(key, value);
  8244. this.dirty(false);
  8245. return this;
  8246. },
  8247. /**
  8248. * Use given style object
  8249. * @param {Object} obj
  8250. */
  8251. useStyle: function (obj) {
  8252. this.style = new Style(obj, this);
  8253. this.dirty(false);
  8254. return this;
  8255. },
  8256. /**
  8257. * The string value of `textPosition` needs to be calculated to a real postion.
  8258. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  8259. * by default. See `contain/text.js#calculateTextPosition` for more details.
  8260. * But some coutom shapes like "pin", "flag" have center that is not exactly
  8261. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  8262. * for those shapes. It will be called if the `style.textPosition` is a string.
  8263. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  8264. * be responsible for creating one.
  8265. * @param {module:zrender/graphic/Style} style
  8266. * @param {Object} rect {x, y, width, height}
  8267. * @return {Obejct} out The same as the input out.
  8268. * {
  8269. * x: number. mandatory.
  8270. * y: number. mandatory.
  8271. * textAlign: string. optional. use style.textAlign by default.
  8272. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  8273. * }
  8274. */
  8275. calculateTextPosition: null
  8276. };
  8277. inherits(Displayable, Element);
  8278. mixin(Displayable, RectText);
  8279. /**
  8280. * @alias zrender/graphic/Image
  8281. * @extends module:zrender/graphic/Displayable
  8282. * @constructor
  8283. * @param {Object} opts
  8284. */
  8285. function ZImage(opts) {
  8286. Displayable.call(this, opts);
  8287. }
  8288. ZImage.prototype = {
  8289. constructor: ZImage,
  8290. type: 'image',
  8291. brush: function (ctx, prevEl) {
  8292. var style = this.style;
  8293. var src = style.image;
  8294. // Must bind each time
  8295. style.bind(ctx, this, prevEl);
  8296. var image = this._image = createOrUpdateImage(
  8297. src,
  8298. this._image,
  8299. this,
  8300. this.onload
  8301. );
  8302. if (!image || !isImageReady(image)) {
  8303. return;
  8304. }
  8305. // 图片已经加载完成
  8306. // if (image.nodeName.toUpperCase() == 'IMG') {
  8307. // if (!image.complete) {
  8308. // return;
  8309. // }
  8310. // }
  8311. // Else is canvas
  8312. var x = style.x || 0;
  8313. var y = style.y || 0;
  8314. var width = style.width;
  8315. var height = style.height;
  8316. var aspect = image.width / image.height;
  8317. if (width == null && height != null) {
  8318. // Keep image/height ratio
  8319. width = height * aspect;
  8320. }
  8321. else if (height == null && width != null) {
  8322. height = width / aspect;
  8323. }
  8324. else if (width == null && height == null) {
  8325. width = image.width;
  8326. height = image.height;
  8327. }
  8328. // 设置transform
  8329. this.setTransform(ctx);
  8330. if (style.sWidth && style.sHeight) {
  8331. var sx = style.sx || 0;
  8332. var sy = style.sy || 0;
  8333. ctx.drawImage(
  8334. image,
  8335. sx, sy, style.sWidth, style.sHeight,
  8336. x, y, width, height
  8337. );
  8338. }
  8339. else if (style.sx && style.sy) {
  8340. var sx = style.sx;
  8341. var sy = style.sy;
  8342. var sWidth = width - sx;
  8343. var sHeight = height - sy;
  8344. ctx.drawImage(
  8345. image,
  8346. sx, sy, sWidth, sHeight,
  8347. x, y, width, height
  8348. );
  8349. }
  8350. else {
  8351. ctx.drawImage(image, x, y, width, height);
  8352. }
  8353. // Draw rect text
  8354. if (style.text != null) {
  8355. // Only restore transform when needs draw text.
  8356. this.restoreTransform(ctx);
  8357. this.drawRectText(ctx, this.getBoundingRect());
  8358. }
  8359. },
  8360. getBoundingRect: function () {
  8361. var style = this.style;
  8362. if (!this._rect) {
  8363. this._rect = new BoundingRect(
  8364. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8365. );
  8366. }
  8367. return this._rect;
  8368. }
  8369. };
  8370. inherits(ZImage, Displayable);
  8371. var HOVER_LAYER_ZLEVEL = 1e5;
  8372. var CANVAS_ZLEVEL = 314159;
  8373. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8374. var INCREMENTAL_INC = 0.001;
  8375. function parseInt10(val) {
  8376. return parseInt(val, 10);
  8377. }
  8378. function isLayerValid(layer) {
  8379. if (!layer) {
  8380. return false;
  8381. }
  8382. if (layer.__builtin__) {
  8383. return true;
  8384. }
  8385. if (typeof (layer.resize) !== 'function'
  8386. || typeof (layer.refresh) !== 'function'
  8387. ) {
  8388. return false;
  8389. }
  8390. return true;
  8391. }
  8392. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8393. var viewRect = new BoundingRect(0, 0, 0, 0);
  8394. function isDisplayableCulled(el, width, height) {
  8395. tmpRect.copy(el.getBoundingRect());
  8396. if (el.transform) {
  8397. tmpRect.applyTransform(el.transform);
  8398. }
  8399. viewRect.width = width;
  8400. viewRect.height = height;
  8401. return !tmpRect.intersect(viewRect);
  8402. }
  8403. function isClipPathChanged(clipPaths, prevClipPaths) {
  8404. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8405. if (clipPaths === prevClipPaths) {
  8406. return false;
  8407. }
  8408. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8409. return true;
  8410. }
  8411. for (var i = 0; i < clipPaths.length; i++) {
  8412. if (clipPaths[i] !== prevClipPaths[i]) {
  8413. return true;
  8414. }
  8415. }
  8416. return false;
  8417. }
  8418. function doClip(clipPaths, ctx) {
  8419. for (var i = 0; i < clipPaths.length; i++) {
  8420. var clipPath = clipPaths[i];
  8421. clipPath.setTransform(ctx);
  8422. ctx.beginPath();
  8423. clipPath.buildPath(ctx, clipPath.shape);
  8424. ctx.clip();
  8425. // Transform back
  8426. clipPath.restoreTransform(ctx);
  8427. }
  8428. }
  8429. function createRoot(width, height) {
  8430. var domRoot = document.createElement('div');
  8431. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8432. domRoot.style.cssText = [
  8433. 'position:relative',
  8434. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8435. // dom does not act as expected) when some of the parent dom has
  8436. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8437. // the canvas is not at the top part of the page.
  8438. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8439. // this `overflow:hidden` to avoid the bug.
  8440. // 'overflow:hidden',
  8441. 'width:' + width + 'px',
  8442. 'height:' + height + 'px',
  8443. 'padding:0',
  8444. 'margin:0',
  8445. 'border-width:0'
  8446. ].join(';') + ';';
  8447. return domRoot;
  8448. }
  8449. /**
  8450. * @alias module:zrender/Painter
  8451. * @constructor
  8452. * @param {HTMLElement} root 绘图容器
  8453. * @param {module:zrender/Storage} storage
  8454. * @param {Object} opts
  8455. */
  8456. var Painter = function (root, storage, opts) {
  8457. this.type = 'canvas';
  8458. // In node environment using node-canvas
  8459. var singleCanvas = !root.nodeName // In node ?
  8460. || root.nodeName.toUpperCase() === 'CANVAS';
  8461. this._opts = opts = extend({}, opts || {});
  8462. /**
  8463. * @type {number}
  8464. */
  8465. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8466. /**
  8467. * @type {boolean}
  8468. * @private
  8469. */
  8470. this._singleCanvas = singleCanvas;
  8471. /**
  8472. * 绘图容器
  8473. * @type {HTMLElement}
  8474. */
  8475. this.root = root;
  8476. var rootStyle = root.style;
  8477. if (rootStyle) {
  8478. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8479. rootStyle['-webkit-user-select'] =
  8480. rootStyle['user-select'] =
  8481. rootStyle['-webkit-touch-callout'] = 'none';
  8482. root.innerHTML = '';
  8483. }
  8484. /**
  8485. * @type {module:zrender/Storage}
  8486. */
  8487. this.storage = storage;
  8488. /**
  8489. * @type {Array.<number>}
  8490. * @private
  8491. */
  8492. var zlevelList = this._zlevelList = [];
  8493. /**
  8494. * @type {Object.<string, module:zrender/Layer>}
  8495. * @private
  8496. */
  8497. var layers = this._layers = {};
  8498. /**
  8499. * @type {Object.<string, Object>}
  8500. * @private
  8501. */
  8502. this._layerConfig = {};
  8503. /**
  8504. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8505. */
  8506. this._needsManuallyCompositing = false;
  8507. if (!singleCanvas) {
  8508. this._width = this._getSize(0);
  8509. this._height = this._getSize(1);
  8510. var domRoot = this._domRoot = createRoot(
  8511. this._width, this._height
  8512. );
  8513. root.appendChild(domRoot);
  8514. }
  8515. else {
  8516. var width = root.width;
  8517. var height = root.height;
  8518. if (opts.width != null) {
  8519. width = opts.width;
  8520. }
  8521. if (opts.height != null) {
  8522. height = opts.height;
  8523. }
  8524. this.dpr = opts.devicePixelRatio || 1;
  8525. // Use canvas width and height directly
  8526. root.width = width * this.dpr;
  8527. root.height = height * this.dpr;
  8528. this._width = width;
  8529. this._height = height;
  8530. // Create layer if only one given canvas
  8531. // Device can be specified to create a high dpi image.
  8532. var mainLayer = new Layer(root, this, this.dpr);
  8533. mainLayer.__builtin__ = true;
  8534. mainLayer.initContext();
  8535. // FIXME Use canvas width and height
  8536. // mainLayer.resize(width, height);
  8537. layers[CANVAS_ZLEVEL] = mainLayer;
  8538. mainLayer.zlevel = CANVAS_ZLEVEL;
  8539. // Not use common zlevel.
  8540. zlevelList.push(CANVAS_ZLEVEL);
  8541. this._domRoot = root;
  8542. }
  8543. /**
  8544. * @type {module:zrender/Layer}
  8545. * @private
  8546. */
  8547. this._hoverlayer = null;
  8548. this._hoverElements = [];
  8549. };
  8550. Painter.prototype = {
  8551. constructor: Painter,
  8552. getType: function () {
  8553. return 'canvas';
  8554. },
  8555. /**
  8556. * If painter use a single canvas
  8557. * @return {boolean}
  8558. */
  8559. isSingleCanvas: function () {
  8560. return this._singleCanvas;
  8561. },
  8562. /**
  8563. * @return {HTMLDivElement}
  8564. */
  8565. getViewportRoot: function () {
  8566. return this._domRoot;
  8567. },
  8568. getViewportRootOffset: function () {
  8569. var viewportRoot = this.getViewportRoot();
  8570. if (viewportRoot) {
  8571. return {
  8572. offsetLeft: viewportRoot.offsetLeft || 0,
  8573. offsetTop: viewportRoot.offsetTop || 0
  8574. };
  8575. }
  8576. },
  8577. /**
  8578. * 刷新
  8579. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8580. */
  8581. refresh: function (paintAll) {
  8582. var list = this.storage.getDisplayList(true);
  8583. var zlevelList = this._zlevelList;
  8584. this._redrawId = Math.random();
  8585. this._paintList(list, paintAll, this._redrawId);
  8586. // Paint custum layers
  8587. for (var i = 0; i < zlevelList.length; i++) {
  8588. var z = zlevelList[i];
  8589. var layer = this._layers[z];
  8590. if (!layer.__builtin__ && layer.refresh) {
  8591. var clearColor = i === 0 ? this._backgroundColor : null;
  8592. layer.refresh(clearColor);
  8593. }
  8594. }
  8595. this.refreshHover();
  8596. return this;
  8597. },
  8598. addHover: function (el, hoverStyle) {
  8599. if (el.__hoverMir) {
  8600. return;
  8601. }
  8602. var elMirror = new el.constructor({
  8603. style: el.style,
  8604. shape: el.shape,
  8605. z: el.z,
  8606. z2: el.z2,
  8607. silent: el.silent
  8608. });
  8609. elMirror.__from = el;
  8610. el.__hoverMir = elMirror;
  8611. hoverStyle && elMirror.setStyle(hoverStyle);
  8612. this._hoverElements.push(elMirror);
  8613. return elMirror;
  8614. },
  8615. removeHover: function (el) {
  8616. var elMirror = el.__hoverMir;
  8617. var hoverElements = this._hoverElements;
  8618. var idx = indexOf(hoverElements, elMirror);
  8619. if (idx >= 0) {
  8620. hoverElements.splice(idx, 1);
  8621. }
  8622. el.__hoverMir = null;
  8623. },
  8624. clearHover: function (el) {
  8625. var hoverElements = this._hoverElements;
  8626. for (var i = 0; i < hoverElements.length; i++) {
  8627. var from = hoverElements[i].__from;
  8628. if (from) {
  8629. from.__hoverMir = null;
  8630. }
  8631. }
  8632. hoverElements.length = 0;
  8633. },
  8634. refreshHover: function () {
  8635. var hoverElements = this._hoverElements;
  8636. var len = hoverElements.length;
  8637. var hoverLayer = this._hoverlayer;
  8638. hoverLayer && hoverLayer.clear();
  8639. if (!len) {
  8640. return;
  8641. }
  8642. sort(hoverElements, this.storage.displayableSortFunc);
  8643. // Use a extream large zlevel
  8644. // FIXME?
  8645. if (!hoverLayer) {
  8646. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8647. }
  8648. var scope = {};
  8649. hoverLayer.ctx.save();
  8650. for (var i = 0; i < len;) {
  8651. var el = hoverElements[i];
  8652. var originalEl = el.__from;
  8653. // Original el is removed
  8654. // PENDING
  8655. if (!(originalEl && originalEl.__zr)) {
  8656. hoverElements.splice(i, 1);
  8657. originalEl.__hoverMir = null;
  8658. len--;
  8659. continue;
  8660. }
  8661. i++;
  8662. // Use transform
  8663. // FIXME style and shape ?
  8664. if (!originalEl.invisible) {
  8665. el.transform = originalEl.transform;
  8666. el.invTransform = originalEl.invTransform;
  8667. el.__clipPaths = originalEl.__clipPaths;
  8668. // el.
  8669. this._doPaintEl(el, hoverLayer, true, scope);
  8670. }
  8671. }
  8672. hoverLayer.ctx.restore();
  8673. },
  8674. getHoverLayer: function () {
  8675. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8676. },
  8677. _paintList: function (list, paintAll, redrawId) {
  8678. if (this._redrawId !== redrawId) {
  8679. return;
  8680. }
  8681. paintAll = paintAll || false;
  8682. this._updateLayerStatus(list);
  8683. var finished = this._doPaintList(list, paintAll);
  8684. if (this._needsManuallyCompositing) {
  8685. this._compositeManually();
  8686. }
  8687. if (!finished) {
  8688. var self = this;
  8689. requestAnimationFrame(function () {
  8690. self._paintList(list, paintAll, redrawId);
  8691. });
  8692. }
  8693. },
  8694. _compositeManually: function () {
  8695. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8696. var width = this._domRoot.width;
  8697. var height = this._domRoot.height;
  8698. ctx.clearRect(0, 0, width, height);
  8699. // PENDING, If only builtin layer?
  8700. this.eachBuiltinLayer(function (layer) {
  8701. if (layer.virtual) {
  8702. ctx.drawImage(layer.dom, 0, 0, width, height);
  8703. }
  8704. });
  8705. },
  8706. _doPaintList: function (list, paintAll) {
  8707. var layerList = [];
  8708. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8709. var zlevel = this._zlevelList[zi];
  8710. var layer = this._layers[zlevel];
  8711. if (layer.__builtin__
  8712. && layer !== this._hoverlayer
  8713. && (layer.__dirty || paintAll)
  8714. ) {
  8715. layerList.push(layer);
  8716. }
  8717. }
  8718. var finished = true;
  8719. for (var k = 0; k < layerList.length; k++) {
  8720. var layer = layerList[k];
  8721. var ctx = layer.ctx;
  8722. var scope = {};
  8723. ctx.save();
  8724. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8725. var useTimer = !paintAll && layer.incremental && Date.now;
  8726. var startTime = useTimer && Date.now();
  8727. var clearColor = layer.zlevel === this._zlevelList[0]
  8728. ? this._backgroundColor : null;
  8729. // All elements in this layer are cleared.
  8730. if (layer.__startIndex === layer.__endIndex) {
  8731. layer.clear(false, clearColor);
  8732. }
  8733. else if (start === layer.__startIndex) {
  8734. var firstEl = list[start];
  8735. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8736. layer.clear(false, clearColor);
  8737. }
  8738. }
  8739. if (start === -1) {
  8740. console.error('For some unknown reason. drawIndex is -1');
  8741. start = layer.__startIndex;
  8742. }
  8743. for (var i = start; i < layer.__endIndex; i++) {
  8744. var el = list[i];
  8745. this._doPaintEl(el, layer, paintAll, scope);
  8746. el.__dirty = el.__dirtyText = false;
  8747. if (useTimer) {
  8748. // Date.now can be executed in 13,025,305 ops/second.
  8749. var dTime = Date.now() - startTime;
  8750. // Give 15 millisecond to draw.
  8751. // The rest elements will be drawn in the next frame.
  8752. if (dTime > 15) {
  8753. break;
  8754. }
  8755. }
  8756. }
  8757. layer.__drawIndex = i;
  8758. if (layer.__drawIndex < layer.__endIndex) {
  8759. finished = false;
  8760. }
  8761. if (scope.prevElClipPaths) {
  8762. // Needs restore the state. If last drawn element is in the clipping area.
  8763. ctx.restore();
  8764. }
  8765. ctx.restore();
  8766. }
  8767. if (env$1.wxa) {
  8768. // Flush for weixin application
  8769. each$1(this._layers, function (layer) {
  8770. if (layer && layer.ctx && layer.ctx.draw) {
  8771. layer.ctx.draw();
  8772. }
  8773. });
  8774. }
  8775. return finished;
  8776. },
  8777. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8778. var ctx = currentLayer.ctx;
  8779. var m = el.transform;
  8780. if (
  8781. (currentLayer.__dirty || forcePaint)
  8782. // Ignore invisible element
  8783. && !el.invisible
  8784. // Ignore transparent element
  8785. && el.style.opacity !== 0
  8786. // Ignore scale 0 element, in some environment like node-canvas
  8787. // Draw a scale 0 element can cause all following draw wrong
  8788. // And setTransform with scale 0 will cause set back transform failed.
  8789. && !(m && !m[0] && !m[3])
  8790. // Ignore culled element
  8791. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8792. ) {
  8793. var clipPaths = el.__clipPaths;
  8794. var prevElClipPaths = scope.prevElClipPaths;
  8795. // Optimize when clipping on group with several elements
  8796. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8797. // If has previous clipping state, restore from it
  8798. if (prevElClipPaths) {
  8799. ctx.restore();
  8800. scope.prevElClipPaths = null;
  8801. // Reset prevEl since context has been restored
  8802. scope.prevEl = null;
  8803. }
  8804. // New clipping state
  8805. if (clipPaths) {
  8806. ctx.save();
  8807. doClip(clipPaths, ctx);
  8808. scope.prevElClipPaths = clipPaths;
  8809. }
  8810. }
  8811. el.beforeBrush && el.beforeBrush(ctx);
  8812. el.brush(ctx, scope.prevEl || null);
  8813. scope.prevEl = el;
  8814. el.afterBrush && el.afterBrush(ctx);
  8815. }
  8816. },
  8817. /**
  8818. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8819. * @param {number} zlevel
  8820. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8821. * @return {module:zrender/Layer}
  8822. */
  8823. getLayer: function (zlevel, virtual) {
  8824. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8825. zlevel = CANVAS_ZLEVEL;
  8826. }
  8827. var layer = this._layers[zlevel];
  8828. if (!layer) {
  8829. // Create a new layer
  8830. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8831. layer.zlevel = zlevel;
  8832. layer.__builtin__ = true;
  8833. if (this._layerConfig[zlevel]) {
  8834. merge(layer, this._layerConfig[zlevel], true);
  8835. }
  8836. if (virtual) {
  8837. layer.virtual = virtual;
  8838. }
  8839. this.insertLayer(zlevel, layer);
  8840. // Context is created after dom inserted to document
  8841. // Or excanvas will get 0px clientWidth and clientHeight
  8842. layer.initContext();
  8843. }
  8844. return layer;
  8845. },
  8846. insertLayer: function (zlevel, layer) {
  8847. var layersMap = this._layers;
  8848. var zlevelList = this._zlevelList;
  8849. var len = zlevelList.length;
  8850. var prevLayer = null;
  8851. var i = -1;
  8852. var domRoot = this._domRoot;
  8853. if (layersMap[zlevel]) {
  8854. logError$1('ZLevel ' + zlevel + ' has been used already');
  8855. return;
  8856. }
  8857. // Check if is a valid layer
  8858. if (!isLayerValid(layer)) {
  8859. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8860. return;
  8861. }
  8862. if (len > 0 && zlevel > zlevelList[0]) {
  8863. for (i = 0; i < len - 1; i++) {
  8864. if (
  8865. zlevelList[i] < zlevel
  8866. && zlevelList[i + 1] > zlevel
  8867. ) {
  8868. break;
  8869. }
  8870. }
  8871. prevLayer = layersMap[zlevelList[i]];
  8872. }
  8873. zlevelList.splice(i + 1, 0, zlevel);
  8874. layersMap[zlevel] = layer;
  8875. // Vitual layer will not directly show on the screen.
  8876. // (It can be a WebGL layer and assigned to a ZImage element)
  8877. // But it still under management of zrender.
  8878. if (!layer.virtual) {
  8879. if (prevLayer) {
  8880. var prevDom = prevLayer.dom;
  8881. if (prevDom.nextSibling) {
  8882. domRoot.insertBefore(
  8883. layer.dom,
  8884. prevDom.nextSibling
  8885. );
  8886. }
  8887. else {
  8888. domRoot.appendChild(layer.dom);
  8889. }
  8890. }
  8891. else {
  8892. if (domRoot.firstChild) {
  8893. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8894. }
  8895. else {
  8896. domRoot.appendChild(layer.dom);
  8897. }
  8898. }
  8899. }
  8900. },
  8901. // Iterate each layer
  8902. eachLayer: function (cb, context) {
  8903. var zlevelList = this._zlevelList;
  8904. var z;
  8905. var i;
  8906. for (i = 0; i < zlevelList.length; i++) {
  8907. z = zlevelList[i];
  8908. cb.call(context, this._layers[z], z);
  8909. }
  8910. },
  8911. // Iterate each buildin layer
  8912. eachBuiltinLayer: function (cb, context) {
  8913. var zlevelList = this._zlevelList;
  8914. var layer;
  8915. var z;
  8916. var i;
  8917. for (i = 0; i < zlevelList.length; i++) {
  8918. z = zlevelList[i];
  8919. layer = this._layers[z];
  8920. if (layer.__builtin__) {
  8921. cb.call(context, layer, z);
  8922. }
  8923. }
  8924. },
  8925. // Iterate each other layer except buildin layer
  8926. eachOtherLayer: function (cb, context) {
  8927. var zlevelList = this._zlevelList;
  8928. var layer;
  8929. var z;
  8930. var i;
  8931. for (i = 0; i < zlevelList.length; i++) {
  8932. z = zlevelList[i];
  8933. layer = this._layers[z];
  8934. if (!layer.__builtin__) {
  8935. cb.call(context, layer, z);
  8936. }
  8937. }
  8938. },
  8939. /**
  8940. * 获取所有已创建的层
  8941. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8942. */
  8943. getLayers: function () {
  8944. return this._layers;
  8945. },
  8946. _updateLayerStatus: function (list) {
  8947. this.eachBuiltinLayer(function (layer, z) {
  8948. layer.__dirty = layer.__used = false;
  8949. });
  8950. function updatePrevLayer(idx) {
  8951. if (prevLayer) {
  8952. if (prevLayer.__endIndex !== idx) {
  8953. prevLayer.__dirty = true;
  8954. }
  8955. prevLayer.__endIndex = idx;
  8956. }
  8957. }
  8958. if (this._singleCanvas) {
  8959. for (var i = 1; i < list.length; i++) {
  8960. var el = list[i];
  8961. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8962. this._needsManuallyCompositing = true;
  8963. break;
  8964. }
  8965. }
  8966. }
  8967. var prevLayer = null;
  8968. var incrementalLayerCount = 0;
  8969. for (var i = 0; i < list.length; i++) {
  8970. var el = list[i];
  8971. var zlevel = el.zlevel;
  8972. var layer;
  8973. // PENDING If change one incremental element style ?
  8974. // TODO Where there are non-incremental elements between incremental elements.
  8975. if (el.incremental) {
  8976. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8977. layer.incremental = true;
  8978. incrementalLayerCount = 1;
  8979. }
  8980. else {
  8981. layer = this.getLayer(
  8982. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  8983. this._needsManuallyCompositing
  8984. );
  8985. }
  8986. if (!layer.__builtin__) {
  8987. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8988. }
  8989. if (layer !== prevLayer) {
  8990. layer.__used = true;
  8991. if (layer.__startIndex !== i) {
  8992. layer.__dirty = true;
  8993. }
  8994. layer.__startIndex = i;
  8995. if (!layer.incremental) {
  8996. layer.__drawIndex = i;
  8997. }
  8998. else {
  8999. // Mark layer draw index needs to update.
  9000. layer.__drawIndex = -1;
  9001. }
  9002. updatePrevLayer(i);
  9003. prevLayer = layer;
  9004. }
  9005. if (el.__dirty) {
  9006. layer.__dirty = true;
  9007. if (layer.incremental && layer.__drawIndex < 0) {
  9008. // Start draw from the first dirty element.
  9009. layer.__drawIndex = i;
  9010. }
  9011. }
  9012. }
  9013. updatePrevLayer(i);
  9014. this.eachBuiltinLayer(function (layer, z) {
  9015. // Used in last frame but not in this frame. Needs clear
  9016. if (!layer.__used && layer.getElementCount() > 0) {
  9017. layer.__dirty = true;
  9018. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  9019. }
  9020. // For incremental layer. In case start index changed and no elements are dirty.
  9021. if (layer.__dirty && layer.__drawIndex < 0) {
  9022. layer.__drawIndex = layer.__startIndex;
  9023. }
  9024. });
  9025. },
  9026. /**
  9027. * 清除hover层外所有内容
  9028. */
  9029. clear: function () {
  9030. this.eachBuiltinLayer(this._clearLayer);
  9031. return this;
  9032. },
  9033. _clearLayer: function (layer) {
  9034. layer.clear();
  9035. },
  9036. setBackgroundColor: function (backgroundColor) {
  9037. this._backgroundColor = backgroundColor;
  9038. },
  9039. /**
  9040. * 修改指定zlevel的绘制参数
  9041. *
  9042. * @param {string} zlevel
  9043. * @param {Object} config 配置对象
  9044. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  9045. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  9046. * @param {number} [config.lastFrameAlpha=0.7]
  9047. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  9048. */
  9049. configLayer: function (zlevel, config) {
  9050. if (config) {
  9051. var layerConfig = this._layerConfig;
  9052. if (!layerConfig[zlevel]) {
  9053. layerConfig[zlevel] = config;
  9054. }
  9055. else {
  9056. merge(layerConfig[zlevel], config, true);
  9057. }
  9058. for (var i = 0; i < this._zlevelList.length; i++) {
  9059. var _zlevel = this._zlevelList[i];
  9060. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  9061. var layer = this._layers[_zlevel];
  9062. merge(layer, layerConfig[zlevel], true);
  9063. }
  9064. }
  9065. }
  9066. },
  9067. /**
  9068. * 删除指定层
  9069. * @param {number} zlevel 层所在的zlevel
  9070. */
  9071. delLayer: function (zlevel) {
  9072. var layers = this._layers;
  9073. var zlevelList = this._zlevelList;
  9074. var layer = layers[zlevel];
  9075. if (!layer) {
  9076. return;
  9077. }
  9078. layer.dom.parentNode.removeChild(layer.dom);
  9079. delete layers[zlevel];
  9080. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  9081. },
  9082. /**
  9083. * 区域大小变化后重绘
  9084. */
  9085. resize: function (width, height) {
  9086. if (!this._domRoot.style) { // Maybe in node or worker
  9087. if (width == null || height == null) {
  9088. return;
  9089. }
  9090. this._width = width;
  9091. this._height = height;
  9092. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  9093. }
  9094. else {
  9095. var domRoot = this._domRoot;
  9096. // FIXME Why ?
  9097. domRoot.style.display = 'none';
  9098. // Save input w/h
  9099. var opts = this._opts;
  9100. width != null && (opts.width = width);
  9101. height != null && (opts.height = height);
  9102. width = this._getSize(0);
  9103. height = this._getSize(1);
  9104. domRoot.style.display = '';
  9105. // 优化没有实际改变的resize
  9106. if (this._width !== width || height !== this._height) {
  9107. domRoot.style.width = width + 'px';
  9108. domRoot.style.height = height + 'px';
  9109. for (var id in this._layers) {
  9110. if (this._layers.hasOwnProperty(id)) {
  9111. this._layers[id].resize(width, height);
  9112. }
  9113. }
  9114. each$1(this._progressiveLayers, function (layer) {
  9115. layer.resize(width, height);
  9116. });
  9117. this.refresh(true);
  9118. }
  9119. this._width = width;
  9120. this._height = height;
  9121. }
  9122. return this;
  9123. },
  9124. /**
  9125. * 清除单独的一个层
  9126. * @param {number} zlevel
  9127. */
  9128. clearLayer: function (zlevel) {
  9129. var layer = this._layers[zlevel];
  9130. if (layer) {
  9131. layer.clear();
  9132. }
  9133. },
  9134. /**
  9135. * 释放
  9136. */
  9137. dispose: function () {
  9138. this.root.innerHTML = '';
  9139. this.root =
  9140. this.storage =
  9141. this._domRoot =
  9142. this._layers = null;
  9143. },
  9144. /**
  9145. * Get canvas which has all thing rendered
  9146. * @param {Object} opts
  9147. * @param {string} [opts.backgroundColor]
  9148. * @param {number} [opts.pixelRatio]
  9149. */
  9150. getRenderedCanvas: function (opts) {
  9151. opts = opts || {};
  9152. if (this._singleCanvas && !this._compositeManually) {
  9153. return this._layers[CANVAS_ZLEVEL].dom;
  9154. }
  9155. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  9156. imageLayer.initContext();
  9157. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  9158. if (opts.pixelRatio <= this.dpr) {
  9159. this.refresh();
  9160. var width = imageLayer.dom.width;
  9161. var height = imageLayer.dom.height;
  9162. var ctx = imageLayer.ctx;
  9163. this.eachLayer(function (layer) {
  9164. if (layer.__builtin__) {
  9165. ctx.drawImage(layer.dom, 0, 0, width, height);
  9166. }
  9167. else if (layer.renderToCanvas) {
  9168. imageLayer.ctx.save();
  9169. layer.renderToCanvas(imageLayer.ctx);
  9170. imageLayer.ctx.restore();
  9171. }
  9172. });
  9173. }
  9174. else {
  9175. // PENDING, echarts-gl and incremental rendering.
  9176. var scope = {};
  9177. var displayList = this.storage.getDisplayList(true);
  9178. for (var i = 0; i < displayList.length; i++) {
  9179. var el = displayList[i];
  9180. this._doPaintEl(el, imageLayer, true, scope);
  9181. }
  9182. }
  9183. return imageLayer.dom;
  9184. },
  9185. /**
  9186. * 获取绘图区域宽度
  9187. */
  9188. getWidth: function () {
  9189. return this._width;
  9190. },
  9191. /**
  9192. * 获取绘图区域高度
  9193. */
  9194. getHeight: function () {
  9195. return this._height;
  9196. },
  9197. _getSize: function (whIdx) {
  9198. var opts = this._opts;
  9199. var wh = ['width', 'height'][whIdx];
  9200. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  9201. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  9202. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  9203. if (opts[wh] != null && opts[wh] !== 'auto') {
  9204. return parseFloat(opts[wh]);
  9205. }
  9206. var root = this.root;
  9207. // IE8 does not support getComputedStyle, but it use VML.
  9208. var stl = document.defaultView.getComputedStyle(root);
  9209. return (
  9210. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  9211. - (parseInt10(stl[plt]) || 0)
  9212. - (parseInt10(stl[prb]) || 0)
  9213. ) | 0;
  9214. },
  9215. pathToImage: function (path, dpr) {
  9216. dpr = dpr || this.dpr;
  9217. var canvas = document.createElement('canvas');
  9218. var ctx = canvas.getContext('2d');
  9219. var rect = path.getBoundingRect();
  9220. var style = path.style;
  9221. var shadowBlurSize = style.shadowBlur * dpr;
  9222. var shadowOffsetX = style.shadowOffsetX * dpr;
  9223. var shadowOffsetY = style.shadowOffsetY * dpr;
  9224. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  9225. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  9226. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  9227. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  9228. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  9229. var width = rect.width + leftMargin + rightMargin;
  9230. var height = rect.height + topMargin + bottomMargin;
  9231. canvas.width = width * dpr;
  9232. canvas.height = height * dpr;
  9233. ctx.scale(dpr, dpr);
  9234. ctx.clearRect(0, 0, width, height);
  9235. ctx.dpr = dpr;
  9236. var pathTransform = {
  9237. position: path.position,
  9238. rotation: path.rotation,
  9239. scale: path.scale
  9240. };
  9241. path.position = [leftMargin - rect.x, topMargin - rect.y];
  9242. path.rotation = 0;
  9243. path.scale = [1, 1];
  9244. path.updateTransform();
  9245. if (path) {
  9246. path.brush(ctx);
  9247. }
  9248. var ImageShape = ZImage;
  9249. var imgShape = new ImageShape({
  9250. style: {
  9251. x: 0,
  9252. y: 0,
  9253. image: canvas
  9254. }
  9255. });
  9256. if (pathTransform.position != null) {
  9257. imgShape.position = path.position = pathTransform.position;
  9258. }
  9259. if (pathTransform.rotation != null) {
  9260. imgShape.rotation = path.rotation = pathTransform.rotation;
  9261. }
  9262. if (pathTransform.scale != null) {
  9263. imgShape.scale = path.scale = pathTransform.scale;
  9264. }
  9265. return imgShape;
  9266. }
  9267. };
  9268. /**
  9269. * 动画主类, 调度和管理所有动画控制器
  9270. *
  9271. * @module zrender/animation/Animation
  9272. * @author pissang(https://github.com/pissang)
  9273. */
  9274. // TODO Additive animation
  9275. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  9276. // https://developer.apple.com/videos/wwdc2014/#236
  9277. /**
  9278. * @typedef {Object} IZRenderStage
  9279. * @property {Function} update
  9280. */
  9281. /**
  9282. * @alias module:zrender/animation/Animation
  9283. * @constructor
  9284. * @param {Object} [options]
  9285. * @param {Function} [options.onframe]
  9286. * @param {IZRenderStage} [options.stage]
  9287. * @example
  9288. * var animation = new Animation();
  9289. * var obj = {
  9290. * x: 100,
  9291. * y: 100
  9292. * };
  9293. * animation.animate(node.position)
  9294. * .when(1000, {
  9295. * x: 500,
  9296. * y: 500
  9297. * })
  9298. * .when(2000, {
  9299. * x: 100,
  9300. * y: 100
  9301. * })
  9302. * .start('spline');
  9303. */
  9304. var Animation = function (options) {
  9305. options = options || {};
  9306. this.stage = options.stage || {};
  9307. this.onframe = options.onframe || function () {};
  9308. // private properties
  9309. this._clips = [];
  9310. this._running = false;
  9311. this._time;
  9312. this._pausedTime;
  9313. this._pauseStart;
  9314. this._paused = false;
  9315. Eventful.call(this);
  9316. };
  9317. Animation.prototype = {
  9318. constructor: Animation,
  9319. /**
  9320. * 添加 clip
  9321. * @param {module:zrender/animation/Clip} clip
  9322. */
  9323. addClip: function (clip) {
  9324. this._clips.push(clip);
  9325. },
  9326. /**
  9327. * 添加 animator
  9328. * @param {module:zrender/animation/Animator} animator
  9329. */
  9330. addAnimator: function (animator) {
  9331. animator.animation = this;
  9332. var clips = animator.getClips();
  9333. for (var i = 0; i < clips.length; i++) {
  9334. this.addClip(clips[i]);
  9335. }
  9336. },
  9337. /**
  9338. * 删除动画片段
  9339. * @param {module:zrender/animation/Clip} clip
  9340. */
  9341. removeClip: function (clip) {
  9342. var idx = indexOf(this._clips, clip);
  9343. if (idx >= 0) {
  9344. this._clips.splice(idx, 1);
  9345. }
  9346. },
  9347. /**
  9348. * 删除动画片段
  9349. * @param {module:zrender/animation/Animator} animator
  9350. */
  9351. removeAnimator: function (animator) {
  9352. var clips = animator.getClips();
  9353. for (var i = 0; i < clips.length; i++) {
  9354. this.removeClip(clips[i]);
  9355. }
  9356. animator.animation = null;
  9357. },
  9358. _update: function () {
  9359. var time = new Date().getTime() - this._pausedTime;
  9360. var delta = time - this._time;
  9361. var clips = this._clips;
  9362. var len = clips.length;
  9363. var deferredEvents = [];
  9364. var deferredClips = [];
  9365. for (var i = 0; i < len; i++) {
  9366. var clip = clips[i];
  9367. var e = clip.step(time, delta);
  9368. // Throw out the events need to be called after
  9369. // stage.update, like destroy
  9370. if (e) {
  9371. deferredEvents.push(e);
  9372. deferredClips.push(clip);
  9373. }
  9374. }
  9375. // Remove the finished clip
  9376. for (var i = 0; i < len;) {
  9377. if (clips[i]._needsRemove) {
  9378. clips[i] = clips[len - 1];
  9379. clips.pop();
  9380. len--;
  9381. }
  9382. else {
  9383. i++;
  9384. }
  9385. }
  9386. len = deferredEvents.length;
  9387. for (var i = 0; i < len; i++) {
  9388. deferredClips[i].fire(deferredEvents[i]);
  9389. }
  9390. this._time = time;
  9391. this.onframe(delta);
  9392. // 'frame' should be triggered before stage, because upper application
  9393. // depends on the sequence (e.g., echarts-stream and finish
  9394. // event judge)
  9395. this.trigger('frame', delta);
  9396. if (this.stage.update) {
  9397. this.stage.update();
  9398. }
  9399. },
  9400. _startLoop: function () {
  9401. var self = this;
  9402. this._running = true;
  9403. function step() {
  9404. if (self._running) {
  9405. requestAnimationFrame(step);
  9406. !self._paused && self._update();
  9407. }
  9408. }
  9409. requestAnimationFrame(step);
  9410. },
  9411. /**
  9412. * Start animation.
  9413. */
  9414. start: function () {
  9415. this._time = new Date().getTime();
  9416. this._pausedTime = 0;
  9417. this._startLoop();
  9418. },
  9419. /**
  9420. * Stop animation.
  9421. */
  9422. stop: function () {
  9423. this._running = false;
  9424. },
  9425. /**
  9426. * Pause animation.
  9427. */
  9428. pause: function () {
  9429. if (!this._paused) {
  9430. this._pauseStart = new Date().getTime();
  9431. this._paused = true;
  9432. }
  9433. },
  9434. /**
  9435. * Resume animation.
  9436. */
  9437. resume: function () {
  9438. if (this._paused) {
  9439. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9440. this._paused = false;
  9441. }
  9442. },
  9443. /**
  9444. * Clear animation.
  9445. */
  9446. clear: function () {
  9447. this._clips = [];
  9448. },
  9449. /**
  9450. * Whether animation finished.
  9451. */
  9452. isFinished: function () {
  9453. return !this._clips.length;
  9454. },
  9455. /**
  9456. * Creat animator for a target, whose props can be animated.
  9457. *
  9458. * @param {Object} target
  9459. * @param {Object} options
  9460. * @param {boolean} [options.loop=false] Whether loop animation.
  9461. * @param {Function} [options.getter=null] Get value from target.
  9462. * @param {Function} [options.setter=null] Set value to target.
  9463. * @return {module:zrender/animation/Animation~Animator}
  9464. */
  9465. // TODO Gap
  9466. animate: function (target, options) {
  9467. options = options || {};
  9468. var animator = new Animator(
  9469. target,
  9470. options.loop,
  9471. options.getter,
  9472. options.setter
  9473. );
  9474. this.addAnimator(animator);
  9475. return animator;
  9476. }
  9477. };
  9478. mixin(Animation, Eventful);
  9479. /* global document */
  9480. var TOUCH_CLICK_DELAY = 300;
  9481. var globalEventSupported = env$1.domSupported;
  9482. var localNativeListenerNames = (function () {
  9483. var mouseHandlerNames = [
  9484. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9485. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9486. ];
  9487. var touchHandlerNames = [
  9488. 'touchstart', 'touchend', 'touchmove'
  9489. ];
  9490. var pointerEventNameMap = {
  9491. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9492. };
  9493. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9494. var nm = name.replace('mouse', 'pointer');
  9495. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9496. });
  9497. return {
  9498. mouse: mouseHandlerNames,
  9499. touch: touchHandlerNames,
  9500. pointer: pointerHandlerNames
  9501. };
  9502. })();
  9503. var globalNativeListenerNames = {
  9504. mouse: ['mousemove', 'mouseup'],
  9505. pointer: ['pointermove', 'pointerup']
  9506. };
  9507. function eventNameFix(name) {
  9508. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9509. }
  9510. function isPointerFromTouch(event) {
  9511. var pointerType = event.pointerType;
  9512. return pointerType === 'pen' || pointerType === 'touch';
  9513. }
  9514. // function useMSGuesture(handlerProxy, event) {
  9515. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9516. // }
  9517. // function onMSGestureChange(proxy, event) {
  9518. // if (event.translationX || event.translationY) {
  9519. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9520. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9521. // }
  9522. // if (event.scale !== 1) {
  9523. // event.pinchX = event.offsetX;
  9524. // event.pinchY = event.offsetY;
  9525. // event.pinchScale = event.scale;
  9526. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9527. // }
  9528. // }
  9529. /**
  9530. * Prevent mouse event from being dispatched after Touch Events action
  9531. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9532. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9533. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9534. * Result: Blocking Mouse Events for 700ms.
  9535. *
  9536. * @param {DOMHandlerScope} scope
  9537. */
  9538. function setTouchTimer(scope) {
  9539. scope.touching = true;
  9540. if (scope.touchTimer != null) {
  9541. clearTimeout(scope.touchTimer);
  9542. scope.touchTimer = null;
  9543. }
  9544. scope.touchTimer = setTimeout(function () {
  9545. scope.touching = false;
  9546. scope.touchTimer = null;
  9547. }, 700);
  9548. }
  9549. // Mark touch, which is useful in distinguish touch and
  9550. // mouse event in upper applicatoin.
  9551. function markTouch(event) {
  9552. event && (event.zrByTouch = true);
  9553. }
  9554. // function markTriggeredFromLocal(event) {
  9555. // event && (event.__zrIsFromLocal = true);
  9556. // }
  9557. // function isTriggeredFromLocal(instance, event) {
  9558. // return !!(event && event.__zrIsFromLocal);
  9559. // }
  9560. function normalizeGlobalEvent(instance, event) {
  9561. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9562. // handlers of the upper applications. Set `true` to force calculate them.
  9563. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9564. }
  9565. /**
  9566. * Detect whether the given el is in `painterRoot`.
  9567. */
  9568. function isLocalEl(instance, el) {
  9569. var isLocal = false;
  9570. do {
  9571. el = el && el.parentNode;
  9572. }
  9573. while (el && el.nodeType !== 9 && !(
  9574. isLocal = el === instance.painterRoot
  9575. ));
  9576. return isLocal;
  9577. }
  9578. /**
  9579. * Make a fake event but not change the original event,
  9580. * becuase the global event probably be used by other
  9581. * listeners not belonging to zrender.
  9582. * @class
  9583. */
  9584. function FakeGlobalEvent(instance, event) {
  9585. this.type = event.type;
  9586. this.target = this.currentTarget = instance.dom;
  9587. this.pointerType = event.pointerType;
  9588. // Necessray for the force calculation of zrX, zrY
  9589. this.clientX = event.clientX;
  9590. this.clientY = event.clientY;
  9591. // Because we do not mount global listeners to touch events,
  9592. // we do not copy `targetTouches` and `changedTouches` here.
  9593. }
  9594. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9595. // we make the default methods on the event do nothing,
  9596. // otherwise it is dangerous. See more details in
  9597. // [Drag outside] in `Handler.js`.
  9598. fakeGlobalEventProto.stopPropagation =
  9599. fakeGlobalEventProto.stopImmediatePropagation =
  9600. fakeGlobalEventProto.preventDefault = noop;
  9601. /**
  9602. * Local DOM Handlers
  9603. * @this {HandlerProxy}
  9604. */
  9605. var localDOMHandlers = {
  9606. mousedown: function (event) {
  9607. event = normalizeEvent(this.dom, event);
  9608. this._mayPointerCapture = [event.zrX, event.zrY];
  9609. this.trigger('mousedown', event);
  9610. },
  9611. mousemove: function (event) {
  9612. event = normalizeEvent(this.dom, event);
  9613. var downPoint = this._mayPointerCapture;
  9614. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9615. togglePointerCapture(this, true);
  9616. }
  9617. this.trigger('mousemove', event);
  9618. },
  9619. mouseup: function (event) {
  9620. event = normalizeEvent(this.dom, event);
  9621. togglePointerCapture(this, false);
  9622. this.trigger('mouseup', event);
  9623. },
  9624. mouseout: function (event) {
  9625. event = normalizeEvent(this.dom, event);
  9626. // Similarly to the browser did on `document` and touch event,
  9627. // `globalout` will be delayed to final pointer cature release.
  9628. if (this._pointerCapturing) {
  9629. event.zrEventControl = 'no_globalout';
  9630. }
  9631. // There might be some doms created by upper layer application
  9632. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9633. // dom created by echarts), where 'globalout' event should not
  9634. // be triggered when mouse enters these doms. (But 'mouseout'
  9635. // should be triggered at the original hovered element as usual).
  9636. var element = event.toElement || event.relatedTarget;
  9637. event.zrIsToLocalDOM = isLocalEl(this, element);
  9638. this.trigger('mouseout', event);
  9639. },
  9640. touchstart: function (event) {
  9641. // Default mouse behaviour should not be disabled here.
  9642. // For example, page may needs to be slided.
  9643. event = normalizeEvent(this.dom, event);
  9644. markTouch(event);
  9645. this._lastTouchMoment = new Date();
  9646. this.handler.processGesture(event, 'start');
  9647. // For consistent event listener for both touch device and mouse device,
  9648. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9649. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9650. // `mousedown`.
  9651. localDOMHandlers.mousemove.call(this, event);
  9652. localDOMHandlers.mousedown.call(this, event);
  9653. },
  9654. touchmove: function (event) {
  9655. event = normalizeEvent(this.dom, event);
  9656. markTouch(event);
  9657. this.handler.processGesture(event, 'change');
  9658. // Mouse move should always be triggered no matter whether
  9659. // there is gestrue event, because mouse move and pinch may
  9660. // be used at the same time.
  9661. localDOMHandlers.mousemove.call(this, event);
  9662. },
  9663. touchend: function (event) {
  9664. event = normalizeEvent(this.dom, event);
  9665. markTouch(event);
  9666. this.handler.processGesture(event, 'end');
  9667. localDOMHandlers.mouseup.call(this, event);
  9668. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9669. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9670. // we can conveniently implement "hover style" in both PC and touch device just
  9671. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9672. // to remove "hover style" on an element, without any additional code for
  9673. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9674. // style" will remain for user view)
  9675. // click event should always be triggered no matter whether
  9676. // there is gestrue event. System click can not be prevented.
  9677. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9678. localDOMHandlers.click.call(this, event);
  9679. }
  9680. },
  9681. pointerdown: function (event) {
  9682. localDOMHandlers.mousedown.call(this, event);
  9683. // if (useMSGuesture(this, event)) {
  9684. // this._msGesture.addPointer(event.pointerId);
  9685. // }
  9686. },
  9687. pointermove: function (event) {
  9688. // FIXME
  9689. // pointermove is so sensitive that it always triggered when
  9690. // tap(click) on touch screen, which affect some judgement in
  9691. // upper application. So, we dont support mousemove on MS touch
  9692. // device yet.
  9693. if (!isPointerFromTouch(event)) {
  9694. localDOMHandlers.mousemove.call(this, event);
  9695. }
  9696. },
  9697. pointerup: function (event) {
  9698. localDOMHandlers.mouseup.call(this, event);
  9699. },
  9700. pointerout: function (event) {
  9701. // pointerout will be triggered when tap on touch screen
  9702. // (IE11+/Edge on MS Surface) after click event triggered,
  9703. // which is inconsistent with the mousout behavior we defined
  9704. // in touchend. So we unify them.
  9705. // (check localDOMHandlers.touchend for detailed explanation)
  9706. if (!isPointerFromTouch(event)) {
  9707. localDOMHandlers.mouseout.call(this, event);
  9708. }
  9709. }
  9710. };
  9711. /**
  9712. * Othere DOM UI Event handlers for zr dom.
  9713. * @this {HandlerProxy}
  9714. */
  9715. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9716. localDOMHandlers[name] = function (event) {
  9717. event = normalizeEvent(this.dom, event);
  9718. this.trigger(name, event);
  9719. };
  9720. });
  9721. /**
  9722. * DOM UI Event handlers for global page.
  9723. *
  9724. * [Caution]:
  9725. * those handlers should both support in capture phase and bubble phase!
  9726. *
  9727. * @this {HandlerProxy}
  9728. */
  9729. var globalDOMHandlers = {
  9730. pointermove: function (event) {
  9731. // FIXME
  9732. // pointermove is so sensitive that it always triggered when
  9733. // tap(click) on touch screen, which affect some judgement in
  9734. // upper application. So, we dont support mousemove on MS touch
  9735. // device yet.
  9736. if (!isPointerFromTouch(event)) {
  9737. globalDOMHandlers.mousemove.call(this, event);
  9738. }
  9739. },
  9740. pointerup: function (event) {
  9741. globalDOMHandlers.mouseup.call(this, event);
  9742. },
  9743. mousemove: function (event) {
  9744. this.trigger('mousemove', event);
  9745. },
  9746. mouseup: function (event) {
  9747. var pointerCaptureReleasing = this._pointerCapturing;
  9748. togglePointerCapture(this, false);
  9749. this.trigger('mouseup', event);
  9750. if (pointerCaptureReleasing) {
  9751. event.zrEventControl = 'only_globalout';
  9752. this.trigger('mouseout', event);
  9753. }
  9754. }
  9755. };
  9756. /**
  9757. * @param {HandlerProxy} instance
  9758. * @param {DOMHandlerScope} scope
  9759. */
  9760. function mountLocalDOMEventListeners(instance, scope) {
  9761. var domHandlers = scope.domHandlers;
  9762. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9763. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9764. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9765. // at the same time.
  9766. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9767. // screen, which do not occurs in pointer event.
  9768. // So we use pointer event to both detect touch gesture and mouse behavior.
  9769. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9770. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9771. // markTriggeredFromLocal(event);
  9772. domHandlers[nativeEventName].call(instance, event);
  9773. });
  9774. });
  9775. // FIXME
  9776. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9777. // which does not prevent defuault behavior occasionally (which may cause view port
  9778. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9779. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9780. // touch screen. And we only support click behavior on MS touch screen now.
  9781. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9782. // We dont support touch on IE on win7.
  9783. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9784. // if (typeof MSGesture === 'function') {
  9785. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9786. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9787. // }
  9788. }
  9789. else {
  9790. if (env$1.touchEventsSupported) {
  9791. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9792. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9793. // markTriggeredFromLocal(event);
  9794. domHandlers[nativeEventName].call(instance, event);
  9795. setTouchTimer(scope);
  9796. });
  9797. });
  9798. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9799. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9800. }
  9801. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9802. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9803. // mouse event can not be handle in those devices.
  9804. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9805. // mouseevent after touch event triggered, see `setTouchTimer`.
  9806. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9807. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9808. event = getNativeEvent(event);
  9809. if (!scope.touching) {
  9810. // markTriggeredFromLocal(event);
  9811. domHandlers[nativeEventName].call(instance, event);
  9812. }
  9813. });
  9814. });
  9815. }
  9816. }
  9817. /**
  9818. * @param {HandlerProxy} instance
  9819. * @param {DOMHandlerScope} scope
  9820. */
  9821. function mountGlobalDOMEventListeners(instance, scope) {
  9822. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9823. if (env$1.pointerEventsSupported) {
  9824. each$1(globalNativeListenerNames.pointer, mount);
  9825. }
  9826. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9827. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9828. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9829. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9830. else if (!env$1.touchEventsSupported) {
  9831. each$1(globalNativeListenerNames.mouse, mount);
  9832. }
  9833. function mount(nativeEventName) {
  9834. function nativeEventListener(event) {
  9835. event = getNativeEvent(event);
  9836. // See the reason in [Drag outside] in `Handler.js`
  9837. // This checking supports both `useCapture` or not.
  9838. // PENDING: if there is performance issue in some devices,
  9839. // we probably can not use `useCapture` and change a easier
  9840. // to judes whether local (mark).
  9841. if (!isLocalEl(instance, event.target)) {
  9842. event = normalizeGlobalEvent(instance, event);
  9843. scope.domHandlers[nativeEventName].call(instance, event);
  9844. }
  9845. }
  9846. mountSingleDOMEventListener(
  9847. scope, nativeEventName, nativeEventListener,
  9848. {capture: true} // See [Drag Outside] in `Handler.js`
  9849. );
  9850. }
  9851. }
  9852. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9853. scope.mounted[nativeEventName] = listener;
  9854. scope.listenerOpts[nativeEventName] = opt;
  9855. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9856. }
  9857. function unmountDOMEventListeners(scope) {
  9858. var mounted = scope.mounted;
  9859. for (var nativeEventName in mounted) {
  9860. if (mounted.hasOwnProperty(nativeEventName)) {
  9861. removeEventListener(
  9862. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9863. scope.listenerOpts[nativeEventName]
  9864. );
  9865. }
  9866. }
  9867. scope.mounted = {};
  9868. }
  9869. /**
  9870. * See [Drag Outside] in `Handler.js`.
  9871. * @implement
  9872. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9873. * `true`: start to capture pointer if it is not capturing.
  9874. * `false`: end the capture if it is capturing.
  9875. */
  9876. function togglePointerCapture(instance, isPointerCapturing) {
  9877. instance._mayPointerCapture = null;
  9878. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9879. instance._pointerCapturing = isPointerCapturing;
  9880. var globalHandlerScope = instance._globalHandlerScope;
  9881. isPointerCapturing
  9882. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9883. : unmountDOMEventListeners(globalHandlerScope);
  9884. }
  9885. }
  9886. /**
  9887. * @inner
  9888. * @class
  9889. */
  9890. function DOMHandlerScope(domTarget, domHandlers) {
  9891. this.domTarget = domTarget;
  9892. this.domHandlers = domHandlers;
  9893. // Key: eventName, value: mounted handler funcitons.
  9894. // Used for unmount.
  9895. this.mounted = {};
  9896. this.listenerOpts = {};
  9897. this.touchTimer = null;
  9898. this.touching = false;
  9899. }
  9900. /**
  9901. * @public
  9902. * @class
  9903. */
  9904. function HandlerDomProxy(dom, painterRoot) {
  9905. Eventful.call(this);
  9906. this.dom = dom;
  9907. this.painterRoot = painterRoot;
  9908. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  9909. if (globalEventSupported) {
  9910. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  9911. }
  9912. /**
  9913. * @type {boolean}
  9914. */
  9915. this._pointerCapturing = false;
  9916. /**
  9917. * @type {Array.<number>} [x, y] or null.
  9918. */
  9919. this._mayPointerCapture = null;
  9920. mountLocalDOMEventListeners(this, this._localHandlerScope);
  9921. }
  9922. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9923. handlerDomProxyProto.dispose = function () {
  9924. unmountDOMEventListeners(this._localHandlerScope);
  9925. if (globalEventSupported) {
  9926. unmountDOMEventListeners(this._globalHandlerScope);
  9927. }
  9928. };
  9929. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9930. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9931. };
  9932. mixin(HandlerDomProxy, Eventful);
  9933. /*!
  9934. * ZRender, a high performance 2d drawing library.
  9935. *
  9936. * Copyright (c) 2013, Baidu Inc.
  9937. * All rights reserved.
  9938. *
  9939. * LICENSE
  9940. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9941. */
  9942. var useVML = !env$1.canvasSupported;
  9943. var painterCtors = {
  9944. canvas: Painter
  9945. };
  9946. var instances$1 = {}; // ZRender实例map索引
  9947. /**
  9948. * @type {string}
  9949. */
  9950. var version$1 = '4.2.0';
  9951. /**
  9952. * Initializing a zrender instance
  9953. * @param {HTMLElement} dom
  9954. * @param {Object} [opts]
  9955. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9956. * @param {number} [opts.devicePixelRatio]
  9957. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9958. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9959. * @return {module:zrender/ZRender}
  9960. */
  9961. function init$1(dom, opts) {
  9962. var zr = new ZRender(guid(), dom, opts);
  9963. instances$1[zr.id] = zr;
  9964. return zr;
  9965. }
  9966. /**
  9967. * Dispose zrender instance
  9968. * @param {module:zrender/ZRender} zr
  9969. */
  9970. function dispose$1(zr) {
  9971. if (zr) {
  9972. zr.dispose();
  9973. }
  9974. else {
  9975. for (var key in instances$1) {
  9976. if (instances$1.hasOwnProperty(key)) {
  9977. instances$1[key].dispose();
  9978. }
  9979. }
  9980. instances$1 = {};
  9981. }
  9982. return this;
  9983. }
  9984. /**
  9985. * Get zrender instance by id
  9986. * @param {string} id zrender instance id
  9987. * @return {module:zrender/ZRender}
  9988. */
  9989. function getInstance(id) {
  9990. return instances$1[id];
  9991. }
  9992. function registerPainter(name, Ctor) {
  9993. painterCtors[name] = Ctor;
  9994. }
  9995. function delInstance(id) {
  9996. delete instances$1[id];
  9997. }
  9998. /**
  9999. * @module zrender/ZRender
  10000. */
  10001. /**
  10002. * @constructor
  10003. * @alias module:zrender/ZRender
  10004. * @param {string} id
  10005. * @param {HTMLElement} dom
  10006. * @param {Object} opts
  10007. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  10008. * @param {number} [opts.devicePixelRatio]
  10009. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  10010. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  10011. */
  10012. var ZRender = function (id, dom, opts) {
  10013. opts = opts || {};
  10014. /**
  10015. * @type {HTMLDomElement}
  10016. */
  10017. this.dom = dom;
  10018. /**
  10019. * @type {string}
  10020. */
  10021. this.id = id;
  10022. var self = this;
  10023. var storage = new Storage();
  10024. var rendererType = opts.renderer;
  10025. // TODO WebGL
  10026. if (useVML) {
  10027. if (!painterCtors.vml) {
  10028. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  10029. }
  10030. rendererType = 'vml';
  10031. }
  10032. else if (!rendererType || !painterCtors[rendererType]) {
  10033. rendererType = 'canvas';
  10034. }
  10035. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  10036. this.storage = storage;
  10037. this.painter = painter;
  10038. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  10039. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  10040. /**
  10041. * @type {module:zrender/animation/Animation}
  10042. */
  10043. this.animation = new Animation({
  10044. stage: {
  10045. update: bind(this.flush, this)
  10046. }
  10047. });
  10048. this.animation.start();
  10049. /**
  10050. * @type {boolean}
  10051. * @private
  10052. */
  10053. this._needsRefresh;
  10054. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  10055. // FIXME 有点ugly
  10056. var oldDelFromStorage = storage.delFromStorage;
  10057. var oldAddToStorage = storage.addToStorage;
  10058. storage.delFromStorage = function (el) {
  10059. oldDelFromStorage.call(storage, el);
  10060. el && el.removeSelfFromZr(self);
  10061. };
  10062. storage.addToStorage = function (el) {
  10063. oldAddToStorage.call(storage, el);
  10064. el.addSelfToZr(self);
  10065. };
  10066. };
  10067. ZRender.prototype = {
  10068. constructor: ZRender,
  10069. /**
  10070. * 获取实例唯一标识
  10071. * @return {string}
  10072. */
  10073. getId: function () {
  10074. return this.id;
  10075. },
  10076. /**
  10077. * 添加元素
  10078. * @param {module:zrender/Element} el
  10079. */
  10080. add: function (el) {
  10081. this.storage.addRoot(el);
  10082. this._needsRefresh = true;
  10083. },
  10084. /**
  10085. * 删除元素
  10086. * @param {module:zrender/Element} el
  10087. */
  10088. remove: function (el) {
  10089. this.storage.delRoot(el);
  10090. this._needsRefresh = true;
  10091. },
  10092. /**
  10093. * Change configuration of layer
  10094. * @param {string} zLevel
  10095. * @param {Object} config
  10096. * @param {string} [config.clearColor=0] Clear color
  10097. * @param {string} [config.motionBlur=false] If enable motion blur
  10098. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  10099. */
  10100. configLayer: function (zLevel, config) {
  10101. if (this.painter.configLayer) {
  10102. this.painter.configLayer(zLevel, config);
  10103. }
  10104. this._needsRefresh = true;
  10105. },
  10106. /**
  10107. * Set background color
  10108. * @param {string} backgroundColor
  10109. */
  10110. setBackgroundColor: function (backgroundColor) {
  10111. if (this.painter.setBackgroundColor) {
  10112. this.painter.setBackgroundColor(backgroundColor);
  10113. }
  10114. this._needsRefresh = true;
  10115. },
  10116. /**
  10117. * Repaint the canvas immediately
  10118. */
  10119. refreshImmediately: function () {
  10120. // var start = new Date();
  10121. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  10122. // Or it will cause zrender refreshes again and again.
  10123. this._needsRefresh = this._needsRefreshHover = false;
  10124. this.painter.refresh();
  10125. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  10126. this._needsRefresh = this._needsRefreshHover = false;
  10127. // var end = new Date();
  10128. // var log = document.getElementById('log');
  10129. // if (log) {
  10130. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  10131. // }
  10132. },
  10133. /**
  10134. * Mark and repaint the canvas in the next frame of browser
  10135. */
  10136. refresh: function () {
  10137. this._needsRefresh = true;
  10138. },
  10139. /**
  10140. * Perform all refresh
  10141. */
  10142. flush: function () {
  10143. var triggerRendered;
  10144. if (this._needsRefresh) {
  10145. triggerRendered = true;
  10146. this.refreshImmediately();
  10147. }
  10148. if (this._needsRefreshHover) {
  10149. triggerRendered = true;
  10150. this.refreshHoverImmediately();
  10151. }
  10152. triggerRendered && this.trigger('rendered');
  10153. },
  10154. /**
  10155. * Add element to hover layer
  10156. * @param {module:zrender/Element} el
  10157. * @param {Object} style
  10158. */
  10159. addHover: function (el, style) {
  10160. if (this.painter.addHover) {
  10161. var elMirror = this.painter.addHover(el, style);
  10162. this.refreshHover();
  10163. return elMirror;
  10164. }
  10165. },
  10166. /**
  10167. * Add element from hover layer
  10168. * @param {module:zrender/Element} el
  10169. */
  10170. removeHover: function (el) {
  10171. if (this.painter.removeHover) {
  10172. this.painter.removeHover(el);
  10173. this.refreshHover();
  10174. }
  10175. },
  10176. /**
  10177. * Clear all hover elements in hover layer
  10178. * @param {module:zrender/Element} el
  10179. */
  10180. clearHover: function () {
  10181. if (this.painter.clearHover) {
  10182. this.painter.clearHover();
  10183. this.refreshHover();
  10184. }
  10185. },
  10186. /**
  10187. * Refresh hover in next frame
  10188. */
  10189. refreshHover: function () {
  10190. this._needsRefreshHover = true;
  10191. },
  10192. /**
  10193. * Refresh hover immediately
  10194. */
  10195. refreshHoverImmediately: function () {
  10196. this._needsRefreshHover = false;
  10197. this.painter.refreshHover && this.painter.refreshHover();
  10198. },
  10199. /**
  10200. * Resize the canvas.
  10201. * Should be invoked when container size is changed
  10202. * @param {Object} [opts]
  10203. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10204. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10205. */
  10206. resize: function (opts) {
  10207. opts = opts || {};
  10208. this.painter.resize(opts.width, opts.height);
  10209. this.handler.resize();
  10210. },
  10211. /**
  10212. * Stop and clear all animation immediately
  10213. */
  10214. clearAnimation: function () {
  10215. this.animation.clear();
  10216. },
  10217. /**
  10218. * Get container width
  10219. */
  10220. getWidth: function () {
  10221. return this.painter.getWidth();
  10222. },
  10223. /**
  10224. * Get container height
  10225. */
  10226. getHeight: function () {
  10227. return this.painter.getHeight();
  10228. },
  10229. /**
  10230. * Export the canvas as Base64 URL
  10231. * @param {string} type
  10232. * @param {string} [backgroundColor='#fff']
  10233. * @return {string} Base64 URL
  10234. */
  10235. // toDataURL: function(type, backgroundColor) {
  10236. // return this.painter.getRenderedCanvas({
  10237. // backgroundColor: backgroundColor
  10238. // }).toDataURL(type);
  10239. // },
  10240. /**
  10241. * Converting a path to image.
  10242. * It has much better performance of drawing image rather than drawing a vector path.
  10243. * @param {module:zrender/graphic/Path} e
  10244. * @param {number} width
  10245. * @param {number} height
  10246. */
  10247. pathToImage: function (e, dpr) {
  10248. return this.painter.pathToImage(e, dpr);
  10249. },
  10250. /**
  10251. * Set default cursor
  10252. * @param {string} [cursorStyle='default'] 例如 crosshair
  10253. */
  10254. setCursorStyle: function (cursorStyle) {
  10255. this.handler.setCursorStyle(cursorStyle);
  10256. },
  10257. /**
  10258. * Find hovered element
  10259. * @param {number} x
  10260. * @param {number} y
  10261. * @return {Object} {target, topTarget}
  10262. */
  10263. findHover: function (x, y) {
  10264. return this.handler.findHover(x, y);
  10265. },
  10266. /**
  10267. * Bind event
  10268. *
  10269. * @param {string} eventName Event name
  10270. * @param {Function} eventHandler Handler function
  10271. * @param {Object} [context] Context object
  10272. */
  10273. on: function (eventName, eventHandler, context) {
  10274. this.handler.on(eventName, eventHandler, context);
  10275. },
  10276. /**
  10277. * Unbind event
  10278. * @param {string} eventName Event name
  10279. * @param {Function} [eventHandler] Handler function
  10280. */
  10281. off: function (eventName, eventHandler) {
  10282. this.handler.off(eventName, eventHandler);
  10283. },
  10284. /**
  10285. * Trigger event manually
  10286. *
  10287. * @param {string} eventName Event name
  10288. * @param {event=} event Event object
  10289. */
  10290. trigger: function (eventName, event) {
  10291. this.handler.trigger(eventName, event);
  10292. },
  10293. /**
  10294. * Clear all objects and the canvas.
  10295. */
  10296. clear: function () {
  10297. this.storage.delRoot();
  10298. this.painter.clear();
  10299. },
  10300. /**
  10301. * Dispose self.
  10302. */
  10303. dispose: function () {
  10304. this.animation.stop();
  10305. this.clear();
  10306. this.storage.dispose();
  10307. this.painter.dispose();
  10308. this.handler.dispose();
  10309. this.animation =
  10310. this.storage =
  10311. this.painter =
  10312. this.handler = null;
  10313. delInstance(this.id);
  10314. }
  10315. };
  10316. var zrender = (Object.freeze || Object)({
  10317. version: version$1,
  10318. init: init$1,
  10319. dispose: dispose$1,
  10320. getInstance: getInstance,
  10321. registerPainter: registerPainter
  10322. });
  10323. /*
  10324. * Licensed to the Apache Software Foundation (ASF) under one
  10325. * or more contributor license agreements. See the NOTICE file
  10326. * distributed with this work for additional information
  10327. * regarding copyright ownership. The ASF licenses this file
  10328. * to you under the Apache License, Version 2.0 (the
  10329. * "License"); you may not use this file except in compliance
  10330. * with the License. You may obtain a copy of the License at
  10331. *
  10332. * http://www.apache.org/licenses/LICENSE-2.0
  10333. *
  10334. * Unless required by applicable law or agreed to in writing,
  10335. * software distributed under the License is distributed on an
  10336. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10337. * KIND, either express or implied. See the License for the
  10338. * specific language governing permissions and limitations
  10339. * under the License.
  10340. */
  10341. var each$2 = each$1;
  10342. var isObject$2 = isObject$1;
  10343. var isArray$1 = isArray;
  10344. /**
  10345. * Make the name displayable. But we should
  10346. * make sure it is not duplicated with user
  10347. * specified name, so use '\0';
  10348. */
  10349. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  10350. /**
  10351. * If value is not array, then translate it to array.
  10352. * @param {*} value
  10353. * @return {Array} [value] or value
  10354. */
  10355. function normalizeToArray(value) {
  10356. return value instanceof Array
  10357. ? value
  10358. : value == null
  10359. ? []
  10360. : [value];
  10361. }
  10362. /**
  10363. * Sync default option between normal and emphasis like `position` and `show`
  10364. * In case some one will write code like
  10365. * label: {
  10366. * show: false,
  10367. * position: 'outside',
  10368. * fontSize: 18
  10369. * },
  10370. * emphasis: {
  10371. * label: { show: true }
  10372. * }
  10373. * @param {Object} opt
  10374. * @param {string} key
  10375. * @param {Array.<string>} subOpts
  10376. */
  10377. function defaultEmphasis(opt, key, subOpts) {
  10378. // Caution: performance sensitive.
  10379. if (opt) {
  10380. opt[key] = opt[key] || {};
  10381. opt.emphasis = opt.emphasis || {};
  10382. opt.emphasis[key] = opt.emphasis[key] || {};
  10383. // Default emphasis option from normal
  10384. for (var i = 0, len = subOpts.length; i < len; i++) {
  10385. var subOptName = subOpts[i];
  10386. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  10387. && opt[key].hasOwnProperty(subOptName)
  10388. ) {
  10389. opt.emphasis[key][subOptName] = opt[key][subOptName];
  10390. }
  10391. }
  10392. }
  10393. }
  10394. var TEXT_STYLE_OPTIONS = [
  10395. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10396. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  10397. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  10398. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  10399. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  10400. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  10401. ];
  10402. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  10403. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  10404. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10405. // // FIXME: deprecated, check and remove it.
  10406. // 'textStyle'
  10407. // ]);
  10408. /**
  10409. * The method do not ensure performance.
  10410. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10411. * This helper method retieves value from data.
  10412. * @param {string|number|Date|Array|Object} dataItem
  10413. * @return {number|string|Date|Array.<number|string|Date>}
  10414. */
  10415. function getDataItemValue(dataItem) {
  10416. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  10417. ? dataItem.value : dataItem;
  10418. }
  10419. /**
  10420. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10421. * This helper method determine if dataItem has extra option besides value
  10422. * @param {string|number|Date|Array|Object} dataItem
  10423. */
  10424. function isDataItemOption(dataItem) {
  10425. return isObject$2(dataItem)
  10426. && !(dataItem instanceof Array);
  10427. // // markLine data can be array
  10428. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  10429. }
  10430. /**
  10431. * Mapping to exists for merge.
  10432. *
  10433. * @public
  10434. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  10435. * @param {Object|Array.<Object>} newCptOptions
  10436. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10437. * index of which is the same as exists.
  10438. */
  10439. function mappingToExists(exists, newCptOptions) {
  10440. // Mapping by the order by original option (but not order of
  10441. // new option) in merge mode. Because we should ensure
  10442. // some specified index (like xAxisIndex) is consistent with
  10443. // original option, which is easy to understand, espatially in
  10444. // media query. And in most case, merge option is used to
  10445. // update partial option but not be expected to change order.
  10446. newCptOptions = (newCptOptions || []).slice();
  10447. var result = map(exists || [], function (obj, index) {
  10448. return {exist: obj};
  10449. });
  10450. // Mapping by id or name if specified.
  10451. each$2(newCptOptions, function (cptOption, index) {
  10452. if (!isObject$2(cptOption)) {
  10453. return;
  10454. }
  10455. // id has highest priority.
  10456. for (var i = 0; i < result.length; i++) {
  10457. if (!result[i].option // Consider name: two map to one.
  10458. && cptOption.id != null
  10459. && result[i].exist.id === cptOption.id + ''
  10460. ) {
  10461. result[i].option = cptOption;
  10462. newCptOptions[index] = null;
  10463. return;
  10464. }
  10465. }
  10466. for (var i = 0; i < result.length; i++) {
  10467. var exist = result[i].exist;
  10468. if (!result[i].option // Consider name: two map to one.
  10469. // Can not match when both ids exist but different.
  10470. && (exist.id == null || cptOption.id == null)
  10471. && cptOption.name != null
  10472. && !isIdInner(cptOption)
  10473. && !isIdInner(exist)
  10474. && exist.name === cptOption.name + ''
  10475. ) {
  10476. result[i].option = cptOption;
  10477. newCptOptions[index] = null;
  10478. return;
  10479. }
  10480. }
  10481. });
  10482. // Otherwise mapping by index.
  10483. each$2(newCptOptions, function (cptOption, index) {
  10484. if (!isObject$2(cptOption)) {
  10485. return;
  10486. }
  10487. var i = 0;
  10488. for (; i < result.length; i++) {
  10489. var exist = result[i].exist;
  10490. if (!result[i].option
  10491. // Existing model that already has id should be able to
  10492. // mapped to (because after mapping performed model may
  10493. // be assigned with a id, whish should not affect next
  10494. // mapping), except those has inner id.
  10495. && !isIdInner(exist)
  10496. // Caution:
  10497. // Do not overwrite id. But name can be overwritten,
  10498. // because axis use name as 'show label text'.
  10499. // 'exist' always has id and name and we dont
  10500. // need to check it.
  10501. && cptOption.id == null
  10502. ) {
  10503. result[i].option = cptOption;
  10504. break;
  10505. }
  10506. }
  10507. if (i >= result.length) {
  10508. result.push({option: cptOption});
  10509. }
  10510. });
  10511. return result;
  10512. }
  10513. /**
  10514. * Make id and name for mapping result (result of mappingToExists)
  10515. * into `keyInfo` field.
  10516. *
  10517. * @public
  10518. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10519. * which order is the same as exists.
  10520. * @return {Array.<Object>} The input.
  10521. */
  10522. function makeIdAndName(mapResult) {
  10523. // We use this id to hash component models and view instances
  10524. // in echarts. id can be specified by user, or auto generated.
  10525. // The id generation rule ensures new view instance are able
  10526. // to mapped to old instance when setOption are called in
  10527. // no-merge mode. So we generate model id by name and plus
  10528. // type in view id.
  10529. // name can be duplicated among components, which is convenient
  10530. // to specify multi components (like series) by one name.
  10531. // Ensure that each id is distinct.
  10532. var idMap = createHashMap();
  10533. each$2(mapResult, function (item, index) {
  10534. var existCpt = item.exist;
  10535. existCpt && idMap.set(existCpt.id, item);
  10536. });
  10537. each$2(mapResult, function (item, index) {
  10538. var opt = item.option;
  10539. assert$1(
  10540. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10541. 'id duplicates: ' + (opt && opt.id)
  10542. );
  10543. opt && opt.id != null && idMap.set(opt.id, item);
  10544. !item.keyInfo && (item.keyInfo = {});
  10545. });
  10546. // Make name and id.
  10547. each$2(mapResult, function (item, index) {
  10548. var existCpt = item.exist;
  10549. var opt = item.option;
  10550. var keyInfo = item.keyInfo;
  10551. if (!isObject$2(opt)) {
  10552. return;
  10553. }
  10554. // name can be overwitten. Consider case: axis.name = '20km'.
  10555. // But id generated by name will not be changed, which affect
  10556. // only in that case: setOption with 'not merge mode' and view
  10557. // instance will be recreated, which can be accepted.
  10558. keyInfo.name = opt.name != null
  10559. ? opt.name + ''
  10560. : existCpt
  10561. ? existCpt.name
  10562. // Avoid diffferent series has the same name,
  10563. // because name may be used like in color pallet.
  10564. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10565. if (existCpt) {
  10566. keyInfo.id = existCpt.id;
  10567. }
  10568. else if (opt.id != null) {
  10569. keyInfo.id = opt.id + '';
  10570. }
  10571. else {
  10572. // Consider this situatoin:
  10573. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10574. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10575. // Series with the same name between optionA and optionB
  10576. // should be mapped.
  10577. var idNum = 0;
  10578. do {
  10579. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10580. }
  10581. while (idMap.get(keyInfo.id));
  10582. }
  10583. idMap.set(keyInfo.id, item);
  10584. });
  10585. }
  10586. function isNameSpecified(componentModel) {
  10587. var name = componentModel.name;
  10588. // Is specified when `indexOf` get -1 or > 0.
  10589. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10590. }
  10591. /**
  10592. * @public
  10593. * @param {Object} cptOption
  10594. * @return {boolean}
  10595. */
  10596. function isIdInner(cptOption) {
  10597. return isObject$2(cptOption)
  10598. && cptOption.id
  10599. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10600. }
  10601. /**
  10602. * A helper for removing duplicate items between batchA and batchB,
  10603. * and in themselves, and categorize by series.
  10604. *
  10605. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10606. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10607. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10608. */
  10609. /**
  10610. * @param {module:echarts/data/List} data
  10611. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10612. * each of which can be Array or primary type.
  10613. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10614. */
  10615. function queryDataIndex(data, payload) {
  10616. if (payload.dataIndexInside != null) {
  10617. return payload.dataIndexInside;
  10618. }
  10619. else if (payload.dataIndex != null) {
  10620. return isArray(payload.dataIndex)
  10621. ? map(payload.dataIndex, function (value) {
  10622. return data.indexOfRawIndex(value);
  10623. })
  10624. : data.indexOfRawIndex(payload.dataIndex);
  10625. }
  10626. else if (payload.name != null) {
  10627. return isArray(payload.name)
  10628. ? map(payload.name, function (value) {
  10629. return data.indexOfName(value);
  10630. })
  10631. : data.indexOfName(payload.name);
  10632. }
  10633. }
  10634. /**
  10635. * Enable property storage to any host object.
  10636. * Notice: Serialization is not supported.
  10637. *
  10638. * For example:
  10639. * var inner = zrUitl.makeInner();
  10640. *
  10641. * function some1(hostObj) {
  10642. * inner(hostObj).someProperty = 1212;
  10643. * ...
  10644. * }
  10645. * function some2() {
  10646. * var fields = inner(this);
  10647. * fields.someProperty1 = 1212;
  10648. * fields.someProperty2 = 'xx';
  10649. * ...
  10650. * }
  10651. *
  10652. * @return {Function}
  10653. */
  10654. function makeInner() {
  10655. // Consider different scope by es module import.
  10656. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10657. return function (hostObj) {
  10658. return hostObj[key] || (hostObj[key] = {});
  10659. };
  10660. }
  10661. var innerUniqueIndex = 0;
  10662. /**
  10663. * @param {module:echarts/model/Global} ecModel
  10664. * @param {string|Object} finder
  10665. * If string, e.g., 'geo', means {geoIndex: 0}.
  10666. * If Object, could contain some of these properties below:
  10667. * {
  10668. * seriesIndex, seriesId, seriesName,
  10669. * geoIndex, geoId, geoName,
  10670. * bmapIndex, bmapId, bmapName,
  10671. * xAxisIndex, xAxisId, xAxisName,
  10672. * yAxisIndex, yAxisId, yAxisName,
  10673. * gridIndex, gridId, gridName,
  10674. * ... (can be extended)
  10675. * }
  10676. * Each properties can be number|string|Array.<number>|Array.<string>
  10677. * For example, a finder could be
  10678. * {
  10679. * seriesIndex: 3,
  10680. * geoId: ['aa', 'cc'],
  10681. * gridName: ['xx', 'rr']
  10682. * }
  10683. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10684. * If nothing or null/undefined specified, return nothing.
  10685. * @param {Object} [opt]
  10686. * @param {string} [opt.defaultMainType]
  10687. * @param {Array.<string>} [opt.includeMainTypes]
  10688. * @return {Object} result like:
  10689. * {
  10690. * seriesModels: [seriesModel1, seriesModel2],
  10691. * seriesModel: seriesModel1, // The first model
  10692. * geoModels: [geoModel1, geoModel2],
  10693. * geoModel: geoModel1, // The first model
  10694. * ...
  10695. * }
  10696. */
  10697. function parseFinder(ecModel, finder, opt) {
  10698. if (isString(finder)) {
  10699. var obj = {};
  10700. obj[finder + 'Index'] = 0;
  10701. finder = obj;
  10702. }
  10703. var defaultMainType = opt && opt.defaultMainType;
  10704. if (defaultMainType
  10705. && !has(finder, defaultMainType + 'Index')
  10706. && !has(finder, defaultMainType + 'Id')
  10707. && !has(finder, defaultMainType + 'Name')
  10708. ) {
  10709. finder[defaultMainType + 'Index'] = 0;
  10710. }
  10711. var result = {};
  10712. each$2(finder, function (value, key) {
  10713. var value = finder[key];
  10714. // Exclude 'dataIndex' and other illgal keys.
  10715. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10716. result[key] = value;
  10717. return;
  10718. }
  10719. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10720. var mainType = parsedKey[1];
  10721. var queryType = (parsedKey[2] || '').toLowerCase();
  10722. if (!mainType
  10723. || !queryType
  10724. || value == null
  10725. || (queryType === 'index' && value === 'none')
  10726. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10727. ) {
  10728. return;
  10729. }
  10730. var queryParam = {mainType: mainType};
  10731. if (queryType !== 'index' || value !== 'all') {
  10732. queryParam[queryType] = value;
  10733. }
  10734. var models = ecModel.queryComponents(queryParam);
  10735. result[mainType + 'Models'] = models;
  10736. result[mainType + 'Model'] = models[0];
  10737. });
  10738. return result;
  10739. }
  10740. function has(obj, prop) {
  10741. return obj && obj.hasOwnProperty(prop);
  10742. }
  10743. function setAttribute(dom, key, value) {
  10744. dom.setAttribute
  10745. ? dom.setAttribute(key, value)
  10746. : (dom[key] = value);
  10747. }
  10748. function getAttribute(dom, key) {
  10749. return dom.getAttribute
  10750. ? dom.getAttribute(key)
  10751. : dom[key];
  10752. }
  10753. function getTooltipRenderMode(renderModeOption) {
  10754. if (renderModeOption === 'auto') {
  10755. // Using html when `document` exists, use richText otherwise
  10756. return env$1.domSupported ? 'html' : 'richText';
  10757. }
  10758. else {
  10759. return renderModeOption || 'html';
  10760. }
  10761. }
  10762. /**
  10763. * Group a list by key.
  10764. *
  10765. * @param {Array} array
  10766. * @param {Function} getKey
  10767. * param {*} Array item
  10768. * return {string} key
  10769. * @return {Object} Result
  10770. * {Array}: keys,
  10771. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10772. */
  10773. /*
  10774. * Licensed to the Apache Software Foundation (ASF) under one
  10775. * or more contributor license agreements. See the NOTICE file
  10776. * distributed with this work for additional information
  10777. * regarding copyright ownership. The ASF licenses this file
  10778. * to you under the Apache License, Version 2.0 (the
  10779. * "License"); you may not use this file except in compliance
  10780. * with the License. You may obtain a copy of the License at
  10781. *
  10782. * http://www.apache.org/licenses/LICENSE-2.0
  10783. *
  10784. * Unless required by applicable law or agreed to in writing,
  10785. * software distributed under the License is distributed on an
  10786. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10787. * KIND, either express or implied. See the License for the
  10788. * specific language governing permissions and limitations
  10789. * under the License.
  10790. */
  10791. var TYPE_DELIMITER = '.';
  10792. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10793. /**
  10794. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10795. * @public
  10796. */
  10797. function parseClassType$1(componentType) {
  10798. var ret = {main: '', sub: ''};
  10799. if (componentType) {
  10800. componentType = componentType.split(TYPE_DELIMITER);
  10801. ret.main = componentType[0] || '';
  10802. ret.sub = componentType[1] || '';
  10803. }
  10804. return ret;
  10805. }
  10806. /**
  10807. * @public
  10808. */
  10809. function checkClassType(componentType) {
  10810. assert$1(
  10811. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10812. 'componentType "' + componentType + '" illegal'
  10813. );
  10814. }
  10815. /**
  10816. * @public
  10817. */
  10818. function enableClassExtend(RootClass, mandatoryMethods) {
  10819. RootClass.$constructor = RootClass;
  10820. RootClass.extend = function (proto) {
  10821. if (__DEV__) {
  10822. each$1(mandatoryMethods, function (method) {
  10823. if (!proto[method]) {
  10824. console.warn(
  10825. 'Method `' + method + '` should be implemented'
  10826. + (proto.type ? ' in ' + proto.type : '') + '.'
  10827. );
  10828. }
  10829. });
  10830. }
  10831. var superClass = this;
  10832. var ExtendedClass = function () {
  10833. if (!proto.$constructor) {
  10834. superClass.apply(this, arguments);
  10835. }
  10836. else {
  10837. proto.$constructor.apply(this, arguments);
  10838. }
  10839. };
  10840. extend(ExtendedClass.prototype, proto);
  10841. ExtendedClass.extend = this.extend;
  10842. ExtendedClass.superCall = superCall;
  10843. ExtendedClass.superApply = superApply;
  10844. inherits(ExtendedClass, this);
  10845. ExtendedClass.superClass = superClass;
  10846. return ExtendedClass;
  10847. };
  10848. }
  10849. var classBase = 0;
  10850. /**
  10851. * Can not use instanceof, consider different scope by
  10852. * cross domain or es module import in ec extensions.
  10853. * Mount a method "isInstance()" to Clz.
  10854. */
  10855. function enableClassCheck(Clz) {
  10856. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10857. Clz.prototype[classAttr] = true;
  10858. if (__DEV__) {
  10859. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10860. }
  10861. Clz.isInstance = function (obj) {
  10862. return !!(obj && obj[classAttr]);
  10863. };
  10864. }
  10865. // superCall should have class info, which can not be fetch from 'this'.
  10866. // Consider this case:
  10867. // class A has method f,
  10868. // class B inherits class A, overrides method f, f call superApply('f'),
  10869. // class C inherits class B, do not overrides method f,
  10870. // then when method of class C is called, dead loop occured.
  10871. function superCall(context, methodName) {
  10872. var args = slice(arguments, 2);
  10873. return this.superClass.prototype[methodName].apply(context, args);
  10874. }
  10875. function superApply(context, methodName, args) {
  10876. return this.superClass.prototype[methodName].apply(context, args);
  10877. }
  10878. /**
  10879. * @param {Object} entity
  10880. * @param {Object} options
  10881. * @param {boolean} [options.registerWhenExtend]
  10882. * @public
  10883. */
  10884. function enableClassManagement(entity, options) {
  10885. options = options || {};
  10886. /**
  10887. * Component model classes
  10888. * key: componentType,
  10889. * value:
  10890. * componentClass, when componentType is 'xxx'
  10891. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10892. * @type {Object}
  10893. */
  10894. var storage = {};
  10895. entity.registerClass = function (Clazz, componentType) {
  10896. if (componentType) {
  10897. checkClassType(componentType);
  10898. componentType = parseClassType$1(componentType);
  10899. if (!componentType.sub) {
  10900. if (__DEV__) {
  10901. if (storage[componentType.main]) {
  10902. console.warn(componentType.main + ' exists.');
  10903. }
  10904. }
  10905. storage[componentType.main] = Clazz;
  10906. }
  10907. else if (componentType.sub !== IS_CONTAINER) {
  10908. var container = makeContainer(componentType);
  10909. container[componentType.sub] = Clazz;
  10910. }
  10911. }
  10912. return Clazz;
  10913. };
  10914. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10915. var Clazz = storage[componentMainType];
  10916. if (Clazz && Clazz[IS_CONTAINER]) {
  10917. Clazz = subType ? Clazz[subType] : null;
  10918. }
  10919. if (throwWhenNotFound && !Clazz) {
  10920. throw new Error(
  10921. !subType
  10922. ? componentMainType + '.' + 'type should be specified.'
  10923. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10924. );
  10925. }
  10926. return Clazz;
  10927. };
  10928. entity.getClassesByMainType = function (componentType) {
  10929. componentType = parseClassType$1(componentType);
  10930. var result = [];
  10931. var obj = storage[componentType.main];
  10932. if (obj && obj[IS_CONTAINER]) {
  10933. each$1(obj, function (o, type) {
  10934. type !== IS_CONTAINER && result.push(o);
  10935. });
  10936. }
  10937. else {
  10938. result.push(obj);
  10939. }
  10940. return result;
  10941. };
  10942. entity.hasClass = function (componentType) {
  10943. // Just consider componentType.main.
  10944. componentType = parseClassType$1(componentType);
  10945. return !!storage[componentType.main];
  10946. };
  10947. /**
  10948. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10949. */
  10950. entity.getAllClassMainTypes = function () {
  10951. var types = [];
  10952. each$1(storage, function (obj, type) {
  10953. types.push(type);
  10954. });
  10955. return types;
  10956. };
  10957. /**
  10958. * If a main type is container and has sub types
  10959. * @param {string} mainType
  10960. * @return {boolean}
  10961. */
  10962. entity.hasSubTypes = function (componentType) {
  10963. componentType = parseClassType$1(componentType);
  10964. var obj = storage[componentType.main];
  10965. return obj && obj[IS_CONTAINER];
  10966. };
  10967. entity.parseClassType = parseClassType$1;
  10968. function makeContainer(componentType) {
  10969. var container = storage[componentType.main];
  10970. if (!container || !container[IS_CONTAINER]) {
  10971. container = storage[componentType.main] = {};
  10972. container[IS_CONTAINER] = true;
  10973. }
  10974. return container;
  10975. }
  10976. if (options.registerWhenExtend) {
  10977. var originalExtend = entity.extend;
  10978. if (originalExtend) {
  10979. entity.extend = function (proto) {
  10980. var ExtendedClass = originalExtend.call(this, proto);
  10981. return entity.registerClass(ExtendedClass, proto.type);
  10982. };
  10983. }
  10984. }
  10985. return entity;
  10986. }
  10987. /**
  10988. * @param {string|Array.<string>} properties
  10989. */
  10990. /*
  10991. * Licensed to the Apache Software Foundation (ASF) under one
  10992. * or more contributor license agreements. See the NOTICE file
  10993. * distributed with this work for additional information
  10994. * regarding copyright ownership. The ASF licenses this file
  10995. * to you under the Apache License, Version 2.0 (the
  10996. * "License"); you may not use this file except in compliance
  10997. * with the License. You may obtain a copy of the License at
  10998. *
  10999. * http://www.apache.org/licenses/LICENSE-2.0
  11000. *
  11001. * Unless required by applicable law or agreed to in writing,
  11002. * software distributed under the License is distributed on an
  11003. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11004. * KIND, either express or implied. See the License for the
  11005. * specific language governing permissions and limitations
  11006. * under the License.
  11007. */
  11008. // TODO Parse shadow style
  11009. // TODO Only shallow path support
  11010. var makeStyleMapper = function (properties) {
  11011. // Normalize
  11012. for (var i = 0; i < properties.length; i++) {
  11013. if (!properties[i][1]) {
  11014. properties[i][1] = properties[i][0];
  11015. }
  11016. }
  11017. return function (model, excludes, includes) {
  11018. var style = {};
  11019. for (var i = 0; i < properties.length; i++) {
  11020. var propName = properties[i][1];
  11021. if ((excludes && indexOf(excludes, propName) >= 0)
  11022. || (includes && indexOf(includes, propName) < 0)
  11023. ) {
  11024. continue;
  11025. }
  11026. var val = model.getShallow(propName);
  11027. if (val != null) {
  11028. style[properties[i][0]] = val;
  11029. }
  11030. }
  11031. return style;
  11032. };
  11033. };
  11034. /*
  11035. * Licensed to the Apache Software Foundation (ASF) under one
  11036. * or more contributor license agreements. See the NOTICE file
  11037. * distributed with this work for additional information
  11038. * regarding copyright ownership. The ASF licenses this file
  11039. * to you under the Apache License, Version 2.0 (the
  11040. * "License"); you may not use this file except in compliance
  11041. * with the License. You may obtain a copy of the License at
  11042. *
  11043. * http://www.apache.org/licenses/LICENSE-2.0
  11044. *
  11045. * Unless required by applicable law or agreed to in writing,
  11046. * software distributed under the License is distributed on an
  11047. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11048. * KIND, either express or implied. See the License for the
  11049. * specific language governing permissions and limitations
  11050. * under the License.
  11051. */
  11052. var getLineStyle = makeStyleMapper(
  11053. [
  11054. ['lineWidth', 'width'],
  11055. ['stroke', 'color'],
  11056. ['opacity'],
  11057. ['shadowBlur'],
  11058. ['shadowOffsetX'],
  11059. ['shadowOffsetY'],
  11060. ['shadowColor']
  11061. ]
  11062. );
  11063. var lineStyleMixin = {
  11064. getLineStyle: function (excludes) {
  11065. var style = getLineStyle(this, excludes);
  11066. // Always set lineDash whether dashed, otherwise we can not
  11067. // erase the previous style when assigning to el.style.
  11068. style.lineDash = this.getLineDash(style.lineWidth);
  11069. return style;
  11070. },
  11071. getLineDash: function (lineWidth) {
  11072. if (lineWidth == null) {
  11073. lineWidth = 1;
  11074. }
  11075. var lineType = this.get('type');
  11076. var dotSize = Math.max(lineWidth, 2);
  11077. var dashSize = lineWidth * 4;
  11078. return (lineType === 'solid' || lineType == null)
  11079. // Use `false` but not `null` for the solid line here, because `null` might be
  11080. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  11081. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  11082. // `lineDash` gotten form the latter one is not able to erase that from the former
  11083. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  11084. ? false
  11085. : lineType === 'dashed'
  11086. ? [dashSize, dashSize]
  11087. : [dotSize, dotSize];
  11088. }
  11089. };
  11090. /*
  11091. * Licensed to the Apache Software Foundation (ASF) under one
  11092. * or more contributor license agreements. See the NOTICE file
  11093. * distributed with this work for additional information
  11094. * regarding copyright ownership. The ASF licenses this file
  11095. * to you under the Apache License, Version 2.0 (the
  11096. * "License"); you may not use this file except in compliance
  11097. * with the License. You may obtain a copy of the License at
  11098. *
  11099. * http://www.apache.org/licenses/LICENSE-2.0
  11100. *
  11101. * Unless required by applicable law or agreed to in writing,
  11102. * software distributed under the License is distributed on an
  11103. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11104. * KIND, either express or implied. See the License for the
  11105. * specific language governing permissions and limitations
  11106. * under the License.
  11107. */
  11108. var getAreaStyle = makeStyleMapper(
  11109. [
  11110. ['fill', 'color'],
  11111. ['shadowBlur'],
  11112. ['shadowOffsetX'],
  11113. ['shadowOffsetY'],
  11114. ['opacity'],
  11115. ['shadowColor']
  11116. ]
  11117. );
  11118. var areaStyleMixin = {
  11119. getAreaStyle: function (excludes, includes) {
  11120. return getAreaStyle(this, excludes, includes);
  11121. }
  11122. };
  11123. /**
  11124. * 曲线辅助模块
  11125. * @module zrender/core/curve
  11126. * @author pissang(https://www.github.com/pissang)
  11127. */
  11128. var mathPow = Math.pow;
  11129. var mathSqrt$2 = Math.sqrt;
  11130. var EPSILON$1 = 1e-8;
  11131. var EPSILON_NUMERIC = 1e-4;
  11132. var THREE_SQRT = mathSqrt$2(3);
  11133. var ONE_THIRD = 1 / 3;
  11134. // 临时变量
  11135. var _v0 = create();
  11136. var _v1 = create();
  11137. var _v2 = create();
  11138. function isAroundZero(val) {
  11139. return val > -EPSILON$1 && val < EPSILON$1;
  11140. }
  11141. function isNotAroundZero$1(val) {
  11142. return val > EPSILON$1 || val < -EPSILON$1;
  11143. }
  11144. /**
  11145. * 计算三次贝塞尔值
  11146. * @memberOf module:zrender/core/curve
  11147. * @param {number} p0
  11148. * @param {number} p1
  11149. * @param {number} p2
  11150. * @param {number} p3
  11151. * @param {number} t
  11152. * @return {number}
  11153. */
  11154. function cubicAt(p0, p1, p2, p3, t) {
  11155. var onet = 1 - t;
  11156. return onet * onet * (onet * p0 + 3 * t * p1)
  11157. + t * t * (t * p3 + 3 * onet * p2);
  11158. }
  11159. /**
  11160. * 计算三次贝塞尔导数值
  11161. * @memberOf module:zrender/core/curve
  11162. * @param {number} p0
  11163. * @param {number} p1
  11164. * @param {number} p2
  11165. * @param {number} p3
  11166. * @param {number} t
  11167. * @return {number}
  11168. */
  11169. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  11170. var onet = 1 - t;
  11171. return 3 * (
  11172. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  11173. + (p3 - p2) * t * t
  11174. );
  11175. }
  11176. /**
  11177. * 计算三次贝塞尔方程根,使用盛金公式
  11178. * @memberOf module:zrender/core/curve
  11179. * @param {number} p0
  11180. * @param {number} p1
  11181. * @param {number} p2
  11182. * @param {number} p3
  11183. * @param {number} val
  11184. * @param {Array.<number>} roots
  11185. * @return {number} 有效根数目
  11186. */
  11187. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  11188. // Evaluate roots of cubic functions
  11189. var a = p3 + 3 * (p1 - p2) - p0;
  11190. var b = 3 * (p2 - p1 * 2 + p0);
  11191. var c = 3 * (p1 - p0);
  11192. var d = p0 - val;
  11193. var A = b * b - 3 * a * c;
  11194. var B = b * c - 9 * a * d;
  11195. var C = c * c - 3 * b * d;
  11196. var n = 0;
  11197. if (isAroundZero(A) && isAroundZero(B)) {
  11198. if (isAroundZero(b)) {
  11199. roots[0] = 0;
  11200. }
  11201. else {
  11202. var t1 = -c / b; //t1, t2, t3, b is not zero
  11203. if (t1 >= 0 && t1 <= 1) {
  11204. roots[n++] = t1;
  11205. }
  11206. }
  11207. }
  11208. else {
  11209. var disc = B * B - 4 * A * C;
  11210. if (isAroundZero(disc)) {
  11211. var K = B / A;
  11212. var t1 = -b / a + K; // t1, a is not zero
  11213. var t2 = -K / 2; // t2, t3
  11214. if (t1 >= 0 && t1 <= 1) {
  11215. roots[n++] = t1;
  11216. }
  11217. if (t2 >= 0 && t2 <= 1) {
  11218. roots[n++] = t2;
  11219. }
  11220. }
  11221. else if (disc > 0) {
  11222. var discSqrt = mathSqrt$2(disc);
  11223. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  11224. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  11225. if (Y1 < 0) {
  11226. Y1 = -mathPow(-Y1, ONE_THIRD);
  11227. }
  11228. else {
  11229. Y1 = mathPow(Y1, ONE_THIRD);
  11230. }
  11231. if (Y2 < 0) {
  11232. Y2 = -mathPow(-Y2, ONE_THIRD);
  11233. }
  11234. else {
  11235. Y2 = mathPow(Y2, ONE_THIRD);
  11236. }
  11237. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  11238. if (t1 >= 0 && t1 <= 1) {
  11239. roots[n++] = t1;
  11240. }
  11241. }
  11242. else {
  11243. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  11244. var theta = Math.acos(T) / 3;
  11245. var ASqrt = mathSqrt$2(A);
  11246. var tmp = Math.cos(theta);
  11247. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  11248. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  11249. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  11250. if (t1 >= 0 && t1 <= 1) {
  11251. roots[n++] = t1;
  11252. }
  11253. if (t2 >= 0 && t2 <= 1) {
  11254. roots[n++] = t2;
  11255. }
  11256. if (t3 >= 0 && t3 <= 1) {
  11257. roots[n++] = t3;
  11258. }
  11259. }
  11260. }
  11261. return n;
  11262. }
  11263. /**
  11264. * 计算三次贝塞尔方程极限值的位置
  11265. * @memberOf module:zrender/core/curve
  11266. * @param {number} p0
  11267. * @param {number} p1
  11268. * @param {number} p2
  11269. * @param {number} p3
  11270. * @param {Array.<number>} extrema
  11271. * @return {number} 有效数目
  11272. */
  11273. function cubicExtrema(p0, p1, p2, p3, extrema) {
  11274. var b = 6 * p2 - 12 * p1 + 6 * p0;
  11275. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  11276. var c = 3 * p1 - 3 * p0;
  11277. var n = 0;
  11278. if (isAroundZero(a)) {
  11279. if (isNotAroundZero$1(b)) {
  11280. var t1 = -c / b;
  11281. if (t1 >= 0 && t1 <= 1) {
  11282. extrema[n++] = t1;
  11283. }
  11284. }
  11285. }
  11286. else {
  11287. var disc = b * b - 4 * a * c;
  11288. if (isAroundZero(disc)) {
  11289. extrema[0] = -b / (2 * a);
  11290. }
  11291. else if (disc > 0) {
  11292. var discSqrt = mathSqrt$2(disc);
  11293. var t1 = (-b + discSqrt) / (2 * a);
  11294. var t2 = (-b - discSqrt) / (2 * a);
  11295. if (t1 >= 0 && t1 <= 1) {
  11296. extrema[n++] = t1;
  11297. }
  11298. if (t2 >= 0 && t2 <= 1) {
  11299. extrema[n++] = t2;
  11300. }
  11301. }
  11302. }
  11303. return n;
  11304. }
  11305. /**
  11306. * 细分三次贝塞尔曲线
  11307. * @memberOf module:zrender/core/curve
  11308. * @param {number} p0
  11309. * @param {number} p1
  11310. * @param {number} p2
  11311. * @param {number} p3
  11312. * @param {number} t
  11313. * @param {Array.<number>} out
  11314. */
  11315. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  11316. var p01 = (p1 - p0) * t + p0;
  11317. var p12 = (p2 - p1) * t + p1;
  11318. var p23 = (p3 - p2) * t + p2;
  11319. var p012 = (p12 - p01) * t + p01;
  11320. var p123 = (p23 - p12) * t + p12;
  11321. var p0123 = (p123 - p012) * t + p012;
  11322. // Seg0
  11323. out[0] = p0;
  11324. out[1] = p01;
  11325. out[2] = p012;
  11326. out[3] = p0123;
  11327. // Seg1
  11328. out[4] = p0123;
  11329. out[5] = p123;
  11330. out[6] = p23;
  11331. out[7] = p3;
  11332. }
  11333. /**
  11334. * 投射点到三次贝塞尔曲线上,返回投射距离。
  11335. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11336. * @param {number} x0
  11337. * @param {number} y0
  11338. * @param {number} x1
  11339. * @param {number} y1
  11340. * @param {number} x2
  11341. * @param {number} y2
  11342. * @param {number} x3
  11343. * @param {number} y3
  11344. * @param {number} x
  11345. * @param {number} y
  11346. * @param {Array.<number>} [out] 投射点
  11347. * @return {number}
  11348. */
  11349. function cubicProjectPoint(
  11350. x0, y0, x1, y1, x2, y2, x3, y3,
  11351. x, y, out
  11352. ) {
  11353. // http://pomax.github.io/bezierinfo/#projections
  11354. var t;
  11355. var interval = 0.005;
  11356. var d = Infinity;
  11357. var prev;
  11358. var next;
  11359. var d1;
  11360. var d2;
  11361. _v0[0] = x;
  11362. _v0[1] = y;
  11363. // 先粗略估计一下可能的最小距离的 t 值
  11364. // PENDING
  11365. for (var _t = 0; _t < 1; _t += 0.05) {
  11366. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  11367. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  11368. d1 = distSquare(_v0, _v1);
  11369. if (d1 < d) {
  11370. t = _t;
  11371. d = d1;
  11372. }
  11373. }
  11374. d = Infinity;
  11375. // At most 32 iteration
  11376. for (var i = 0; i < 32; i++) {
  11377. if (interval < EPSILON_NUMERIC) {
  11378. break;
  11379. }
  11380. prev = t - interval;
  11381. next = t + interval;
  11382. // t - interval
  11383. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  11384. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  11385. d1 = distSquare(_v1, _v0);
  11386. if (prev >= 0 && d1 < d) {
  11387. t = prev;
  11388. d = d1;
  11389. }
  11390. else {
  11391. // t + interval
  11392. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  11393. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  11394. d2 = distSquare(_v2, _v0);
  11395. if (next <= 1 && d2 < d) {
  11396. t = next;
  11397. d = d2;
  11398. }
  11399. else {
  11400. interval *= 0.5;
  11401. }
  11402. }
  11403. }
  11404. // t
  11405. if (out) {
  11406. out[0] = cubicAt(x0, x1, x2, x3, t);
  11407. out[1] = cubicAt(y0, y1, y2, y3, t);
  11408. }
  11409. // console.log(interval, i);
  11410. return mathSqrt$2(d);
  11411. }
  11412. /**
  11413. * 计算二次方贝塞尔值
  11414. * @param {number} p0
  11415. * @param {number} p1
  11416. * @param {number} p2
  11417. * @param {number} t
  11418. * @return {number}
  11419. */
  11420. function quadraticAt(p0, p1, p2, t) {
  11421. var onet = 1 - t;
  11422. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  11423. }
  11424. /**
  11425. * 计算二次方贝塞尔导数值
  11426. * @param {number} p0
  11427. * @param {number} p1
  11428. * @param {number} p2
  11429. * @param {number} t
  11430. * @return {number}
  11431. */
  11432. function quadraticDerivativeAt(p0, p1, p2, t) {
  11433. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  11434. }
  11435. /**
  11436. * 计算二次方贝塞尔方程根
  11437. * @param {number} p0
  11438. * @param {number} p1
  11439. * @param {number} p2
  11440. * @param {number} t
  11441. * @param {Array.<number>} roots
  11442. * @return {number} 有效根数目
  11443. */
  11444. function quadraticRootAt(p0, p1, p2, val, roots) {
  11445. var a = p0 - 2 * p1 + p2;
  11446. var b = 2 * (p1 - p0);
  11447. var c = p0 - val;
  11448. var n = 0;
  11449. if (isAroundZero(a)) {
  11450. if (isNotAroundZero$1(b)) {
  11451. var t1 = -c / b;
  11452. if (t1 >= 0 && t1 <= 1) {
  11453. roots[n++] = t1;
  11454. }
  11455. }
  11456. }
  11457. else {
  11458. var disc = b * b - 4 * a * c;
  11459. if (isAroundZero(disc)) {
  11460. var t1 = -b / (2 * a);
  11461. if (t1 >= 0 && t1 <= 1) {
  11462. roots[n++] = t1;
  11463. }
  11464. }
  11465. else if (disc > 0) {
  11466. var discSqrt = mathSqrt$2(disc);
  11467. var t1 = (-b + discSqrt) / (2 * a);
  11468. var t2 = (-b - discSqrt) / (2 * a);
  11469. if (t1 >= 0 && t1 <= 1) {
  11470. roots[n++] = t1;
  11471. }
  11472. if (t2 >= 0 && t2 <= 1) {
  11473. roots[n++] = t2;
  11474. }
  11475. }
  11476. }
  11477. return n;
  11478. }
  11479. /**
  11480. * 计算二次贝塞尔方程极限值
  11481. * @memberOf module:zrender/core/curve
  11482. * @param {number} p0
  11483. * @param {number} p1
  11484. * @param {number} p2
  11485. * @return {number}
  11486. */
  11487. function quadraticExtremum(p0, p1, p2) {
  11488. var divider = p0 + p2 - 2 * p1;
  11489. if (divider === 0) {
  11490. // p1 is center of p0 and p2
  11491. return 0.5;
  11492. }
  11493. else {
  11494. return (p0 - p1) / divider;
  11495. }
  11496. }
  11497. /**
  11498. * 细分二次贝塞尔曲线
  11499. * @memberOf module:zrender/core/curve
  11500. * @param {number} p0
  11501. * @param {number} p1
  11502. * @param {number} p2
  11503. * @param {number} t
  11504. * @param {Array.<number>} out
  11505. */
  11506. function quadraticSubdivide(p0, p1, p2, t, out) {
  11507. var p01 = (p1 - p0) * t + p0;
  11508. var p12 = (p2 - p1) * t + p1;
  11509. var p012 = (p12 - p01) * t + p01;
  11510. // Seg0
  11511. out[0] = p0;
  11512. out[1] = p01;
  11513. out[2] = p012;
  11514. // Seg1
  11515. out[3] = p012;
  11516. out[4] = p12;
  11517. out[5] = p2;
  11518. }
  11519. /**
  11520. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11521. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11522. * @param {number} x0
  11523. * @param {number} y0
  11524. * @param {number} x1
  11525. * @param {number} y1
  11526. * @param {number} x2
  11527. * @param {number} y2
  11528. * @param {number} x
  11529. * @param {number} y
  11530. * @param {Array.<number>} out 投射点
  11531. * @return {number}
  11532. */
  11533. function quadraticProjectPoint(
  11534. x0, y0, x1, y1, x2, y2,
  11535. x, y, out
  11536. ) {
  11537. // http://pomax.github.io/bezierinfo/#projections
  11538. var t;
  11539. var interval = 0.005;
  11540. var d = Infinity;
  11541. _v0[0] = x;
  11542. _v0[1] = y;
  11543. // 先粗略估计一下可能的最小距离的 t 值
  11544. // PENDING
  11545. for (var _t = 0; _t < 1; _t += 0.05) {
  11546. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11547. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11548. var d1 = distSquare(_v0, _v1);
  11549. if (d1 < d) {
  11550. t = _t;
  11551. d = d1;
  11552. }
  11553. }
  11554. d = Infinity;
  11555. // At most 32 iteration
  11556. for (var i = 0; i < 32; i++) {
  11557. if (interval < EPSILON_NUMERIC) {
  11558. break;
  11559. }
  11560. var prev = t - interval;
  11561. var next = t + interval;
  11562. // t - interval
  11563. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11564. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11565. var d1 = distSquare(_v1, _v0);
  11566. if (prev >= 0 && d1 < d) {
  11567. t = prev;
  11568. d = d1;
  11569. }
  11570. else {
  11571. // t + interval
  11572. _v2[0] = quadraticAt(x0, x1, x2, next);
  11573. _v2[1] = quadraticAt(y0, y1, y2, next);
  11574. var d2 = distSquare(_v2, _v0);
  11575. if (next <= 1 && d2 < d) {
  11576. t = next;
  11577. d = d2;
  11578. }
  11579. else {
  11580. interval *= 0.5;
  11581. }
  11582. }
  11583. }
  11584. // t
  11585. if (out) {
  11586. out[0] = quadraticAt(x0, x1, x2, t);
  11587. out[1] = quadraticAt(y0, y1, y2, t);
  11588. }
  11589. // console.log(interval, i);
  11590. return mathSqrt$2(d);
  11591. }
  11592. /**
  11593. * @author Yi Shen(https://github.com/pissang)
  11594. */
  11595. var mathMin$3 = Math.min;
  11596. var mathMax$3 = Math.max;
  11597. var mathSin$2 = Math.sin;
  11598. var mathCos$2 = Math.cos;
  11599. var PI2 = Math.PI * 2;
  11600. var start = create();
  11601. var end = create();
  11602. var extremity = create();
  11603. /**
  11604. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11605. * @module zrender/core/bbox
  11606. * @param {Array<Object>} points 顶点数组
  11607. * @param {number} min
  11608. * @param {number} max
  11609. */
  11610. function fromPoints(points, min$$1, max$$1) {
  11611. if (points.length === 0) {
  11612. return;
  11613. }
  11614. var p = points[0];
  11615. var left = p[0];
  11616. var right = p[0];
  11617. var top = p[1];
  11618. var bottom = p[1];
  11619. var i;
  11620. for (i = 1; i < points.length; i++) {
  11621. p = points[i];
  11622. left = mathMin$3(left, p[0]);
  11623. right = mathMax$3(right, p[0]);
  11624. top = mathMin$3(top, p[1]);
  11625. bottom = mathMax$3(bottom, p[1]);
  11626. }
  11627. min$$1[0] = left;
  11628. min$$1[1] = top;
  11629. max$$1[0] = right;
  11630. max$$1[1] = bottom;
  11631. }
  11632. /**
  11633. * @memberOf module:zrender/core/bbox
  11634. * @param {number} x0
  11635. * @param {number} y0
  11636. * @param {number} x1
  11637. * @param {number} y1
  11638. * @param {Array.<number>} min
  11639. * @param {Array.<number>} max
  11640. */
  11641. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11642. min$$1[0] = mathMin$3(x0, x1);
  11643. min$$1[1] = mathMin$3(y0, y1);
  11644. max$$1[0] = mathMax$3(x0, x1);
  11645. max$$1[1] = mathMax$3(y0, y1);
  11646. }
  11647. var xDim = [];
  11648. var yDim = [];
  11649. /**
  11650. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11651. * @memberOf module:zrender/core/bbox
  11652. * @param {number} x0
  11653. * @param {number} y0
  11654. * @param {number} x1
  11655. * @param {number} y1
  11656. * @param {number} x2
  11657. * @param {number} y2
  11658. * @param {number} x3
  11659. * @param {number} y3
  11660. * @param {Array.<number>} min
  11661. * @param {Array.<number>} max
  11662. */
  11663. function fromCubic(
  11664. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11665. ) {
  11666. var cubicExtrema$$1 = cubicExtrema;
  11667. var cubicAt$$1 = cubicAt;
  11668. var i;
  11669. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11670. min$$1[0] = Infinity;
  11671. min$$1[1] = Infinity;
  11672. max$$1[0] = -Infinity;
  11673. max$$1[1] = -Infinity;
  11674. for (i = 0; i < n; i++) {
  11675. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11676. min$$1[0] = mathMin$3(x, min$$1[0]);
  11677. max$$1[0] = mathMax$3(x, max$$1[0]);
  11678. }
  11679. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11680. for (i = 0; i < n; i++) {
  11681. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11682. min$$1[1] = mathMin$3(y, min$$1[1]);
  11683. max$$1[1] = mathMax$3(y, max$$1[1]);
  11684. }
  11685. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11686. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11687. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11688. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11689. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11690. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11691. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11692. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11693. }
  11694. /**
  11695. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11696. * @memberOf module:zrender/core/bbox
  11697. * @param {number} x0
  11698. * @param {number} y0
  11699. * @param {number} x1
  11700. * @param {number} y1
  11701. * @param {number} x2
  11702. * @param {number} y2
  11703. * @param {Array.<number>} min
  11704. * @param {Array.<number>} max
  11705. */
  11706. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11707. var quadraticExtremum$$1 = quadraticExtremum;
  11708. var quadraticAt$$1 = quadraticAt;
  11709. // Find extremities, where derivative in x dim or y dim is zero
  11710. var tx =
  11711. mathMax$3(
  11712. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11713. );
  11714. var ty =
  11715. mathMax$3(
  11716. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11717. );
  11718. var x = quadraticAt$$1(x0, x1, x2, tx);
  11719. var y = quadraticAt$$1(y0, y1, y2, ty);
  11720. min$$1[0] = mathMin$3(x0, x2, x);
  11721. min$$1[1] = mathMin$3(y0, y2, y);
  11722. max$$1[0] = mathMax$3(x0, x2, x);
  11723. max$$1[1] = mathMax$3(y0, y2, y);
  11724. }
  11725. /**
  11726. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11727. * @method
  11728. * @memberOf module:zrender/core/bbox
  11729. * @param {number} x
  11730. * @param {number} y
  11731. * @param {number} rx
  11732. * @param {number} ry
  11733. * @param {number} startAngle
  11734. * @param {number} endAngle
  11735. * @param {number} anticlockwise
  11736. * @param {Array.<number>} min
  11737. * @param {Array.<number>} max
  11738. */
  11739. function fromArc(
  11740. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11741. ) {
  11742. var vec2Min = min;
  11743. var vec2Max = max;
  11744. var diff = Math.abs(startAngle - endAngle);
  11745. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11746. // Is a circle
  11747. min$$1[0] = x - rx;
  11748. min$$1[1] = y - ry;
  11749. max$$1[0] = x + rx;
  11750. max$$1[1] = y + ry;
  11751. return;
  11752. }
  11753. start[0] = mathCos$2(startAngle) * rx + x;
  11754. start[1] = mathSin$2(startAngle) * ry + y;
  11755. end[0] = mathCos$2(endAngle) * rx + x;
  11756. end[1] = mathSin$2(endAngle) * ry + y;
  11757. vec2Min(min$$1, start, end);
  11758. vec2Max(max$$1, start, end);
  11759. // Thresh to [0, Math.PI * 2]
  11760. startAngle = startAngle % (PI2);
  11761. if (startAngle < 0) {
  11762. startAngle = startAngle + PI2;
  11763. }
  11764. endAngle = endAngle % (PI2);
  11765. if (endAngle < 0) {
  11766. endAngle = endAngle + PI2;
  11767. }
  11768. if (startAngle > endAngle && !anticlockwise) {
  11769. endAngle += PI2;
  11770. }
  11771. else if (startAngle < endAngle && anticlockwise) {
  11772. startAngle += PI2;
  11773. }
  11774. if (anticlockwise) {
  11775. var tmp = endAngle;
  11776. endAngle = startAngle;
  11777. startAngle = tmp;
  11778. }
  11779. // var number = 0;
  11780. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11781. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11782. if (angle > startAngle) {
  11783. extremity[0] = mathCos$2(angle) * rx + x;
  11784. extremity[1] = mathSin$2(angle) * ry + y;
  11785. vec2Min(min$$1, extremity, min$$1);
  11786. vec2Max(max$$1, extremity, max$$1);
  11787. }
  11788. }
  11789. }
  11790. /**
  11791. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11792. * 可以用于 isInsidePath 判断以及获取boundingRect
  11793. *
  11794. * @module zrender/core/PathProxy
  11795. * @author Yi Shen (http://www.github.com/pissang)
  11796. */
  11797. // TODO getTotalLength, getPointAtLength
  11798. /* global Float32Array */
  11799. var CMD = {
  11800. M: 1,
  11801. L: 2,
  11802. C: 3,
  11803. Q: 4,
  11804. A: 5,
  11805. Z: 6,
  11806. // Rect
  11807. R: 7
  11808. };
  11809. // var CMD_MEM_SIZE = {
  11810. // M: 3,
  11811. // L: 3,
  11812. // C: 7,
  11813. // Q: 5,
  11814. // A: 9,
  11815. // R: 5,
  11816. // Z: 1
  11817. // };
  11818. var min$1 = [];
  11819. var max$1 = [];
  11820. var min2 = [];
  11821. var max2 = [];
  11822. var mathMin$2 = Math.min;
  11823. var mathMax$2 = Math.max;
  11824. var mathCos$1 = Math.cos;
  11825. var mathSin$1 = Math.sin;
  11826. var mathSqrt$1 = Math.sqrt;
  11827. var mathAbs = Math.abs;
  11828. var hasTypedArray = typeof Float32Array !== 'undefined';
  11829. /**
  11830. * @alias module:zrender/core/PathProxy
  11831. * @constructor
  11832. */
  11833. var PathProxy = function (notSaveData) {
  11834. this._saveData = !(notSaveData || false);
  11835. if (this._saveData) {
  11836. /**
  11837. * Path data. Stored as flat array
  11838. * @type {Array.<Object>}
  11839. */
  11840. this.data = [];
  11841. }
  11842. this._ctx = null;
  11843. };
  11844. /**
  11845. * 快速计算Path包围盒(并不是最小包围盒)
  11846. * @return {Object}
  11847. */
  11848. PathProxy.prototype = {
  11849. constructor: PathProxy,
  11850. _xi: 0,
  11851. _yi: 0,
  11852. _x0: 0,
  11853. _y0: 0,
  11854. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11855. _ux: 0,
  11856. _uy: 0,
  11857. _len: 0,
  11858. _lineDash: null,
  11859. _dashOffset: 0,
  11860. _dashIdx: 0,
  11861. _dashSum: 0,
  11862. /**
  11863. * @readOnly
  11864. */
  11865. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11866. // Compat. Previously there is no segmentIgnoreThreshold.
  11867. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11868. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11869. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11870. },
  11871. getContext: function () {
  11872. return this._ctx;
  11873. },
  11874. /**
  11875. * @param {CanvasRenderingContext2D} ctx
  11876. * @return {module:zrender/core/PathProxy}
  11877. */
  11878. beginPath: function (ctx) {
  11879. this._ctx = ctx;
  11880. ctx && ctx.beginPath();
  11881. ctx && (this.dpr = ctx.dpr);
  11882. // Reset
  11883. if (this._saveData) {
  11884. this._len = 0;
  11885. }
  11886. if (this._lineDash) {
  11887. this._lineDash = null;
  11888. this._dashOffset = 0;
  11889. }
  11890. return this;
  11891. },
  11892. /**
  11893. * @param {number} x
  11894. * @param {number} y
  11895. * @return {module:zrender/core/PathProxy}
  11896. */
  11897. moveTo: function (x, y) {
  11898. this.addData(CMD.M, x, y);
  11899. this._ctx && this._ctx.moveTo(x, y);
  11900. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11901. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11902. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11903. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11904. this._x0 = x;
  11905. this._y0 = y;
  11906. this._xi = x;
  11907. this._yi = y;
  11908. return this;
  11909. },
  11910. /**
  11911. * @param {number} x
  11912. * @param {number} y
  11913. * @return {module:zrender/core/PathProxy}
  11914. */
  11915. lineTo: function (x, y) {
  11916. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11917. || mathAbs(y - this._yi) > this._uy
  11918. // Force draw the first segment
  11919. || this._len < 5;
  11920. this.addData(CMD.L, x, y);
  11921. if (this._ctx && exceedUnit) {
  11922. this._needsDash() ? this._dashedLineTo(x, y)
  11923. : this._ctx.lineTo(x, y);
  11924. }
  11925. if (exceedUnit) {
  11926. this._xi = x;
  11927. this._yi = y;
  11928. }
  11929. return this;
  11930. },
  11931. /**
  11932. * @param {number} x1
  11933. * @param {number} y1
  11934. * @param {number} x2
  11935. * @param {number} y2
  11936. * @param {number} x3
  11937. * @param {number} y3
  11938. * @return {module:zrender/core/PathProxy}
  11939. */
  11940. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11941. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11942. if (this._ctx) {
  11943. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11944. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11945. }
  11946. this._xi = x3;
  11947. this._yi = y3;
  11948. return this;
  11949. },
  11950. /**
  11951. * @param {number} x1
  11952. * @param {number} y1
  11953. * @param {number} x2
  11954. * @param {number} y2
  11955. * @return {module:zrender/core/PathProxy}
  11956. */
  11957. quadraticCurveTo: function (x1, y1, x2, y2) {
  11958. this.addData(CMD.Q, x1, y1, x2, y2);
  11959. if (this._ctx) {
  11960. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11961. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11962. }
  11963. this._xi = x2;
  11964. this._yi = y2;
  11965. return this;
  11966. },
  11967. /**
  11968. * @param {number} cx
  11969. * @param {number} cy
  11970. * @param {number} r
  11971. * @param {number} startAngle
  11972. * @param {number} endAngle
  11973. * @param {boolean} anticlockwise
  11974. * @return {module:zrender/core/PathProxy}
  11975. */
  11976. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11977. this.addData(
  11978. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11979. );
  11980. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11981. this._xi = mathCos$1(endAngle) * r + cx;
  11982. this._yi = mathSin$1(endAngle) * r + cy;
  11983. return this;
  11984. },
  11985. // TODO
  11986. arcTo: function (x1, y1, x2, y2, radius) {
  11987. if (this._ctx) {
  11988. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11989. }
  11990. return this;
  11991. },
  11992. // TODO
  11993. rect: function (x, y, w, h) {
  11994. this._ctx && this._ctx.rect(x, y, w, h);
  11995. this.addData(CMD.R, x, y, w, h);
  11996. return this;
  11997. },
  11998. /**
  11999. * @return {module:zrender/core/PathProxy}
  12000. */
  12001. closePath: function () {
  12002. this.addData(CMD.Z);
  12003. var ctx = this._ctx;
  12004. var x0 = this._x0;
  12005. var y0 = this._y0;
  12006. if (ctx) {
  12007. this._needsDash() && this._dashedLineTo(x0, y0);
  12008. ctx.closePath();
  12009. }
  12010. this._xi = x0;
  12011. this._yi = y0;
  12012. return this;
  12013. },
  12014. /**
  12015. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  12016. * stroke 同样
  12017. * @param {CanvasRenderingContext2D} ctx
  12018. * @return {module:zrender/core/PathProxy}
  12019. */
  12020. fill: function (ctx) {
  12021. ctx && ctx.fill();
  12022. this.toStatic();
  12023. },
  12024. /**
  12025. * @param {CanvasRenderingContext2D} ctx
  12026. * @return {module:zrender/core/PathProxy}
  12027. */
  12028. stroke: function (ctx) {
  12029. ctx && ctx.stroke();
  12030. this.toStatic();
  12031. },
  12032. /**
  12033. * 必须在其它绘制命令前调用
  12034. * Must be invoked before all other path drawing methods
  12035. * @return {module:zrender/core/PathProxy}
  12036. */
  12037. setLineDash: function (lineDash) {
  12038. if (lineDash instanceof Array) {
  12039. this._lineDash = lineDash;
  12040. this._dashIdx = 0;
  12041. var lineDashSum = 0;
  12042. for (var i = 0; i < lineDash.length; i++) {
  12043. lineDashSum += lineDash[i];
  12044. }
  12045. this._dashSum = lineDashSum;
  12046. }
  12047. return this;
  12048. },
  12049. /**
  12050. * 必须在其它绘制命令前调用
  12051. * Must be invoked before all other path drawing methods
  12052. * @return {module:zrender/core/PathProxy}
  12053. */
  12054. setLineDashOffset: function (offset) {
  12055. this._dashOffset = offset;
  12056. return this;
  12057. },
  12058. /**
  12059. *
  12060. * @return {boolean}
  12061. */
  12062. len: function () {
  12063. return this._len;
  12064. },
  12065. /**
  12066. * 直接设置 Path 数据
  12067. */
  12068. setData: function (data) {
  12069. var len$$1 = data.length;
  12070. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  12071. this.data = new Float32Array(len$$1);
  12072. }
  12073. for (var i = 0; i < len$$1; i++) {
  12074. this.data[i] = data[i];
  12075. }
  12076. this._len = len$$1;
  12077. },
  12078. /**
  12079. * 添加子路径
  12080. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  12081. */
  12082. appendPath: function (path) {
  12083. if (!(path instanceof Array)) {
  12084. path = [path];
  12085. }
  12086. var len$$1 = path.length;
  12087. var appendSize = 0;
  12088. var offset = this._len;
  12089. for (var i = 0; i < len$$1; i++) {
  12090. appendSize += path[i].len();
  12091. }
  12092. if (hasTypedArray && (this.data instanceof Float32Array)) {
  12093. this.data = new Float32Array(offset + appendSize);
  12094. }
  12095. for (var i = 0; i < len$$1; i++) {
  12096. var appendPathData = path[i].data;
  12097. for (var k = 0; k < appendPathData.length; k++) {
  12098. this.data[offset++] = appendPathData[k];
  12099. }
  12100. }
  12101. this._len = offset;
  12102. },
  12103. /**
  12104. * 填充 Path 数据。
  12105. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  12106. */
  12107. addData: function (cmd) {
  12108. if (!this._saveData) {
  12109. return;
  12110. }
  12111. var data = this.data;
  12112. if (this._len + arguments.length > data.length) {
  12113. // 因为之前的数组已经转换成静态的 Float32Array
  12114. // 所以不够用时需要扩展一个新的动态数组
  12115. this._expandData();
  12116. data = this.data;
  12117. }
  12118. for (var i = 0; i < arguments.length; i++) {
  12119. data[this._len++] = arguments[i];
  12120. }
  12121. this._prevCmd = cmd;
  12122. },
  12123. _expandData: function () {
  12124. // Only if data is Float32Array
  12125. if (!(this.data instanceof Array)) {
  12126. var newData = [];
  12127. for (var i = 0; i < this._len; i++) {
  12128. newData[i] = this.data[i];
  12129. }
  12130. this.data = newData;
  12131. }
  12132. },
  12133. /**
  12134. * If needs js implemented dashed line
  12135. * @return {boolean}
  12136. * @private
  12137. */
  12138. _needsDash: function () {
  12139. return this._lineDash;
  12140. },
  12141. _dashedLineTo: function (x1, y1) {
  12142. var dashSum = this._dashSum;
  12143. var offset = this._dashOffset;
  12144. var lineDash = this._lineDash;
  12145. var ctx = this._ctx;
  12146. var x0 = this._xi;
  12147. var y0 = this._yi;
  12148. var dx = x1 - x0;
  12149. var dy = y1 - y0;
  12150. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  12151. var x = x0;
  12152. var y = y0;
  12153. var dash;
  12154. var nDash = lineDash.length;
  12155. var idx;
  12156. dx /= dist$$1;
  12157. dy /= dist$$1;
  12158. if (offset < 0) {
  12159. // Convert to positive offset
  12160. offset = dashSum + offset;
  12161. }
  12162. offset %= dashSum;
  12163. x -= offset * dx;
  12164. y -= offset * dy;
  12165. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  12166. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  12167. idx = this._dashIdx;
  12168. dash = lineDash[idx];
  12169. x += dx * dash;
  12170. y += dy * dash;
  12171. this._dashIdx = (idx + 1) % nDash;
  12172. // Skip positive offset
  12173. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  12174. continue;
  12175. }
  12176. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  12177. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  12178. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  12179. );
  12180. }
  12181. // Offset for next lineTo
  12182. dx = x - x1;
  12183. dy = y - y1;
  12184. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12185. },
  12186. // Not accurate dashed line to
  12187. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  12188. var dashSum = this._dashSum;
  12189. var offset = this._dashOffset;
  12190. var lineDash = this._lineDash;
  12191. var ctx = this._ctx;
  12192. var x0 = this._xi;
  12193. var y0 = this._yi;
  12194. var t;
  12195. var dx;
  12196. var dy;
  12197. var cubicAt$$1 = cubicAt;
  12198. var bezierLen = 0;
  12199. var idx = this._dashIdx;
  12200. var nDash = lineDash.length;
  12201. var x;
  12202. var y;
  12203. var tmpLen = 0;
  12204. if (offset < 0) {
  12205. // Convert to positive offset
  12206. offset = dashSum + offset;
  12207. }
  12208. offset %= dashSum;
  12209. // Bezier approx length
  12210. for (t = 0; t < 1; t += 0.1) {
  12211. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  12212. - cubicAt$$1(x0, x1, x2, x3, t);
  12213. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  12214. - cubicAt$$1(y0, y1, y2, y3, t);
  12215. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  12216. }
  12217. // Find idx after add offset
  12218. for (; idx < nDash; idx++) {
  12219. tmpLen += lineDash[idx];
  12220. if (tmpLen > offset) {
  12221. break;
  12222. }
  12223. }
  12224. t = (tmpLen - offset) / bezierLen;
  12225. while (t <= 1) {
  12226. x = cubicAt$$1(x0, x1, x2, x3, t);
  12227. y = cubicAt$$1(y0, y1, y2, y3, t);
  12228. // Use line to approximate dashed bezier
  12229. // Bad result if dash is long
  12230. idx % 2 ? ctx.moveTo(x, y)
  12231. : ctx.lineTo(x, y);
  12232. t += lineDash[idx] / bezierLen;
  12233. idx = (idx + 1) % nDash;
  12234. }
  12235. // Finish the last segment and calculate the new offset
  12236. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  12237. dx = x3 - x;
  12238. dy = y3 - y;
  12239. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12240. },
  12241. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  12242. // Convert quadratic to cubic using degree elevation
  12243. var x3 = x2;
  12244. var y3 = y2;
  12245. x2 = (x2 + 2 * x1) / 3;
  12246. y2 = (y2 + 2 * y1) / 3;
  12247. x1 = (this._xi + 2 * x1) / 3;
  12248. y1 = (this._yi + 2 * y1) / 3;
  12249. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  12250. },
  12251. /**
  12252. * 转成静态的 Float32Array 减少堆内存占用
  12253. * Convert dynamic array to static Float32Array
  12254. */
  12255. toStatic: function () {
  12256. var data = this.data;
  12257. if (data instanceof Array) {
  12258. data.length = this._len;
  12259. if (hasTypedArray) {
  12260. this.data = new Float32Array(data);
  12261. }
  12262. }
  12263. },
  12264. /**
  12265. * @return {module:zrender/core/BoundingRect}
  12266. */
  12267. getBoundingRect: function () {
  12268. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  12269. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  12270. var data = this.data;
  12271. var xi = 0;
  12272. var yi = 0;
  12273. var x0 = 0;
  12274. var y0 = 0;
  12275. for (var i = 0; i < data.length;) {
  12276. var cmd = data[i++];
  12277. if (i === 1) {
  12278. // 如果第一个命令是 L, C, Q
  12279. // 则 previous point 同绘制命令的第一个 point
  12280. //
  12281. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12282. xi = data[i];
  12283. yi = data[i + 1];
  12284. x0 = xi;
  12285. y0 = yi;
  12286. }
  12287. switch (cmd) {
  12288. case CMD.M:
  12289. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12290. // 在 closePath 的时候使用
  12291. x0 = data[i++];
  12292. y0 = data[i++];
  12293. xi = x0;
  12294. yi = y0;
  12295. min2[0] = x0;
  12296. min2[1] = y0;
  12297. max2[0] = x0;
  12298. max2[1] = y0;
  12299. break;
  12300. case CMD.L:
  12301. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  12302. xi = data[i++];
  12303. yi = data[i++];
  12304. break;
  12305. case CMD.C:
  12306. fromCubic(
  12307. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12308. min2, max2
  12309. );
  12310. xi = data[i++];
  12311. yi = data[i++];
  12312. break;
  12313. case CMD.Q:
  12314. fromQuadratic(
  12315. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  12316. min2, max2
  12317. );
  12318. xi = data[i++];
  12319. yi = data[i++];
  12320. break;
  12321. case CMD.A:
  12322. // TODO Arc 判断的开销比较大
  12323. var cx = data[i++];
  12324. var cy = data[i++];
  12325. var rx = data[i++];
  12326. var ry = data[i++];
  12327. var startAngle = data[i++];
  12328. var endAngle = data[i++] + startAngle;
  12329. // TODO Arc 旋转
  12330. i += 1;
  12331. var anticlockwise = 1 - data[i++];
  12332. if (i === 1) {
  12333. // 直接使用 arc 命令
  12334. // 第一个命令起点还未定义
  12335. x0 = mathCos$1(startAngle) * rx + cx;
  12336. y0 = mathSin$1(startAngle) * ry + cy;
  12337. }
  12338. fromArc(
  12339. cx, cy, rx, ry, startAngle, endAngle,
  12340. anticlockwise, min2, max2
  12341. );
  12342. xi = mathCos$1(endAngle) * rx + cx;
  12343. yi = mathSin$1(endAngle) * ry + cy;
  12344. break;
  12345. case CMD.R:
  12346. x0 = xi = data[i++];
  12347. y0 = yi = data[i++];
  12348. var width = data[i++];
  12349. var height = data[i++];
  12350. // Use fromLine
  12351. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  12352. break;
  12353. case CMD.Z:
  12354. xi = x0;
  12355. yi = y0;
  12356. break;
  12357. }
  12358. // Union
  12359. min(min$1, min$1, min2);
  12360. max(max$1, max$1, max2);
  12361. }
  12362. // No data
  12363. if (i === 0) {
  12364. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  12365. }
  12366. return new BoundingRect(
  12367. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  12368. );
  12369. },
  12370. /**
  12371. * Rebuild path from current data
  12372. * Rebuild path will not consider javascript implemented line dash.
  12373. * @param {CanvasRenderingContext2D} ctx
  12374. */
  12375. rebuildPath: function (ctx) {
  12376. var d = this.data;
  12377. var x0;
  12378. var y0;
  12379. var xi;
  12380. var yi;
  12381. var x;
  12382. var y;
  12383. var ux = this._ux;
  12384. var uy = this._uy;
  12385. var len$$1 = this._len;
  12386. for (var i = 0; i < len$$1;) {
  12387. var cmd = d[i++];
  12388. if (i === 1) {
  12389. // 如果第一个命令是 L, C, Q
  12390. // 则 previous point 同绘制命令的第一个 point
  12391. //
  12392. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12393. xi = d[i];
  12394. yi = d[i + 1];
  12395. x0 = xi;
  12396. y0 = yi;
  12397. }
  12398. switch (cmd) {
  12399. case CMD.M:
  12400. x0 = xi = d[i++];
  12401. y0 = yi = d[i++];
  12402. ctx.moveTo(xi, yi);
  12403. break;
  12404. case CMD.L:
  12405. x = d[i++];
  12406. y = d[i++];
  12407. // Not draw too small seg between
  12408. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  12409. ctx.lineTo(x, y);
  12410. xi = x;
  12411. yi = y;
  12412. }
  12413. break;
  12414. case CMD.C:
  12415. ctx.bezierCurveTo(
  12416. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  12417. );
  12418. xi = d[i - 2];
  12419. yi = d[i - 1];
  12420. break;
  12421. case CMD.Q:
  12422. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  12423. xi = d[i - 2];
  12424. yi = d[i - 1];
  12425. break;
  12426. case CMD.A:
  12427. var cx = d[i++];
  12428. var cy = d[i++];
  12429. var rx = d[i++];
  12430. var ry = d[i++];
  12431. var theta = d[i++];
  12432. var dTheta = d[i++];
  12433. var psi = d[i++];
  12434. var fs = d[i++];
  12435. var r = (rx > ry) ? rx : ry;
  12436. var scaleX = (rx > ry) ? 1 : rx / ry;
  12437. var scaleY = (rx > ry) ? ry / rx : 1;
  12438. var isEllipse = Math.abs(rx - ry) > 1e-3;
  12439. var endAngle = theta + dTheta;
  12440. if (isEllipse) {
  12441. ctx.translate(cx, cy);
  12442. ctx.rotate(psi);
  12443. ctx.scale(scaleX, scaleY);
  12444. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  12445. ctx.scale(1 / scaleX, 1 / scaleY);
  12446. ctx.rotate(-psi);
  12447. ctx.translate(-cx, -cy);
  12448. }
  12449. else {
  12450. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  12451. }
  12452. if (i === 1) {
  12453. // 直接使用 arc 命令
  12454. // 第一个命令起点还未定义
  12455. x0 = mathCos$1(theta) * rx + cx;
  12456. y0 = mathSin$1(theta) * ry + cy;
  12457. }
  12458. xi = mathCos$1(endAngle) * rx + cx;
  12459. yi = mathSin$1(endAngle) * ry + cy;
  12460. break;
  12461. case CMD.R:
  12462. x0 = xi = d[i];
  12463. y0 = yi = d[i + 1];
  12464. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  12465. break;
  12466. case CMD.Z:
  12467. ctx.closePath();
  12468. xi = x0;
  12469. yi = y0;
  12470. }
  12471. }
  12472. }
  12473. };
  12474. PathProxy.CMD = CMD;
  12475. /**
  12476. * 线段包含判断
  12477. * @param {number} x0
  12478. * @param {number} y0
  12479. * @param {number} x1
  12480. * @param {number} y1
  12481. * @param {number} lineWidth
  12482. * @param {number} x
  12483. * @param {number} y
  12484. * @return {boolean}
  12485. */
  12486. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  12487. if (lineWidth === 0) {
  12488. return false;
  12489. }
  12490. var _l = lineWidth;
  12491. var _a = 0;
  12492. var _b = x0;
  12493. // Quick reject
  12494. if (
  12495. (y > y0 + _l && y > y1 + _l)
  12496. || (y < y0 - _l && y < y1 - _l)
  12497. || (x > x0 + _l && x > x1 + _l)
  12498. || (x < x0 - _l && x < x1 - _l)
  12499. ) {
  12500. return false;
  12501. }
  12502. if (x0 !== x1) {
  12503. _a = (y0 - y1) / (x0 - x1);
  12504. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12505. }
  12506. else {
  12507. return Math.abs(x - x0) <= _l / 2;
  12508. }
  12509. var tmp = _a * x - y + _b;
  12510. var _s = tmp * tmp / (_a * _a + 1);
  12511. return _s <= _l / 2 * _l / 2;
  12512. }
  12513. /**
  12514. * 三次贝塞尔曲线描边包含判断
  12515. * @param {number} x0
  12516. * @param {number} y0
  12517. * @param {number} x1
  12518. * @param {number} y1
  12519. * @param {number} x2
  12520. * @param {number} y2
  12521. * @param {number} x3
  12522. * @param {number} y3
  12523. * @param {number} lineWidth
  12524. * @param {number} x
  12525. * @param {number} y
  12526. * @return {boolean}
  12527. */
  12528. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12529. if (lineWidth === 0) {
  12530. return false;
  12531. }
  12532. var _l = lineWidth;
  12533. // Quick reject
  12534. if (
  12535. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12536. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12537. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12538. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12539. ) {
  12540. return false;
  12541. }
  12542. var d = cubicProjectPoint(
  12543. x0, y0, x1, y1, x2, y2, x3, y3,
  12544. x, y, null
  12545. );
  12546. return d <= _l / 2;
  12547. }
  12548. /**
  12549. * 二次贝塞尔曲线描边包含判断
  12550. * @param {number} x0
  12551. * @param {number} y0
  12552. * @param {number} x1
  12553. * @param {number} y1
  12554. * @param {number} x2
  12555. * @param {number} y2
  12556. * @param {number} lineWidth
  12557. * @param {number} x
  12558. * @param {number} y
  12559. * @return {boolean}
  12560. */
  12561. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12562. if (lineWidth === 0) {
  12563. return false;
  12564. }
  12565. var _l = lineWidth;
  12566. // Quick reject
  12567. if (
  12568. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12569. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12570. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12571. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12572. ) {
  12573. return false;
  12574. }
  12575. var d = quadraticProjectPoint(
  12576. x0, y0, x1, y1, x2, y2,
  12577. x, y, null
  12578. );
  12579. return d <= _l / 2;
  12580. }
  12581. var PI2$3 = Math.PI * 2;
  12582. function normalizeRadian(angle) {
  12583. angle %= PI2$3;
  12584. if (angle < 0) {
  12585. angle += PI2$3;
  12586. }
  12587. return angle;
  12588. }
  12589. var PI2$2 = Math.PI * 2;
  12590. /**
  12591. * 圆弧描边包含判断
  12592. * @param {number} cx
  12593. * @param {number} cy
  12594. * @param {number} r
  12595. * @param {number} startAngle
  12596. * @param {number} endAngle
  12597. * @param {boolean} anticlockwise
  12598. * @param {number} lineWidth
  12599. * @param {number} x
  12600. * @param {number} y
  12601. * @return {Boolean}
  12602. */
  12603. function containStroke$4(
  12604. cx, cy, r, startAngle, endAngle, anticlockwise,
  12605. lineWidth, x, y
  12606. ) {
  12607. if (lineWidth === 0) {
  12608. return false;
  12609. }
  12610. var _l = lineWidth;
  12611. x -= cx;
  12612. y -= cy;
  12613. var d = Math.sqrt(x * x + y * y);
  12614. if ((d - _l > r) || (d + _l < r)) {
  12615. return false;
  12616. }
  12617. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12618. // Is a circle
  12619. return true;
  12620. }
  12621. if (anticlockwise) {
  12622. var tmp = startAngle;
  12623. startAngle = normalizeRadian(endAngle);
  12624. endAngle = normalizeRadian(tmp);
  12625. }
  12626. else {
  12627. startAngle = normalizeRadian(startAngle);
  12628. endAngle = normalizeRadian(endAngle);
  12629. }
  12630. if (startAngle > endAngle) {
  12631. endAngle += PI2$2;
  12632. }
  12633. var angle = Math.atan2(y, x);
  12634. if (angle < 0) {
  12635. angle += PI2$2;
  12636. }
  12637. return (angle >= startAngle && angle <= endAngle)
  12638. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12639. }
  12640. function windingLine(x0, y0, x1, y1, x, y) {
  12641. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12642. return 0;
  12643. }
  12644. // Ignore horizontal line
  12645. if (y1 === y0) {
  12646. return 0;
  12647. }
  12648. var dir = y1 < y0 ? 1 : -1;
  12649. var t = (y - y0) / (y1 - y0);
  12650. // Avoid winding error when intersection point is the connect point of two line of polygon
  12651. if (t === 1 || t === 0) {
  12652. dir = y1 < y0 ? 0.5 : -0.5;
  12653. }
  12654. var x_ = t * (x1 - x0) + x0;
  12655. // If (x, y) on the line, considered as "contain".
  12656. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12657. }
  12658. var CMD$1 = PathProxy.CMD;
  12659. var PI2$1 = Math.PI * 2;
  12660. var EPSILON$2 = 1e-4;
  12661. function isAroundEqual(a, b) {
  12662. return Math.abs(a - b) < EPSILON$2;
  12663. }
  12664. // 临时数组
  12665. var roots = [-1, -1, -1];
  12666. var extrema = [-1, -1];
  12667. function swapExtrema() {
  12668. var tmp = extrema[0];
  12669. extrema[0] = extrema[1];
  12670. extrema[1] = tmp;
  12671. }
  12672. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12673. // Quick reject
  12674. if (
  12675. (y > y0 && y > y1 && y > y2 && y > y3)
  12676. || (y < y0 && y < y1 && y < y2 && y < y3)
  12677. ) {
  12678. return 0;
  12679. }
  12680. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12681. if (nRoots === 0) {
  12682. return 0;
  12683. }
  12684. else {
  12685. var w = 0;
  12686. var nExtrema = -1;
  12687. var y0_;
  12688. var y1_;
  12689. for (var i = 0; i < nRoots; i++) {
  12690. var t = roots[i];
  12691. // Avoid winding error when intersection point is the connect point of two line of polygon
  12692. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12693. var x_ = cubicAt(x0, x1, x2, x3, t);
  12694. if (x_ < x) { // Quick reject
  12695. continue;
  12696. }
  12697. if (nExtrema < 0) {
  12698. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12699. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12700. swapExtrema();
  12701. }
  12702. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12703. if (nExtrema > 1) {
  12704. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12705. }
  12706. }
  12707. if (nExtrema === 2) {
  12708. // 分成三段单调函数
  12709. if (t < extrema[0]) {
  12710. w += y0_ < y0 ? unit : -unit;
  12711. }
  12712. else if (t < extrema[1]) {
  12713. w += y1_ < y0_ ? unit : -unit;
  12714. }
  12715. else {
  12716. w += y3 < y1_ ? unit : -unit;
  12717. }
  12718. }
  12719. else {
  12720. // 分成两段单调函数
  12721. if (t < extrema[0]) {
  12722. w += y0_ < y0 ? unit : -unit;
  12723. }
  12724. else {
  12725. w += y3 < y0_ ? unit : -unit;
  12726. }
  12727. }
  12728. }
  12729. return w;
  12730. }
  12731. }
  12732. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12733. // Quick reject
  12734. if (
  12735. (y > y0 && y > y1 && y > y2)
  12736. || (y < y0 && y < y1 && y < y2)
  12737. ) {
  12738. return 0;
  12739. }
  12740. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12741. if (nRoots === 0) {
  12742. return 0;
  12743. }
  12744. else {
  12745. var t = quadraticExtremum(y0, y1, y2);
  12746. if (t >= 0 && t <= 1) {
  12747. var w = 0;
  12748. var y_ = quadraticAt(y0, y1, y2, t);
  12749. for (var i = 0; i < nRoots; i++) {
  12750. // Remove one endpoint.
  12751. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12752. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12753. if (x_ < x) { // Quick reject
  12754. continue;
  12755. }
  12756. if (roots[i] < t) {
  12757. w += y_ < y0 ? unit : -unit;
  12758. }
  12759. else {
  12760. w += y2 < y_ ? unit : -unit;
  12761. }
  12762. }
  12763. return w;
  12764. }
  12765. else {
  12766. // Remove one endpoint.
  12767. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12768. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12769. if (x_ < x) { // Quick reject
  12770. return 0;
  12771. }
  12772. return y2 < y0 ? unit : -unit;
  12773. }
  12774. }
  12775. }
  12776. // TODO
  12777. // Arc 旋转
  12778. function windingArc(
  12779. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12780. ) {
  12781. y -= cy;
  12782. if (y > r || y < -r) {
  12783. return 0;
  12784. }
  12785. var tmp = Math.sqrt(r * r - y * y);
  12786. roots[0] = -tmp;
  12787. roots[1] = tmp;
  12788. var diff = Math.abs(startAngle - endAngle);
  12789. if (diff < 1e-4) {
  12790. return 0;
  12791. }
  12792. if (diff % PI2$1 < 1e-4) {
  12793. // Is a circle
  12794. startAngle = 0;
  12795. endAngle = PI2$1;
  12796. var dir = anticlockwise ? 1 : -1;
  12797. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12798. return dir;
  12799. }
  12800. else {
  12801. return 0;
  12802. }
  12803. }
  12804. if (anticlockwise) {
  12805. var tmp = startAngle;
  12806. startAngle = normalizeRadian(endAngle);
  12807. endAngle = normalizeRadian(tmp);
  12808. }
  12809. else {
  12810. startAngle = normalizeRadian(startAngle);
  12811. endAngle = normalizeRadian(endAngle);
  12812. }
  12813. if (startAngle > endAngle) {
  12814. endAngle += PI2$1;
  12815. }
  12816. var w = 0;
  12817. for (var i = 0; i < 2; i++) {
  12818. var x_ = roots[i];
  12819. if (x_ + cx > x) {
  12820. var angle = Math.atan2(y, x_);
  12821. var dir = anticlockwise ? 1 : -1;
  12822. if (angle < 0) {
  12823. angle = PI2$1 + angle;
  12824. }
  12825. if (
  12826. (angle >= startAngle && angle <= endAngle)
  12827. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12828. ) {
  12829. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12830. dir = -dir;
  12831. }
  12832. w += dir;
  12833. }
  12834. }
  12835. }
  12836. return w;
  12837. }
  12838. function containPath(data, lineWidth, isStroke, x, y) {
  12839. var w = 0;
  12840. var xi = 0;
  12841. var yi = 0;
  12842. var x0 = 0;
  12843. var y0 = 0;
  12844. for (var i = 0; i < data.length;) {
  12845. var cmd = data[i++];
  12846. // Begin a new subpath
  12847. if (cmd === CMD$1.M && i > 1) {
  12848. // Close previous subpath
  12849. if (!isStroke) {
  12850. w += windingLine(xi, yi, x0, y0, x, y);
  12851. }
  12852. // 如果被任何一个 subpath 包含
  12853. // if (w !== 0) {
  12854. // return true;
  12855. // }
  12856. }
  12857. if (i === 1) {
  12858. // 如果第一个命令是 L, C, Q
  12859. // 则 previous point 同绘制命令的第一个 point
  12860. //
  12861. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12862. xi = data[i];
  12863. yi = data[i + 1];
  12864. x0 = xi;
  12865. y0 = yi;
  12866. }
  12867. switch (cmd) {
  12868. case CMD$1.M:
  12869. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12870. // 在 closePath 的时候使用
  12871. x0 = data[i++];
  12872. y0 = data[i++];
  12873. xi = x0;
  12874. yi = y0;
  12875. break;
  12876. case CMD$1.L:
  12877. if (isStroke) {
  12878. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12879. return true;
  12880. }
  12881. }
  12882. else {
  12883. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12884. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12885. }
  12886. xi = data[i++];
  12887. yi = data[i++];
  12888. break;
  12889. case CMD$1.C:
  12890. if (isStroke) {
  12891. if (containStroke$2(xi, yi,
  12892. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12893. lineWidth, x, y
  12894. )) {
  12895. return true;
  12896. }
  12897. }
  12898. else {
  12899. w += windingCubic(
  12900. xi, yi,
  12901. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12902. x, y
  12903. ) || 0;
  12904. }
  12905. xi = data[i++];
  12906. yi = data[i++];
  12907. break;
  12908. case CMD$1.Q:
  12909. if (isStroke) {
  12910. if (containStroke$3(xi, yi,
  12911. data[i++], data[i++], data[i], data[i + 1],
  12912. lineWidth, x, y
  12913. )) {
  12914. return true;
  12915. }
  12916. }
  12917. else {
  12918. w += windingQuadratic(
  12919. xi, yi,
  12920. data[i++], data[i++], data[i], data[i + 1],
  12921. x, y
  12922. ) || 0;
  12923. }
  12924. xi = data[i++];
  12925. yi = data[i++];
  12926. break;
  12927. case CMD$1.A:
  12928. // TODO Arc 判断的开销比较大
  12929. var cx = data[i++];
  12930. var cy = data[i++];
  12931. var rx = data[i++];
  12932. var ry = data[i++];
  12933. var theta = data[i++];
  12934. var dTheta = data[i++];
  12935. // TODO Arc 旋转
  12936. i += 1;
  12937. var anticlockwise = 1 - data[i++];
  12938. var x1 = Math.cos(theta) * rx + cx;
  12939. var y1 = Math.sin(theta) * ry + cy;
  12940. // 不是直接使用 arc 命令
  12941. if (i > 1) {
  12942. w += windingLine(xi, yi, x1, y1, x, y);
  12943. }
  12944. else {
  12945. // 第一个命令起点还未定义
  12946. x0 = x1;
  12947. y0 = y1;
  12948. }
  12949. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12950. var _x = (x - cx) * ry / rx + cx;
  12951. if (isStroke) {
  12952. if (containStroke$4(
  12953. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12954. lineWidth, _x, y
  12955. )) {
  12956. return true;
  12957. }
  12958. }
  12959. else {
  12960. w += windingArc(
  12961. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12962. _x, y
  12963. );
  12964. }
  12965. xi = Math.cos(theta + dTheta) * rx + cx;
  12966. yi = Math.sin(theta + dTheta) * ry + cy;
  12967. break;
  12968. case CMD$1.R:
  12969. x0 = xi = data[i++];
  12970. y0 = yi = data[i++];
  12971. var width = data[i++];
  12972. var height = data[i++];
  12973. var x1 = x0 + width;
  12974. var y1 = y0 + height;
  12975. if (isStroke) {
  12976. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12977. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12978. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12979. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12980. ) {
  12981. return true;
  12982. }
  12983. }
  12984. else {
  12985. // FIXME Clockwise ?
  12986. w += windingLine(x1, y0, x1, y1, x, y);
  12987. w += windingLine(x0, y1, x0, y0, x, y);
  12988. }
  12989. break;
  12990. case CMD$1.Z:
  12991. if (isStroke) {
  12992. if (containStroke$1(
  12993. xi, yi, x0, y0, lineWidth, x, y
  12994. )) {
  12995. return true;
  12996. }
  12997. }
  12998. else {
  12999. // Close a subpath
  13000. w += windingLine(xi, yi, x0, y0, x, y);
  13001. // 如果被任何一个 subpath 包含
  13002. // FIXME subpaths may overlap
  13003. // if (w !== 0) {
  13004. // return true;
  13005. // }
  13006. }
  13007. xi = x0;
  13008. yi = y0;
  13009. break;
  13010. }
  13011. }
  13012. if (!isStroke && !isAroundEqual(yi, y0)) {
  13013. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  13014. }
  13015. return w !== 0;
  13016. }
  13017. function contain(pathData, x, y) {
  13018. return containPath(pathData, 0, false, x, y);
  13019. }
  13020. function containStroke(pathData, lineWidth, x, y) {
  13021. return containPath(pathData, lineWidth, true, x, y);
  13022. }
  13023. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  13024. var abs = Math.abs;
  13025. var pathProxyForDraw = new PathProxy(true);
  13026. /**
  13027. * @alias module:zrender/graphic/Path
  13028. * @extends module:zrender/graphic/Displayable
  13029. * @constructor
  13030. * @param {Object} opts
  13031. */
  13032. function Path(opts) {
  13033. Displayable.call(this, opts);
  13034. /**
  13035. * @type {module:zrender/core/PathProxy}
  13036. * @readOnly
  13037. */
  13038. this.path = null;
  13039. }
  13040. Path.prototype = {
  13041. constructor: Path,
  13042. type: 'path',
  13043. __dirtyPath: true,
  13044. strokeContainThreshold: 5,
  13045. // This item default to be false. But in map series in echarts,
  13046. // in order to improve performance, it should be set to true,
  13047. // so the shorty segment won't draw.
  13048. segmentIgnoreThreshold: 0,
  13049. /**
  13050. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  13051. * @type {boolean}
  13052. */
  13053. subPixelOptimize: false,
  13054. brush: function (ctx, prevEl) {
  13055. var style = this.style;
  13056. var path = this.path || pathProxyForDraw;
  13057. var hasStroke = style.hasStroke();
  13058. var hasFill = style.hasFill();
  13059. var fill = style.fill;
  13060. var stroke = style.stroke;
  13061. var hasFillGradient = hasFill && !!(fill.colorStops);
  13062. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  13063. var hasFillPattern = hasFill && !!(fill.image);
  13064. var hasStrokePattern = hasStroke && !!(stroke.image);
  13065. style.bind(ctx, this, prevEl);
  13066. this.setTransform(ctx);
  13067. if (this.__dirty) {
  13068. var rect;
  13069. // Update gradient because bounding rect may changed
  13070. if (hasFillGradient) {
  13071. rect = rect || this.getBoundingRect();
  13072. this._fillGradient = style.getGradient(ctx, fill, rect);
  13073. }
  13074. if (hasStrokeGradient) {
  13075. rect = rect || this.getBoundingRect();
  13076. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  13077. }
  13078. }
  13079. // Use the gradient or pattern
  13080. if (hasFillGradient) {
  13081. // PENDING If may have affect the state
  13082. ctx.fillStyle = this._fillGradient;
  13083. }
  13084. else if (hasFillPattern) {
  13085. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  13086. }
  13087. if (hasStrokeGradient) {
  13088. ctx.strokeStyle = this._strokeGradient;
  13089. }
  13090. else if (hasStrokePattern) {
  13091. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  13092. }
  13093. var lineDash = style.lineDash;
  13094. var lineDashOffset = style.lineDashOffset;
  13095. var ctxLineDash = !!ctx.setLineDash;
  13096. // Update path sx, sy
  13097. var scale = this.getGlobalScale();
  13098. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  13099. // Proxy context
  13100. // Rebuild path in following 2 cases
  13101. // 1. Path is dirty
  13102. // 2. Path needs javascript implemented lineDash stroking.
  13103. // In this case, lineDash information will not be saved in PathProxy
  13104. if (this.__dirtyPath
  13105. || (lineDash && !ctxLineDash && hasStroke)
  13106. ) {
  13107. path.beginPath(ctx);
  13108. // Setting line dash before build path
  13109. if (lineDash && !ctxLineDash) {
  13110. path.setLineDash(lineDash);
  13111. path.setLineDashOffset(lineDashOffset);
  13112. }
  13113. this.buildPath(path, this.shape, false);
  13114. // Clear path dirty flag
  13115. if (this.path) {
  13116. this.__dirtyPath = false;
  13117. }
  13118. }
  13119. else {
  13120. // Replay path building
  13121. ctx.beginPath();
  13122. this.path.rebuildPath(ctx);
  13123. }
  13124. if (hasFill) {
  13125. if (style.fillOpacity != null) {
  13126. var originalGlobalAlpha = ctx.globalAlpha;
  13127. ctx.globalAlpha = style.fillOpacity * style.opacity;
  13128. path.fill(ctx);
  13129. ctx.globalAlpha = originalGlobalAlpha;
  13130. }
  13131. else {
  13132. path.fill(ctx);
  13133. }
  13134. }
  13135. if (lineDash && ctxLineDash) {
  13136. ctx.setLineDash(lineDash);
  13137. ctx.lineDashOffset = lineDashOffset;
  13138. }
  13139. if (hasStroke) {
  13140. if (style.strokeOpacity != null) {
  13141. var originalGlobalAlpha = ctx.globalAlpha;
  13142. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  13143. path.stroke(ctx);
  13144. ctx.globalAlpha = originalGlobalAlpha;
  13145. }
  13146. else {
  13147. path.stroke(ctx);
  13148. }
  13149. }
  13150. if (lineDash && ctxLineDash) {
  13151. // PENDING
  13152. // Remove lineDash
  13153. ctx.setLineDash([]);
  13154. }
  13155. // Draw rect text
  13156. if (style.text != null) {
  13157. // Only restore transform when needs draw text.
  13158. this.restoreTransform(ctx);
  13159. this.drawRectText(ctx, this.getBoundingRect());
  13160. }
  13161. },
  13162. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  13163. // Like in circle
  13164. buildPath: function (ctx, shapeCfg, inBundle) {},
  13165. createPathProxy: function () {
  13166. this.path = new PathProxy();
  13167. },
  13168. getBoundingRect: function () {
  13169. var rect = this._rect;
  13170. var style = this.style;
  13171. var needsUpdateRect = !rect;
  13172. if (needsUpdateRect) {
  13173. var path = this.path;
  13174. if (!path) {
  13175. // Create path on demand.
  13176. path = this.path = new PathProxy();
  13177. }
  13178. if (this.__dirtyPath) {
  13179. path.beginPath();
  13180. this.buildPath(path, this.shape, false);
  13181. }
  13182. rect = path.getBoundingRect();
  13183. }
  13184. this._rect = rect;
  13185. if (style.hasStroke()) {
  13186. // Needs update rect with stroke lineWidth when
  13187. // 1. Element changes scale or lineWidth
  13188. // 2. Shape is changed
  13189. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  13190. if (this.__dirty || needsUpdateRect) {
  13191. rectWithStroke.copy(rect);
  13192. // FIXME Must after updateTransform
  13193. var w = style.lineWidth;
  13194. // PENDING, Min line width is needed when line is horizontal or vertical
  13195. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13196. // Only add extra hover lineWidth when there are no fill
  13197. if (!style.hasFill()) {
  13198. w = Math.max(w, this.strokeContainThreshold || 4);
  13199. }
  13200. // Consider line width
  13201. // Line scale can't be 0;
  13202. if (lineScale > 1e-10) {
  13203. rectWithStroke.width += w / lineScale;
  13204. rectWithStroke.height += w / lineScale;
  13205. rectWithStroke.x -= w / lineScale / 2;
  13206. rectWithStroke.y -= w / lineScale / 2;
  13207. }
  13208. }
  13209. // Return rect with stroke
  13210. return rectWithStroke;
  13211. }
  13212. return rect;
  13213. },
  13214. contain: function (x, y) {
  13215. var localPos = this.transformCoordToLocal(x, y);
  13216. var rect = this.getBoundingRect();
  13217. var style = this.style;
  13218. x = localPos[0];
  13219. y = localPos[1];
  13220. if (rect.contain(x, y)) {
  13221. var pathData = this.path.data;
  13222. if (style.hasStroke()) {
  13223. var lineWidth = style.lineWidth;
  13224. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13225. // Line scale can't be 0;
  13226. if (lineScale > 1e-10) {
  13227. // Only add extra hover lineWidth when there are no fill
  13228. if (!style.hasFill()) {
  13229. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  13230. }
  13231. if (containStroke(
  13232. pathData, lineWidth / lineScale, x, y
  13233. )) {
  13234. return true;
  13235. }
  13236. }
  13237. }
  13238. if (style.hasFill()) {
  13239. return contain(pathData, x, y);
  13240. }
  13241. }
  13242. return false;
  13243. },
  13244. /**
  13245. * @param {boolean} dirtyPath
  13246. */
  13247. dirty: function (dirtyPath) {
  13248. if (dirtyPath == null) {
  13249. dirtyPath = true;
  13250. }
  13251. // Only mark dirty, not mark clean
  13252. if (dirtyPath) {
  13253. this.__dirtyPath = dirtyPath;
  13254. this._rect = null;
  13255. }
  13256. this.__dirty = this.__dirtyText = true;
  13257. this.__zr && this.__zr.refresh();
  13258. // Used as a clipping path
  13259. if (this.__clipTarget) {
  13260. this.__clipTarget.dirty();
  13261. }
  13262. },
  13263. /**
  13264. * Alias for animate('shape')
  13265. * @param {boolean} loop
  13266. */
  13267. animateShape: function (loop) {
  13268. return this.animate('shape', loop);
  13269. },
  13270. // Overwrite attrKV
  13271. attrKV: function (key, value) {
  13272. // FIXME
  13273. if (key === 'shape') {
  13274. this.setShape(value);
  13275. this.__dirtyPath = true;
  13276. this._rect = null;
  13277. }
  13278. else {
  13279. Displayable.prototype.attrKV.call(this, key, value);
  13280. }
  13281. },
  13282. /**
  13283. * @param {Object|string} key
  13284. * @param {*} value
  13285. */
  13286. setShape: function (key, value) {
  13287. var shape = this.shape;
  13288. // Path from string may not have shape
  13289. if (shape) {
  13290. if (isObject$1(key)) {
  13291. for (var name in key) {
  13292. if (key.hasOwnProperty(name)) {
  13293. shape[name] = key[name];
  13294. }
  13295. }
  13296. }
  13297. else {
  13298. shape[key] = value;
  13299. }
  13300. this.dirty(true);
  13301. }
  13302. return this;
  13303. },
  13304. getLineScale: function () {
  13305. var m = this.transform;
  13306. // Get the line scale.
  13307. // Determinant of `m` means how much the area is enlarged by the
  13308. // transformation. So its square root can be used as a scale factor
  13309. // for width.
  13310. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  13311. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  13312. : 1;
  13313. }
  13314. };
  13315. /**
  13316. * 扩展一个 Path element, 比如星形,圆等。
  13317. * Extend a path element
  13318. * @param {Object} props
  13319. * @param {string} props.type Path type
  13320. * @param {Function} props.init Initialize
  13321. * @param {Function} props.buildPath Overwrite buildPath method
  13322. * @param {Object} [props.style] Extended default style config
  13323. * @param {Object} [props.shape] Extended default shape config
  13324. */
  13325. Path.extend = function (defaults$$1) {
  13326. var Sub = function (opts) {
  13327. Path.call(this, opts);
  13328. if (defaults$$1.style) {
  13329. // Extend default style
  13330. this.style.extendFrom(defaults$$1.style, false);
  13331. }
  13332. // Extend default shape
  13333. var defaultShape = defaults$$1.shape;
  13334. if (defaultShape) {
  13335. this.shape = this.shape || {};
  13336. var thisShape = this.shape;
  13337. for (var name in defaultShape) {
  13338. if (
  13339. !thisShape.hasOwnProperty(name)
  13340. && defaultShape.hasOwnProperty(name)
  13341. ) {
  13342. thisShape[name] = defaultShape[name];
  13343. }
  13344. }
  13345. }
  13346. defaults$$1.init && defaults$$1.init.call(this, opts);
  13347. };
  13348. inherits(Sub, Path);
  13349. // FIXME 不能 extend position, rotation 等引用对象
  13350. for (var name in defaults$$1) {
  13351. // Extending prototype values and methods
  13352. if (name !== 'style' && name !== 'shape') {
  13353. Sub.prototype[name] = defaults$$1[name];
  13354. }
  13355. }
  13356. return Sub;
  13357. };
  13358. inherits(Path, Displayable);
  13359. var CMD$2 = PathProxy.CMD;
  13360. var points = [[], [], []];
  13361. var mathSqrt$3 = Math.sqrt;
  13362. var mathAtan2 = Math.atan2;
  13363. var transformPath = function (path, m) {
  13364. var data = path.data;
  13365. var cmd;
  13366. var nPoint;
  13367. var i;
  13368. var j;
  13369. var k;
  13370. var p;
  13371. var M = CMD$2.M;
  13372. var C = CMD$2.C;
  13373. var L = CMD$2.L;
  13374. var R = CMD$2.R;
  13375. var A = CMD$2.A;
  13376. var Q = CMD$2.Q;
  13377. for (i = 0, j = 0; i < data.length;) {
  13378. cmd = data[i++];
  13379. j = i;
  13380. nPoint = 0;
  13381. switch (cmd) {
  13382. case M:
  13383. nPoint = 1;
  13384. break;
  13385. case L:
  13386. nPoint = 1;
  13387. break;
  13388. case C:
  13389. nPoint = 3;
  13390. break;
  13391. case Q:
  13392. nPoint = 2;
  13393. break;
  13394. case A:
  13395. var x = m[4];
  13396. var y = m[5];
  13397. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  13398. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  13399. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13400. // cx
  13401. data[i] *= sx;
  13402. data[i++] += x;
  13403. // cy
  13404. data[i] *= sy;
  13405. data[i++] += y;
  13406. // Scale rx and ry
  13407. // FIXME Assume psi is 0 here
  13408. data[i++] *= sx;
  13409. data[i++] *= sy;
  13410. // Start angle
  13411. data[i++] += angle;
  13412. // end angle
  13413. data[i++] += angle;
  13414. // FIXME psi
  13415. i += 2;
  13416. j = i;
  13417. break;
  13418. case R:
  13419. // x0, y0
  13420. p[0] = data[i++];
  13421. p[1] = data[i++];
  13422. applyTransform(p, p, m);
  13423. data[j++] = p[0];
  13424. data[j++] = p[1];
  13425. // x1, y1
  13426. p[0] += data[i++];
  13427. p[1] += data[i++];
  13428. applyTransform(p, p, m);
  13429. data[j++] = p[0];
  13430. data[j++] = p[1];
  13431. }
  13432. for (k = 0; k < nPoint; k++) {
  13433. var p = points[k];
  13434. p[0] = data[i++];
  13435. p[1] = data[i++];
  13436. applyTransform(p, p, m);
  13437. // Write back
  13438. data[j++] = p[0];
  13439. data[j++] = p[1];
  13440. }
  13441. }
  13442. };
  13443. // command chars
  13444. // var cc = [
  13445. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  13446. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  13447. // ];
  13448. var mathSqrt = Math.sqrt;
  13449. var mathSin = Math.sin;
  13450. var mathCos = Math.cos;
  13451. var PI = Math.PI;
  13452. var vMag = function (v) {
  13453. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13454. };
  13455. var vRatio = function (u, v) {
  13456. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13457. };
  13458. var vAngle = function (u, v) {
  13459. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13460. * Math.acos(vRatio(u, v));
  13461. };
  13462. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13463. var psi = psiDeg * (PI / 180.0);
  13464. var xp = mathCos(psi) * (x1 - x2) / 2.0
  13465. + mathSin(psi) * (y1 - y2) / 2.0;
  13466. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  13467. + mathCos(psi) * (y1 - y2) / 2.0;
  13468. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13469. if (lambda > 1) {
  13470. rx *= mathSqrt(lambda);
  13471. ry *= mathSqrt(lambda);
  13472. }
  13473. var f = (fa === fs ? -1 : 1)
  13474. * mathSqrt((((rx * rx) * (ry * ry))
  13475. - ((rx * rx) * (yp * yp))
  13476. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13477. + (ry * ry) * (xp * xp))
  13478. ) || 0;
  13479. var cxp = f * rx * yp / ry;
  13480. var cyp = f * -ry * xp / rx;
  13481. var cx = (x1 + x2) / 2.0
  13482. + mathCos(psi) * cxp
  13483. - mathSin(psi) * cyp;
  13484. var cy = (y1 + y2) / 2.0
  13485. + mathSin(psi) * cxp
  13486. + mathCos(psi) * cyp;
  13487. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  13488. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  13489. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  13490. var dTheta = vAngle(u, v);
  13491. if (vRatio(u, v) <= -1) {
  13492. dTheta = PI;
  13493. }
  13494. if (vRatio(u, v) >= 1) {
  13495. dTheta = 0;
  13496. }
  13497. if (fs === 0 && dTheta > 0) {
  13498. dTheta = dTheta - 2 * PI;
  13499. }
  13500. if (fs === 1 && dTheta < 0) {
  13501. dTheta = dTheta + 2 * PI;
  13502. }
  13503. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13504. }
  13505. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13506. // Consider case:
  13507. // (1) delimiter can be comma or space, where continuous commas
  13508. // or spaces should be seen as one comma.
  13509. // (2) value can be like:
  13510. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13511. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13512. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13513. // var valueSplitReg = /[\s,]+/;
  13514. function createPathProxyFromString(data) {
  13515. if (!data) {
  13516. return new PathProxy();
  13517. }
  13518. // var data = data.replace(/-/g, ' -')
  13519. // .replace(/ /g, ' ')
  13520. // .replace(/ /g, ',')
  13521. // .replace(/,,/g, ',');
  13522. // var n;
  13523. // create pipes so that we can split the data
  13524. // for (n = 0; n < cc.length; n++) {
  13525. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13526. // }
  13527. // data = data.replace(/-/g, ',-');
  13528. // create array
  13529. // var arr = cs.split('|');
  13530. // init context point
  13531. var cpx = 0;
  13532. var cpy = 0;
  13533. var subpathX = cpx;
  13534. var subpathY = cpy;
  13535. var prevCmd;
  13536. var path = new PathProxy();
  13537. var CMD = PathProxy.CMD;
  13538. // commandReg.lastIndex = 0;
  13539. // var cmdResult;
  13540. // while ((cmdResult = commandReg.exec(data)) != null) {
  13541. // var cmdStr = cmdResult[1];
  13542. // var cmdContent = cmdResult[2];
  13543. var cmdList = data.match(commandReg);
  13544. for (var l = 0; l < cmdList.length; l++) {
  13545. var cmdText = cmdList[l];
  13546. var cmdStr = cmdText.charAt(0);
  13547. var cmd;
  13548. // String#split is faster a little bit than String#replace or RegExp#exec.
  13549. // var p = cmdContent.split(valueSplitReg);
  13550. // var pLen = 0;
  13551. // for (var i = 0; i < p.length; i++) {
  13552. // // '' and other invalid str => NaN
  13553. // var val = parseFloat(p[i]);
  13554. // !isNaN(val) && (p[pLen++] = val);
  13555. // }
  13556. var p = cmdText.match(numberReg) || [];
  13557. var pLen = p.length;
  13558. for (var i = 0; i < pLen; i++) {
  13559. p[i] = parseFloat(p[i]);
  13560. }
  13561. var off = 0;
  13562. while (off < pLen) {
  13563. var ctlPtx;
  13564. var ctlPty;
  13565. var rx;
  13566. var ry;
  13567. var psi;
  13568. var fa;
  13569. var fs;
  13570. var x1 = cpx;
  13571. var y1 = cpy;
  13572. // convert l, H, h, V, and v to L
  13573. switch (cmdStr) {
  13574. case 'l':
  13575. cpx += p[off++];
  13576. cpy += p[off++];
  13577. cmd = CMD.L;
  13578. path.addData(cmd, cpx, cpy);
  13579. break;
  13580. case 'L':
  13581. cpx = p[off++];
  13582. cpy = p[off++];
  13583. cmd = CMD.L;
  13584. path.addData(cmd, cpx, cpy);
  13585. break;
  13586. case 'm':
  13587. cpx += p[off++];
  13588. cpy += p[off++];
  13589. cmd = CMD.M;
  13590. path.addData(cmd, cpx, cpy);
  13591. subpathX = cpx;
  13592. subpathY = cpy;
  13593. cmdStr = 'l';
  13594. break;
  13595. case 'M':
  13596. cpx = p[off++];
  13597. cpy = p[off++];
  13598. cmd = CMD.M;
  13599. path.addData(cmd, cpx, cpy);
  13600. subpathX = cpx;
  13601. subpathY = cpy;
  13602. cmdStr = 'L';
  13603. break;
  13604. case 'h':
  13605. cpx += p[off++];
  13606. cmd = CMD.L;
  13607. path.addData(cmd, cpx, cpy);
  13608. break;
  13609. case 'H':
  13610. cpx = p[off++];
  13611. cmd = CMD.L;
  13612. path.addData(cmd, cpx, cpy);
  13613. break;
  13614. case 'v':
  13615. cpy += p[off++];
  13616. cmd = CMD.L;
  13617. path.addData(cmd, cpx, cpy);
  13618. break;
  13619. case 'V':
  13620. cpy = p[off++];
  13621. cmd = CMD.L;
  13622. path.addData(cmd, cpx, cpy);
  13623. break;
  13624. case 'C':
  13625. cmd = CMD.C;
  13626. path.addData(
  13627. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13628. );
  13629. cpx = p[off - 2];
  13630. cpy = p[off - 1];
  13631. break;
  13632. case 'c':
  13633. cmd = CMD.C;
  13634. path.addData(
  13635. cmd,
  13636. p[off++] + cpx, p[off++] + cpy,
  13637. p[off++] + cpx, p[off++] + cpy,
  13638. p[off++] + cpx, p[off++] + cpy
  13639. );
  13640. cpx += p[off - 2];
  13641. cpy += p[off - 1];
  13642. break;
  13643. case 'S':
  13644. ctlPtx = cpx;
  13645. ctlPty = cpy;
  13646. var len = path.len();
  13647. var pathData = path.data;
  13648. if (prevCmd === CMD.C) {
  13649. ctlPtx += cpx - pathData[len - 4];
  13650. ctlPty += cpy - pathData[len - 3];
  13651. }
  13652. cmd = CMD.C;
  13653. x1 = p[off++];
  13654. y1 = p[off++];
  13655. cpx = p[off++];
  13656. cpy = p[off++];
  13657. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13658. break;
  13659. case 's':
  13660. ctlPtx = cpx;
  13661. ctlPty = cpy;
  13662. var len = path.len();
  13663. var pathData = path.data;
  13664. if (prevCmd === CMD.C) {
  13665. ctlPtx += cpx - pathData[len - 4];
  13666. ctlPty += cpy - pathData[len - 3];
  13667. }
  13668. cmd = CMD.C;
  13669. x1 = cpx + p[off++];
  13670. y1 = cpy + p[off++];
  13671. cpx += p[off++];
  13672. cpy += p[off++];
  13673. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13674. break;
  13675. case 'Q':
  13676. x1 = p[off++];
  13677. y1 = p[off++];
  13678. cpx = p[off++];
  13679. cpy = p[off++];
  13680. cmd = CMD.Q;
  13681. path.addData(cmd, x1, y1, cpx, cpy);
  13682. break;
  13683. case 'q':
  13684. x1 = p[off++] + cpx;
  13685. y1 = p[off++] + cpy;
  13686. cpx += p[off++];
  13687. cpy += p[off++];
  13688. cmd = CMD.Q;
  13689. path.addData(cmd, x1, y1, cpx, cpy);
  13690. break;
  13691. case 'T':
  13692. ctlPtx = cpx;
  13693. ctlPty = cpy;
  13694. var len = path.len();
  13695. var pathData = path.data;
  13696. if (prevCmd === CMD.Q) {
  13697. ctlPtx += cpx - pathData[len - 4];
  13698. ctlPty += cpy - pathData[len - 3];
  13699. }
  13700. cpx = p[off++];
  13701. cpy = p[off++];
  13702. cmd = CMD.Q;
  13703. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13704. break;
  13705. case 't':
  13706. ctlPtx = cpx;
  13707. ctlPty = cpy;
  13708. var len = path.len();
  13709. var pathData = path.data;
  13710. if (prevCmd === CMD.Q) {
  13711. ctlPtx += cpx - pathData[len - 4];
  13712. ctlPty += cpy - pathData[len - 3];
  13713. }
  13714. cpx += p[off++];
  13715. cpy += p[off++];
  13716. cmd = CMD.Q;
  13717. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13718. break;
  13719. case 'A':
  13720. rx = p[off++];
  13721. ry = p[off++];
  13722. psi = p[off++];
  13723. fa = p[off++];
  13724. fs = p[off++];
  13725. x1 = cpx, y1 = cpy;
  13726. cpx = p[off++];
  13727. cpy = p[off++];
  13728. cmd = CMD.A;
  13729. processArc(
  13730. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13731. );
  13732. break;
  13733. case 'a':
  13734. rx = p[off++];
  13735. ry = p[off++];
  13736. psi = p[off++];
  13737. fa = p[off++];
  13738. fs = p[off++];
  13739. x1 = cpx, y1 = cpy;
  13740. cpx += p[off++];
  13741. cpy += p[off++];
  13742. cmd = CMD.A;
  13743. processArc(
  13744. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13745. );
  13746. break;
  13747. }
  13748. }
  13749. if (cmdStr === 'z' || cmdStr === 'Z') {
  13750. cmd = CMD.Z;
  13751. path.addData(cmd);
  13752. // z may be in the middle of the path.
  13753. cpx = subpathX;
  13754. cpy = subpathY;
  13755. }
  13756. prevCmd = cmd;
  13757. }
  13758. path.toStatic();
  13759. return path;
  13760. }
  13761. // TODO Optimize double memory cost problem
  13762. function createPathOptions(str, opts) {
  13763. var pathProxy = createPathProxyFromString(str);
  13764. opts = opts || {};
  13765. opts.buildPath = function (path) {
  13766. if (path.setData) {
  13767. path.setData(pathProxy.data);
  13768. // Svg and vml renderer don't have context
  13769. var ctx = path.getContext();
  13770. if (ctx) {
  13771. path.rebuildPath(ctx);
  13772. }
  13773. }
  13774. else {
  13775. var ctx = path;
  13776. pathProxy.rebuildPath(ctx);
  13777. }
  13778. };
  13779. opts.applyTransform = function (m) {
  13780. transformPath(pathProxy, m);
  13781. this.dirty(true);
  13782. };
  13783. return opts;
  13784. }
  13785. /**
  13786. * Create a Path object from path string data
  13787. * http://www.w3.org/TR/SVG/paths.html#PathData
  13788. * @param {Object} opts Other options
  13789. */
  13790. function createFromString(str, opts) {
  13791. return new Path(createPathOptions(str, opts));
  13792. }
  13793. /**
  13794. * Create a Path class from path string data
  13795. * @param {string} str
  13796. * @param {Object} opts Other options
  13797. */
  13798. function extendFromString(str, opts) {
  13799. return Path.extend(createPathOptions(str, opts));
  13800. }
  13801. /**
  13802. * Merge multiple paths
  13803. */
  13804. // TODO Apply transform
  13805. // TODO stroke dash
  13806. // TODO Optimize double memory cost problem
  13807. function mergePath$1(pathEls, opts) {
  13808. var pathList = [];
  13809. var len = pathEls.length;
  13810. for (var i = 0; i < len; i++) {
  13811. var pathEl = pathEls[i];
  13812. if (!pathEl.path) {
  13813. pathEl.createPathProxy();
  13814. }
  13815. if (pathEl.__dirtyPath) {
  13816. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13817. }
  13818. pathList.push(pathEl.path);
  13819. }
  13820. var pathBundle = new Path(opts);
  13821. // Need path proxy.
  13822. pathBundle.createPathProxy();
  13823. pathBundle.buildPath = function (path) {
  13824. path.appendPath(pathList);
  13825. // Svg and vml renderer don't have context
  13826. var ctx = path.getContext();
  13827. if (ctx) {
  13828. path.rebuildPath(ctx);
  13829. }
  13830. };
  13831. return pathBundle;
  13832. }
  13833. /**
  13834. * @alias zrender/graphic/Text
  13835. * @extends module:zrender/graphic/Displayable
  13836. * @constructor
  13837. * @param {Object} opts
  13838. */
  13839. var Text = function (opts) { // jshint ignore:line
  13840. Displayable.call(this, opts);
  13841. };
  13842. Text.prototype = {
  13843. constructor: Text,
  13844. type: 'text',
  13845. brush: function (ctx, prevEl) {
  13846. var style = this.style;
  13847. // Optimize, avoid normalize every time.
  13848. this.__dirty && normalizeTextStyle(style, true);
  13849. // Use props with prefix 'text'.
  13850. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13851. style.shadowOffsetX = style.shadowOffsetY = null;
  13852. var text = style.text;
  13853. // Convert to string
  13854. text != null && (text += '');
  13855. // Do not apply style.bind in Text node. Because the real bind job
  13856. // is in textHelper.renderText, and performance of text render should
  13857. // be considered.
  13858. // style.bind(ctx, this, prevEl);
  13859. if (!needDrawText(text, style)) {
  13860. // The current el.style is not applied
  13861. // and should not be used as cache.
  13862. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13863. return;
  13864. }
  13865. this.setTransform(ctx);
  13866. renderText(this, ctx, text, style, null, prevEl);
  13867. this.restoreTransform(ctx);
  13868. },
  13869. getBoundingRect: function () {
  13870. var style = this.style;
  13871. // Optimize, avoid normalize every time.
  13872. this.__dirty && normalizeTextStyle(style, true);
  13873. if (!this._rect) {
  13874. var text = style.text;
  13875. text != null ? (text += '') : (text = '');
  13876. var rect = getBoundingRect(
  13877. style.text + '',
  13878. style.font,
  13879. style.textAlign,
  13880. style.textVerticalAlign,
  13881. style.textPadding,
  13882. style.textLineHeight,
  13883. style.rich
  13884. );
  13885. rect.x += style.x || 0;
  13886. rect.y += style.y || 0;
  13887. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13888. var w = style.textStrokeWidth;
  13889. rect.x -= w / 2;
  13890. rect.y -= w / 2;
  13891. rect.width += w;
  13892. rect.height += w;
  13893. }
  13894. this._rect = rect;
  13895. }
  13896. return this._rect;
  13897. }
  13898. };
  13899. inherits(Text, Displayable);
  13900. /**
  13901. * 圆形
  13902. * @module zrender/shape/Circle
  13903. */
  13904. var Circle = Path.extend({
  13905. type: 'circle',
  13906. shape: {
  13907. cx: 0,
  13908. cy: 0,
  13909. r: 0
  13910. },
  13911. buildPath: function (ctx, shape, inBundle) {
  13912. // Better stroking in ShapeBundle
  13913. // Always do it may have performence issue ( fill may be 2x more cost)
  13914. if (inBundle) {
  13915. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13916. }
  13917. // else {
  13918. // if (ctx.allocate && !ctx.data.length) {
  13919. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13920. // }
  13921. // }
  13922. // Better stroking in ShapeBundle
  13923. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13924. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13925. }
  13926. });
  13927. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13928. // where exception "unexpected call to method or property access"
  13929. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13930. // whose area size is zero is drawn and ctx.clip() is called and
  13931. // shadowBlur is set. See #4572, #3112, #5777.
  13932. // (e.g.,
  13933. // ctx.moveTo(10, 10);
  13934. // ctx.lineTo(20, 10);
  13935. // ctx.closePath();
  13936. // ctx.clip();
  13937. // ctx.shadowBlur = 10;
  13938. // ...
  13939. // ctx.fill();
  13940. // )
  13941. var shadowTemp = [
  13942. ['shadowBlur', 0],
  13943. ['shadowColor', '#000'],
  13944. ['shadowOffsetX', 0],
  13945. ['shadowOffsetY', 0]
  13946. ];
  13947. var fixClipWithShadow = function (orignalBrush) {
  13948. // version string can be: '11.0'
  13949. return (env$1.browser.ie && env$1.browser.version >= 11)
  13950. ? function () {
  13951. var clipPaths = this.__clipPaths;
  13952. var style = this.style;
  13953. var modified;
  13954. if (clipPaths) {
  13955. for (var i = 0; i < clipPaths.length; i++) {
  13956. var clipPath = clipPaths[i];
  13957. var shape = clipPath && clipPath.shape;
  13958. var type = clipPath && clipPath.type;
  13959. if (shape && (
  13960. (type === 'sector' && shape.startAngle === shape.endAngle)
  13961. || (type === 'rect' && (!shape.width || !shape.height))
  13962. )) {
  13963. for (var j = 0; j < shadowTemp.length; j++) {
  13964. // It is save to put shadowTemp static, because shadowTemp
  13965. // will be all modified each item brush called.
  13966. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13967. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13968. }
  13969. modified = true;
  13970. break;
  13971. }
  13972. }
  13973. }
  13974. orignalBrush.apply(this, arguments);
  13975. if (modified) {
  13976. for (var j = 0; j < shadowTemp.length; j++) {
  13977. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13978. }
  13979. }
  13980. }
  13981. : orignalBrush;
  13982. };
  13983. /**
  13984. * 扇形
  13985. * @module zrender/graphic/shape/Sector
  13986. */
  13987. var Sector = Path.extend({
  13988. type: 'sector',
  13989. shape: {
  13990. cx: 0,
  13991. cy: 0,
  13992. r0: 0,
  13993. r: 0,
  13994. startAngle: 0,
  13995. endAngle: Math.PI * 2,
  13996. clockwise: true
  13997. },
  13998. brush: fixClipWithShadow(Path.prototype.brush),
  13999. buildPath: function (ctx, shape) {
  14000. var x = shape.cx;
  14001. var y = shape.cy;
  14002. var r0 = Math.max(shape.r0 || 0, 0);
  14003. var r = Math.max(shape.r, 0);
  14004. var startAngle = shape.startAngle;
  14005. var endAngle = shape.endAngle;
  14006. var clockwise = shape.clockwise;
  14007. var unitX = Math.cos(startAngle);
  14008. var unitY = Math.sin(startAngle);
  14009. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  14010. ctx.lineTo(unitX * r + x, unitY * r + y);
  14011. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14012. ctx.lineTo(
  14013. Math.cos(endAngle) * r0 + x,
  14014. Math.sin(endAngle) * r0 + y
  14015. );
  14016. if (r0 !== 0) {
  14017. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  14018. }
  14019. ctx.closePath();
  14020. }
  14021. });
  14022. /**
  14023. * 圆环
  14024. * @module zrender/graphic/shape/Ring
  14025. */
  14026. var Ring = Path.extend({
  14027. type: 'ring',
  14028. shape: {
  14029. cx: 0,
  14030. cy: 0,
  14031. r: 0,
  14032. r0: 0
  14033. },
  14034. buildPath: function (ctx, shape) {
  14035. var x = shape.cx;
  14036. var y = shape.cy;
  14037. var PI2 = Math.PI * 2;
  14038. ctx.moveTo(x + shape.r, y);
  14039. ctx.arc(x, y, shape.r, 0, PI2, false);
  14040. ctx.moveTo(x + shape.r0, y);
  14041. ctx.arc(x, y, shape.r0, 0, PI2, true);
  14042. }
  14043. });
  14044. /**
  14045. * Catmull-Rom spline 插值折线
  14046. * @module zrender/shape/util/smoothSpline
  14047. * @author pissang (https://www.github.com/pissang)
  14048. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14049. * errorrik (errorrik@gmail.com)
  14050. */
  14051. /**
  14052. * @inner
  14053. */
  14054. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  14055. var v0 = (p2 - p0) * 0.5;
  14056. var v1 = (p3 - p1) * 0.5;
  14057. return (2 * (p1 - p2) + v0 + v1) * t3
  14058. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  14059. + v0 * t + p1;
  14060. }
  14061. /**
  14062. * @alias module:zrender/shape/util/smoothSpline
  14063. * @param {Array} points 线段顶点数组
  14064. * @param {boolean} isLoop
  14065. * @return {Array}
  14066. */
  14067. var smoothSpline = function (points, isLoop) {
  14068. var len$$1 = points.length;
  14069. var ret = [];
  14070. var distance$$1 = 0;
  14071. for (var i = 1; i < len$$1; i++) {
  14072. distance$$1 += distance(points[i - 1], points[i]);
  14073. }
  14074. var segs = distance$$1 / 2;
  14075. segs = segs < len$$1 ? len$$1 : segs;
  14076. for (var i = 0; i < segs; i++) {
  14077. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  14078. var idx = Math.floor(pos);
  14079. var w = pos - idx;
  14080. var p0;
  14081. var p1 = points[idx % len$$1];
  14082. var p2;
  14083. var p3;
  14084. if (!isLoop) {
  14085. p0 = points[idx === 0 ? idx : idx - 1];
  14086. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  14087. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  14088. }
  14089. else {
  14090. p0 = points[(idx - 1 + len$$1) % len$$1];
  14091. p2 = points[(idx + 1) % len$$1];
  14092. p3 = points[(idx + 2) % len$$1];
  14093. }
  14094. var w2 = w * w;
  14095. var w3 = w * w2;
  14096. ret.push([
  14097. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  14098. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  14099. ]);
  14100. }
  14101. return ret;
  14102. };
  14103. /**
  14104. * 贝塞尔平滑曲线
  14105. * @module zrender/shape/util/smoothBezier
  14106. * @author pissang (https://www.github.com/pissang)
  14107. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14108. * errorrik (errorrik@gmail.com)
  14109. */
  14110. /**
  14111. * 贝塞尔平滑曲线
  14112. * @alias module:zrender/shape/util/smoothBezier
  14113. * @param {Array} points 线段顶点数组
  14114. * @param {number} smooth 平滑等级, 0-1
  14115. * @param {boolean} isLoop
  14116. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  14117. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  14118. * 整个折线的包围盒做一个并集用来约束控制点。
  14119. * @param {Array} 计算出来的控制点数组
  14120. */
  14121. var smoothBezier = function (points, smooth, isLoop, constraint) {
  14122. var cps = [];
  14123. var v = [];
  14124. var v1 = [];
  14125. var v2 = [];
  14126. var prevPoint;
  14127. var nextPoint;
  14128. var min$$1;
  14129. var max$$1;
  14130. if (constraint) {
  14131. min$$1 = [Infinity, Infinity];
  14132. max$$1 = [-Infinity, -Infinity];
  14133. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14134. min(min$$1, min$$1, points[i]);
  14135. max(max$$1, max$$1, points[i]);
  14136. }
  14137. // 与指定的包围盒做并集
  14138. min(min$$1, min$$1, constraint[0]);
  14139. max(max$$1, max$$1, constraint[1]);
  14140. }
  14141. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14142. var point = points[i];
  14143. if (isLoop) {
  14144. prevPoint = points[i ? i - 1 : len$$1 - 1];
  14145. nextPoint = points[(i + 1) % len$$1];
  14146. }
  14147. else {
  14148. if (i === 0 || i === len$$1 - 1) {
  14149. cps.push(clone$1(points[i]));
  14150. continue;
  14151. }
  14152. else {
  14153. prevPoint = points[i - 1];
  14154. nextPoint = points[i + 1];
  14155. }
  14156. }
  14157. sub(v, nextPoint, prevPoint);
  14158. // use degree to scale the handle length
  14159. scale(v, v, smooth);
  14160. var d0 = distance(point, prevPoint);
  14161. var d1 = distance(point, nextPoint);
  14162. var sum = d0 + d1;
  14163. if (sum !== 0) {
  14164. d0 /= sum;
  14165. d1 /= sum;
  14166. }
  14167. scale(v1, v, -d0);
  14168. scale(v2, v, d1);
  14169. var cp0 = add([], point, v1);
  14170. var cp1 = add([], point, v2);
  14171. if (constraint) {
  14172. max(cp0, cp0, min$$1);
  14173. min(cp0, cp0, max$$1);
  14174. max(cp1, cp1, min$$1);
  14175. min(cp1, cp1, max$$1);
  14176. }
  14177. cps.push(cp0);
  14178. cps.push(cp1);
  14179. }
  14180. if (isLoop) {
  14181. cps.push(cps.shift());
  14182. }
  14183. return cps;
  14184. };
  14185. function buildPath$1(ctx, shape, closePath) {
  14186. var points = shape.points;
  14187. var smooth = shape.smooth;
  14188. if (points && points.length >= 2) {
  14189. if (smooth && smooth !== 'spline') {
  14190. var controlPoints = smoothBezier(
  14191. points, smooth, closePath, shape.smoothConstraint
  14192. );
  14193. ctx.moveTo(points[0][0], points[0][1]);
  14194. var len = points.length;
  14195. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  14196. var cp1 = controlPoints[i * 2];
  14197. var cp2 = controlPoints[i * 2 + 1];
  14198. var p = points[(i + 1) % len];
  14199. ctx.bezierCurveTo(
  14200. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  14201. );
  14202. }
  14203. }
  14204. else {
  14205. if (smooth === 'spline') {
  14206. points = smoothSpline(points, closePath);
  14207. }
  14208. ctx.moveTo(points[0][0], points[0][1]);
  14209. for (var i = 1, l = points.length; i < l; i++) {
  14210. ctx.lineTo(points[i][0], points[i][1]);
  14211. }
  14212. }
  14213. closePath && ctx.closePath();
  14214. }
  14215. }
  14216. /**
  14217. * 多边形
  14218. * @module zrender/shape/Polygon
  14219. */
  14220. var Polygon = Path.extend({
  14221. type: 'polygon',
  14222. shape: {
  14223. points: null,
  14224. smooth: false,
  14225. smoothConstraint: null
  14226. },
  14227. buildPath: function (ctx, shape) {
  14228. buildPath$1(ctx, shape, true);
  14229. }
  14230. });
  14231. /**
  14232. * @module zrender/graphic/shape/Polyline
  14233. */
  14234. var Polyline = Path.extend({
  14235. type: 'polyline',
  14236. shape: {
  14237. points: null,
  14238. smooth: false,
  14239. smoothConstraint: null
  14240. },
  14241. style: {
  14242. stroke: '#000',
  14243. fill: null
  14244. },
  14245. buildPath: function (ctx, shape) {
  14246. buildPath$1(ctx, shape, false);
  14247. }
  14248. });
  14249. /**
  14250. * Sub-pixel optimize for canvas rendering, prevent from blur
  14251. * when rendering a thin vertical/horizontal line.
  14252. */
  14253. var round = Math.round;
  14254. /**
  14255. * Sub pixel optimize line for canvas
  14256. *
  14257. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14258. * `outputShape` and `inputShape` can be the same object.
  14259. * `outputShape` object can be used repeatly, because all of
  14260. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  14261. * @param {Object} [inputShape]
  14262. * @param {number} [inputShape.x1]
  14263. * @param {number} [inputShape.y1]
  14264. * @param {number} [inputShape.x2]
  14265. * @param {number} [inputShape.y2]
  14266. * @param {Object} [style]
  14267. * @param {number} [style.lineWidth]
  14268. */
  14269. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  14270. var lineWidth = style && style.lineWidth;
  14271. if (!inputShape || !lineWidth) {
  14272. return;
  14273. }
  14274. var x1 = inputShape.x1;
  14275. var x2 = inputShape.x2;
  14276. var y1 = inputShape.y1;
  14277. var y2 = inputShape.y2;
  14278. if (round(x1 * 2) === round(x2 * 2)) {
  14279. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  14280. }
  14281. else {
  14282. outputShape.x1 = x1;
  14283. outputShape.x2 = x2;
  14284. }
  14285. if (round(y1 * 2) === round(y2 * 2)) {
  14286. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  14287. }
  14288. else {
  14289. outputShape.y1 = y1;
  14290. outputShape.y2 = y2;
  14291. }
  14292. }
  14293. /**
  14294. * Sub pixel optimize rect for canvas
  14295. *
  14296. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14297. * `outputShape` and `inputShape` can be the same object.
  14298. * `outputShape` object can be used repeatly, because all of
  14299. * the `x`, `y`, `width`, `height` will be assigned in this method.
  14300. * @param {Object} [inputShape]
  14301. * @param {number} [inputShape.x]
  14302. * @param {number} [inputShape.y]
  14303. * @param {number} [inputShape.width]
  14304. * @param {number} [inputShape.height]
  14305. * @param {Object} [style]
  14306. * @param {number} [style.lineWidth]
  14307. */
  14308. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  14309. var lineWidth = style && style.lineWidth;
  14310. if (!inputShape || !lineWidth) {
  14311. return;
  14312. }
  14313. var originX = inputShape.x;
  14314. var originY = inputShape.y;
  14315. var originWidth = inputShape.width;
  14316. var originHeight = inputShape.height;
  14317. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  14318. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  14319. outputShape.width = Math.max(
  14320. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  14321. originWidth === 0 ? 0 : 1
  14322. );
  14323. outputShape.height = Math.max(
  14324. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  14325. originHeight === 0 ? 0 : 1
  14326. );
  14327. }
  14328. /**
  14329. * Sub pixel optimize for canvas
  14330. *
  14331. * @param {number} position Coordinate, such as x, y
  14332. * @param {number} lineWidth Should be nonnegative integer.
  14333. * @param {boolean=} positiveOrNegative Default false (negative).
  14334. * @return {number} Optimized position.
  14335. */
  14336. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  14337. // Assure that (position + lineWidth / 2) is near integer edge,
  14338. // otherwise line will be fuzzy in canvas.
  14339. var doubledPosition = round(position * 2);
  14340. return (doubledPosition + round(lineWidth)) % 2 === 0
  14341. ? doubledPosition / 2
  14342. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14343. }
  14344. /**
  14345. * 矩形
  14346. * @module zrender/graphic/shape/Rect
  14347. */
  14348. // Avoid create repeatly.
  14349. var subPixelOptimizeOutputShape = {};
  14350. var Rect = Path.extend({
  14351. type: 'rect',
  14352. shape: {
  14353. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  14354. // r缩写为1 相当于 [1, 1, 1, 1]
  14355. // r缩写为[1] 相当于 [1, 1, 1, 1]
  14356. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  14357. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  14358. r: 0,
  14359. x: 0,
  14360. y: 0,
  14361. width: 0,
  14362. height: 0
  14363. },
  14364. buildPath: function (ctx, shape) {
  14365. var x;
  14366. var y;
  14367. var width;
  14368. var height;
  14369. if (this.subPixelOptimize) {
  14370. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  14371. x = subPixelOptimizeOutputShape.x;
  14372. y = subPixelOptimizeOutputShape.y;
  14373. width = subPixelOptimizeOutputShape.width;
  14374. height = subPixelOptimizeOutputShape.height;
  14375. subPixelOptimizeOutputShape.r = shape.r;
  14376. shape = subPixelOptimizeOutputShape;
  14377. }
  14378. else {
  14379. x = shape.x;
  14380. y = shape.y;
  14381. width = shape.width;
  14382. height = shape.height;
  14383. }
  14384. if (!shape.r) {
  14385. ctx.rect(x, y, width, height);
  14386. }
  14387. else {
  14388. buildPath(ctx, shape);
  14389. }
  14390. ctx.closePath();
  14391. return;
  14392. }
  14393. });
  14394. /**
  14395. * 直线
  14396. * @module zrender/graphic/shape/Line
  14397. */
  14398. // Avoid create repeatly.
  14399. var subPixelOptimizeOutputShape$1 = {};
  14400. var Line = Path.extend({
  14401. type: 'line',
  14402. shape: {
  14403. // Start point
  14404. x1: 0,
  14405. y1: 0,
  14406. // End point
  14407. x2: 0,
  14408. y2: 0,
  14409. percent: 1
  14410. },
  14411. style: {
  14412. stroke: '#000',
  14413. fill: null
  14414. },
  14415. buildPath: function (ctx, shape) {
  14416. var x1;
  14417. var y1;
  14418. var x2;
  14419. var y2;
  14420. if (this.subPixelOptimize) {
  14421. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  14422. x1 = subPixelOptimizeOutputShape$1.x1;
  14423. y1 = subPixelOptimizeOutputShape$1.y1;
  14424. x2 = subPixelOptimizeOutputShape$1.x2;
  14425. y2 = subPixelOptimizeOutputShape$1.y2;
  14426. }
  14427. else {
  14428. x1 = shape.x1;
  14429. y1 = shape.y1;
  14430. x2 = shape.x2;
  14431. y2 = shape.y2;
  14432. }
  14433. var percent = shape.percent;
  14434. if (percent === 0) {
  14435. return;
  14436. }
  14437. ctx.moveTo(x1, y1);
  14438. if (percent < 1) {
  14439. x2 = x1 * (1 - percent) + x2 * percent;
  14440. y2 = y1 * (1 - percent) + y2 * percent;
  14441. }
  14442. ctx.lineTo(x2, y2);
  14443. },
  14444. /**
  14445. * Get point at percent
  14446. * @param {number} percent
  14447. * @return {Array.<number>}
  14448. */
  14449. pointAt: function (p) {
  14450. var shape = this.shape;
  14451. return [
  14452. shape.x1 * (1 - p) + shape.x2 * p,
  14453. shape.y1 * (1 - p) + shape.y2 * p
  14454. ];
  14455. }
  14456. });
  14457. /**
  14458. * 贝塞尔曲线
  14459. * @module zrender/shape/BezierCurve
  14460. */
  14461. var out = [];
  14462. function someVectorAt(shape, t, isTangent) {
  14463. var cpx2 = shape.cpx2;
  14464. var cpy2 = shape.cpy2;
  14465. if (cpx2 === null || cpy2 === null) {
  14466. return [
  14467. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14468. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14469. ];
  14470. }
  14471. else {
  14472. return [
  14473. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14474. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14475. ];
  14476. }
  14477. }
  14478. var BezierCurve = Path.extend({
  14479. type: 'bezier-curve',
  14480. shape: {
  14481. x1: 0,
  14482. y1: 0,
  14483. x2: 0,
  14484. y2: 0,
  14485. cpx1: 0,
  14486. cpy1: 0,
  14487. // cpx2: 0,
  14488. // cpy2: 0
  14489. // Curve show percent, for animating
  14490. percent: 1
  14491. },
  14492. style: {
  14493. stroke: '#000',
  14494. fill: null
  14495. },
  14496. buildPath: function (ctx, shape) {
  14497. var x1 = shape.x1;
  14498. var y1 = shape.y1;
  14499. var x2 = shape.x2;
  14500. var y2 = shape.y2;
  14501. var cpx1 = shape.cpx1;
  14502. var cpy1 = shape.cpy1;
  14503. var cpx2 = shape.cpx2;
  14504. var cpy2 = shape.cpy2;
  14505. var percent = shape.percent;
  14506. if (percent === 0) {
  14507. return;
  14508. }
  14509. ctx.moveTo(x1, y1);
  14510. if (cpx2 == null || cpy2 == null) {
  14511. if (percent < 1) {
  14512. quadraticSubdivide(
  14513. x1, cpx1, x2, percent, out
  14514. );
  14515. cpx1 = out[1];
  14516. x2 = out[2];
  14517. quadraticSubdivide(
  14518. y1, cpy1, y2, percent, out
  14519. );
  14520. cpy1 = out[1];
  14521. y2 = out[2];
  14522. }
  14523. ctx.quadraticCurveTo(
  14524. cpx1, cpy1,
  14525. x2, y2
  14526. );
  14527. }
  14528. else {
  14529. if (percent < 1) {
  14530. cubicSubdivide(
  14531. x1, cpx1, cpx2, x2, percent, out
  14532. );
  14533. cpx1 = out[1];
  14534. cpx2 = out[2];
  14535. x2 = out[3];
  14536. cubicSubdivide(
  14537. y1, cpy1, cpy2, y2, percent, out
  14538. );
  14539. cpy1 = out[1];
  14540. cpy2 = out[2];
  14541. y2 = out[3];
  14542. }
  14543. ctx.bezierCurveTo(
  14544. cpx1, cpy1,
  14545. cpx2, cpy2,
  14546. x2, y2
  14547. );
  14548. }
  14549. },
  14550. /**
  14551. * Get point at percent
  14552. * @param {number} t
  14553. * @return {Array.<number>}
  14554. */
  14555. pointAt: function (t) {
  14556. return someVectorAt(this.shape, t, false);
  14557. },
  14558. /**
  14559. * Get tangent at percent
  14560. * @param {number} t
  14561. * @return {Array.<number>}
  14562. */
  14563. tangentAt: function (t) {
  14564. var p = someVectorAt(this.shape, t, true);
  14565. return normalize(p, p);
  14566. }
  14567. });
  14568. /**
  14569. * 圆弧
  14570. * @module zrender/graphic/shape/Arc
  14571. */
  14572. var Arc = Path.extend({
  14573. type: 'arc',
  14574. shape: {
  14575. cx: 0,
  14576. cy: 0,
  14577. r: 0,
  14578. startAngle: 0,
  14579. endAngle: Math.PI * 2,
  14580. clockwise: true
  14581. },
  14582. style: {
  14583. stroke: '#000',
  14584. fill: null
  14585. },
  14586. buildPath: function (ctx, shape) {
  14587. var x = shape.cx;
  14588. var y = shape.cy;
  14589. var r = Math.max(shape.r, 0);
  14590. var startAngle = shape.startAngle;
  14591. var endAngle = shape.endAngle;
  14592. var clockwise = shape.clockwise;
  14593. var unitX = Math.cos(startAngle);
  14594. var unitY = Math.sin(startAngle);
  14595. ctx.moveTo(unitX * r + x, unitY * r + y);
  14596. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14597. }
  14598. });
  14599. // CompoundPath to improve performance
  14600. var CompoundPath = Path.extend({
  14601. type: 'compound',
  14602. shape: {
  14603. paths: null
  14604. },
  14605. _updatePathDirty: function () {
  14606. var dirtyPath = this.__dirtyPath;
  14607. var paths = this.shape.paths;
  14608. for (var i = 0; i < paths.length; i++) {
  14609. // Mark as dirty if any subpath is dirty
  14610. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14611. }
  14612. this.__dirtyPath = dirtyPath;
  14613. this.__dirty = this.__dirty || dirtyPath;
  14614. },
  14615. beforeBrush: function () {
  14616. this._updatePathDirty();
  14617. var paths = this.shape.paths || [];
  14618. var scale = this.getGlobalScale();
  14619. // Update path scale
  14620. for (var i = 0; i < paths.length; i++) {
  14621. if (!paths[i].path) {
  14622. paths[i].createPathProxy();
  14623. }
  14624. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14625. }
  14626. },
  14627. buildPath: function (ctx, shape) {
  14628. var paths = shape.paths || [];
  14629. for (var i = 0; i < paths.length; i++) {
  14630. paths[i].buildPath(ctx, paths[i].shape, true);
  14631. }
  14632. },
  14633. afterBrush: function () {
  14634. var paths = this.shape.paths || [];
  14635. for (var i = 0; i < paths.length; i++) {
  14636. paths[i].__dirtyPath = false;
  14637. }
  14638. },
  14639. getBoundingRect: function () {
  14640. this._updatePathDirty();
  14641. return Path.prototype.getBoundingRect.call(this);
  14642. }
  14643. });
  14644. /**
  14645. * @param {Array.<Object>} colorStops
  14646. */
  14647. var Gradient = function (colorStops) {
  14648. this.colorStops = colorStops || [];
  14649. };
  14650. Gradient.prototype = {
  14651. constructor: Gradient,
  14652. addColorStop: function (offset, color) {
  14653. this.colorStops.push({
  14654. offset: offset,
  14655. color: color
  14656. });
  14657. }
  14658. };
  14659. /**
  14660. * x, y, x2, y2 are all percent from 0 to 1
  14661. * @param {number} [x=0]
  14662. * @param {number} [y=0]
  14663. * @param {number} [x2=1]
  14664. * @param {number} [y2=0]
  14665. * @param {Array.<Object>} colorStops
  14666. * @param {boolean} [globalCoord=false]
  14667. */
  14668. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14669. // Should do nothing more in this constructor. Because gradient can be
  14670. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14671. // this constructor will not be called.
  14672. this.x = x == null ? 0 : x;
  14673. this.y = y == null ? 0 : y;
  14674. this.x2 = x2 == null ? 1 : x2;
  14675. this.y2 = y2 == null ? 0 : y2;
  14676. // Can be cloned
  14677. this.type = 'linear';
  14678. // If use global coord
  14679. this.global = globalCoord || false;
  14680. Gradient.call(this, colorStops);
  14681. };
  14682. LinearGradient.prototype = {
  14683. constructor: LinearGradient
  14684. };
  14685. inherits(LinearGradient, Gradient);
  14686. /**
  14687. * x, y, r are all percent from 0 to 1
  14688. * @param {number} [x=0.5]
  14689. * @param {number} [y=0.5]
  14690. * @param {number} [r=0.5]
  14691. * @param {Array.<Object>} [colorStops]
  14692. * @param {boolean} [globalCoord=false]
  14693. */
  14694. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14695. // Should do nothing more in this constructor. Because gradient can be
  14696. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14697. // this constructor will not be called.
  14698. this.x = x == null ? 0.5 : x;
  14699. this.y = y == null ? 0.5 : y;
  14700. this.r = r == null ? 0.5 : r;
  14701. // Can be cloned
  14702. this.type = 'radial';
  14703. // If use global coord
  14704. this.global = globalCoord || false;
  14705. Gradient.call(this, colorStops);
  14706. };
  14707. RadialGradient.prototype = {
  14708. constructor: RadialGradient
  14709. };
  14710. inherits(RadialGradient, Gradient);
  14711. /**
  14712. * Displayable for incremental rendering. It will be rendered in a separate layer
  14713. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14714. * addDisplayables will render the added displayables incremetally.
  14715. *
  14716. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14717. */
  14718. // TODO Style override ?
  14719. function IncrementalDisplayble(opts) {
  14720. Displayable.call(this, opts);
  14721. this._displayables = [];
  14722. this._temporaryDisplayables = [];
  14723. this._cursor = 0;
  14724. this.notClear = true;
  14725. }
  14726. IncrementalDisplayble.prototype.incremental = true;
  14727. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14728. this._displayables = [];
  14729. this._temporaryDisplayables = [];
  14730. this._cursor = 0;
  14731. this.dirty();
  14732. this.notClear = false;
  14733. };
  14734. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14735. if (notPersistent) {
  14736. this._temporaryDisplayables.push(displayable);
  14737. }
  14738. else {
  14739. this._displayables.push(displayable);
  14740. }
  14741. this.dirty();
  14742. };
  14743. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14744. notPersistent = notPersistent || false;
  14745. for (var i = 0; i < displayables.length; i++) {
  14746. this.addDisplayable(displayables[i], notPersistent);
  14747. }
  14748. };
  14749. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14750. for (var i = this._cursor; i < this._displayables.length; i++) {
  14751. cb && cb(this._displayables[i]);
  14752. }
  14753. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14754. cb && cb(this._temporaryDisplayables[i]);
  14755. }
  14756. };
  14757. IncrementalDisplayble.prototype.update = function () {
  14758. this.updateTransform();
  14759. for (var i = this._cursor; i < this._displayables.length; i++) {
  14760. var displayable = this._displayables[i];
  14761. // PENDING
  14762. displayable.parent = this;
  14763. displayable.update();
  14764. displayable.parent = null;
  14765. }
  14766. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14767. var displayable = this._temporaryDisplayables[i];
  14768. // PENDING
  14769. displayable.parent = this;
  14770. displayable.update();
  14771. displayable.parent = null;
  14772. }
  14773. };
  14774. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14775. // Render persistant displayables.
  14776. for (var i = this._cursor; i < this._displayables.length; i++) {
  14777. var displayable = this._displayables[i];
  14778. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14779. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14780. displayable.afterBrush && displayable.afterBrush(ctx);
  14781. }
  14782. this._cursor = i;
  14783. // Render temporary displayables.
  14784. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14785. var displayable = this._temporaryDisplayables[i];
  14786. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14787. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14788. displayable.afterBrush && displayable.afterBrush(ctx);
  14789. }
  14790. this._temporaryDisplayables = [];
  14791. this.notClear = true;
  14792. };
  14793. var m = [];
  14794. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14795. if (!this._rect) {
  14796. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14797. for (var i = 0; i < this._displayables.length; i++) {
  14798. var displayable = this._displayables[i];
  14799. var childRect = displayable.getBoundingRect().clone();
  14800. if (displayable.needLocalTransform()) {
  14801. childRect.applyTransform(displayable.getLocalTransform(m));
  14802. }
  14803. rect.union(childRect);
  14804. }
  14805. this._rect = rect;
  14806. }
  14807. return this._rect;
  14808. };
  14809. IncrementalDisplayble.prototype.contain = function (x, y) {
  14810. var localPos = this.transformCoordToLocal(x, y);
  14811. var rect = this.getBoundingRect();
  14812. if (rect.contain(localPos[0], localPos[1])) {
  14813. for (var i = 0; i < this._displayables.length; i++) {
  14814. var displayable = this._displayables[i];
  14815. if (displayable.contain(x, y)) {
  14816. return true;
  14817. }
  14818. }
  14819. }
  14820. return false;
  14821. };
  14822. inherits(IncrementalDisplayble, Displayable);
  14823. /*
  14824. * Licensed to the Apache Software Foundation (ASF) under one
  14825. * or more contributor license agreements. See the NOTICE file
  14826. * distributed with this work for additional information
  14827. * regarding copyright ownership. The ASF licenses this file
  14828. * to you under the Apache License, Version 2.0 (the
  14829. * "License"); you may not use this file except in compliance
  14830. * with the License. You may obtain a copy of the License at
  14831. *
  14832. * http://www.apache.org/licenses/LICENSE-2.0
  14833. *
  14834. * Unless required by applicable law or agreed to in writing,
  14835. * software distributed under the License is distributed on an
  14836. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14837. * KIND, either express or implied. See the License for the
  14838. * specific language governing permissions and limitations
  14839. * under the License.
  14840. */
  14841. var mathMax$1 = Math.max;
  14842. var mathMin$1 = Math.min;
  14843. var EMPTY_OBJ = {};
  14844. var Z2_EMPHASIS_LIFT = 1;
  14845. // key: label model property nane, value: style property name.
  14846. var CACHED_LABEL_STYLE_PROPERTIES = {
  14847. color: 'textFill',
  14848. textBorderColor: 'textStroke',
  14849. textBorderWidth: 'textStrokeWidth'
  14850. };
  14851. var EMPHASIS = 'emphasis';
  14852. var NORMAL = 'normal';
  14853. // Reserve 0 as default.
  14854. var _highlightNextDigit = 1;
  14855. var _highlightKeyMap = {};
  14856. var _customShapeMap = {};
  14857. /**
  14858. * Extend shape with parameters
  14859. */
  14860. function extendShape(opts) {
  14861. return Path.extend(opts);
  14862. }
  14863. /**
  14864. * Extend path
  14865. */
  14866. function extendPath(pathData, opts) {
  14867. return extendFromString(pathData, opts);
  14868. }
  14869. /**
  14870. * Register a user defined shape.
  14871. * The shape class can be fetched by `getShapeClass`
  14872. * This method will overwrite the registered shapes, including
  14873. * the registered built-in shapes, if using the same `name`.
  14874. * The shape can be used in `custom series` and
  14875. * `graphic component` by declaring `{type: name}`.
  14876. *
  14877. * @param {string} name
  14878. * @param {Object} ShapeClass Can be generated by `extendShape`.
  14879. */
  14880. function registerShape(name, ShapeClass) {
  14881. _customShapeMap[name] = ShapeClass;
  14882. }
  14883. /**
  14884. * Find shape class registered by `registerShape`. Usually used in
  14885. * fetching user defined shape.
  14886. *
  14887. * [Caution]:
  14888. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14889. * to use user registered shapes.
  14890. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14891. * `registerShape` by default. That enables users to get both built-in
  14892. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14893. * the built-in shapes by using names like 'circle', 'rect' via calling
  14894. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14895. * in case that it is overwritten by users, except that some features, like
  14896. * `custom series`, `graphic component`, do it deliberately.
  14897. *
  14898. * (2) In the features like `custom series`, `graphic component`, the user input
  14899. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14900. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14901. * are reserved names, that is, if some user register a shape named `'image'`,
  14902. * the shape will not be used. If we intending to add some more reserved names
  14903. * in feature, that might bring break changes (disable some existing user shape
  14904. * names). But that case probably rearly happen. So we dont make more mechanism
  14905. * to resolve this issue here.
  14906. *
  14907. * @param {string} name
  14908. * @return {Object} The shape class. If not found, return nothing.
  14909. */
  14910. function getShapeClass(name) {
  14911. if (_customShapeMap.hasOwnProperty(name)) {
  14912. return _customShapeMap[name];
  14913. }
  14914. }
  14915. /**
  14916. * Create a path element from path data string
  14917. * @param {string} pathData
  14918. * @param {Object} opts
  14919. * @param {module:zrender/core/BoundingRect} rect
  14920. * @param {string} [layout=cover] 'center' or 'cover'
  14921. */
  14922. function makePath(pathData, opts, rect, layout) {
  14923. var path = createFromString(pathData, opts);
  14924. if (rect) {
  14925. if (layout === 'center') {
  14926. rect = centerGraphic(rect, path.getBoundingRect());
  14927. }
  14928. resizePath(path, rect);
  14929. }
  14930. return path;
  14931. }
  14932. /**
  14933. * Create a image element from image url
  14934. * @param {string} imageUrl image url
  14935. * @param {Object} opts options
  14936. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14937. * @param {string} [layout=cover] 'center' or 'cover'
  14938. */
  14939. function makeImage(imageUrl, rect, layout) {
  14940. var path = new ZImage({
  14941. style: {
  14942. image: imageUrl,
  14943. x: rect.x,
  14944. y: rect.y,
  14945. width: rect.width,
  14946. height: rect.height
  14947. },
  14948. onload: function (img) {
  14949. if (layout === 'center') {
  14950. var boundingRect = {
  14951. width: img.width,
  14952. height: img.height
  14953. };
  14954. path.setStyle(centerGraphic(rect, boundingRect));
  14955. }
  14956. }
  14957. });
  14958. return path;
  14959. }
  14960. /**
  14961. * Get position of centered element in bounding box.
  14962. *
  14963. * @param {Object} rect element local bounding box
  14964. * @param {Object} boundingRect constraint bounding box
  14965. * @return {Object} element position containing x, y, width, and height
  14966. */
  14967. function centerGraphic(rect, boundingRect) {
  14968. // Set rect to center, keep width / height ratio.
  14969. var aspect = boundingRect.width / boundingRect.height;
  14970. var width = rect.height * aspect;
  14971. var height;
  14972. if (width <= rect.width) {
  14973. height = rect.height;
  14974. }
  14975. else {
  14976. width = rect.width;
  14977. height = width / aspect;
  14978. }
  14979. var cx = rect.x + rect.width / 2;
  14980. var cy = rect.y + rect.height / 2;
  14981. return {
  14982. x: cx - width / 2,
  14983. y: cy - height / 2,
  14984. width: width,
  14985. height: height
  14986. };
  14987. }
  14988. var mergePath = mergePath$1;
  14989. /**
  14990. * Resize a path to fit the rect
  14991. * @param {module:zrender/graphic/Path} path
  14992. * @param {Object} rect
  14993. */
  14994. function resizePath(path, rect) {
  14995. if (!path.applyTransform) {
  14996. return;
  14997. }
  14998. var pathRect = path.getBoundingRect();
  14999. var m = pathRect.calculateTransform(rect);
  15000. path.applyTransform(m);
  15001. }
  15002. /**
  15003. * Sub pixel optimize line for canvas
  15004. *
  15005. * @param {Object} param
  15006. * @param {Object} [param.shape]
  15007. * @param {number} [param.shape.x1]
  15008. * @param {number} [param.shape.y1]
  15009. * @param {number} [param.shape.x2]
  15010. * @param {number} [param.shape.y2]
  15011. * @param {Object} [param.style]
  15012. * @param {number} [param.style.lineWidth]
  15013. * @return {Object} Modified param
  15014. */
  15015. function subPixelOptimizeLine(param) {
  15016. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  15017. return param;
  15018. }
  15019. /**
  15020. * Sub pixel optimize rect for canvas
  15021. *
  15022. * @param {Object} param
  15023. * @param {Object} [param.shape]
  15024. * @param {number} [param.shape.x]
  15025. * @param {number} [param.shape.y]
  15026. * @param {number} [param.shape.width]
  15027. * @param {number} [param.shape.height]
  15028. * @param {Object} [param.style]
  15029. * @param {number} [param.style.lineWidth]
  15030. * @return {Object} Modified param
  15031. */
  15032. function subPixelOptimizeRect(param) {
  15033. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  15034. return param;
  15035. }
  15036. /**
  15037. * Sub pixel optimize for canvas
  15038. *
  15039. * @param {number} position Coordinate, such as x, y
  15040. * @param {number} lineWidth Should be nonnegative integer.
  15041. * @param {boolean=} positiveOrNegative Default false (negative).
  15042. * @return {number} Optimized position.
  15043. */
  15044. var subPixelOptimize = subPixelOptimize$1;
  15045. function hasFillOrStroke(fillOrStroke) {
  15046. return fillOrStroke != null && fillOrStroke !== 'none';
  15047. }
  15048. // Most lifted color are duplicated.
  15049. var liftedColorMap = createHashMap();
  15050. var liftedColorCount = 0;
  15051. function liftColor(color) {
  15052. if (typeof color !== 'string') {
  15053. return color;
  15054. }
  15055. var liftedColor = liftedColorMap.get(color);
  15056. if (!liftedColor) {
  15057. liftedColor = lift(color, -0.1);
  15058. if (liftedColorCount < 10000) {
  15059. liftedColorMap.set(color, liftedColor);
  15060. liftedColorCount++;
  15061. }
  15062. }
  15063. return liftedColor;
  15064. }
  15065. function cacheElementStl(el) {
  15066. if (!el.__hoverStlDirty) {
  15067. return;
  15068. }
  15069. el.__hoverStlDirty = false;
  15070. var hoverStyle = el.__hoverStl;
  15071. if (!hoverStyle) {
  15072. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  15073. return;
  15074. }
  15075. var normalStyle = el.__cachedNormalStl = {};
  15076. el.__cachedNormalZ2 = el.z2;
  15077. var elStyle = el.style;
  15078. for (var name in hoverStyle) {
  15079. // See comment in `singleEnterEmphasis`.
  15080. if (hoverStyle[name] != null) {
  15081. normalStyle[name] = elStyle[name];
  15082. }
  15083. }
  15084. // Always cache fill and stroke to normalStyle for lifting color.
  15085. normalStyle.fill = elStyle.fill;
  15086. normalStyle.stroke = elStyle.stroke;
  15087. }
  15088. function singleEnterEmphasis(el) {
  15089. var hoverStl = el.__hoverStl;
  15090. if (!hoverStl || el.__highlighted) {
  15091. return;
  15092. }
  15093. var zr = el.__zr;
  15094. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  15095. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  15096. if (el.isGroup || (!zr && el.useHoverLayer)) {
  15097. return;
  15098. }
  15099. var elTarget = el;
  15100. var targetStyle = el.style;
  15101. if (useHoverLayer) {
  15102. elTarget = zr.addHover(el);
  15103. targetStyle = elTarget.style;
  15104. }
  15105. rollbackDefaultTextStyle(targetStyle);
  15106. if (!useHoverLayer) {
  15107. cacheElementStl(elTarget);
  15108. }
  15109. // styles can be:
  15110. // {
  15111. // label: {
  15112. // show: false,
  15113. // position: 'outside',
  15114. // fontSize: 18
  15115. // },
  15116. // emphasis: {
  15117. // label: {
  15118. // show: true
  15119. // }
  15120. // }
  15121. // },
  15122. // where properties of `emphasis` may not appear in `normal`. We previously use
  15123. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  15124. // But consider rich text and setOption in merge mode, it is impossible to cover
  15125. // all properties in merge. So we use merge mode when setting style here.
  15126. // But we choose the merge strategy that only properties that is not `null/undefined`.
  15127. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  15128. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  15129. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  15130. // style any more in `emphasis`. Users can both set properties directly on normal and
  15131. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  15132. targetStyle.extendFrom(hoverStl);
  15133. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  15134. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  15135. applyDefaultTextStyle(targetStyle);
  15136. if (!useHoverLayer) {
  15137. el.dirty(false);
  15138. el.z2 += Z2_EMPHASIS_LIFT;
  15139. }
  15140. }
  15141. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  15142. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  15143. targetStyle[prop] = liftColor(targetStyle[prop]);
  15144. }
  15145. }
  15146. function singleEnterNormal(el) {
  15147. var highlighted = el.__highlighted;
  15148. if (!highlighted) {
  15149. return;
  15150. }
  15151. el.__highlighted = false;
  15152. if (el.isGroup) {
  15153. return;
  15154. }
  15155. if (highlighted === 'layer') {
  15156. el.__zr && el.__zr.removeHover(el);
  15157. }
  15158. else {
  15159. var style = el.style;
  15160. var normalStl = el.__cachedNormalStl;
  15161. if (normalStl) {
  15162. rollbackDefaultTextStyle(style);
  15163. el.setStyle(normalStl);
  15164. applyDefaultTextStyle(style);
  15165. }
  15166. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  15167. // when `el` is on emphasis state. So here by comparing with 1, we try
  15168. // hard to make the bug case rare.
  15169. var normalZ2 = el.__cachedNormalZ2;
  15170. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  15171. el.z2 = normalZ2;
  15172. }
  15173. }
  15174. }
  15175. function traverseUpdate(el, updater, commonParam) {
  15176. // If root is group, also enter updater for `highDownOnUpdate`.
  15177. var fromState = NORMAL;
  15178. var toState = NORMAL;
  15179. var trigger;
  15180. // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  15181. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  15182. updater(el, commonParam);
  15183. el.__highlighted && (toState = EMPHASIS, trigger = true);
  15184. el.isGroup && el.traverse(function (child) {
  15185. !child.isGroup && updater(child, commonParam);
  15186. });
  15187. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  15188. }
  15189. /**
  15190. * Set hover style (namely "emphasis style") of element, based on the current
  15191. * style of the given `el`.
  15192. * This method should be called after all of the normal styles have been adopted
  15193. * to the `el`. See the reason on `setHoverStyle`.
  15194. *
  15195. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  15196. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  15197. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  15198. * Often used when item group has a label element and it's hoverStyle is different.
  15199. * @param {Object|boolean} [hoverStl] The specified hover style.
  15200. * If set as `false`, disable the hover style.
  15201. * Similarly, The `el.hoverStyle` can alse be set
  15202. * as `false` to disable the hover style.
  15203. * Otherwise, use the default hover style if not provided.
  15204. */
  15205. function setElementHoverStyle(el, hoverStl) {
  15206. // For performance consideration, it might be better to make the "hover style" only the
  15207. // difference properties from the "normal style", but not a entire copy of all styles.
  15208. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  15209. el.__hoverStlDirty = true;
  15210. // FIXME
  15211. // It is not completely right to save "normal"/"emphasis" flag on elements.
  15212. // It probably should be saved on `data` of series. Consider the cases:
  15213. // (1) A highlighted elements are moved out of the view port and re-enter
  15214. // again by dataZoom.
  15215. // (2) call `setOption` and replace elements totally when they are highlighted.
  15216. if (el.__highlighted) {
  15217. // Consider the case:
  15218. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  15219. // should be adapted to the `el`. Notice here new "normal styles" should have
  15220. // been set outside and the cached "normal style" is out of date.
  15221. el.__cachedNormalStl = null;
  15222. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  15223. // of this method. In most cases, `z2` is not set and hover style should be able
  15224. // to rollback. Of course, that would bring bug, but only in a rare case, see
  15225. // `doSingleLeaveHover` for details.
  15226. singleEnterNormal(el);
  15227. singleEnterEmphasis(el);
  15228. }
  15229. }
  15230. function onElementMouseOver(e) {
  15231. !shouldSilent(this, e)
  15232. // "emphasis" event highlight has higher priority than mouse highlight.
  15233. && !this.__highByOuter
  15234. && traverseUpdate(this, singleEnterEmphasis);
  15235. }
  15236. function onElementMouseOut(e) {
  15237. !shouldSilent(this, e)
  15238. // "emphasis" event highlight has higher priority than mouse highlight.
  15239. && !this.__highByOuter
  15240. && traverseUpdate(this, singleEnterNormal);
  15241. }
  15242. function onElementEmphasisEvent(highlightDigit) {
  15243. this.__highByOuter |= 1 << (highlightDigit || 0);
  15244. traverseUpdate(this, singleEnterEmphasis);
  15245. }
  15246. function onElementNormalEvent(highlightDigit) {
  15247. !(this.__highByOuter &= ~(1 << (highlightDigit || 0)))
  15248. && traverseUpdate(this, singleEnterNormal);
  15249. }
  15250. function shouldSilent(el, e) {
  15251. return el.__highDownSilentOnTouch && e.zrByTouch;
  15252. }
  15253. /**
  15254. * Set hover style (namely "emphasis style") of element,
  15255. * based on the current style of the given `el`.
  15256. *
  15257. * (1)
  15258. * **CONSTRAINTS** for this method:
  15259. * <A> This method MUST be called after all of the normal styles having been adopted
  15260. * to the `el`.
  15261. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  15262. * "normal style" having been set to the el.
  15263. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  15264. * a default hover style).
  15265. *
  15266. * The reason: this method treat the current style of the `el` as the "normal style"
  15267. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  15268. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  15269. * logic, where the el should shift from the original emphasis style to the new
  15270. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  15271. *
  15272. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  15273. * not found a better solution yet to fit the backward compatibility, performance and
  15274. * the current programming style.
  15275. *
  15276. * (2)
  15277. * Call the method for a "root" element once. Do not call it for each descendants.
  15278. * If the descendants elemenets of a group has itself hover style different from the
  15279. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  15280. * not call this method for them.
  15281. *
  15282. * (3) These input parameters can be set directly on `el`:
  15283. *
  15284. * @param {module:zrender/Element} el
  15285. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  15286. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  15287. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  15288. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  15289. */
  15290. function setHoverStyle(el, hoverStyle) {
  15291. setAsHighDownDispatcher(el, true);
  15292. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  15293. }
  15294. /**
  15295. * @param {module:zrender/Element} el
  15296. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  15297. * Since `setHoverStyle` has the constraint that it must be called after
  15298. * all of the normal style updated, `highDownOnUpdate` is not needed to
  15299. * trigger if both `fromState` and `toState` is 'normal', and needed to
  15300. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  15301. * to sync outside style settings to "emphasis" state.
  15302. * @this {string} This dispatcher `el`.
  15303. * @param {string} fromState Can be "normal" or "emphasis".
  15304. * `fromState` might equal to `toState`,
  15305. * for example, when this method is called when `el` is
  15306. * on "emphasis" state.
  15307. * @param {string} toState Can be "normal" or "emphasis".
  15308. *
  15309. * FIXME
  15310. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  15311. * Because it is not a complete solution. The update
  15312. * listener should not have been mount in element,
  15313. * and the normal/emphasis state should not have
  15314. * mantained on elements.
  15315. *
  15316. * @param {boolean} [el.highDownSilentOnTouch=false]
  15317. * In touch device, mouseover event will be trigger on touchstart event
  15318. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  15319. * conveniently use hoverStyle when tap on touch screen without additional
  15320. * code for compatibility.
  15321. * But if the chart/component has select feature, which usually also use
  15322. * hoverStyle, there might be conflict between 'select-highlight' and
  15323. * 'hover-highlight' especially when roam is enabled (see geo for example).
  15324. * In this case, `highDownSilentOnTouch` should be used to disable
  15325. * hover-highlight on touch device.
  15326. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  15327. */
  15328. function setAsHighDownDispatcher(el, asDispatcher) {
  15329. var disable = asDispatcher === false;
  15330. // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  15331. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  15332. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  15333. el.__highDownOnUpdate = el.highDownOnUpdate;
  15334. // Simple optimize, since this method might be
  15335. // called for each elements of a group in some cases.
  15336. if (!disable || el.__highDownDispatcher) {
  15337. var method = disable ? 'off' : 'on';
  15338. // Duplicated function will be auto-ignored, see Eventful.js.
  15339. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  15340. // Emphasis, normal can be triggered manually by API or other components like hover link.
  15341. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  15342. // Also keep previous record.
  15343. el.__highByOuter = el.__highByOuter || 0;
  15344. el.__highDownDispatcher = !disable;
  15345. }
  15346. }
  15347. /**
  15348. * @param {module:zrender/src/Element} el
  15349. * @return {boolean}
  15350. */
  15351. function isHighDownDispatcher(el) {
  15352. return !!(el && el.__highDownDispatcher);
  15353. }
  15354. /**
  15355. * Support hightlight/downplay record on each elements.
  15356. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  15357. * user triggerred hightlight/downplay should not conflict.
  15358. * Only all of the highlightDigit cleared, return to normal.
  15359. * @param {string} highlightKey
  15360. * @return {number} highlightDigit
  15361. */
  15362. function getHighlightDigit(highlightKey) {
  15363. var highlightDigit = _highlightKeyMap[highlightKey];
  15364. if (highlightDigit == null && _highlightNextDigit <= 32) {
  15365. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  15366. }
  15367. return highlightDigit;
  15368. }
  15369. /**
  15370. * See more info in `setTextStyleCommon`.
  15371. * @param {Object|module:zrender/graphic/Style} normalStyle
  15372. * @param {Object} emphasisStyle
  15373. * @param {module:echarts/model/Model} normalModel
  15374. * @param {module:echarts/model/Model} emphasisModel
  15375. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  15376. * @param {string|Function} [opt.defaultText]
  15377. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  15378. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15379. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  15380. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15381. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  15382. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15383. * @param {Object} [normalSpecified]
  15384. * @param {Object} [emphasisSpecified]
  15385. */
  15386. function setLabelStyle(
  15387. normalStyle, emphasisStyle,
  15388. normalModel, emphasisModel,
  15389. opt,
  15390. normalSpecified, emphasisSpecified
  15391. ) {
  15392. opt = opt || EMPTY_OBJ;
  15393. var labelFetcher = opt.labelFetcher;
  15394. var labelDataIndex = opt.labelDataIndex;
  15395. var labelDimIndex = opt.labelDimIndex;
  15396. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  15397. // is not supported util someone requests.
  15398. var showNormal = normalModel.getShallow('show');
  15399. var showEmphasis = emphasisModel.getShallow('show');
  15400. // Consider performance, only fetch label when necessary.
  15401. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  15402. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  15403. var baseText;
  15404. if (showNormal || showEmphasis) {
  15405. if (labelFetcher) {
  15406. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  15407. }
  15408. if (baseText == null) {
  15409. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  15410. }
  15411. }
  15412. var normalStyleText = showNormal ? baseText : null;
  15413. var emphasisStyleText = showEmphasis
  15414. ? retrieve2(
  15415. labelFetcher
  15416. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  15417. : null,
  15418. baseText
  15419. )
  15420. : null;
  15421. // Optimize: If style.text is null, text will not be drawn.
  15422. if (normalStyleText != null || emphasisStyleText != null) {
  15423. // Always set `textStyle` even if `normalStyle.text` is null, because default
  15424. // values have to be set on `normalStyle`.
  15425. // If we set default values on `emphasisStyle`, consider case:
  15426. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  15427. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  15428. // Then the 'red' will not work on emphasis.
  15429. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  15430. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  15431. }
  15432. normalStyle.text = normalStyleText;
  15433. emphasisStyle.text = emphasisStyleText;
  15434. }
  15435. /**
  15436. * Modify label style manually.
  15437. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  15438. *
  15439. * @param {module:zrender/src/Element} el
  15440. * @param {Object} [normalStyleProps] optional
  15441. * @param {Object} [emphasisStyleProps] optional
  15442. */
  15443. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  15444. var elStyle = el.style;
  15445. if (normalStyleProps) {
  15446. rollbackDefaultTextStyle(elStyle);
  15447. el.setStyle(normalStyleProps);
  15448. applyDefaultTextStyle(elStyle);
  15449. }
  15450. elStyle = el.__hoverStl;
  15451. if (emphasisStyleProps && elStyle) {
  15452. rollbackDefaultTextStyle(elStyle);
  15453. extend(elStyle, emphasisStyleProps);
  15454. applyDefaultTextStyle(elStyle);
  15455. }
  15456. }
  15457. /**
  15458. * Set basic textStyle properties.
  15459. * See more info in `setTextStyleCommon`.
  15460. * @param {Object|module:zrender/graphic/Style} textStyle
  15461. * @param {module:echarts/model/Model} model
  15462. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  15463. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  15464. * @param {boolean} [isEmphasis]
  15465. */
  15466. function setTextStyle(
  15467. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  15468. ) {
  15469. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  15470. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15471. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15472. return textStyle;
  15473. }
  15474. /**
  15475. * Set text option in the style.
  15476. * See more info in `setTextStyleCommon`.
  15477. * @deprecated
  15478. * @param {Object} textStyle
  15479. * @param {module:echarts/model/Model} labelModel
  15480. * @param {string|boolean} defaultColor Default text color.
  15481. * If set as false, it will be processed as a emphasis style.
  15482. */
  15483. function setText(textStyle, labelModel, defaultColor) {
  15484. var opt = {isRectText: true};
  15485. var isEmphasis;
  15486. if (defaultColor === false) {
  15487. isEmphasis = true;
  15488. }
  15489. else {
  15490. // Support setting color as 'auto' to get visual color.
  15491. opt.autoColor = defaultColor;
  15492. }
  15493. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  15494. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15495. }
  15496. /**
  15497. * The uniform entry of set text style, that is, retrieve style definitions
  15498. * from `model` and set to `textStyle` object.
  15499. *
  15500. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15501. * properties will be set. (Consider the states of normal and emphasis and
  15502. * default value can be adopted, merge would make the logic too complicated
  15503. * to manage.)
  15504. *
  15505. * The `textStyle` object can either be a plain object or an instance of
  15506. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  15507. * After this mothod called, the `textStyle` object can then be used in
  15508. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  15509. *
  15510. * Default value will be adopted and `insideRollbackOpt` will be created.
  15511. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  15512. *
  15513. * opt: {
  15514. * disableBox: boolean, Whether diable drawing box of block (outer most).
  15515. * isRectText: boolean,
  15516. * autoColor: string, specify a color when color is 'auto',
  15517. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  15518. * If autoColor specified, it is used as default textFill.
  15519. * useInsideStyle:
  15520. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  15521. * if `textFill` is not specified.
  15522. * `false`: Do not use inside style.
  15523. * `null/undefined`: use inside style if `isRectText` is true and
  15524. * `textFill` is not specified and textPosition contains `'inside'`.
  15525. * forceRich: boolean
  15526. * }
  15527. */
  15528. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  15529. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15530. opt = opt || EMPTY_OBJ;
  15531. if (opt.isRectText) {
  15532. var textPosition;
  15533. if (opt.getTextPosition) {
  15534. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  15535. }
  15536. else {
  15537. textPosition = textStyleModel.getShallow('position')
  15538. || (isEmphasis ? null : 'inside');
  15539. // 'outside' is not a valid zr textPostion value, but used
  15540. // in bar series, and magric type should be considered.
  15541. textPosition === 'outside' && (textPosition = 'top');
  15542. }
  15543. textStyle.textPosition = textPosition;
  15544. textStyle.textOffset = textStyleModel.getShallow('offset');
  15545. var labelRotate = textStyleModel.getShallow('rotate');
  15546. labelRotate != null && (labelRotate *= Math.PI / 180);
  15547. textStyle.textRotation = labelRotate;
  15548. textStyle.textDistance = retrieve2(
  15549. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  15550. );
  15551. }
  15552. var ecModel = textStyleModel.ecModel;
  15553. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15554. // Consider case:
  15555. // {
  15556. // data: [{
  15557. // value: 12,
  15558. // label: {
  15559. // rich: {
  15560. // // no 'a' here but using parent 'a'.
  15561. // }
  15562. // }
  15563. // }],
  15564. // rich: {
  15565. // a: { ... }
  15566. // }
  15567. // }
  15568. var richItemNames = getRichItemNames(textStyleModel);
  15569. var richResult;
  15570. if (richItemNames) {
  15571. richResult = {};
  15572. for (var name in richItemNames) {
  15573. if (richItemNames.hasOwnProperty(name)) {
  15574. // Cascade is supported in rich.
  15575. var richTextStyle = textStyleModel.getModel(['rich', name]);
  15576. // In rich, never `disableBox`.
  15577. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15578. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15579. // That might confuses users. So probably we should put `textStyleModel` as the
  15580. // root ancestor of the `richTextStyle`. But that would be a break change.
  15581. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  15582. }
  15583. }
  15584. }
  15585. textStyle.rich = richResult;
  15586. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  15587. if (opt.forceRich && !opt.textStyle) {
  15588. opt.textStyle = {};
  15589. }
  15590. return textStyle;
  15591. }
  15592. // Consider case:
  15593. // {
  15594. // data: [{
  15595. // value: 12,
  15596. // label: {
  15597. // rich: {
  15598. // // no 'a' here but using parent 'a'.
  15599. // }
  15600. // }
  15601. // }],
  15602. // rich: {
  15603. // a: { ... }
  15604. // }
  15605. // }
  15606. function getRichItemNames(textStyleModel) {
  15607. // Use object to remove duplicated names.
  15608. var richItemNameMap;
  15609. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15610. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15611. if (rich) {
  15612. richItemNameMap = richItemNameMap || {};
  15613. for (var name in rich) {
  15614. if (rich.hasOwnProperty(name)) {
  15615. richItemNameMap[name] = 1;
  15616. }
  15617. }
  15618. }
  15619. textStyleModel = textStyleModel.parentModel;
  15620. }
  15621. return richItemNameMap;
  15622. }
  15623. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15624. // In merge mode, default value should not be given.
  15625. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15626. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15627. || globalTextStyle.color;
  15628. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15629. || globalTextStyle.textBorderColor;
  15630. textStyle.textStrokeWidth = retrieve2(
  15631. textStyleModel.getShallow('textBorderWidth'),
  15632. globalTextStyle.textBorderWidth
  15633. );
  15634. if (!isEmphasis) {
  15635. if (isBlock) {
  15636. textStyle.insideRollbackOpt = opt;
  15637. applyDefaultTextStyle(textStyle);
  15638. }
  15639. // Set default finally.
  15640. if (textStyle.textFill == null) {
  15641. textStyle.textFill = opt.autoColor;
  15642. }
  15643. }
  15644. // Do not use `getFont` here, because merge should be supported, where
  15645. // part of these properties may be changed in emphasis style, and the
  15646. // others should remain their original value got from normal style.
  15647. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15648. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15649. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15650. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15651. textStyle.textAlign = textStyleModel.getShallow('align');
  15652. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15653. || textStyleModel.getShallow('baseline');
  15654. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15655. textStyle.textWidth = textStyleModel.getShallow('width');
  15656. textStyle.textHeight = textStyleModel.getShallow('height');
  15657. textStyle.textTag = textStyleModel.getShallow('tag');
  15658. if (!isBlock || !opt.disableBox) {
  15659. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15660. textStyle.textPadding = textStyleModel.getShallow('padding');
  15661. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15662. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15663. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15664. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15665. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15666. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15667. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15668. }
  15669. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15670. || globalTextStyle.textShadowColor;
  15671. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15672. || globalTextStyle.textShadowBlur;
  15673. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15674. || globalTextStyle.textShadowOffsetX;
  15675. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15676. || globalTextStyle.textShadowOffsetY;
  15677. }
  15678. function getAutoColor(color, opt) {
  15679. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15680. }
  15681. /**
  15682. * Give some default value to the input `textStyle` object, based on the current settings
  15683. * in this `textStyle` object.
  15684. *
  15685. * The Scenario:
  15686. * when text position is `inside` and `textFill` is not specified, we show
  15687. * text border by default for better view. But it should be considered that text position
  15688. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15689. * restore the style.
  15690. *
  15691. * Usage (& NOTICE):
  15692. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15693. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15694. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15695. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15696. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15697. */
  15698. function applyDefaultTextStyle(textStyle) {
  15699. var textPosition = textStyle.textPosition;
  15700. var opt = textStyle.insideRollbackOpt;
  15701. var insideRollback;
  15702. if (opt && textStyle.textFill == null) {
  15703. var autoColor = opt.autoColor;
  15704. var isRectText = opt.isRectText;
  15705. var useInsideStyle = opt.useInsideStyle;
  15706. var useInsideStyleCache = useInsideStyle !== false
  15707. && (useInsideStyle === true
  15708. || (isRectText
  15709. && textPosition
  15710. // textPosition can be [10, 30]
  15711. && typeof textPosition === 'string'
  15712. && textPosition.indexOf('inside') >= 0
  15713. )
  15714. );
  15715. var useAutoColorCache = !useInsideStyleCache && autoColor != null;
  15716. // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  15717. if (useInsideStyleCache || useAutoColorCache) {
  15718. insideRollback = {
  15719. textFill: textStyle.textFill,
  15720. textStroke: textStyle.textStroke,
  15721. textStrokeWidth: textStyle.textStrokeWidth
  15722. };
  15723. }
  15724. if (useInsideStyleCache) {
  15725. textStyle.textFill = '#fff';
  15726. // Consider text with #fff overflow its container.
  15727. if (textStyle.textStroke == null) {
  15728. textStyle.textStroke = autoColor;
  15729. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15730. }
  15731. }
  15732. if (useAutoColorCache) {
  15733. textStyle.textFill = autoColor;
  15734. }
  15735. }
  15736. // Always set `insideRollback`, so that the previous one can be cleared.
  15737. textStyle.insideRollback = insideRollback;
  15738. }
  15739. /**
  15740. * Consider the case: in a scatter,
  15741. * label: {
  15742. * normal: {position: 'inside'},
  15743. * emphasis: {position: 'top'}
  15744. * }
  15745. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15746. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15747. * should be retured to 'autoColor', but not keep '#fff'.
  15748. */
  15749. function rollbackDefaultTextStyle(style) {
  15750. var insideRollback = style.insideRollback;
  15751. if (insideRollback) {
  15752. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  15753. style.textFill = insideRollback.textFill;
  15754. style.textStroke = insideRollback.textStroke;
  15755. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15756. style.insideRollback = null;
  15757. }
  15758. }
  15759. function getFont(opt, ecModel) {
  15760. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15761. return trim([
  15762. // FIXME in node-canvas fontWeight is before fontStyle
  15763. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15764. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15765. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15766. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15767. ].join(' '));
  15768. }
  15769. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15770. if (typeof dataIndex === 'function') {
  15771. cb = dataIndex;
  15772. dataIndex = null;
  15773. }
  15774. // Do not check 'animation' property directly here. Consider this case:
  15775. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15776. // but its parent model (`seriesModel`) does.
  15777. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15778. if (animationEnabled) {
  15779. var postfix = isUpdate ? 'Update' : '';
  15780. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15781. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15782. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15783. if (typeof animationDelay === 'function') {
  15784. animationDelay = animationDelay(
  15785. dataIndex,
  15786. animatableModel.getAnimationDelayParams
  15787. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15788. : null
  15789. );
  15790. }
  15791. if (typeof duration === 'function') {
  15792. duration = duration(dataIndex);
  15793. }
  15794. duration > 0
  15795. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15796. : (el.stopAnimation(), el.attr(props), cb && cb());
  15797. }
  15798. else {
  15799. el.stopAnimation();
  15800. el.attr(props);
  15801. cb && cb();
  15802. }
  15803. }
  15804. /**
  15805. * Update graphic element properties with or without animation according to the
  15806. * configuration in series.
  15807. *
  15808. * Caution: this method will stop previous animation.
  15809. * So if do not use this method to one element twice before
  15810. * animation starts, unless you know what you are doing.
  15811. *
  15812. * @param {module:zrender/Element} el
  15813. * @param {Object} props
  15814. * @param {module:echarts/model/Model} [animatableModel]
  15815. * @param {number} [dataIndex]
  15816. * @param {Function} [cb]
  15817. * @example
  15818. * graphic.updateProps(el, {
  15819. * position: [100, 100]
  15820. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15821. * // Or
  15822. * graphic.updateProps(el, {
  15823. * position: [100, 100]
  15824. * }, seriesModel, function () { console.log('Animation done!'); });
  15825. */
  15826. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15827. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15828. }
  15829. /**
  15830. * Init graphic element properties with or without animation according to the
  15831. * configuration in series.
  15832. *
  15833. * Caution: this method will stop previous animation.
  15834. * So if do not use this method to one element twice before
  15835. * animation starts, unless you know what you are doing.
  15836. *
  15837. * @param {module:zrender/Element} el
  15838. * @param {Object} props
  15839. * @param {module:echarts/model/Model} [animatableModel]
  15840. * @param {number} [dataIndex]
  15841. * @param {Function} cb
  15842. */
  15843. function initProps(el, props, animatableModel, dataIndex, cb) {
  15844. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15845. }
  15846. /**
  15847. * Get transform matrix of target (param target),
  15848. * in coordinate of its ancestor (param ancestor)
  15849. *
  15850. * @param {module:zrender/mixin/Transformable} target
  15851. * @param {module:zrender/mixin/Transformable} [ancestor]
  15852. */
  15853. function getTransform(target, ancestor) {
  15854. var mat = identity([]);
  15855. while (target && target !== ancestor) {
  15856. mul$1(mat, target.getLocalTransform(), mat);
  15857. target = target.parent;
  15858. }
  15859. return mat;
  15860. }
  15861. /**
  15862. * Apply transform to an vertex.
  15863. * @param {Array.<number>} target [x, y]
  15864. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15865. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15866. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15867. * @param {boolean=} invert Whether use invert matrix.
  15868. * @return {Array.<number>} [x, y]
  15869. */
  15870. function applyTransform$1(target, transform, invert$$1) {
  15871. if (transform && !isArrayLike(transform)) {
  15872. transform = Transformable.getLocalTransform(transform);
  15873. }
  15874. if (invert$$1) {
  15875. transform = invert([], transform);
  15876. }
  15877. return applyTransform([], target, transform);
  15878. }
  15879. /**
  15880. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15881. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15882. * @param {boolean=} invert Whether use invert matrix.
  15883. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15884. */
  15885. function transformDirection(direction, transform, invert$$1) {
  15886. // Pick a base, ensure that transform result will not be (0, 0).
  15887. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  15888. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  15889. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  15890. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  15891. var vertex = [
  15892. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  15893. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  15894. ];
  15895. vertex = applyTransform$1(vertex, transform, invert$$1);
  15896. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  15897. ? (vertex[0] > 0 ? 'right' : 'left')
  15898. : (vertex[1] > 0 ? 'bottom' : 'top');
  15899. }
  15900. /**
  15901. * Apply group transition animation from g1 to g2.
  15902. * If no animatableModel, no animation.
  15903. */
  15904. function groupTransition(g1, g2, animatableModel, cb) {
  15905. if (!g1 || !g2) {
  15906. return;
  15907. }
  15908. function getElMap(g) {
  15909. var elMap = {};
  15910. g.traverse(function (el) {
  15911. if (!el.isGroup && el.anid) {
  15912. elMap[el.anid] = el;
  15913. }
  15914. });
  15915. return elMap;
  15916. }
  15917. function getAnimatableProps(el) {
  15918. var obj = {
  15919. position: clone$1(el.position),
  15920. rotation: el.rotation
  15921. };
  15922. if (el.shape) {
  15923. obj.shape = extend({}, el.shape);
  15924. }
  15925. return obj;
  15926. }
  15927. var elMap1 = getElMap(g1);
  15928. g2.traverse(function (el) {
  15929. if (!el.isGroup && el.anid) {
  15930. var oldEl = elMap1[el.anid];
  15931. if (oldEl) {
  15932. var newProp = getAnimatableProps(el);
  15933. el.attr(getAnimatableProps(oldEl));
  15934. updateProps(el, newProp, animatableModel, el.dataIndex);
  15935. }
  15936. // else {
  15937. // if (el.previousProps) {
  15938. // graphic.updateProps
  15939. // }
  15940. // }
  15941. }
  15942. });
  15943. }
  15944. /**
  15945. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15946. * @param {Object} rect {x, y, width, height}
  15947. * @return {Array.<Array.<number>>} A new clipped points.
  15948. */
  15949. function clipPointsByRect(points, rect) {
  15950. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  15951. // and when element have border.
  15952. return map(points, function (point) {
  15953. var x = point[0];
  15954. x = mathMax$1(x, rect.x);
  15955. x = mathMin$1(x, rect.x + rect.width);
  15956. var y = point[1];
  15957. y = mathMax$1(y, rect.y);
  15958. y = mathMin$1(y, rect.y + rect.height);
  15959. return [x, y];
  15960. });
  15961. }
  15962. /**
  15963. * @param {Object} targetRect {x, y, width, height}
  15964. * @param {Object} rect {x, y, width, height}
  15965. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  15966. */
  15967. function clipRectByRect(targetRect, rect) {
  15968. var x = mathMax$1(targetRect.x, rect.x);
  15969. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  15970. var y = mathMax$1(targetRect.y, rect.y);
  15971. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  15972. // If the total rect is cliped, nothing, including the border,
  15973. // should be painted. So return undefined.
  15974. if (x2 >= x && y2 >= y) {
  15975. return {
  15976. x: x,
  15977. y: y,
  15978. width: x2 - x,
  15979. height: y2 - y
  15980. };
  15981. }
  15982. }
  15983. /**
  15984. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  15985. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  15986. * @param {Object} [rect] {x, y, width, height}
  15987. * @return {module:zrender/Element} Icon path or image element.
  15988. */
  15989. function createIcon(iconStr, opt, rect) {
  15990. opt = extend({rectHover: true}, opt);
  15991. var style = opt.style = {strokeNoScale: true};
  15992. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  15993. if (iconStr) {
  15994. return iconStr.indexOf('image://') === 0
  15995. ? (
  15996. style.image = iconStr.slice(8),
  15997. defaults(style, rect),
  15998. new ZImage(opt)
  15999. )
  16000. : (
  16001. makePath(
  16002. iconStr.replace('path://', ''),
  16003. opt,
  16004. rect,
  16005. 'center'
  16006. )
  16007. );
  16008. }
  16009. }
  16010. /**
  16011. * Return `true` if the given line (line `a`) and the given polygon
  16012. * are intersect.
  16013. * Note that we do not count colinear as intersect here because no
  16014. * requirement for that. We could do that if required in future.
  16015. *
  16016. * @param {number} a1x
  16017. * @param {number} a1y
  16018. * @param {number} a2x
  16019. * @param {number} a2y
  16020. * @param {Array.<Array.<number>>} points Points of the polygon.
  16021. * @return {boolean}
  16022. */
  16023. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  16024. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  16025. var p = points[i];
  16026. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  16027. return true;
  16028. }
  16029. p2 = p;
  16030. }
  16031. }
  16032. /**
  16033. * Return `true` if the given two lines (line `a` and line `b`)
  16034. * are intersect.
  16035. * Note that we do not count colinear as intersect here because no
  16036. * requirement for that. We could do that if required in future.
  16037. *
  16038. * @param {number} a1x
  16039. * @param {number} a1y
  16040. * @param {number} a2x
  16041. * @param {number} a2y
  16042. * @param {number} b1x
  16043. * @param {number} b1y
  16044. * @param {number} b2x
  16045. * @param {number} b2y
  16046. * @return {boolean}
  16047. */
  16048. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  16049. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  16050. var mx = a2x - a1x;
  16051. var my = a2y - a1y;
  16052. var nx = b2x - b1x;
  16053. var ny = b2y - b1y;
  16054. // `vec_m` and `vec_n` are parallel iff
  16055. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  16056. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  16057. if (nearZero(nmCrossProduct)) {
  16058. return false;
  16059. }
  16060. // `vec_m` and `vec_n` are intersect iff
  16061. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  16062. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  16063. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  16064. var b1a1x = a1x - b1x;
  16065. var b1a1y = a1y - b1y;
  16066. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  16067. if (q < 0 || q > 1) {
  16068. return false;
  16069. }
  16070. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  16071. if (p < 0 || p > 1) {
  16072. return false;
  16073. }
  16074. return true;
  16075. }
  16076. /**
  16077. * Cross product of 2-dimension vector.
  16078. */
  16079. function crossProduct2d(x1, y1, x2, y2) {
  16080. return x1 * y2 - x2 * y1;
  16081. }
  16082. function nearZero(val) {
  16083. return val <= (1e-6) && val >= -(1e-6);
  16084. }
  16085. // Register built-in shapes. These shapes might be overwirtten
  16086. // by users, although we do not recommend that.
  16087. registerShape('circle', Circle);
  16088. registerShape('sector', Sector);
  16089. registerShape('ring', Ring);
  16090. registerShape('polygon', Polygon);
  16091. registerShape('polyline', Polyline);
  16092. registerShape('rect', Rect);
  16093. registerShape('line', Line);
  16094. registerShape('bezierCurve', BezierCurve);
  16095. registerShape('arc', Arc);
  16096. var graphic = (Object.freeze || Object)({
  16097. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  16098. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  16099. extendShape: extendShape,
  16100. extendPath: extendPath,
  16101. registerShape: registerShape,
  16102. getShapeClass: getShapeClass,
  16103. makePath: makePath,
  16104. makeImage: makeImage,
  16105. mergePath: mergePath,
  16106. resizePath: resizePath,
  16107. subPixelOptimizeLine: subPixelOptimizeLine,
  16108. subPixelOptimizeRect: subPixelOptimizeRect,
  16109. subPixelOptimize: subPixelOptimize,
  16110. setElementHoverStyle: setElementHoverStyle,
  16111. setHoverStyle: setHoverStyle,
  16112. setAsHighDownDispatcher: setAsHighDownDispatcher,
  16113. isHighDownDispatcher: isHighDownDispatcher,
  16114. getHighlightDigit: getHighlightDigit,
  16115. setLabelStyle: setLabelStyle,
  16116. modifyLabelStyle: modifyLabelStyle,
  16117. setTextStyle: setTextStyle,
  16118. setText: setText,
  16119. getFont: getFont,
  16120. updateProps: updateProps,
  16121. initProps: initProps,
  16122. getTransform: getTransform,
  16123. applyTransform: applyTransform$1,
  16124. transformDirection: transformDirection,
  16125. groupTransition: groupTransition,
  16126. clipPointsByRect: clipPointsByRect,
  16127. clipRectByRect: clipRectByRect,
  16128. createIcon: createIcon,
  16129. linePolygonIntersect: linePolygonIntersect,
  16130. lineLineIntersect: lineLineIntersect,
  16131. Group: Group,
  16132. Image: ZImage,
  16133. Text: Text,
  16134. Circle: Circle,
  16135. Sector: Sector,
  16136. Ring: Ring,
  16137. Polygon: Polygon,
  16138. Polyline: Polyline,
  16139. Rect: Rect,
  16140. Line: Line,
  16141. BezierCurve: BezierCurve,
  16142. Arc: Arc,
  16143. IncrementalDisplayable: IncrementalDisplayble,
  16144. CompoundPath: CompoundPath,
  16145. LinearGradient: LinearGradient,
  16146. RadialGradient: RadialGradient,
  16147. BoundingRect: BoundingRect
  16148. });
  16149. /*
  16150. * Licensed to the Apache Software Foundation (ASF) under one
  16151. * or more contributor license agreements. See the NOTICE file
  16152. * distributed with this work for additional information
  16153. * regarding copyright ownership. The ASF licenses this file
  16154. * to you under the Apache License, Version 2.0 (the
  16155. * "License"); you may not use this file except in compliance
  16156. * with the License. You may obtain a copy of the License at
  16157. *
  16158. * http://www.apache.org/licenses/LICENSE-2.0
  16159. *
  16160. * Unless required by applicable law or agreed to in writing,
  16161. * software distributed under the License is distributed on an
  16162. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16163. * KIND, either express or implied. See the License for the
  16164. * specific language governing permissions and limitations
  16165. * under the License.
  16166. */
  16167. var PATH_COLOR = ['textStyle', 'color'];
  16168. var textStyleMixin = {
  16169. /**
  16170. * Get color property or get color from option.textStyle.color
  16171. * @param {boolean} [isEmphasis]
  16172. * @return {string}
  16173. */
  16174. getTextColor: function (isEmphasis) {
  16175. var ecModel = this.ecModel;
  16176. return this.getShallow('color')
  16177. || (
  16178. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  16179. );
  16180. },
  16181. /**
  16182. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  16183. * @return {string}
  16184. */
  16185. getFont: function () {
  16186. return getFont({
  16187. fontStyle: this.getShallow('fontStyle'),
  16188. fontWeight: this.getShallow('fontWeight'),
  16189. fontSize: this.getShallow('fontSize'),
  16190. fontFamily: this.getShallow('fontFamily')
  16191. }, this.ecModel);
  16192. },
  16193. getTextRect: function (text) {
  16194. return getBoundingRect(
  16195. text,
  16196. this.getFont(),
  16197. this.getShallow('align'),
  16198. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  16199. this.getShallow('padding'),
  16200. this.getShallow('lineHeight'),
  16201. this.getShallow('rich'),
  16202. this.getShallow('truncateText')
  16203. );
  16204. }
  16205. };
  16206. /*
  16207. * Licensed to the Apache Software Foundation (ASF) under one
  16208. * or more contributor license agreements. See the NOTICE file
  16209. * distributed with this work for additional information
  16210. * regarding copyright ownership. The ASF licenses this file
  16211. * to you under the Apache License, Version 2.0 (the
  16212. * "License"); you may not use this file except in compliance
  16213. * with the License. You may obtain a copy of the License at
  16214. *
  16215. * http://www.apache.org/licenses/LICENSE-2.0
  16216. *
  16217. * Unless required by applicable law or agreed to in writing,
  16218. * software distributed under the License is distributed on an
  16219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16220. * KIND, either express or implied. See the License for the
  16221. * specific language governing permissions and limitations
  16222. * under the License.
  16223. */
  16224. var getItemStyle = makeStyleMapper(
  16225. [
  16226. ['fill', 'color'],
  16227. ['stroke', 'borderColor'],
  16228. ['lineWidth', 'borderWidth'],
  16229. ['opacity'],
  16230. ['shadowBlur'],
  16231. ['shadowOffsetX'],
  16232. ['shadowOffsetY'],
  16233. ['shadowColor'],
  16234. ['textPosition'],
  16235. ['textAlign']
  16236. ]
  16237. );
  16238. var itemStyleMixin = {
  16239. getItemStyle: function (excludes, includes) {
  16240. var style = getItemStyle(this, excludes, includes);
  16241. var lineDash = this.getBorderLineDash();
  16242. lineDash && (style.lineDash = lineDash);
  16243. return style;
  16244. },
  16245. getBorderLineDash: function () {
  16246. var lineType = this.get('borderType');
  16247. return (lineType === 'solid' || lineType == null) ? null
  16248. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  16249. }
  16250. };
  16251. /*
  16252. * Licensed to the Apache Software Foundation (ASF) under one
  16253. * or more contributor license agreements. See the NOTICE file
  16254. * distributed with this work for additional information
  16255. * regarding copyright ownership. The ASF licenses this file
  16256. * to you under the Apache License, Version 2.0 (the
  16257. * "License"); you may not use this file except in compliance
  16258. * with the License. You may obtain a copy of the License at
  16259. *
  16260. * http://www.apache.org/licenses/LICENSE-2.0
  16261. *
  16262. * Unless required by applicable law or agreed to in writing,
  16263. * software distributed under the License is distributed on an
  16264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16265. * KIND, either express or implied. See the License for the
  16266. * specific language governing permissions and limitations
  16267. * under the License.
  16268. */
  16269. /**
  16270. * @module echarts/model/Model
  16271. */
  16272. var mixin$1 = mixin;
  16273. var inner = makeInner();
  16274. /**
  16275. * @alias module:echarts/model/Model
  16276. * @constructor
  16277. * @param {Object} [option]
  16278. * @param {module:echarts/model/Model} [parentModel]
  16279. * @param {module:echarts/model/Global} [ecModel]
  16280. */
  16281. function Model(option, parentModel, ecModel) {
  16282. /**
  16283. * @type {module:echarts/model/Model}
  16284. * @readOnly
  16285. */
  16286. this.parentModel = parentModel;
  16287. /**
  16288. * @type {module:echarts/model/Global}
  16289. * @readOnly
  16290. */
  16291. this.ecModel = ecModel;
  16292. /**
  16293. * @type {Object}
  16294. * @protected
  16295. */
  16296. this.option = option;
  16297. // Simple optimization
  16298. // if (this.init) {
  16299. // if (arguments.length <= 4) {
  16300. // this.init(option, parentModel, ecModel, extraOpt);
  16301. // }
  16302. // else {
  16303. // this.init.apply(this, arguments);
  16304. // }
  16305. // }
  16306. }
  16307. Model.prototype = {
  16308. constructor: Model,
  16309. /**
  16310. * Model 的初始化函数
  16311. * @param {Object} option
  16312. */
  16313. init: null,
  16314. /**
  16315. * 从新的 Option merge
  16316. */
  16317. mergeOption: function (option) {
  16318. merge(this.option, option, true);
  16319. },
  16320. /**
  16321. * @param {string|Array.<string>} path
  16322. * @param {boolean} [ignoreParent=false]
  16323. * @return {*}
  16324. */
  16325. get: function (path, ignoreParent) {
  16326. if (path == null) {
  16327. return this.option;
  16328. }
  16329. return doGet(
  16330. this.option,
  16331. this.parsePath(path),
  16332. !ignoreParent && getParent(this, path)
  16333. );
  16334. },
  16335. /**
  16336. * @param {string} key
  16337. * @param {boolean} [ignoreParent=false]
  16338. * @return {*}
  16339. */
  16340. getShallow: function (key, ignoreParent) {
  16341. var option = this.option;
  16342. var val = option == null ? option : option[key];
  16343. var parentModel = !ignoreParent && getParent(this, key);
  16344. if (val == null && parentModel) {
  16345. val = parentModel.getShallow(key);
  16346. }
  16347. return val;
  16348. },
  16349. /**
  16350. * @param {string|Array.<string>} [path]
  16351. * @param {module:echarts/model/Model} [parentModel]
  16352. * @return {module:echarts/model/Model}
  16353. */
  16354. getModel: function (path, parentModel) {
  16355. var obj = path == null
  16356. ? this.option
  16357. : doGet(this.option, path = this.parsePath(path));
  16358. var thisParentModel;
  16359. parentModel = parentModel || (
  16360. (thisParentModel = getParent(this, path))
  16361. && thisParentModel.getModel(path)
  16362. );
  16363. return new Model(obj, parentModel, this.ecModel);
  16364. },
  16365. /**
  16366. * If model has option
  16367. */
  16368. isEmpty: function () {
  16369. return this.option == null;
  16370. },
  16371. restoreData: function () {},
  16372. // Pending
  16373. clone: function () {
  16374. var Ctor = this.constructor;
  16375. return new Ctor(clone(this.option));
  16376. },
  16377. setReadOnly: function (properties) {
  16378. // clazzUtil.setReadOnly(this, properties);
  16379. },
  16380. // If path is null/undefined, return null/undefined.
  16381. parsePath: function (path) {
  16382. if (typeof path === 'string') {
  16383. path = path.split('.');
  16384. }
  16385. return path;
  16386. },
  16387. /**
  16388. * @param {Function} getParentMethod
  16389. * param {Array.<string>|string} path
  16390. * return {module:echarts/model/Model}
  16391. */
  16392. customizeGetParent: function (getParentMethod) {
  16393. inner(this).getParent = getParentMethod;
  16394. },
  16395. isAnimationEnabled: function () {
  16396. if (!env$1.node) {
  16397. if (this.option.animation != null) {
  16398. return !!this.option.animation;
  16399. }
  16400. else if (this.parentModel) {
  16401. return this.parentModel.isAnimationEnabled();
  16402. }
  16403. }
  16404. }
  16405. };
  16406. function doGet(obj, pathArr, parentModel) {
  16407. for (var i = 0; i < pathArr.length; i++) {
  16408. // Ignore empty
  16409. if (!pathArr[i]) {
  16410. continue;
  16411. }
  16412. // obj could be number/string/... (like 0)
  16413. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  16414. if (obj == null) {
  16415. break;
  16416. }
  16417. }
  16418. if (obj == null && parentModel) {
  16419. obj = parentModel.get(pathArr);
  16420. }
  16421. return obj;
  16422. }
  16423. // `path` can be null/undefined
  16424. function getParent(model, path) {
  16425. var getParentMethod = inner(model).getParent;
  16426. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  16427. }
  16428. // Enable Model.extend.
  16429. enableClassExtend(Model);
  16430. enableClassCheck(Model);
  16431. mixin$1(Model, lineStyleMixin);
  16432. mixin$1(Model, areaStyleMixin);
  16433. mixin$1(Model, textStyleMixin);
  16434. mixin$1(Model, itemStyleMixin);
  16435. /*
  16436. * Licensed to the Apache Software Foundation (ASF) under one
  16437. * or more contributor license agreements. See the NOTICE file
  16438. * distributed with this work for additional information
  16439. * regarding copyright ownership. The ASF licenses this file
  16440. * to you under the Apache License, Version 2.0 (the
  16441. * "License"); you may not use this file except in compliance
  16442. * with the License. You may obtain a copy of the License at
  16443. *
  16444. * http://www.apache.org/licenses/LICENSE-2.0
  16445. *
  16446. * Unless required by applicable law or agreed to in writing,
  16447. * software distributed under the License is distributed on an
  16448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16449. * KIND, either express or implied. See the License for the
  16450. * specific language governing permissions and limitations
  16451. * under the License.
  16452. */
  16453. var base = 0;
  16454. /**
  16455. * @public
  16456. * @param {string} type
  16457. * @return {string}
  16458. */
  16459. function getUID(type) {
  16460. // Considering the case of crossing js context,
  16461. // use Math.random to make id as unique as possible.
  16462. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  16463. }
  16464. /**
  16465. * @inner
  16466. */
  16467. function enableSubTypeDefaulter(entity) {
  16468. var subTypeDefaulters = {};
  16469. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  16470. componentType = parseClassType$1(componentType);
  16471. subTypeDefaulters[componentType.main] = defaulter;
  16472. };
  16473. entity.determineSubType = function (componentType, option) {
  16474. var type = option.type;
  16475. if (!type) {
  16476. var componentTypeMain = parseClassType$1(componentType).main;
  16477. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16478. type = subTypeDefaulters[componentTypeMain](option);
  16479. }
  16480. }
  16481. return type;
  16482. };
  16483. return entity;
  16484. }
  16485. /**
  16486. * Topological travel on Activity Network (Activity On Vertices).
  16487. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16488. *
  16489. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16490. *
  16491. * If there is circle dependencey, Error will be thrown.
  16492. *
  16493. */
  16494. function enableTopologicalTravel(entity, dependencyGetter) {
  16495. /**
  16496. * @public
  16497. * @param {Array.<string>} targetNameList Target Component type list.
  16498. * Can be ['aa', 'bb', 'aa.xx']
  16499. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  16500. * @param {Function} callback Params: componentType, dependencies.
  16501. * @param {Object} context Scope of callback.
  16502. */
  16503. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16504. if (!targetNameList.length) {
  16505. return;
  16506. }
  16507. var result = makeDepndencyGraph(fullNameList);
  16508. var graph = result.graph;
  16509. var stack = result.noEntryList;
  16510. var targetNameSet = {};
  16511. each$1(targetNameList, function (name) {
  16512. targetNameSet[name] = true;
  16513. });
  16514. while (stack.length) {
  16515. var currComponentType = stack.pop();
  16516. var currVertex = graph[currComponentType];
  16517. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16518. if (isInTargetNameSet) {
  16519. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16520. delete targetNameSet[currComponentType];
  16521. }
  16522. each$1(
  16523. currVertex.successor,
  16524. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  16525. );
  16526. }
  16527. each$1(targetNameSet, function () {
  16528. throw new Error('Circle dependency may exists');
  16529. });
  16530. function removeEdge(succComponentType) {
  16531. graph[succComponentType].entryCount--;
  16532. if (graph[succComponentType].entryCount === 0) {
  16533. stack.push(succComponentType);
  16534. }
  16535. }
  16536. // Consider this case: legend depends on series, and we call
  16537. // chart.setOption({series: [...]}), where only series is in option.
  16538. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16539. // not be called, but only sereis.mergeOption is called. Thus legend
  16540. // have no chance to update its local record about series (like which
  16541. // name of series is available in legend).
  16542. function removeEdgeAndAdd(succComponentType) {
  16543. targetNameSet[succComponentType] = true;
  16544. removeEdge(succComponentType);
  16545. }
  16546. };
  16547. /**
  16548. * DepndencyGraph: {Object}
  16549. * key: conponentType,
  16550. * value: {
  16551. * successor: [conponentTypes...],
  16552. * originalDeps: [conponentTypes...],
  16553. * entryCount: {number}
  16554. * }
  16555. */
  16556. function makeDepndencyGraph(fullNameList) {
  16557. var graph = {};
  16558. var noEntryList = [];
  16559. each$1(fullNameList, function (name) {
  16560. var thisItem = createDependencyGraphItem(graph, name);
  16561. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16562. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16563. thisItem.entryCount = availableDeps.length;
  16564. if (thisItem.entryCount === 0) {
  16565. noEntryList.push(name);
  16566. }
  16567. each$1(availableDeps, function (dependentName) {
  16568. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16569. thisItem.predecessor.push(dependentName);
  16570. }
  16571. var thatItem = createDependencyGraphItem(graph, dependentName);
  16572. if (indexOf(thatItem.successor, dependentName) < 0) {
  16573. thatItem.successor.push(name);
  16574. }
  16575. });
  16576. });
  16577. return {graph: graph, noEntryList: noEntryList};
  16578. }
  16579. function createDependencyGraphItem(graph, name) {
  16580. if (!graph[name]) {
  16581. graph[name] = {predecessor: [], successor: []};
  16582. }
  16583. return graph[name];
  16584. }
  16585. function getAvailableDependencies(originalDeps, fullNameList) {
  16586. var availableDeps = [];
  16587. each$1(originalDeps, function (dep) {
  16588. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16589. });
  16590. return availableDeps;
  16591. }
  16592. }
  16593. /*
  16594. * Licensed to the Apache Software Foundation (ASF) under one
  16595. * or more contributor license agreements. See the NOTICE file
  16596. * distributed with this work for additional information
  16597. * regarding copyright ownership. The ASF licenses this file
  16598. * to you under the Apache License, Version 2.0 (the
  16599. * "License"); you may not use this file except in compliance
  16600. * with the License. You may obtain a copy of the License at
  16601. *
  16602. * http://www.apache.org/licenses/LICENSE-2.0
  16603. *
  16604. * Unless required by applicable law or agreed to in writing,
  16605. * software distributed under the License is distributed on an
  16606. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16607. * KIND, either express or implied. See the License for the
  16608. * specific language governing permissions and limitations
  16609. * under the License.
  16610. */
  16611. /*
  16612. * A third-party license is embeded for some of the code in this file:
  16613. * The method "quantile" was copied from "d3.js".
  16614. * (See more details in the comment of the method below.)
  16615. * The use of the source code of this file is also subject to the terms
  16616. * and consitions of the license of "d3.js" (BSD-3Clause, see
  16617. * </licenses/LICENSE-d3>).
  16618. */
  16619. var RADIAN_EPSILON = 1e-4;
  16620. function _trim(str) {
  16621. return str.replace(/^\s+|\s+$/g, '');
  16622. }
  16623. /**
  16624. * Linear mapping a value from domain to range
  16625. * @memberOf module:echarts/util/number
  16626. * @param {(number|Array.<number>)} val
  16627. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  16628. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  16629. * @param {boolean} clamp
  16630. * @return {(number|Array.<number>}
  16631. */
  16632. function linearMap(val, domain, range, clamp) {
  16633. var subDomain = domain[1] - domain[0];
  16634. var subRange = range[1] - range[0];
  16635. if (subDomain === 0) {
  16636. return subRange === 0
  16637. ? range[0]
  16638. : (range[0] + range[1]) / 2;
  16639. }
  16640. // Avoid accuracy problem in edge, such as
  16641. // 146.39 - 62.83 === 83.55999999999999.
  16642. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  16643. // It is a little verbose for efficiency considering this method
  16644. // is a hotspot.
  16645. if (clamp) {
  16646. if (subDomain > 0) {
  16647. if (val <= domain[0]) {
  16648. return range[0];
  16649. }
  16650. else if (val >= domain[1]) {
  16651. return range[1];
  16652. }
  16653. }
  16654. else {
  16655. if (val >= domain[0]) {
  16656. return range[0];
  16657. }
  16658. else if (val <= domain[1]) {
  16659. return range[1];
  16660. }
  16661. }
  16662. }
  16663. else {
  16664. if (val === domain[0]) {
  16665. return range[0];
  16666. }
  16667. if (val === domain[1]) {
  16668. return range[1];
  16669. }
  16670. }
  16671. return (val - domain[0]) / subDomain * subRange + range[0];
  16672. }
  16673. /**
  16674. * Convert a percent string to absolute number.
  16675. * Returns NaN if percent is not a valid string or number
  16676. * @memberOf module:echarts/util/number
  16677. * @param {string|number} percent
  16678. * @param {number} all
  16679. * @return {number}
  16680. */
  16681. function parsePercent$1(percent, all) {
  16682. switch (percent) {
  16683. case 'center':
  16684. case 'middle':
  16685. percent = '50%';
  16686. break;
  16687. case 'left':
  16688. case 'top':
  16689. percent = '0%';
  16690. break;
  16691. case 'right':
  16692. case 'bottom':
  16693. percent = '100%';
  16694. break;
  16695. }
  16696. if (typeof percent === 'string') {
  16697. if (_trim(percent).match(/%$/)) {
  16698. return parseFloat(percent) / 100 * all;
  16699. }
  16700. return parseFloat(percent);
  16701. }
  16702. return percent == null ? NaN : +percent;
  16703. }
  16704. /**
  16705. * (1) Fix rounding error of float numbers.
  16706. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16707. *
  16708. * @param {number} x
  16709. * @param {number} [precision]
  16710. * @param {boolean} [returnStr]
  16711. * @return {number|string}
  16712. */
  16713. function round$1(x, precision, returnStr) {
  16714. if (precision == null) {
  16715. precision = 10;
  16716. }
  16717. // Avoid range error
  16718. precision = Math.min(Math.max(0, precision), 20);
  16719. x = (+x).toFixed(precision);
  16720. return returnStr ? x : +x;
  16721. }
  16722. /**
  16723. * asc sort arr.
  16724. * The input arr will be modified.
  16725. *
  16726. * @param {Array} arr
  16727. * @return {Array} The input arr.
  16728. */
  16729. function asc(arr) {
  16730. arr.sort(function (a, b) {
  16731. return a - b;
  16732. });
  16733. return arr;
  16734. }
  16735. /**
  16736. * Get precision
  16737. * @param {number} val
  16738. */
  16739. function getPrecision(val) {
  16740. val = +val;
  16741. if (isNaN(val)) {
  16742. return 0;
  16743. }
  16744. // It is much faster than methods converting number to string as follows
  16745. // var tmp = val.toString();
  16746. // return tmp.length - 1 - tmp.indexOf('.');
  16747. // especially when precision is low
  16748. var e = 1;
  16749. var count = 0;
  16750. while (Math.round(val * e) / e !== val) {
  16751. e *= 10;
  16752. count++;
  16753. }
  16754. return count;
  16755. }
  16756. /**
  16757. * @param {string|number} val
  16758. * @return {number}
  16759. */
  16760. function getPrecisionSafe(val) {
  16761. var str = val.toString();
  16762. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16763. var eIndex = str.indexOf('e');
  16764. if (eIndex > 0) {
  16765. var precision = +str.slice(eIndex + 1);
  16766. return precision < 0 ? -precision : 0;
  16767. }
  16768. else {
  16769. var dotIndex = str.indexOf('.');
  16770. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16771. }
  16772. }
  16773. /**
  16774. * Minimal dicernible data precisioin according to a single pixel.
  16775. *
  16776. * @param {Array.<number>} dataExtent
  16777. * @param {Array.<number>} pixelExtent
  16778. * @return {number} precision
  16779. */
  16780. function getPixelPrecision(dataExtent, pixelExtent) {
  16781. var log = Math.log;
  16782. var LN10 = Math.LN10;
  16783. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16784. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16785. // toFixed() digits argument must be between 0 and 20.
  16786. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16787. return !isFinite(precision) ? 20 : precision;
  16788. }
  16789. /**
  16790. * Get a data of given precision, assuring the sum of percentages
  16791. * in valueList is 1.
  16792. * The largest remainer method is used.
  16793. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16794. *
  16795. * @param {Array.<number>} valueList a list of all data
  16796. * @param {number} idx index of the data to be processed in valueList
  16797. * @param {number} precision integer number showing digits of precision
  16798. * @return {number} percent ranging from 0 to 100
  16799. */
  16800. function getPercentWithPrecision(valueList, idx, precision) {
  16801. if (!valueList[idx]) {
  16802. return 0;
  16803. }
  16804. var sum = reduce(valueList, function (acc, val) {
  16805. return acc + (isNaN(val) ? 0 : val);
  16806. }, 0);
  16807. if (sum === 0) {
  16808. return 0;
  16809. }
  16810. var digits = Math.pow(10, precision);
  16811. var votesPerQuota = map(valueList, function (val) {
  16812. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16813. });
  16814. var targetSeats = digits * 100;
  16815. var seats = map(votesPerQuota, function (votes) {
  16816. // Assign automatic seats.
  16817. return Math.floor(votes);
  16818. });
  16819. var currentSum = reduce(seats, function (acc, val) {
  16820. return acc + val;
  16821. }, 0);
  16822. var remainder = map(votesPerQuota, function (votes, idx) {
  16823. return votes - seats[idx];
  16824. });
  16825. // Has remainding votes.
  16826. while (currentSum < targetSeats) {
  16827. // Find next largest remainder.
  16828. var max = Number.NEGATIVE_INFINITY;
  16829. var maxId = null;
  16830. for (var i = 0, len = remainder.length; i < len; ++i) {
  16831. if (remainder[i] > max) {
  16832. max = remainder[i];
  16833. maxId = i;
  16834. }
  16835. }
  16836. // Add a vote to max remainder.
  16837. ++seats[maxId];
  16838. remainder[maxId] = 0;
  16839. ++currentSum;
  16840. }
  16841. return seats[idx] / digits;
  16842. }
  16843. // Number.MAX_SAFE_INTEGER, ie do not support.
  16844. var MAX_SAFE_INTEGER = 9007199254740991;
  16845. /**
  16846. * To 0 - 2 * PI, considering negative radian.
  16847. * @param {number} radian
  16848. * @return {number}
  16849. */
  16850. function remRadian(radian) {
  16851. var pi2 = Math.PI * 2;
  16852. return (radian % pi2 + pi2) % pi2;
  16853. }
  16854. /**
  16855. * @param {type} radian
  16856. * @return {boolean}
  16857. */
  16858. function isRadianAroundZero(val) {
  16859. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16860. }
  16861. /* eslint-disable */
  16862. 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
  16863. /* eslint-enable */
  16864. /**
  16865. * @param {string|Date|number} value These values can be accepted:
  16866. * + An instance of Date, represent a time in its own time zone.
  16867. * + Or string in a subset of ISO 8601, only including:
  16868. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16869. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16870. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16871. * all of which will be treated as local time if time zone is not specified
  16872. * (see <https://momentjs.com/>).
  16873. * + Or other string format, including (all of which will be treated as loacal time):
  16874. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16875. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16876. * + a timestamp, which represent a time in UTC.
  16877. * @return {Date} date
  16878. */
  16879. function parseDate(value) {
  16880. if (value instanceof Date) {
  16881. return value;
  16882. }
  16883. else if (typeof value === 'string') {
  16884. // Different browsers parse date in different way, so we parse it manually.
  16885. // Some other issues:
  16886. // new Date('1970-01-01') is UTC,
  16887. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  16888. // See issue #3623
  16889. var match = TIME_REG.exec(value);
  16890. if (!match) {
  16891. // return Invalid Date.
  16892. return new Date(NaN);
  16893. }
  16894. // Use local time when no timezone offset specifed.
  16895. if (!match[8]) {
  16896. // match[n] can only be string or undefined.
  16897. // But take care of '12' + 1 => '121'.
  16898. return new Date(
  16899. +match[1],
  16900. +(match[2] || 1) - 1,
  16901. +match[3] || 1,
  16902. +match[4] || 0,
  16903. +(match[5] || 0),
  16904. +match[6] || 0,
  16905. +match[7] || 0
  16906. );
  16907. }
  16908. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  16909. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  16910. // For example, system timezone is set as "Time Zone: America/Toronto",
  16911. // then these code will get different result:
  16912. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  16913. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  16914. // So we should not use `new Date`, but use `Date.UTC`.
  16915. else {
  16916. var hour = +match[4] || 0;
  16917. if (match[8].toUpperCase() !== 'Z') {
  16918. hour -= match[8].slice(0, 3);
  16919. }
  16920. return new Date(Date.UTC(
  16921. +match[1],
  16922. +(match[2] || 1) - 1,
  16923. +match[3] || 1,
  16924. hour,
  16925. +(match[5] || 0),
  16926. +match[6] || 0,
  16927. +match[7] || 0
  16928. ));
  16929. }
  16930. }
  16931. else if (value == null) {
  16932. return new Date(NaN);
  16933. }
  16934. return new Date(Math.round(value));
  16935. }
  16936. /**
  16937. * Quantity of a number. e.g. 0.1, 1, 10, 100
  16938. *
  16939. * @param {number} val
  16940. * @return {number}
  16941. */
  16942. function quantity(val) {
  16943. return Math.pow(10, quantityExponent(val));
  16944. }
  16945. /**
  16946. * Exponent of the quantity of a number
  16947. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  16948. *
  16949. * @param {number} val non-negative value
  16950. * @return {number}
  16951. */
  16952. function quantityExponent(val) {
  16953. if (val === 0) {
  16954. return 0;
  16955. }
  16956. var exp = Math.floor(Math.log(val) / Math.LN10);
  16957. /**
  16958. * exp is expected to be the rounded-down result of the base-10 log of val.
  16959. * But due to the precision loss with Math.log(val), we need to restore it
  16960. * using 10^exp to make sure we can get val back from exp. #11249
  16961. */
  16962. if (val / Math.pow(10, exp) >= 10) {
  16963. exp++;
  16964. }
  16965. return exp;
  16966. }
  16967. /**
  16968. * find a “nice” number approximately equal to x. Round the number if round = true,
  16969. * take ceiling if round = false. The primary observation is that the “nicest”
  16970. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  16971. *
  16972. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  16973. *
  16974. * @param {number} val Non-negative value.
  16975. * @param {boolean} round
  16976. * @return {number}
  16977. */
  16978. function nice(val, round) {
  16979. var exponent = quantityExponent(val);
  16980. var exp10 = Math.pow(10, exponent);
  16981. var f = val / exp10; // 1 <= f < 10
  16982. var nf;
  16983. if (round) {
  16984. if (f < 1.5) {
  16985. nf = 1;
  16986. }
  16987. else if (f < 2.5) {
  16988. nf = 2;
  16989. }
  16990. else if (f < 4) {
  16991. nf = 3;
  16992. }
  16993. else if (f < 7) {
  16994. nf = 5;
  16995. }
  16996. else {
  16997. nf = 10;
  16998. }
  16999. }
  17000. else {
  17001. if (f < 1) {
  17002. nf = 1;
  17003. }
  17004. else if (f < 2) {
  17005. nf = 2;
  17006. }
  17007. else if (f < 3) {
  17008. nf = 3;
  17009. }
  17010. else if (f < 5) {
  17011. nf = 5;
  17012. }
  17013. else {
  17014. nf = 10;
  17015. }
  17016. }
  17017. val = nf * exp10;
  17018. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  17019. // 20 is the uppper bound of toFixed.
  17020. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  17021. }
  17022. /**
  17023. * This code was copied from "d3.js"
  17024. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  17025. * See the license statement at the head of this file.
  17026. * @param {Array.<number>} ascArr
  17027. */
  17028. function quantile(ascArr, p) {
  17029. var H = (ascArr.length - 1) * p + 1;
  17030. var h = Math.floor(H);
  17031. var v = +ascArr[h - 1];
  17032. var e = H - h;
  17033. return e ? v + e * (ascArr[h] - v) : v;
  17034. }
  17035. /**
  17036. * Order intervals asc, and split them when overlap.
  17037. * expect(numberUtil.reformIntervals([
  17038. * {interval: [18, 62], close: [1, 1]},
  17039. * {interval: [-Infinity, -70], close: [0, 0]},
  17040. * {interval: [-70, -26], close: [1, 1]},
  17041. * {interval: [-26, 18], close: [1, 1]},
  17042. * {interval: [62, 150], close: [1, 1]},
  17043. * {interval: [106, 150], close: [1, 1]},
  17044. * {interval: [150, Infinity], close: [0, 0]}
  17045. * ])).toEqual([
  17046. * {interval: [-Infinity, -70], close: [0, 0]},
  17047. * {interval: [-70, -26], close: [1, 1]},
  17048. * {interval: [-26, 18], close: [0, 1]},
  17049. * {interval: [18, 62], close: [0, 1]},
  17050. * {interval: [62, 150], close: [0, 1]},
  17051. * {interval: [150, Infinity], close: [0, 0]}
  17052. * ]);
  17053. * @param {Array.<Object>} list, where `close` mean open or close
  17054. * of the interval, and Infinity can be used.
  17055. * @return {Array.<Object>} The origin list, which has been reformed.
  17056. */
  17057. function reformIntervals(list) {
  17058. list.sort(function (a, b) {
  17059. return littleThan(a, b, 0) ? -1 : 1;
  17060. });
  17061. var curr = -Infinity;
  17062. var currClose = 1;
  17063. for (var i = 0; i < list.length;) {
  17064. var interval = list[i].interval;
  17065. var close = list[i].close;
  17066. for (var lg = 0; lg < 2; lg++) {
  17067. if (interval[lg] <= curr) {
  17068. interval[lg] = curr;
  17069. close[lg] = !lg ? 1 - currClose : 1;
  17070. }
  17071. curr = interval[lg];
  17072. currClose = close[lg];
  17073. }
  17074. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  17075. list.splice(i, 1);
  17076. }
  17077. else {
  17078. i++;
  17079. }
  17080. }
  17081. return list;
  17082. function littleThan(a, b, lg) {
  17083. return a.interval[lg] < b.interval[lg]
  17084. || (
  17085. a.interval[lg] === b.interval[lg]
  17086. && (
  17087. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  17088. || (!lg && littleThan(a, b, 1))
  17089. )
  17090. );
  17091. }
  17092. }
  17093. /**
  17094. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  17095. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  17096. * subtraction forces infinities to NaN
  17097. *
  17098. * @param {*} v
  17099. * @return {boolean}
  17100. */
  17101. function isNumeric(v) {
  17102. return v - parseFloat(v) >= 0;
  17103. }
  17104. var number = (Object.freeze || Object)({
  17105. linearMap: linearMap,
  17106. parsePercent: parsePercent$1,
  17107. round: round$1,
  17108. asc: asc,
  17109. getPrecision: getPrecision,
  17110. getPrecisionSafe: getPrecisionSafe,
  17111. getPixelPrecision: getPixelPrecision,
  17112. getPercentWithPrecision: getPercentWithPrecision,
  17113. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  17114. remRadian: remRadian,
  17115. isRadianAroundZero: isRadianAroundZero,
  17116. parseDate: parseDate,
  17117. quantity: quantity,
  17118. quantityExponent: quantityExponent,
  17119. nice: nice,
  17120. quantile: quantile,
  17121. reformIntervals: reformIntervals,
  17122. isNumeric: isNumeric
  17123. });
  17124. /*
  17125. * Licensed to the Apache Software Foundation (ASF) under one
  17126. * or more contributor license agreements. See the NOTICE file
  17127. * distributed with this work for additional information
  17128. * regarding copyright ownership. The ASF licenses this file
  17129. * to you under the Apache License, Version 2.0 (the
  17130. * "License"); you may not use this file except in compliance
  17131. * with the License. You may obtain a copy of the License at
  17132. *
  17133. * http://www.apache.org/licenses/LICENSE-2.0
  17134. *
  17135. * Unless required by applicable law or agreed to in writing,
  17136. * software distributed under the License is distributed on an
  17137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17138. * KIND, either express or implied. See the License for the
  17139. * specific language governing permissions and limitations
  17140. * under the License.
  17141. */
  17142. // import Text from 'zrender/src/graphic/Text';
  17143. /**
  17144. * 每三位默认加,格式化
  17145. * @param {string|number} x
  17146. * @return {string}
  17147. */
  17148. function addCommas(x) {
  17149. if (isNaN(x)) {
  17150. return '-';
  17151. }
  17152. x = (x + '').split('.');
  17153. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  17154. + (x.length > 1 ? ('.' + x[1]) : '');
  17155. }
  17156. /**
  17157. * @param {string} str
  17158. * @param {boolean} [upperCaseFirst=false]
  17159. * @return {string} str
  17160. */
  17161. function toCamelCase(str, upperCaseFirst) {
  17162. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  17163. return group1.toUpperCase();
  17164. });
  17165. if (upperCaseFirst && str) {
  17166. str = str.charAt(0).toUpperCase() + str.slice(1);
  17167. }
  17168. return str;
  17169. }
  17170. var normalizeCssArray$1 = normalizeCssArray;
  17171. var replaceReg = /([&<>"'])/g;
  17172. var replaceMap = {
  17173. '&': '&amp;',
  17174. '<': '&lt;',
  17175. '>': '&gt;',
  17176. '"': '&quot;',
  17177. '\'': '&#39;'
  17178. };
  17179. function encodeHTML(source) {
  17180. return source == null
  17181. ? ''
  17182. : (source + '').replace(replaceReg, function (str, c) {
  17183. return replaceMap[c];
  17184. });
  17185. }
  17186. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  17187. var wrapVar = function (varName, seriesIdx) {
  17188. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  17189. };
  17190. /**
  17191. * Template formatter
  17192. * @param {string} tpl
  17193. * @param {Array.<Object>|Object} paramsList
  17194. * @param {boolean} [encode=false]
  17195. * @return {string}
  17196. */
  17197. function formatTpl(tpl, paramsList, encode) {
  17198. if (!isArray(paramsList)) {
  17199. paramsList = [paramsList];
  17200. }
  17201. var seriesLen = paramsList.length;
  17202. if (!seriesLen) {
  17203. return '';
  17204. }
  17205. var $vars = paramsList[0].$vars || [];
  17206. for (var i = 0; i < $vars.length; i++) {
  17207. var alias = TPL_VAR_ALIAS[i];
  17208. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  17209. }
  17210. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  17211. for (var k = 0; k < $vars.length; k++) {
  17212. var val = paramsList[seriesIdx][$vars[k]];
  17213. tpl = tpl.replace(
  17214. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  17215. encode ? encodeHTML(val) : val
  17216. );
  17217. }
  17218. }
  17219. return tpl;
  17220. }
  17221. /**
  17222. * simple Template formatter
  17223. *
  17224. * @param {string} tpl
  17225. * @param {Object} param
  17226. * @param {boolean} [encode=false]
  17227. * @return {string}
  17228. */
  17229. function formatTplSimple(tpl, param, encode) {
  17230. each$1(param, function (value, key) {
  17231. tpl = tpl.replace(
  17232. '{' + key + '}',
  17233. encode ? encodeHTML(value) : value
  17234. );
  17235. });
  17236. return tpl;
  17237. }
  17238. /**
  17239. * @param {Object|string} [opt] If string, means color.
  17240. * @param {string} [opt.color]
  17241. * @param {string} [opt.extraCssText]
  17242. * @param {string} [opt.type='item'] 'item' or 'subItem'
  17243. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  17244. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  17245. * @return {string}
  17246. */
  17247. function getTooltipMarker(opt, extraCssText) {
  17248. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  17249. var color = opt.color;
  17250. var type = opt.type;
  17251. var extraCssText = opt.extraCssText;
  17252. var renderMode = opt.renderMode || 'html';
  17253. var markerId = opt.markerId || 'X';
  17254. if (!color) {
  17255. return '';
  17256. }
  17257. if (renderMode === 'html') {
  17258. return type === 'subItem'
  17259. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  17260. + 'border-radius:4px;width:4px;height:4px;background-color:'
  17261. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  17262. : '<span style="display:inline-block;margin-right:5px;'
  17263. + 'border-radius:10px;width:10px;height:10px;background-color:'
  17264. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  17265. }
  17266. else {
  17267. // Space for rich element marker
  17268. return {
  17269. renderMode: renderMode,
  17270. content: '{marker' + markerId + '|} ',
  17271. style: {
  17272. color: color
  17273. }
  17274. };
  17275. }
  17276. }
  17277. function pad(str, len) {
  17278. str += '';
  17279. return '0000'.substr(0, len - str.length) + str;
  17280. }
  17281. /**
  17282. * ISO Date format
  17283. * @param {string} tpl
  17284. * @param {number} value
  17285. * @param {boolean} [isUTC=false] Default in local time.
  17286. * see `module:echarts/scale/Time`
  17287. * and `module:echarts/util/number#parseDate`.
  17288. * @inner
  17289. */
  17290. function formatTime(tpl, value, isUTC) {
  17291. if (tpl === 'week'
  17292. || tpl === 'month'
  17293. || tpl === 'quarter'
  17294. || tpl === 'half-year'
  17295. || tpl === 'year'
  17296. ) {
  17297. tpl = 'MM-dd\nyyyy';
  17298. }
  17299. var date = parseDate(value);
  17300. var utc = isUTC ? 'UTC' : '';
  17301. var y = date['get' + utc + 'FullYear']();
  17302. var M = date['get' + utc + 'Month']() + 1;
  17303. var d = date['get' + utc + 'Date']();
  17304. var h = date['get' + utc + 'Hours']();
  17305. var m = date['get' + utc + 'Minutes']();
  17306. var s = date['get' + utc + 'Seconds']();
  17307. var S = date['get' + utc + 'Milliseconds']();
  17308. tpl = tpl.replace('MM', pad(M, 2))
  17309. .replace('M', M)
  17310. .replace('yyyy', y)
  17311. .replace('yy', y % 100)
  17312. .replace('dd', pad(d, 2))
  17313. .replace('d', d)
  17314. .replace('hh', pad(h, 2))
  17315. .replace('h', h)
  17316. .replace('mm', pad(m, 2))
  17317. .replace('m', m)
  17318. .replace('ss', pad(s, 2))
  17319. .replace('s', s)
  17320. .replace('SSS', pad(S, 3));
  17321. return tpl;
  17322. }
  17323. /**
  17324. * Capital first
  17325. * @param {string} str
  17326. * @return {string}
  17327. */
  17328. function capitalFirst(str) {
  17329. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  17330. }
  17331. var truncateText$1 = truncateText;
  17332. /**
  17333. * @public
  17334. * @param {Object} opt
  17335. * @param {string} opt.text
  17336. * @param {string} opt.font
  17337. * @param {string} [opt.textAlign='left']
  17338. * @param {string} [opt.textVerticalAlign='top']
  17339. * @param {Array.<number>} [opt.textPadding]
  17340. * @param {number} [opt.textLineHeight]
  17341. * @param {Object} [opt.rich]
  17342. * @param {Object} [opt.truncate]
  17343. * @return {Object} {x, y, width, height, lineHeight}
  17344. */
  17345. function getTextBoundingRect(opt) {
  17346. return getBoundingRect(
  17347. opt.text,
  17348. opt.font,
  17349. opt.textAlign,
  17350. opt.textVerticalAlign,
  17351. opt.textPadding,
  17352. opt.textLineHeight,
  17353. opt.rich,
  17354. opt.truncate
  17355. );
  17356. }
  17357. /**
  17358. * @deprecated
  17359. * the `textLineHeight` was added later.
  17360. * For backward compatiblility, put it as the last parameter.
  17361. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  17362. */
  17363. function getTextRect(
  17364. text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight
  17365. ) {
  17366. return getBoundingRect(
  17367. text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate
  17368. );
  17369. }
  17370. var format = (Object.freeze || Object)({
  17371. addCommas: addCommas,
  17372. toCamelCase: toCamelCase,
  17373. normalizeCssArray: normalizeCssArray$1,
  17374. encodeHTML: encodeHTML,
  17375. formatTpl: formatTpl,
  17376. formatTplSimple: formatTplSimple,
  17377. getTooltipMarker: getTooltipMarker,
  17378. formatTime: formatTime,
  17379. capitalFirst: capitalFirst,
  17380. truncateText: truncateText$1,
  17381. getTextBoundingRect: getTextBoundingRect,
  17382. getTextRect: getTextRect
  17383. });
  17384. /*
  17385. * Licensed to the Apache Software Foundation (ASF) under one
  17386. * or more contributor license agreements. See the NOTICE file
  17387. * distributed with this work for additional information
  17388. * regarding copyright ownership. The ASF licenses this file
  17389. * to you under the Apache License, Version 2.0 (the
  17390. * "License"); you may not use this file except in compliance
  17391. * with the License. You may obtain a copy of the License at
  17392. *
  17393. * http://www.apache.org/licenses/LICENSE-2.0
  17394. *
  17395. * Unless required by applicable law or agreed to in writing,
  17396. * software distributed under the License is distributed on an
  17397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17398. * KIND, either express or implied. See the License for the
  17399. * specific language governing permissions and limitations
  17400. * under the License.
  17401. */
  17402. // Layout helpers for each component positioning
  17403. var each$3 = each$1;
  17404. /**
  17405. * @public
  17406. */
  17407. var LOCATION_PARAMS = [
  17408. 'left', 'right', 'top', 'bottom', 'width', 'height'
  17409. ];
  17410. /**
  17411. * @public
  17412. */
  17413. var HV_NAMES = [
  17414. ['width', 'left', 'right'],
  17415. ['height', 'top', 'bottom']
  17416. ];
  17417. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  17418. var x = 0;
  17419. var y = 0;
  17420. if (maxWidth == null) {
  17421. maxWidth = Infinity;
  17422. }
  17423. if (maxHeight == null) {
  17424. maxHeight = Infinity;
  17425. }
  17426. var currentLineMaxSize = 0;
  17427. group.eachChild(function (child, idx) {
  17428. var position = child.position;
  17429. var rect = child.getBoundingRect();
  17430. var nextChild = group.childAt(idx + 1);
  17431. var nextChildRect = nextChild && nextChild.getBoundingRect();
  17432. var nextX;
  17433. var nextY;
  17434. if (orient === 'horizontal') {
  17435. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  17436. nextX = x + moveX;
  17437. // Wrap when width exceeds maxWidth or meet a `newline` group
  17438. // FIXME compare before adding gap?
  17439. if (nextX > maxWidth || child.newline) {
  17440. x = 0;
  17441. nextX = moveX;
  17442. y += currentLineMaxSize + gap;
  17443. currentLineMaxSize = rect.height;
  17444. }
  17445. else {
  17446. // FIXME: consider rect.y is not `0`?
  17447. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  17448. }
  17449. }
  17450. else {
  17451. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  17452. nextY = y + moveY;
  17453. // Wrap when width exceeds maxHeight or meet a `newline` group
  17454. if (nextY > maxHeight || child.newline) {
  17455. x += currentLineMaxSize + gap;
  17456. y = 0;
  17457. nextY = moveY;
  17458. currentLineMaxSize = rect.width;
  17459. }
  17460. else {
  17461. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  17462. }
  17463. }
  17464. if (child.newline) {
  17465. return;
  17466. }
  17467. position[0] = x;
  17468. position[1] = y;
  17469. orient === 'horizontal'
  17470. ? (x = nextX + gap)
  17471. : (y = nextY + gap);
  17472. });
  17473. }
  17474. /**
  17475. * VBox or HBox layouting
  17476. * @param {string} orient
  17477. * @param {module:zrender/container/Group} group
  17478. * @param {number} gap
  17479. * @param {number} [width=Infinity]
  17480. * @param {number} [height=Infinity]
  17481. */
  17482. var box = boxLayout;
  17483. /**
  17484. * VBox layouting
  17485. * @param {module:zrender/container/Group} group
  17486. * @param {number} gap
  17487. * @param {number} [width=Infinity]
  17488. * @param {number} [height=Infinity]
  17489. */
  17490. var vbox = curry(boxLayout, 'vertical');
  17491. /**
  17492. * HBox layouting
  17493. * @param {module:zrender/container/Group} group
  17494. * @param {number} gap
  17495. * @param {number} [width=Infinity]
  17496. * @param {number} [height=Infinity]
  17497. */
  17498. var hbox = curry(boxLayout, 'horizontal');
  17499. /**
  17500. * If x or x2 is not specified or 'center' 'left' 'right',
  17501. * the width would be as long as possible.
  17502. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  17503. * the height would be as long as possible.
  17504. *
  17505. * @param {Object} positionInfo
  17506. * @param {number|string} [positionInfo.x]
  17507. * @param {number|string} [positionInfo.y]
  17508. * @param {number|string} [positionInfo.x2]
  17509. * @param {number|string} [positionInfo.y2]
  17510. * @param {Object} containerRect {width, height}
  17511. * @param {string|number} margin
  17512. * @return {Object} {width, height}
  17513. */
  17514. /**
  17515. * Parse position info.
  17516. *
  17517. * @param {Object} positionInfo
  17518. * @param {number|string} [positionInfo.left]
  17519. * @param {number|string} [positionInfo.top]
  17520. * @param {number|string} [positionInfo.right]
  17521. * @param {number|string} [positionInfo.bottom]
  17522. * @param {number|string} [positionInfo.width]
  17523. * @param {number|string} [positionInfo.height]
  17524. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  17525. * @param {Object} containerRect
  17526. * @param {string|number} [margin]
  17527. *
  17528. * @return {module:zrender/core/BoundingRect}
  17529. */
  17530. function getLayoutRect(
  17531. positionInfo, containerRect, margin
  17532. ) {
  17533. margin = normalizeCssArray$1(margin || 0);
  17534. var containerWidth = containerRect.width;
  17535. var containerHeight = containerRect.height;
  17536. var left = parsePercent$1(positionInfo.left, containerWidth);
  17537. var top = parsePercent$1(positionInfo.top, containerHeight);
  17538. var right = parsePercent$1(positionInfo.right, containerWidth);
  17539. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17540. var width = parsePercent$1(positionInfo.width, containerWidth);
  17541. var height = parsePercent$1(positionInfo.height, containerHeight);
  17542. var verticalMargin = margin[2] + margin[0];
  17543. var horizontalMargin = margin[1] + margin[3];
  17544. var aspect = positionInfo.aspect;
  17545. // If width is not specified, calculate width from left and right
  17546. if (isNaN(width)) {
  17547. width = containerWidth - right - horizontalMargin - left;
  17548. }
  17549. if (isNaN(height)) {
  17550. height = containerHeight - bottom - verticalMargin - top;
  17551. }
  17552. if (aspect != null) {
  17553. // If width and height are not given
  17554. // 1. Graph should not exceeds the container
  17555. // 2. Aspect must be keeped
  17556. // 3. Graph should take the space as more as possible
  17557. // FIXME
  17558. // Margin is not considered, because there is no case that both
  17559. // using margin and aspect so far.
  17560. if (isNaN(width) && isNaN(height)) {
  17561. if (aspect > containerWidth / containerHeight) {
  17562. width = containerWidth * 0.8;
  17563. }
  17564. else {
  17565. height = containerHeight * 0.8;
  17566. }
  17567. }
  17568. // Calculate width or height with given aspect
  17569. if (isNaN(width)) {
  17570. width = aspect * height;
  17571. }
  17572. if (isNaN(height)) {
  17573. height = width / aspect;
  17574. }
  17575. }
  17576. // If left is not specified, calculate left from right and width
  17577. if (isNaN(left)) {
  17578. left = containerWidth - right - width - horizontalMargin;
  17579. }
  17580. if (isNaN(top)) {
  17581. top = containerHeight - bottom - height - verticalMargin;
  17582. }
  17583. // Align left and top
  17584. switch (positionInfo.left || positionInfo.right) {
  17585. case 'center':
  17586. left = containerWidth / 2 - width / 2 - margin[3];
  17587. break;
  17588. case 'right':
  17589. left = containerWidth - width - horizontalMargin;
  17590. break;
  17591. }
  17592. switch (positionInfo.top || positionInfo.bottom) {
  17593. case 'middle':
  17594. case 'center':
  17595. top = containerHeight / 2 - height / 2 - margin[0];
  17596. break;
  17597. case 'bottom':
  17598. top = containerHeight - height - verticalMargin;
  17599. break;
  17600. }
  17601. // If something is wrong and left, top, width, height are calculated as NaN
  17602. left = left || 0;
  17603. top = top || 0;
  17604. if (isNaN(width)) {
  17605. // Width may be NaN if only one value is given except width
  17606. width = containerWidth - horizontalMargin - left - (right || 0);
  17607. }
  17608. if (isNaN(height)) {
  17609. // Height may be NaN if only one value is given except height
  17610. height = containerHeight - verticalMargin - top - (bottom || 0);
  17611. }
  17612. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  17613. rect.margin = margin;
  17614. return rect;
  17615. }
  17616. /**
  17617. * Position a zr element in viewport
  17618. * Group position is specified by either
  17619. * {left, top}, {right, bottom}
  17620. * If all properties exists, right and bottom will be igonred.
  17621. *
  17622. * Logic:
  17623. * 1. Scale (against origin point in parent coord)
  17624. * 2. Rotate (against origin point in parent coord)
  17625. * 3. Traslate (with el.position by this method)
  17626. * So this method only fixes the last step 'Traslate', which does not affect
  17627. * scaling and rotating.
  17628. *
  17629. * If be called repeatly with the same input el, the same result will be gotten.
  17630. *
  17631. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  17632. * @param {Object} positionInfo
  17633. * @param {number|string} [positionInfo.left]
  17634. * @param {number|string} [positionInfo.top]
  17635. * @param {number|string} [positionInfo.right]
  17636. * @param {number|string} [positionInfo.bottom]
  17637. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  17638. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  17639. * @param {Object} containerRect
  17640. * @param {string|number} margin
  17641. * @param {Object} [opt]
  17642. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  17643. * @param {Array.<number>} [opt.boundingMode='all']
  17644. * Specify how to calculate boundingRect when locating.
  17645. * 'all': Position the boundingRect that is transformed and uioned
  17646. * both itself and its descendants.
  17647. * This mode simplies confine the elements in the bounding
  17648. * of their container (e.g., using 'right: 0').
  17649. * 'raw': Position the boundingRect that is not transformed and only itself.
  17650. * This mode is useful when you want a element can overflow its
  17651. * container. (Consider a rotated circle needs to be located in a corner.)
  17652. * In this mode positionInfo.width/height can only be number.
  17653. */
  17654. function positionElement(el, positionInfo, containerRect, margin, opt) {
  17655. var h = !opt || !opt.hv || opt.hv[0];
  17656. var v = !opt || !opt.hv || opt.hv[1];
  17657. var boundingMode = opt && opt.boundingMode || 'all';
  17658. if (!h && !v) {
  17659. return;
  17660. }
  17661. var rect;
  17662. if (boundingMode === 'raw') {
  17663. rect = el.type === 'group'
  17664. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  17665. : el.getBoundingRect();
  17666. }
  17667. else {
  17668. rect = el.getBoundingRect();
  17669. if (el.needLocalTransform()) {
  17670. var transform = el.getLocalTransform();
  17671. // Notice: raw rect may be inner object of el,
  17672. // which should not be modified.
  17673. rect = rect.clone();
  17674. rect.applyTransform(transform);
  17675. }
  17676. }
  17677. // The real width and height can not be specified but calculated by the given el.
  17678. positionInfo = getLayoutRect(
  17679. defaults(
  17680. {width: rect.width, height: rect.height},
  17681. positionInfo
  17682. ),
  17683. containerRect,
  17684. margin
  17685. );
  17686. // Because 'tranlate' is the last step in transform
  17687. // (see zrender/core/Transformable#getLocalTransform),
  17688. // we can just only modify el.position to get final result.
  17689. var elPos = el.position;
  17690. var dx = h ? positionInfo.x - rect.x : 0;
  17691. var dy = v ? positionInfo.y - rect.y : 0;
  17692. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  17693. }
  17694. /**
  17695. * @param {Object} option Contains some of the properties in HV_NAMES.
  17696. * @param {number} hvIdx 0: horizontal; 1: vertical.
  17697. */
  17698. /**
  17699. * Consider Case:
  17700. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  17701. * through setOption or media query, using normal zrUtil.merge will cause
  17702. * {right: 0} does not take effect.
  17703. *
  17704. * @example
  17705. * ComponentModel.extend({
  17706. * init: function () {
  17707. * ...
  17708. * var inputPositionParams = layout.getLayoutParams(option);
  17709. * this.mergeOption(inputPositionParams);
  17710. * },
  17711. * mergeOption: function (newOption) {
  17712. * newOption && zrUtil.merge(thisOption, newOption, true);
  17713. * layout.mergeLayoutParam(thisOption, newOption);
  17714. * }
  17715. * });
  17716. *
  17717. * @param {Object} targetOption
  17718. * @param {Object} newOption
  17719. * @param {Object|string} [opt]
  17720. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17721. * that width (or height) should not be calculated by left and right (or top and bottom).
  17722. */
  17723. function mergeLayoutParam(targetOption, newOption, opt) {
  17724. !isObject$1(opt) && (opt = {});
  17725. var ignoreSize = opt.ignoreSize;
  17726. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17727. var hResult = merge$$1(HV_NAMES[0], 0);
  17728. var vResult = merge$$1(HV_NAMES[1], 1);
  17729. copy(HV_NAMES[0], targetOption, hResult);
  17730. copy(HV_NAMES[1], targetOption, vResult);
  17731. function merge$$1(names, hvIdx) {
  17732. var newParams = {};
  17733. var newValueCount = 0;
  17734. var merged = {};
  17735. var mergedValueCount = 0;
  17736. var enoughParamNumber = 2;
  17737. each$3(names, function (name) {
  17738. merged[name] = targetOption[name];
  17739. });
  17740. each$3(names, function (name) {
  17741. // Consider case: newOption.width is null, which is
  17742. // set by user for removing width setting.
  17743. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17744. hasValue(newParams, name) && newValueCount++;
  17745. hasValue(merged, name) && mergedValueCount++;
  17746. });
  17747. if (ignoreSize[hvIdx]) {
  17748. // Only one of left/right is premitted to exist.
  17749. if (hasValue(newOption, names[1])) {
  17750. merged[names[2]] = null;
  17751. }
  17752. else if (hasValue(newOption, names[2])) {
  17753. merged[names[1]] = null;
  17754. }
  17755. return merged;
  17756. }
  17757. // Case: newOption: {width: ..., right: ...},
  17758. // or targetOption: {right: ...} and newOption: {width: ...},
  17759. // There is no conflict when merged only has params count
  17760. // little than enoughParamNumber.
  17761. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17762. return merged;
  17763. }
  17764. // Case: newOption: {width: ..., right: ...},
  17765. // Than we can make sure user only want those two, and ignore
  17766. // all origin params in targetOption.
  17767. else if (newValueCount >= enoughParamNumber) {
  17768. return newParams;
  17769. }
  17770. else {
  17771. // Chose another param from targetOption by priority.
  17772. for (var i = 0; i < names.length; i++) {
  17773. var name = names[i];
  17774. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17775. newParams[name] = targetOption[name];
  17776. break;
  17777. }
  17778. }
  17779. return newParams;
  17780. }
  17781. }
  17782. function hasProp(obj, name) {
  17783. return obj.hasOwnProperty(name);
  17784. }
  17785. function hasValue(obj, name) {
  17786. return obj[name] != null && obj[name] !== 'auto';
  17787. }
  17788. function copy(names, target, source) {
  17789. each$3(names, function (name) {
  17790. target[name] = source[name];
  17791. });
  17792. }
  17793. }
  17794. /**
  17795. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17796. * @param {Object} source
  17797. * @return {Object} Result contains those props.
  17798. */
  17799. function getLayoutParams(source) {
  17800. return copyLayoutParams({}, source);
  17801. }
  17802. /**
  17803. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17804. * @param {Object} source
  17805. * @return {Object} Result contains those props.
  17806. */
  17807. function copyLayoutParams(target, source) {
  17808. source && target && each$3(LOCATION_PARAMS, function (name) {
  17809. source.hasOwnProperty(name) && (target[name] = source[name]);
  17810. });
  17811. return target;
  17812. }
  17813. /*
  17814. * Licensed to the Apache Software Foundation (ASF) under one
  17815. * or more contributor license agreements. See the NOTICE file
  17816. * distributed with this work for additional information
  17817. * regarding copyright ownership. The ASF licenses this file
  17818. * to you under the Apache License, Version 2.0 (the
  17819. * "License"); you may not use this file except in compliance
  17820. * with the License. You may obtain a copy of the License at
  17821. *
  17822. * http://www.apache.org/licenses/LICENSE-2.0
  17823. *
  17824. * Unless required by applicable law or agreed to in writing,
  17825. * software distributed under the License is distributed on an
  17826. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17827. * KIND, either express or implied. See the License for the
  17828. * specific language governing permissions and limitations
  17829. * under the License.
  17830. */
  17831. var boxLayoutMixin = {
  17832. getBoxLayoutParams: function () {
  17833. return {
  17834. left: this.get('left'),
  17835. top: this.get('top'),
  17836. right: this.get('right'),
  17837. bottom: this.get('bottom'),
  17838. width: this.get('width'),
  17839. height: this.get('height')
  17840. };
  17841. }
  17842. };
  17843. /*
  17844. * Licensed to the Apache Software Foundation (ASF) under one
  17845. * or more contributor license agreements. See the NOTICE file
  17846. * distributed with this work for additional information
  17847. * regarding copyright ownership. The ASF licenses this file
  17848. * to you under the Apache License, Version 2.0 (the
  17849. * "License"); you may not use this file except in compliance
  17850. * with the License. You may obtain a copy of the License at
  17851. *
  17852. * http://www.apache.org/licenses/LICENSE-2.0
  17853. *
  17854. * Unless required by applicable law or agreed to in writing,
  17855. * software distributed under the License is distributed on an
  17856. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17857. * KIND, either express or implied. See the License for the
  17858. * specific language governing permissions and limitations
  17859. * under the License.
  17860. */
  17861. /**
  17862. * Component model
  17863. *
  17864. * @module echarts/model/Component
  17865. */
  17866. var inner$1 = makeInner();
  17867. /**
  17868. * @alias module:echarts/model/Component
  17869. * @constructor
  17870. * @param {Object} option
  17871. * @param {module:echarts/model/Model} parentModel
  17872. * @param {module:echarts/model/Model} ecModel
  17873. */
  17874. var ComponentModel = Model.extend({
  17875. type: 'component',
  17876. /**
  17877. * @readOnly
  17878. * @type {string}
  17879. */
  17880. id: '',
  17881. /**
  17882. * Because simplified concept is probably better, series.name (or component.name)
  17883. * has been having too many resposibilities:
  17884. * (1) Generating id (which requires name in option should not be modified).
  17885. * (2) As an index to mapping series when merging option or calling API (a name
  17886. * can refer to more then one components, which is convinient is some case).
  17887. * (3) Display.
  17888. * @readOnly
  17889. */
  17890. name: '',
  17891. /**
  17892. * @readOnly
  17893. * @type {string}
  17894. */
  17895. mainType: '',
  17896. /**
  17897. * @readOnly
  17898. * @type {string}
  17899. */
  17900. subType: '',
  17901. /**
  17902. * @readOnly
  17903. * @type {number}
  17904. */
  17905. componentIndex: 0,
  17906. /**
  17907. * @type {Object}
  17908. * @protected
  17909. */
  17910. defaultOption: null,
  17911. /**
  17912. * @type {module:echarts/model/Global}
  17913. * @readOnly
  17914. */
  17915. ecModel: null,
  17916. /**
  17917. * key: componentType
  17918. * value: Component model list, can not be null.
  17919. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17920. * @readOnly
  17921. */
  17922. dependentModels: [],
  17923. /**
  17924. * @type {string}
  17925. * @readOnly
  17926. */
  17927. uid: null,
  17928. /**
  17929. * Support merge layout params.
  17930. * Only support 'box' now (left/right/top/bottom/width/height).
  17931. * @type {string|Object} Object can be {ignoreSize: true}
  17932. * @readOnly
  17933. */
  17934. layoutMode: null,
  17935. $constructor: function (option, parentModel, ecModel, extraOpt) {
  17936. Model.call(this, option, parentModel, ecModel, extraOpt);
  17937. this.uid = getUID('ec_cpt_model');
  17938. },
  17939. init: function (option, parentModel, ecModel, extraOpt) {
  17940. this.mergeDefaultAndTheme(option, ecModel);
  17941. },
  17942. mergeDefaultAndTheme: function (option, ecModel) {
  17943. var layoutMode = this.layoutMode;
  17944. var inputPositionParams = layoutMode
  17945. ? getLayoutParams(option) : {};
  17946. var themeModel = ecModel.getTheme();
  17947. merge(option, themeModel.get(this.mainType));
  17948. merge(option, this.getDefaultOption());
  17949. if (layoutMode) {
  17950. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17951. }
  17952. },
  17953. mergeOption: function (option, extraOpt) {
  17954. merge(this.option, option, true);
  17955. var layoutMode = this.layoutMode;
  17956. if (layoutMode) {
  17957. mergeLayoutParam(this.option, option, layoutMode);
  17958. }
  17959. },
  17960. // Hooker after init or mergeOption
  17961. optionUpdated: function (newCptOption, isInit) {},
  17962. getDefaultOption: function () {
  17963. var fields = inner$1(this);
  17964. if (!fields.defaultOption) {
  17965. var optList = [];
  17966. var Class = this.constructor;
  17967. while (Class) {
  17968. var opt = Class.prototype.defaultOption;
  17969. opt && optList.push(opt);
  17970. Class = Class.superClass;
  17971. }
  17972. var defaultOption = {};
  17973. for (var i = optList.length - 1; i >= 0; i--) {
  17974. defaultOption = merge(defaultOption, optList[i], true);
  17975. }
  17976. fields.defaultOption = defaultOption;
  17977. }
  17978. return fields.defaultOption;
  17979. },
  17980. getReferringComponents: function (mainType) {
  17981. return this.ecModel.queryComponents({
  17982. mainType: mainType,
  17983. index: this.get(mainType + 'Index', true),
  17984. id: this.get(mainType + 'Id', true)
  17985. });
  17986. }
  17987. });
  17988. // Reset ComponentModel.extend, add preConstruct.
  17989. // clazzUtil.enableClassExtend(
  17990. // ComponentModel,
  17991. // function (option, parentModel, ecModel, extraOpt) {
  17992. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  17993. // zrUtil.extend(this, extraOpt);
  17994. // this.uid = componentUtil.getUID('componentModel');
  17995. // // this.setReadOnly([
  17996. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  17997. // // 'dependentModels', 'componentIndex'
  17998. // // ]);
  17999. // }
  18000. // );
  18001. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  18002. enableClassManagement(
  18003. ComponentModel, {registerWhenExtend: true}
  18004. );
  18005. enableSubTypeDefaulter(ComponentModel);
  18006. // Add capability of ComponentModel.topologicalTravel.
  18007. enableTopologicalTravel(ComponentModel, getDependencies);
  18008. function getDependencies(componentType) {
  18009. var deps = [];
  18010. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  18011. deps = deps.concat(Clazz.prototype.dependencies || []);
  18012. });
  18013. // Ensure main type.
  18014. deps = map(deps, function (type) {
  18015. return parseClassType$1(type).main;
  18016. });
  18017. // Hack dataset for convenience.
  18018. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  18019. deps.unshift('dataset');
  18020. }
  18021. return deps;
  18022. }
  18023. mixin(ComponentModel, boxLayoutMixin);
  18024. /*
  18025. * Licensed to the Apache Software Foundation (ASF) under one
  18026. * or more contributor license agreements. See the NOTICE file
  18027. * distributed with this work for additional information
  18028. * regarding copyright ownership. The ASF licenses this file
  18029. * to you under the Apache License, Version 2.0 (the
  18030. * "License"); you may not use this file except in compliance
  18031. * with the License. You may obtain a copy of the License at
  18032. *
  18033. * http://www.apache.org/licenses/LICENSE-2.0
  18034. *
  18035. * Unless required by applicable law or agreed to in writing,
  18036. * software distributed under the License is distributed on an
  18037. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18038. * KIND, either express or implied. See the License for the
  18039. * specific language governing permissions and limitations
  18040. * under the License.
  18041. */
  18042. var platform = '';
  18043. // Navigator not exists in node
  18044. if (typeof navigator !== 'undefined') {
  18045. platform = navigator.platform || '';
  18046. }
  18047. var globalDefault = {
  18048. // backgroundColor: 'rgba(0,0,0,0)',
  18049. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  18050. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  18051. // Light colors:
  18052. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  18053. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  18054. // Dark colors:
  18055. color: [
  18056. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  18057. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  18058. ],
  18059. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  18060. // If xAxis and yAxis declared, grid is created by default.
  18061. // grid: {},
  18062. textStyle: {
  18063. // color: '#000',
  18064. // decoration: 'none',
  18065. // PENDING
  18066. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  18067. // fontFamily: 'Arial, Verdana, sans-serif',
  18068. fontSize: 12,
  18069. fontStyle: 'normal',
  18070. fontWeight: 'normal'
  18071. },
  18072. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  18073. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  18074. // Default is source-over
  18075. blendMode: null,
  18076. animation: 'auto',
  18077. animationDuration: 1000,
  18078. animationDurationUpdate: 300,
  18079. animationEasing: 'exponentialOut',
  18080. animationEasingUpdate: 'cubicOut',
  18081. animationThreshold: 2000,
  18082. // Configuration for progressive/incremental rendering
  18083. progressiveThreshold: 3000,
  18084. progressive: 400,
  18085. // Threshold of if use single hover layer to optimize.
  18086. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  18087. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  18088. // which is unexpected.
  18089. // see example <echarts/test/heatmap-large.html>.
  18090. hoverLayerThreshold: 3000,
  18091. // See: module:echarts/scale/Time
  18092. useUTC: false
  18093. };
  18094. /*
  18095. * Licensed to the Apache Software Foundation (ASF) under one
  18096. * or more contributor license agreements. See the NOTICE file
  18097. * distributed with this work for additional information
  18098. * regarding copyright ownership. The ASF licenses this file
  18099. * to you under the Apache License, Version 2.0 (the
  18100. * "License"); you may not use this file except in compliance
  18101. * with the License. You may obtain a copy of the License at
  18102. *
  18103. * http://www.apache.org/licenses/LICENSE-2.0
  18104. *
  18105. * Unless required by applicable law or agreed to in writing,
  18106. * software distributed under the License is distributed on an
  18107. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18108. * KIND, either express or implied. See the License for the
  18109. * specific language governing permissions and limitations
  18110. * under the License.
  18111. */
  18112. var inner$2 = makeInner();
  18113. function getNearestColorPalette(colors, requestColorNum) {
  18114. var paletteNum = colors.length;
  18115. // TODO colors must be in order
  18116. for (var i = 0; i < paletteNum; i++) {
  18117. if (colors[i].length > requestColorNum) {
  18118. return colors[i];
  18119. }
  18120. }
  18121. return colors[paletteNum - 1];
  18122. }
  18123. var colorPaletteMixin = {
  18124. clearColorPalette: function () {
  18125. inner$2(this).colorIdx = 0;
  18126. inner$2(this).colorNameMap = {};
  18127. },
  18128. /**
  18129. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  18130. * twise with the same parameters will get different result.
  18131. * @param {Object} [scope=this]
  18132. * @param {Object} [requestColorNum]
  18133. * @return {string} color string.
  18134. */
  18135. getColorFromPalette: function (name, scope, requestColorNum) {
  18136. scope = scope || this;
  18137. var scopeFields = inner$2(scope);
  18138. var colorIdx = scopeFields.colorIdx || 0;
  18139. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  18140. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  18141. if (colorNameMap.hasOwnProperty(name)) {
  18142. return colorNameMap[name];
  18143. }
  18144. var defaultColorPalette = normalizeToArray(this.get('color', true));
  18145. var layeredColorPalette = this.get('colorLayer', true);
  18146. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  18147. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  18148. // In case can't find in layered color palette.
  18149. colorPalette = colorPalette || defaultColorPalette;
  18150. if (!colorPalette || !colorPalette.length) {
  18151. return;
  18152. }
  18153. var color = colorPalette[colorIdx];
  18154. if (name) {
  18155. colorNameMap[name] = color;
  18156. }
  18157. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  18158. return color;
  18159. }
  18160. };
  18161. /*
  18162. * Licensed to the Apache Software Foundation (ASF) under one
  18163. * or more contributor license agreements. See the NOTICE file
  18164. * distributed with this work for additional information
  18165. * regarding copyright ownership. The ASF licenses this file
  18166. * to you under the Apache License, Version 2.0 (the
  18167. * "License"); you may not use this file except in compliance
  18168. * with the License. You may obtain a copy of the License at
  18169. *
  18170. * http://www.apache.org/licenses/LICENSE-2.0
  18171. *
  18172. * Unless required by applicable law or agreed to in writing,
  18173. * software distributed under the License is distributed on an
  18174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18175. * KIND, either express or implied. See the License for the
  18176. * specific language governing permissions and limitations
  18177. * under the License.
  18178. */
  18179. // Avoid typo.
  18180. var SOURCE_FORMAT_ORIGINAL = 'original';
  18181. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  18182. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  18183. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  18184. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  18185. // ??? CHANGE A NAME
  18186. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  18187. var SERIES_LAYOUT_BY_COLUMN = 'column';
  18188. var SERIES_LAYOUT_BY_ROW = 'row';
  18189. /*
  18190. * Licensed to the Apache Software Foundation (ASF) under one
  18191. * or more contributor license agreements. See the NOTICE file
  18192. * distributed with this work for additional information
  18193. * regarding copyright ownership. The ASF licenses this file
  18194. * to you under the Apache License, Version 2.0 (the
  18195. * "License"); you may not use this file except in compliance
  18196. * with the License. You may obtain a copy of the License at
  18197. *
  18198. * http://www.apache.org/licenses/LICENSE-2.0
  18199. *
  18200. * Unless required by applicable law or agreed to in writing,
  18201. * software distributed under the License is distributed on an
  18202. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18203. * KIND, either express or implied. See the License for the
  18204. * specific language governing permissions and limitations
  18205. * under the License.
  18206. */
  18207. /**
  18208. * [sourceFormat]
  18209. *
  18210. * + "original":
  18211. * This format is only used in series.data, where
  18212. * itemStyle can be specified in data item.
  18213. *
  18214. * + "arrayRows":
  18215. * [
  18216. * ['product', 'score', 'amount'],
  18217. * ['Matcha Latte', 89.3, 95.8],
  18218. * ['Milk Tea', 92.1, 89.4],
  18219. * ['Cheese Cocoa', 94.4, 91.2],
  18220. * ['Walnut Brownie', 85.4, 76.9]
  18221. * ]
  18222. *
  18223. * + "objectRows":
  18224. * [
  18225. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  18226. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  18227. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  18228. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  18229. * ]
  18230. *
  18231. * + "keyedColumns":
  18232. * {
  18233. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  18234. * 'count': [823, 235, 1042, 988],
  18235. * 'score': [95.8, 81.4, 91.2, 76.9]
  18236. * }
  18237. *
  18238. * + "typedArray"
  18239. *
  18240. * + "unknown"
  18241. */
  18242. /**
  18243. * @constructor
  18244. * @param {Object} fields
  18245. * @param {string} fields.sourceFormat
  18246. * @param {Array|Object} fields.fromDataset
  18247. * @param {Array|Object} [fields.data]
  18248. * @param {string} [seriesLayoutBy='column']
  18249. * @param {Array.<Object|string>} [dimensionsDefine]
  18250. * @param {Objet|HashMap} [encodeDefine]
  18251. * @param {number} [startIndex=0]
  18252. * @param {number} [dimensionsDetectCount]
  18253. */
  18254. function Source(fields) {
  18255. /**
  18256. * @type {boolean}
  18257. */
  18258. this.fromDataset = fields.fromDataset;
  18259. /**
  18260. * Not null/undefined.
  18261. * @type {Array|Object}
  18262. */
  18263. this.data = fields.data || (
  18264. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  18265. );
  18266. /**
  18267. * See also "detectSourceFormat".
  18268. * Not null/undefined.
  18269. * @type {string}
  18270. */
  18271. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  18272. /**
  18273. * 'row' or 'column'
  18274. * Not null/undefined.
  18275. * @type {string} seriesLayoutBy
  18276. */
  18277. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18278. /**
  18279. * dimensions definition in option.
  18280. * can be null/undefined.
  18281. * @type {Array.<Object|string>}
  18282. */
  18283. this.dimensionsDefine = fields.dimensionsDefine;
  18284. /**
  18285. * encode definition in option.
  18286. * can be null/undefined.
  18287. * @type {Objet|HashMap}
  18288. */
  18289. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  18290. /**
  18291. * Not null/undefined, uint.
  18292. * @type {number}
  18293. */
  18294. this.startIndex = fields.startIndex || 0;
  18295. /**
  18296. * Can be null/undefined (when unknown), uint.
  18297. * @type {number}
  18298. */
  18299. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  18300. }
  18301. /**
  18302. * Wrap original series data for some compatibility cases.
  18303. */
  18304. Source.seriesDataToSource = function (data) {
  18305. return new Source({
  18306. data: data,
  18307. sourceFormat: isTypedArray(data)
  18308. ? SOURCE_FORMAT_TYPED_ARRAY
  18309. : SOURCE_FORMAT_ORIGINAL,
  18310. fromDataset: false
  18311. });
  18312. };
  18313. enableClassCheck(Source);
  18314. /*
  18315. * Licensed to the Apache Software Foundation (ASF) under one
  18316. * or more contributor license agreements. See the NOTICE file
  18317. * distributed with this work for additional information
  18318. * regarding copyright ownership. The ASF licenses this file
  18319. * to you under the Apache License, Version 2.0 (the
  18320. * "License"); you may not use this file except in compliance
  18321. * with the License. You may obtain a copy of the License at
  18322. *
  18323. * http://www.apache.org/licenses/LICENSE-2.0
  18324. *
  18325. * Unless required by applicable law or agreed to in writing,
  18326. * software distributed under the License is distributed on an
  18327. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18328. * KIND, either express or implied. See the License for the
  18329. * specific language governing permissions and limitations
  18330. * under the License.
  18331. */
  18332. // The result of `guessOrdinal`.
  18333. var BE_ORDINAL = {
  18334. Must: 1, // Encounter string but not '-' and not number-like.
  18335. Might: 2, // Encounter string but number-like.
  18336. Not: 3 // Other cases
  18337. };
  18338. var inner$3 = makeInner();
  18339. /**
  18340. * @see {module:echarts/data/Source}
  18341. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  18342. * @return {string} sourceFormat
  18343. */
  18344. function detectSourceFormat(datasetModel) {
  18345. var data = datasetModel.option.source;
  18346. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18347. if (isTypedArray(data)) {
  18348. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18349. }
  18350. else if (isArray(data)) {
  18351. // FIXME Whether tolerate null in top level array?
  18352. if (data.length === 0) {
  18353. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18354. }
  18355. for (var i = 0, len = data.length; i < len; i++) {
  18356. var item = data[i];
  18357. if (item == null) {
  18358. continue;
  18359. }
  18360. else if (isArray(item)) {
  18361. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18362. break;
  18363. }
  18364. else if (isObject$1(item)) {
  18365. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18366. break;
  18367. }
  18368. }
  18369. }
  18370. else if (isObject$1(data)) {
  18371. for (var key in data) {
  18372. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  18373. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18374. break;
  18375. }
  18376. }
  18377. }
  18378. else if (data != null) {
  18379. throw new Error('Invalid data');
  18380. }
  18381. inner$3(datasetModel).sourceFormat = sourceFormat;
  18382. }
  18383. /**
  18384. * [Scenarios]:
  18385. * (1) Provide source data directly:
  18386. * series: {
  18387. * encode: {...},
  18388. * dimensions: [...]
  18389. * seriesLayoutBy: 'row',
  18390. * data: [[...]]
  18391. * }
  18392. * (2) Refer to datasetModel.
  18393. * series: [{
  18394. * encode: {...}
  18395. * // Ignore datasetIndex means `datasetIndex: 0`
  18396. * // and the dimensions defination in dataset is used
  18397. * }, {
  18398. * encode: {...},
  18399. * seriesLayoutBy: 'column',
  18400. * datasetIndex: 1
  18401. * }]
  18402. *
  18403. * Get data from series itself or datset.
  18404. * @return {module:echarts/data/Source} source
  18405. */
  18406. function getSource(seriesModel) {
  18407. return inner$3(seriesModel).source;
  18408. }
  18409. /**
  18410. * MUST be called before mergeOption of all series.
  18411. * @param {module:echarts/model/Global} ecModel
  18412. */
  18413. function resetSourceDefaulter(ecModel) {
  18414. // `datasetMap` is used to make default encode.
  18415. inner$3(ecModel).datasetMap = createHashMap();
  18416. }
  18417. /**
  18418. * [Caution]:
  18419. * MUST be called after series option merged and
  18420. * before "series.getInitailData()" called.
  18421. *
  18422. * [The rule of making default encode]:
  18423. * Category axis (if exists) alway map to the first dimension.
  18424. * Each other axis occupies a subsequent dimension.
  18425. *
  18426. * [Why make default encode]:
  18427. * Simplify the typing of encode in option, avoiding the case like that:
  18428. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  18429. * where the "y" have to be manually typed as "1, 2, 3, ...".
  18430. *
  18431. * @param {module:echarts/model/Series} seriesModel
  18432. */
  18433. function prepareSource(seriesModel) {
  18434. var seriesOption = seriesModel.option;
  18435. var data = seriesOption.data;
  18436. var sourceFormat = isTypedArray(data)
  18437. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  18438. var fromDataset = false;
  18439. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  18440. var sourceHeader = seriesOption.sourceHeader;
  18441. var dimensionsDefine = seriesOption.dimensions;
  18442. var datasetModel = getDatasetModel(seriesModel);
  18443. if (datasetModel) {
  18444. var datasetOption = datasetModel.option;
  18445. data = datasetOption.source;
  18446. sourceFormat = inner$3(datasetModel).sourceFormat;
  18447. fromDataset = true;
  18448. // These settings from series has higher priority.
  18449. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  18450. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  18451. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  18452. }
  18453. var completeResult = completeBySourceData(
  18454. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  18455. );
  18456. inner$3(seriesModel).source = new Source({
  18457. data: data,
  18458. fromDataset: fromDataset,
  18459. seriesLayoutBy: seriesLayoutBy,
  18460. sourceFormat: sourceFormat,
  18461. dimensionsDefine: completeResult.dimensionsDefine,
  18462. startIndex: completeResult.startIndex,
  18463. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  18464. // Note: dataset option does not have `encode`.
  18465. encodeDefine: seriesOption.encode
  18466. });
  18467. }
  18468. // return {startIndex, dimensionsDefine, dimensionsCount}
  18469. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  18470. if (!data) {
  18471. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  18472. }
  18473. var dimensionsDetectCount;
  18474. var startIndex;
  18475. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18476. // Rule: Most of the first line are string: it is header.
  18477. // Caution: consider a line with 5 string and 1 number,
  18478. // it still can not be sure it is a head, because the
  18479. // 5 string may be 5 values of category columns.
  18480. if (sourceHeader === 'auto' || sourceHeader == null) {
  18481. arrayRowsTravelFirst(function (val) {
  18482. // '-' is regarded as null/undefined.
  18483. if (val != null && val !== '-') {
  18484. if (isString(val)) {
  18485. startIndex == null && (startIndex = 1);
  18486. }
  18487. else {
  18488. startIndex = 0;
  18489. }
  18490. }
  18491. // 10 is an experience number, avoid long loop.
  18492. }, seriesLayoutBy, data, 10);
  18493. }
  18494. else {
  18495. startIndex = sourceHeader ? 1 : 0;
  18496. }
  18497. if (!dimensionsDefine && startIndex === 1) {
  18498. dimensionsDefine = [];
  18499. arrayRowsTravelFirst(function (val, index) {
  18500. dimensionsDefine[index] = val != null ? val : '';
  18501. }, seriesLayoutBy, data);
  18502. }
  18503. dimensionsDetectCount = dimensionsDefine
  18504. ? dimensionsDefine.length
  18505. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  18506. ? data.length
  18507. : data[0]
  18508. ? data[0].length
  18509. : null;
  18510. }
  18511. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18512. if (!dimensionsDefine) {
  18513. dimensionsDefine = objectRowsCollectDimensions(data);
  18514. }
  18515. }
  18516. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18517. if (!dimensionsDefine) {
  18518. dimensionsDefine = [];
  18519. each$1(data, function (colArr, key) {
  18520. dimensionsDefine.push(key);
  18521. });
  18522. }
  18523. }
  18524. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18525. var value0 = getDataItemValue(data[0]);
  18526. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  18527. }
  18528. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18529. if (__DEV__) {
  18530. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18531. }
  18532. }
  18533. return {
  18534. startIndex: startIndex,
  18535. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  18536. dimensionsDetectCount: dimensionsDetectCount
  18537. };
  18538. }
  18539. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18540. // which is reasonable. But dimension name is duplicated.
  18541. // Returns undefined or an array contains only object without null/undefiend or string.
  18542. function normalizeDimensionsDefine(dimensionsDefine) {
  18543. if (!dimensionsDefine) {
  18544. // The meaning of null/undefined is different from empty array.
  18545. return;
  18546. }
  18547. var nameMap = createHashMap();
  18548. return map(dimensionsDefine, function (item, index) {
  18549. item = extend({}, isObject$1(item) ? item : {name: item});
  18550. // User can set null in dimensions.
  18551. // We dont auto specify name, othewise a given name may
  18552. // cause it be refered unexpectedly.
  18553. if (item.name == null) {
  18554. return item;
  18555. }
  18556. // Also consider number form like 2012.
  18557. item.name += '';
  18558. // User may also specify displayName.
  18559. // displayName will always exists except user not
  18560. // specified or dim name is not specified or detected.
  18561. // (A auto generated dim name will not be used as
  18562. // displayName).
  18563. if (item.displayName == null) {
  18564. item.displayName = item.name;
  18565. }
  18566. var exist = nameMap.get(item.name);
  18567. if (!exist) {
  18568. nameMap.set(item.name, {count: 1});
  18569. }
  18570. else {
  18571. item.name += '-' + exist.count++;
  18572. }
  18573. return item;
  18574. });
  18575. }
  18576. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18577. maxLoop == null && (maxLoop = Infinity);
  18578. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18579. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18580. cb(data[i] ? data[i][0] : null, i);
  18581. }
  18582. }
  18583. else {
  18584. var value0 = data[0] || [];
  18585. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18586. cb(value0[i], i);
  18587. }
  18588. }
  18589. }
  18590. function objectRowsCollectDimensions(data) {
  18591. var firstIndex = 0;
  18592. var obj;
  18593. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18594. if (obj) {
  18595. var dimensions = [];
  18596. each$1(obj, function (value, key) {
  18597. dimensions.push(key);
  18598. });
  18599. return dimensions;
  18600. }
  18601. }
  18602. /**
  18603. * [The strategy of the arrengment of data dimensions for dataset]:
  18604. * "value way": all axes are non-category axes. So series one by one take
  18605. * several (the number is coordSysDims.length) dimensions from dataset.
  18606. * The result of data arrengment of data dimensions like:
  18607. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18608. * "category way": at least one axis is category axis. So the the first data
  18609. * dimension is always mapped to the first category axis and shared by
  18610. * all of the series. The other data dimensions are taken by series like
  18611. * "value way" does.
  18612. * The result of data arrengment of data dimensions like:
  18613. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18614. *
  18615. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  18616. * @param {module:model/Series} seriesModel
  18617. * @param {module:data/Source} source
  18618. * @return {Object} encode Never be `null/undefined`.
  18619. */
  18620. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18621. var encode = {};
  18622. var datasetModel = getDatasetModel(seriesModel);
  18623. // Currently only make default when using dataset, util more reqirements occur.
  18624. if (!datasetModel || !coordDimensions) {
  18625. return encode;
  18626. }
  18627. var encodeItemName = [];
  18628. var encodeSeriesName = [];
  18629. var ecModel = seriesModel.ecModel;
  18630. var datasetMap = inner$3(ecModel).datasetMap;
  18631. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18632. var baseCategoryDimIndex;
  18633. var categoryWayValueDimStart;
  18634. coordDimensions = coordDimensions.slice();
  18635. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18636. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {name: coordDimInfo});
  18637. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18638. baseCategoryDimIndex = coordDimIdx;
  18639. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  18640. }
  18641. encode[coordDimInfo.name] = [];
  18642. });
  18643. var datasetRecord = datasetMap.get(key)
  18644. || datasetMap.set(key, {categoryWayDim: categoryWayValueDimStart, valueWayDim: 0});
  18645. // TODO
  18646. // Auto detect first time axis and do arrangement.
  18647. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18648. var coordDimName = coordDimInfo.name;
  18649. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18650. // In value way.
  18651. if (baseCategoryDimIndex == null) {
  18652. var start = datasetRecord.valueWayDim;
  18653. pushDim(encode[coordDimName], start, count);
  18654. pushDim(encodeSeriesName, start, count);
  18655. datasetRecord.valueWayDim += count;
  18656. // ??? TODO give a better default series name rule?
  18657. // especially when encode x y specified.
  18658. // consider: when mutiple series share one dimension
  18659. // category axis, series name should better use
  18660. // the other dimsion name. On the other hand, use
  18661. // both dimensions name.
  18662. }
  18663. // In category way, the first category axis.
  18664. else if (baseCategoryDimIndex === coordDimIdx) {
  18665. pushDim(encode[coordDimName], 0, count);
  18666. pushDim(encodeItemName, 0, count);
  18667. }
  18668. // In category way, the other axis.
  18669. else {
  18670. var start = datasetRecord.categoryWayDim;
  18671. pushDim(encode[coordDimName], start, count);
  18672. pushDim(encodeSeriesName, start, count);
  18673. datasetRecord.categoryWayDim += count;
  18674. }
  18675. });
  18676. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18677. for (var i = 0; i < idxCount; i++) {
  18678. dimIdxArr.push(idxFrom + i);
  18679. }
  18680. }
  18681. function getDataDimCountOnCoordDim(coordDimInfo) {
  18682. var dimsDef = coordDimInfo.dimsDef;
  18683. return dimsDef ? dimsDef.length : 1;
  18684. }
  18685. encodeItemName.length && (encode.itemName = encodeItemName);
  18686. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18687. return encode;
  18688. }
  18689. /**
  18690. * Work for data like [{name: ..., value: ...}, ...].
  18691. *
  18692. * @param {module:model/Series} seriesModel
  18693. * @param {module:data/Source} source
  18694. * @return {Object} encode Never be `null/undefined`.
  18695. */
  18696. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18697. var encode = {};
  18698. var datasetModel = getDatasetModel(seriesModel);
  18699. // Currently only make default when using dataset, util more reqirements occur.
  18700. if (!datasetModel) {
  18701. return encode;
  18702. }
  18703. var sourceFormat = source.sourceFormat;
  18704. var dimensionsDefine = source.dimensionsDefine;
  18705. var potentialNameDimIndex;
  18706. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18707. each$1(dimensionsDefine, function (dim, idx) {
  18708. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  18709. potentialNameDimIndex = idx;
  18710. }
  18711. });
  18712. }
  18713. // idxResult: {v, n}.
  18714. var idxResult = (function () {
  18715. var idxRes0 = {};
  18716. var idxRes1 = {};
  18717. var guessRecords = [];
  18718. // 5 is an experience value.
  18719. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18720. var guessResult = doGuessOrdinal(
  18721. source.data, sourceFormat, source.seriesLayoutBy,
  18722. dimensionsDefine, source.startIndex, i
  18723. );
  18724. guessRecords.push(guessResult);
  18725. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18726. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18727. // and then find a name dim with the priority:
  18728. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18729. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18730. idxRes0.v = i;
  18731. }
  18732. if (idxRes0.n == null
  18733. || (idxRes0.n === idxRes0.v)
  18734. || (!isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not)
  18735. ) {
  18736. idxRes0.n = i;
  18737. }
  18738. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18739. return idxRes0;
  18740. }
  18741. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18742. // find the first BE_ORDINAL.Might as the value dim,
  18743. // and then find a name dim with the priority:
  18744. // "other dim" > "the value dim itself".
  18745. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18746. // treated as number.
  18747. if (!isPureNumber) {
  18748. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18749. idxRes1.v = i;
  18750. }
  18751. if (idxRes1.n == null || (idxRes1.n === idxRes1.v)) {
  18752. idxRes1.n = i;
  18753. }
  18754. }
  18755. }
  18756. function fulfilled(idxResult) {
  18757. return idxResult.v != null && idxResult.n != null;
  18758. }
  18759. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18760. })();
  18761. if (idxResult) {
  18762. encode.value = idxResult.v;
  18763. // `potentialNameDimIndex` has highest priority.
  18764. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18765. // By default, label use itemName in charts.
  18766. // So we dont set encodeLabel here.
  18767. encode.itemName = [nameDimIndex];
  18768. encode.seriesName = [nameDimIndex];
  18769. }
  18770. return encode;
  18771. }
  18772. /**
  18773. * If return null/undefined, indicate that should not use datasetModel.
  18774. */
  18775. function getDatasetModel(seriesModel) {
  18776. var option = seriesModel.option;
  18777. // Caution: consider the scenario:
  18778. // A dataset is declared and a series is not expected to use the dataset,
  18779. // and at the beginning `setOption({series: { noData })` (just prepare other
  18780. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18781. // the user should set an empty array to avoid that dataset is used by default.
  18782. var thisData = option.data;
  18783. if (!thisData) {
  18784. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18785. }
  18786. }
  18787. /**
  18788. * The rule should not be complex, otherwise user might not
  18789. * be able to known where the data is wrong.
  18790. * The code is ugly, but how to make it neat?
  18791. *
  18792. * @param {module:echars/data/Source} source
  18793. * @param {number} dimIndex
  18794. * @return {BE_ORDINAL} guess result.
  18795. */
  18796. function guessOrdinal(source, dimIndex) {
  18797. return doGuessOrdinal(
  18798. source.data,
  18799. source.sourceFormat,
  18800. source.seriesLayoutBy,
  18801. source.dimensionsDefine,
  18802. source.startIndex,
  18803. dimIndex
  18804. );
  18805. }
  18806. // dimIndex may be overflow source data.
  18807. // return {BE_ORDINAL}
  18808. function doGuessOrdinal(
  18809. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18810. ) {
  18811. var result;
  18812. // Experience value.
  18813. var maxLoop = 5;
  18814. if (isTypedArray(data)) {
  18815. return BE_ORDINAL.Not;
  18816. }
  18817. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18818. // always exists in source.
  18819. var dimName;
  18820. var dimType;
  18821. if (dimensionsDefine) {
  18822. var dimDefItem = dimensionsDefine[dimIndex];
  18823. if (isObject$1(dimDefItem)) {
  18824. dimName = dimDefItem.name;
  18825. dimType = dimDefItem.type;
  18826. }
  18827. else if (isString(dimDefItem)) {
  18828. dimName = dimDefItem;
  18829. }
  18830. }
  18831. if (dimType != null) {
  18832. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  18833. }
  18834. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18835. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18836. var sample = data[dimIndex];
  18837. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18838. if ((result = detectValue(sample[startIndex + i])) != null) {
  18839. return result;
  18840. }
  18841. }
  18842. }
  18843. else {
  18844. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18845. var row = data[startIndex + i];
  18846. if (row && (result = detectValue(row[dimIndex])) != null) {
  18847. return result;
  18848. }
  18849. }
  18850. }
  18851. }
  18852. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18853. if (!dimName) {
  18854. return BE_ORDINAL.Not;
  18855. }
  18856. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18857. var item = data[i];
  18858. if (item && (result = detectValue(item[dimName])) != null) {
  18859. return result;
  18860. }
  18861. }
  18862. }
  18863. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18864. if (!dimName) {
  18865. return BE_ORDINAL.Not;
  18866. }
  18867. var sample = data[dimName];
  18868. if (!sample || isTypedArray(sample)) {
  18869. return BE_ORDINAL.Not;
  18870. }
  18871. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18872. if ((result = detectValue(sample[i])) != null) {
  18873. return result;
  18874. }
  18875. }
  18876. }
  18877. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18878. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18879. var item = data[i];
  18880. var val = getDataItemValue(item);
  18881. if (!isArray(val)) {
  18882. return BE_ORDINAL.Not;
  18883. }
  18884. if ((result = detectValue(val[dimIndex])) != null) {
  18885. return result;
  18886. }
  18887. }
  18888. }
  18889. function detectValue(val) {
  18890. var beStr = isString(val);
  18891. // Consider usage convenience, '1', '2' will be treated as "number".
  18892. // `isFinit('')` get `true`.
  18893. if (val != null && isFinite(val) && val !== '') {
  18894. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  18895. }
  18896. else if (beStr && val !== '-') {
  18897. return BE_ORDINAL.Must;
  18898. }
  18899. }
  18900. return BE_ORDINAL.Not;
  18901. }
  18902. /*
  18903. * Licensed to the Apache Software Foundation (ASF) under one
  18904. * or more contributor license agreements. See the NOTICE file
  18905. * distributed with this work for additional information
  18906. * regarding copyright ownership. The ASF licenses this file
  18907. * to you under the Apache License, Version 2.0 (the
  18908. * "License"); you may not use this file except in compliance
  18909. * with the License. You may obtain a copy of the License at
  18910. *
  18911. * http://www.apache.org/licenses/LICENSE-2.0
  18912. *
  18913. * Unless required by applicable law or agreed to in writing,
  18914. * software distributed under the License is distributed on an
  18915. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18916. * KIND, either express or implied. See the License for the
  18917. * specific language governing permissions and limitations
  18918. * under the License.
  18919. */
  18920. /**
  18921. * ECharts global model
  18922. *
  18923. * @module {echarts/model/Global}
  18924. */
  18925. /**
  18926. * Caution: If the mechanism should be changed some day, these cases
  18927. * should be considered:
  18928. *
  18929. * (1) In `merge option` mode, if using the same option to call `setOption`
  18930. * many times, the result should be the same (try our best to ensure that).
  18931. * (2) In `merge option` mode, if a component has no id/name specified, it
  18932. * will be merged by index, and the result sequence of the components is
  18933. * consistent to the original sequence.
  18934. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  18935. * `mergeOption` in module:echarts/model/OptionManager.
  18936. */
  18937. var OPTION_INNER_KEY = '\0_ec_inner';
  18938. /**
  18939. * @alias module:echarts/model/Global
  18940. *
  18941. * @param {Object} option
  18942. * @param {module:echarts/model/Model} parentModel
  18943. * @param {Object} theme
  18944. */
  18945. var GlobalModel = Model.extend({
  18946. init: function (option, parentModel, theme, optionManager) {
  18947. theme = theme || {};
  18948. this.option = null; // Mark as not initialized.
  18949. /**
  18950. * @type {module:echarts/model/Model}
  18951. * @private
  18952. */
  18953. this._theme = new Model(theme);
  18954. /**
  18955. * @type {module:echarts/model/OptionManager}
  18956. */
  18957. this._optionManager = optionManager;
  18958. },
  18959. setOption: function (option, optionPreprocessorFuncs) {
  18960. assert$1(
  18961. !(OPTION_INNER_KEY in option),
  18962. 'please use chart.getOption()'
  18963. );
  18964. this._optionManager.setOption(option, optionPreprocessorFuncs);
  18965. this.resetOption(null);
  18966. },
  18967. /**
  18968. * @param {string} type null/undefined: reset all.
  18969. * 'recreate': force recreate all.
  18970. * 'timeline': only reset timeline option
  18971. * 'media': only reset media query option
  18972. * @return {boolean} Whether option changed.
  18973. */
  18974. resetOption: function (type) {
  18975. var optionChanged = false;
  18976. var optionManager = this._optionManager;
  18977. if (!type || type === 'recreate') {
  18978. var baseOption = optionManager.mountOption(type === 'recreate');
  18979. if (!this.option || type === 'recreate') {
  18980. initBase.call(this, baseOption);
  18981. }
  18982. else {
  18983. this.restoreData();
  18984. this.mergeOption(baseOption);
  18985. }
  18986. optionChanged = true;
  18987. }
  18988. if (type === 'timeline' || type === 'media') {
  18989. this.restoreData();
  18990. }
  18991. if (!type || type === 'recreate' || type === 'timeline') {
  18992. var timelineOption = optionManager.getTimelineOption(this);
  18993. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  18994. }
  18995. if (!type || type === 'recreate' || type === 'media') {
  18996. var mediaOptions = optionManager.getMediaOption(this, this._api);
  18997. if (mediaOptions.length) {
  18998. each$1(mediaOptions, function (mediaOption) {
  18999. this.mergeOption(mediaOption, optionChanged = true);
  19000. }, this);
  19001. }
  19002. }
  19003. return optionChanged;
  19004. },
  19005. /**
  19006. * @protected
  19007. */
  19008. mergeOption: function (newOption) {
  19009. var option = this.option;
  19010. var componentsMap = this._componentsMap;
  19011. var newCptTypes = [];
  19012. resetSourceDefaulter(this);
  19013. // If no component class, merge directly.
  19014. // For example: color, animaiton options, etc.
  19015. each$1(newOption, function (componentOption, mainType) {
  19016. if (componentOption == null) {
  19017. return;
  19018. }
  19019. if (!ComponentModel.hasClass(mainType)) {
  19020. // globalSettingTask.dirty();
  19021. option[mainType] = option[mainType] == null
  19022. ? clone(componentOption)
  19023. : merge(option[mainType], componentOption, true);
  19024. }
  19025. else if (mainType) {
  19026. newCptTypes.push(mainType);
  19027. }
  19028. });
  19029. ComponentModel.topologicalTravel(
  19030. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  19031. );
  19032. function visitComponent(mainType, dependencies) {
  19033. var newCptOptionList = normalizeToArray(newOption[mainType]);
  19034. var mapResult = mappingToExists(
  19035. componentsMap.get(mainType), newCptOptionList
  19036. );
  19037. makeIdAndName(mapResult);
  19038. // Set mainType and complete subType.
  19039. each$1(mapResult, function (item, index) {
  19040. var opt = item.option;
  19041. if (isObject$1(opt)) {
  19042. item.keyInfo.mainType = mainType;
  19043. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  19044. }
  19045. });
  19046. var dependentModels = getComponentsByTypes(
  19047. componentsMap, dependencies
  19048. );
  19049. option[mainType] = [];
  19050. componentsMap.set(mainType, []);
  19051. each$1(mapResult, function (resultItem, index) {
  19052. var componentModel = resultItem.exist;
  19053. var newCptOption = resultItem.option;
  19054. assert$1(
  19055. isObject$1(newCptOption) || componentModel,
  19056. 'Empty component definition'
  19057. );
  19058. // Consider where is no new option and should be merged using {},
  19059. // see removeEdgeAndAdd in topologicalTravel and
  19060. // ComponentModel.getAllClassMainTypes.
  19061. if (!newCptOption) {
  19062. componentModel.mergeOption({}, this);
  19063. componentModel.optionUpdated({}, false);
  19064. }
  19065. else {
  19066. var ComponentModelClass = ComponentModel.getClass(
  19067. mainType, resultItem.keyInfo.subType, true
  19068. );
  19069. if (componentModel && componentModel.constructor === ComponentModelClass) {
  19070. componentModel.name = resultItem.keyInfo.name;
  19071. // componentModel.settingTask && componentModel.settingTask.dirty();
  19072. componentModel.mergeOption(newCptOption, this);
  19073. componentModel.optionUpdated(newCptOption, false);
  19074. }
  19075. else {
  19076. // PENDING Global as parent ?
  19077. var extraOpt = extend(
  19078. {
  19079. dependentModels: dependentModels,
  19080. componentIndex: index
  19081. },
  19082. resultItem.keyInfo
  19083. );
  19084. componentModel = new ComponentModelClass(
  19085. newCptOption, this, this, extraOpt
  19086. );
  19087. extend(componentModel, extraOpt);
  19088. componentModel.init(newCptOption, this, this, extraOpt);
  19089. // Call optionUpdated after init.
  19090. // newCptOption has been used as componentModel.option
  19091. // and may be merged with theme and default, so pass null
  19092. // to avoid confusion.
  19093. componentModel.optionUpdated(null, true);
  19094. }
  19095. }
  19096. componentsMap.get(mainType)[index] = componentModel;
  19097. option[mainType][index] = componentModel.option;
  19098. }, this);
  19099. // Backup series for filtering.
  19100. if (mainType === 'series') {
  19101. createSeriesIndices(this, componentsMap.get('series'));
  19102. }
  19103. }
  19104. this._seriesIndicesMap = createHashMap(
  19105. this._seriesIndices = this._seriesIndices || []
  19106. );
  19107. },
  19108. /**
  19109. * Get option for output (cloned option and inner info removed)
  19110. * @public
  19111. * @return {Object}
  19112. */
  19113. getOption: function () {
  19114. var option = clone(this.option);
  19115. each$1(option, function (opts, mainType) {
  19116. if (ComponentModel.hasClass(mainType)) {
  19117. var opts = normalizeToArray(opts);
  19118. for (var i = opts.length - 1; i >= 0; i--) {
  19119. // Remove options with inner id.
  19120. if (isIdInner(opts[i])) {
  19121. opts.splice(i, 1);
  19122. }
  19123. }
  19124. option[mainType] = opts;
  19125. }
  19126. });
  19127. delete option[OPTION_INNER_KEY];
  19128. return option;
  19129. },
  19130. /**
  19131. * @return {module:echarts/model/Model}
  19132. */
  19133. getTheme: function () {
  19134. return this._theme;
  19135. },
  19136. /**
  19137. * @param {string} mainType
  19138. * @param {number} [idx=0]
  19139. * @return {module:echarts/model/Component}
  19140. */
  19141. getComponent: function (mainType, idx) {
  19142. var list = this._componentsMap.get(mainType);
  19143. if (list) {
  19144. return list[idx || 0];
  19145. }
  19146. },
  19147. /**
  19148. * If none of index and id and name used, return all components with mainType.
  19149. * @param {Object} condition
  19150. * @param {string} condition.mainType
  19151. * @param {string} [condition.subType] If ignore, only query by mainType
  19152. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  19153. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  19154. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  19155. * @return {Array.<module:echarts/model/Component>}
  19156. */
  19157. queryComponents: function (condition) {
  19158. var mainType = condition.mainType;
  19159. if (!mainType) {
  19160. return [];
  19161. }
  19162. var index = condition.index;
  19163. var id = condition.id;
  19164. var name = condition.name;
  19165. var cpts = this._componentsMap.get(mainType);
  19166. if (!cpts || !cpts.length) {
  19167. return [];
  19168. }
  19169. var result;
  19170. if (index != null) {
  19171. if (!isArray(index)) {
  19172. index = [index];
  19173. }
  19174. result = filter(map(index, function (idx) {
  19175. return cpts[idx];
  19176. }), function (val) {
  19177. return !!val;
  19178. });
  19179. }
  19180. else if (id != null) {
  19181. var isIdArray = isArray(id);
  19182. result = filter(cpts, function (cpt) {
  19183. return (isIdArray && indexOf(id, cpt.id) >= 0)
  19184. || (!isIdArray && cpt.id === id);
  19185. });
  19186. }
  19187. else if (name != null) {
  19188. var isNameArray = isArray(name);
  19189. result = filter(cpts, function (cpt) {
  19190. return (isNameArray && indexOf(name, cpt.name) >= 0)
  19191. || (!isNameArray && cpt.name === name);
  19192. });
  19193. }
  19194. else {
  19195. // Return all components with mainType
  19196. result = cpts.slice();
  19197. }
  19198. return filterBySubType(result, condition);
  19199. },
  19200. /**
  19201. * The interface is different from queryComponents,
  19202. * which is convenient for inner usage.
  19203. *
  19204. * @usage
  19205. * var result = findComponents(
  19206. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  19207. * );
  19208. * var result = findComponents(
  19209. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  19210. * );
  19211. * var result = findComponents(
  19212. * {mainType: 'series',
  19213. * filter: function (model, index) {...}}
  19214. * );
  19215. * // result like [component0, componnet1, ...]
  19216. *
  19217. * @param {Object} condition
  19218. * @param {string} condition.mainType Mandatory.
  19219. * @param {string} [condition.subType] Optional.
  19220. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  19221. * where xxx is mainType.
  19222. * If query attribute is null/undefined or has no index/id/name,
  19223. * do not filtering by query conditions, which is convenient for
  19224. * no-payload situations or when target of action is global.
  19225. * @param {Function} [condition.filter] parameter: component, return boolean.
  19226. * @return {Array.<module:echarts/model/Component>}
  19227. */
  19228. findComponents: function (condition) {
  19229. var query = condition.query;
  19230. var mainType = condition.mainType;
  19231. var queryCond = getQueryCond(query);
  19232. var result = queryCond
  19233. ? this.queryComponents(queryCond)
  19234. : this._componentsMap.get(mainType);
  19235. return doFilter(filterBySubType(result, condition));
  19236. function getQueryCond(q) {
  19237. var indexAttr = mainType + 'Index';
  19238. var idAttr = mainType + 'Id';
  19239. var nameAttr = mainType + 'Name';
  19240. return q && (
  19241. q[indexAttr] != null
  19242. || q[idAttr] != null
  19243. || q[nameAttr] != null
  19244. )
  19245. ? {
  19246. mainType: mainType,
  19247. // subType will be filtered finally.
  19248. index: q[indexAttr],
  19249. id: q[idAttr],
  19250. name: q[nameAttr]
  19251. }
  19252. : null;
  19253. }
  19254. function doFilter(res) {
  19255. return condition.filter
  19256. ? filter(res, condition.filter)
  19257. : res;
  19258. }
  19259. },
  19260. /**
  19261. * @usage
  19262. * eachComponent('legend', function (legendModel, index) {
  19263. * ...
  19264. * });
  19265. * eachComponent(function (componentType, model, index) {
  19266. * // componentType does not include subType
  19267. * // (componentType is 'xxx' but not 'xxx.aa')
  19268. * });
  19269. * eachComponent(
  19270. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  19271. * function (model, index) {...}
  19272. * );
  19273. * eachComponent(
  19274. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  19275. * function (model, index) {...}
  19276. * );
  19277. *
  19278. * @param {string|Object=} mainType When mainType is object, the definition
  19279. * is the same as the method 'findComponents'.
  19280. * @param {Function} cb
  19281. * @param {*} context
  19282. */
  19283. eachComponent: function (mainType, cb, context) {
  19284. var componentsMap = this._componentsMap;
  19285. if (typeof mainType === 'function') {
  19286. context = cb;
  19287. cb = mainType;
  19288. componentsMap.each(function (components, componentType) {
  19289. each$1(components, function (component, index) {
  19290. cb.call(context, componentType, component, index);
  19291. });
  19292. });
  19293. }
  19294. else if (isString(mainType)) {
  19295. each$1(componentsMap.get(mainType), cb, context);
  19296. }
  19297. else if (isObject$1(mainType)) {
  19298. var queryResult = this.findComponents(mainType);
  19299. each$1(queryResult, cb, context);
  19300. }
  19301. },
  19302. /**
  19303. * @param {string} name
  19304. * @return {Array.<module:echarts/model/Series>}
  19305. */
  19306. getSeriesByName: function (name) {
  19307. var series = this._componentsMap.get('series');
  19308. return filter(series, function (oneSeries) {
  19309. return oneSeries.name === name;
  19310. });
  19311. },
  19312. /**
  19313. * @param {number} seriesIndex
  19314. * @return {module:echarts/model/Series}
  19315. */
  19316. getSeriesByIndex: function (seriesIndex) {
  19317. return this._componentsMap.get('series')[seriesIndex];
  19318. },
  19319. /**
  19320. * Get series list before filtered by type.
  19321. * FIXME: rename to getRawSeriesByType?
  19322. *
  19323. * @param {string} subType
  19324. * @return {Array.<module:echarts/model/Series>}
  19325. */
  19326. getSeriesByType: function (subType) {
  19327. var series = this._componentsMap.get('series');
  19328. return filter(series, function (oneSeries) {
  19329. return oneSeries.subType === subType;
  19330. });
  19331. },
  19332. /**
  19333. * @return {Array.<module:echarts/model/Series>}
  19334. */
  19335. getSeries: function () {
  19336. return this._componentsMap.get('series').slice();
  19337. },
  19338. /**
  19339. * @return {number}
  19340. */
  19341. getSeriesCount: function () {
  19342. return this._componentsMap.get('series').length;
  19343. },
  19344. /**
  19345. * After filtering, series may be different
  19346. * frome raw series.
  19347. *
  19348. * @param {Function} cb
  19349. * @param {*} context
  19350. */
  19351. eachSeries: function (cb, context) {
  19352. assertSeriesInitialized(this);
  19353. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19354. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19355. cb.call(context, series, rawSeriesIndex);
  19356. }, this);
  19357. },
  19358. /**
  19359. * Iterate raw series before filtered.
  19360. *
  19361. * @param {Function} cb
  19362. * @param {*} context
  19363. */
  19364. eachRawSeries: function (cb, context) {
  19365. each$1(this._componentsMap.get('series'), cb, context);
  19366. },
  19367. /**
  19368. * After filtering, series may be different.
  19369. * frome raw series.
  19370. *
  19371. * @param {string} subType.
  19372. * @param {Function} cb
  19373. * @param {*} context
  19374. */
  19375. eachSeriesByType: function (subType, cb, context) {
  19376. assertSeriesInitialized(this);
  19377. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19378. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19379. if (series.subType === subType) {
  19380. cb.call(context, series, rawSeriesIndex);
  19381. }
  19382. }, this);
  19383. },
  19384. /**
  19385. * Iterate raw series before filtered of given type.
  19386. *
  19387. * @parma {string} subType
  19388. * @param {Function} cb
  19389. * @param {*} context
  19390. */
  19391. eachRawSeriesByType: function (subType, cb, context) {
  19392. return each$1(this.getSeriesByType(subType), cb, context);
  19393. },
  19394. /**
  19395. * @param {module:echarts/model/Series} seriesModel
  19396. */
  19397. isSeriesFiltered: function (seriesModel) {
  19398. assertSeriesInitialized(this);
  19399. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  19400. },
  19401. /**
  19402. * @return {Array.<number>}
  19403. */
  19404. getCurrentSeriesIndices: function () {
  19405. return (this._seriesIndices || []).slice();
  19406. },
  19407. /**
  19408. * @param {Function} cb
  19409. * @param {*} context
  19410. */
  19411. filterSeries: function (cb, context) {
  19412. assertSeriesInitialized(this);
  19413. var filteredSeries = filter(
  19414. this._componentsMap.get('series'), cb, context
  19415. );
  19416. createSeriesIndices(this, filteredSeries);
  19417. },
  19418. restoreData: function (payload) {
  19419. var componentsMap = this._componentsMap;
  19420. createSeriesIndices(this, componentsMap.get('series'));
  19421. var componentTypes = [];
  19422. componentsMap.each(function (components, componentType) {
  19423. componentTypes.push(componentType);
  19424. });
  19425. ComponentModel.topologicalTravel(
  19426. componentTypes,
  19427. ComponentModel.getAllClassMainTypes(),
  19428. function (componentType, dependencies) {
  19429. each$1(componentsMap.get(componentType), function (component) {
  19430. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  19431. && component.restoreData();
  19432. });
  19433. }
  19434. );
  19435. }
  19436. });
  19437. function isNotTargetSeries(seriesModel, payload) {
  19438. if (payload) {
  19439. var index = payload.seiresIndex;
  19440. var id = payload.seriesId;
  19441. var name = payload.seriesName;
  19442. return (index != null && seriesModel.componentIndex !== index)
  19443. || (id != null && seriesModel.id !== id)
  19444. || (name != null && seriesModel.name !== name);
  19445. }
  19446. }
  19447. /**
  19448. * @inner
  19449. */
  19450. function mergeTheme(option, theme) {
  19451. // PENDING
  19452. // NOT use `colorLayer` in theme if option has `color`
  19453. var notMergeColorLayer = option.color && !option.colorLayer;
  19454. each$1(theme, function (themeItem, name) {
  19455. if (name === 'colorLayer' && notMergeColorLayer) {
  19456. return;
  19457. }
  19458. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  19459. if (!ComponentModel.hasClass(name)) {
  19460. if (typeof themeItem === 'object') {
  19461. option[name] = !option[name]
  19462. ? clone(themeItem)
  19463. : merge(option[name], themeItem, false);
  19464. }
  19465. else {
  19466. if (option[name] == null) {
  19467. option[name] = themeItem;
  19468. }
  19469. }
  19470. }
  19471. });
  19472. }
  19473. function initBase(baseOption) {
  19474. baseOption = baseOption;
  19475. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  19476. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  19477. this.option = {};
  19478. this.option[OPTION_INNER_KEY] = 1;
  19479. /**
  19480. * Init with series: [], in case of calling findSeries method
  19481. * before series initialized.
  19482. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  19483. * @private
  19484. */
  19485. this._componentsMap = createHashMap({series: []});
  19486. /**
  19487. * Mapping between filtered series list and raw series list.
  19488. * key: filtered series indices, value: raw series indices.
  19489. * @type {Array.<nubmer>}
  19490. * @private
  19491. */
  19492. this._seriesIndices;
  19493. this._seriesIndicesMap;
  19494. mergeTheme(baseOption, this._theme.option);
  19495. // TODO Needs clone when merging to the unexisted property
  19496. merge(baseOption, globalDefault, false);
  19497. this.mergeOption(baseOption);
  19498. }
  19499. /**
  19500. * @inner
  19501. * @param {Array.<string>|string} types model types
  19502. * @return {Object} key: {string} type, value: {Array.<Object>} models
  19503. */
  19504. function getComponentsByTypes(componentsMap, types) {
  19505. if (!isArray(types)) {
  19506. types = types ? [types] : [];
  19507. }
  19508. var ret = {};
  19509. each$1(types, function (type) {
  19510. ret[type] = (componentsMap.get(type) || []).slice();
  19511. });
  19512. return ret;
  19513. }
  19514. /**
  19515. * @inner
  19516. */
  19517. function determineSubType(mainType, newCptOption, existComponent) {
  19518. var subType = newCptOption.type
  19519. ? newCptOption.type
  19520. : existComponent
  19521. ? existComponent.subType
  19522. // Use determineSubType only when there is no existComponent.
  19523. : ComponentModel.determineSubType(mainType, newCptOption);
  19524. // tooltip, markline, markpoint may always has no subType
  19525. return subType;
  19526. }
  19527. /**
  19528. * @inner
  19529. */
  19530. function createSeriesIndices(ecModel, seriesModels) {
  19531. ecModel._seriesIndicesMap = createHashMap(
  19532. ecModel._seriesIndices = map(seriesModels, function (series) {
  19533. return series.componentIndex;
  19534. }) || []
  19535. );
  19536. }
  19537. /**
  19538. * @inner
  19539. */
  19540. function filterBySubType(components, condition) {
  19541. // Using hasOwnProperty for restrict. Consider
  19542. // subType is undefined in user payload.
  19543. return condition.hasOwnProperty('subType')
  19544. ? filter(components, function (cpt) {
  19545. return cpt.subType === condition.subType;
  19546. })
  19547. : components;
  19548. }
  19549. /**
  19550. * @inner
  19551. */
  19552. function assertSeriesInitialized(ecModel) {
  19553. // Components that use _seriesIndices should depends on series component,
  19554. // which make sure that their initialization is after series.
  19555. if (__DEV__) {
  19556. if (!ecModel._seriesIndices) {
  19557. throw new Error('Option should contains series.');
  19558. }
  19559. }
  19560. }
  19561. mixin(GlobalModel, colorPaletteMixin);
  19562. /*
  19563. * Licensed to the Apache Software Foundation (ASF) under one
  19564. * or more contributor license agreements. See the NOTICE file
  19565. * distributed with this work for additional information
  19566. * regarding copyright ownership. The ASF licenses this file
  19567. * to you under the Apache License, Version 2.0 (the
  19568. * "License"); you may not use this file except in compliance
  19569. * with the License. You may obtain a copy of the License at
  19570. *
  19571. * http://www.apache.org/licenses/LICENSE-2.0
  19572. *
  19573. * Unless required by applicable law or agreed to in writing,
  19574. * software distributed under the License is distributed on an
  19575. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19576. * KIND, either express or implied. See the License for the
  19577. * specific language governing permissions and limitations
  19578. * under the License.
  19579. */
  19580. var echartsAPIList = [
  19581. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  19582. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  19583. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  19584. ];
  19585. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  19586. function ExtensionAPI(chartInstance) {
  19587. each$1(echartsAPIList, function (name) {
  19588. this[name] = bind(chartInstance[name], chartInstance);
  19589. }, this);
  19590. }
  19591. /*
  19592. * Licensed to the Apache Software Foundation (ASF) under one
  19593. * or more contributor license agreements. See the NOTICE file
  19594. * distributed with this work for additional information
  19595. * regarding copyright ownership. The ASF licenses this file
  19596. * to you under the Apache License, Version 2.0 (the
  19597. * "License"); you may not use this file except in compliance
  19598. * with the License. You may obtain a copy of the License at
  19599. *
  19600. * http://www.apache.org/licenses/LICENSE-2.0
  19601. *
  19602. * Unless required by applicable law or agreed to in writing,
  19603. * software distributed under the License is distributed on an
  19604. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19605. * KIND, either express or implied. See the License for the
  19606. * specific language governing permissions and limitations
  19607. * under the License.
  19608. */
  19609. var coordinateSystemCreators = {};
  19610. function CoordinateSystemManager() {
  19611. this._coordinateSystems = [];
  19612. }
  19613. CoordinateSystemManager.prototype = {
  19614. constructor: CoordinateSystemManager,
  19615. create: function (ecModel, api) {
  19616. var coordinateSystems = [];
  19617. each$1(coordinateSystemCreators, function (creater, type) {
  19618. var list = creater.create(ecModel, api);
  19619. coordinateSystems = coordinateSystems.concat(list || []);
  19620. });
  19621. this._coordinateSystems = coordinateSystems;
  19622. },
  19623. update: function (ecModel, api) {
  19624. each$1(this._coordinateSystems, function (coordSys) {
  19625. coordSys.update && coordSys.update(ecModel, api);
  19626. });
  19627. },
  19628. getCoordinateSystems: function () {
  19629. return this._coordinateSystems.slice();
  19630. }
  19631. };
  19632. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  19633. coordinateSystemCreators[type] = coordinateSystemCreator;
  19634. };
  19635. CoordinateSystemManager.get = function (type) {
  19636. return coordinateSystemCreators[type];
  19637. };
  19638. /*
  19639. * Licensed to the Apache Software Foundation (ASF) under one
  19640. * or more contributor license agreements. See the NOTICE file
  19641. * distributed with this work for additional information
  19642. * regarding copyright ownership. The ASF licenses this file
  19643. * to you under the Apache License, Version 2.0 (the
  19644. * "License"); you may not use this file except in compliance
  19645. * with the License. You may obtain a copy of the License at
  19646. *
  19647. * http://www.apache.org/licenses/LICENSE-2.0
  19648. *
  19649. * Unless required by applicable law or agreed to in writing,
  19650. * software distributed under the License is distributed on an
  19651. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19652. * KIND, either express or implied. See the License for the
  19653. * specific language governing permissions and limitations
  19654. * under the License.
  19655. */
  19656. /**
  19657. * ECharts option manager
  19658. *
  19659. * @module {echarts/model/OptionManager}
  19660. */
  19661. var each$4 = each$1;
  19662. var clone$3 = clone;
  19663. var map$1 = map;
  19664. var merge$1 = merge;
  19665. var QUERY_REG = /^(min|max)?(.+)$/;
  19666. /**
  19667. * TERM EXPLANATIONS:
  19668. *
  19669. * [option]:
  19670. *
  19671. * An object that contains definitions of components. For example:
  19672. * var option = {
  19673. * title: {...},
  19674. * legend: {...},
  19675. * visualMap: {...},
  19676. * series: [
  19677. * {data: [...]},
  19678. * {data: [...]},
  19679. * ...
  19680. * ]
  19681. * };
  19682. *
  19683. * [rawOption]:
  19684. *
  19685. * An object input to echarts.setOption. 'rawOption' may be an
  19686. * 'option', or may be an object contains multi-options. For example:
  19687. * var option = {
  19688. * baseOption: {
  19689. * title: {...},
  19690. * legend: {...},
  19691. * series: [
  19692. * {data: [...]},
  19693. * {data: [...]},
  19694. * ...
  19695. * ]
  19696. * },
  19697. * timeline: {...},
  19698. * options: [
  19699. * {title: {...}, series: {data: [...]}},
  19700. * {title: {...}, series: {data: [...]}},
  19701. * ...
  19702. * ],
  19703. * media: [
  19704. * {
  19705. * query: {maxWidth: 320},
  19706. * option: {series: {x: 20}, visualMap: {show: false}}
  19707. * },
  19708. * {
  19709. * query: {minWidth: 320, maxWidth: 720},
  19710. * option: {series: {x: 500}, visualMap: {show: true}}
  19711. * },
  19712. * {
  19713. * option: {series: {x: 1200}, visualMap: {show: true}}
  19714. * }
  19715. * ]
  19716. * };
  19717. *
  19718. * @alias module:echarts/model/OptionManager
  19719. * @param {module:echarts/ExtensionAPI} api
  19720. */
  19721. function OptionManager(api) {
  19722. /**
  19723. * @private
  19724. * @type {module:echarts/ExtensionAPI}
  19725. */
  19726. this._api = api;
  19727. /**
  19728. * @private
  19729. * @type {Array.<number>}
  19730. */
  19731. this._timelineOptions = [];
  19732. /**
  19733. * @private
  19734. * @type {Array.<Object>}
  19735. */
  19736. this._mediaList = [];
  19737. /**
  19738. * @private
  19739. * @type {Object}
  19740. */
  19741. this._mediaDefault;
  19742. /**
  19743. * -1, means default.
  19744. * empty means no media.
  19745. * @private
  19746. * @type {Array.<number>}
  19747. */
  19748. this._currentMediaIndices = [];
  19749. /**
  19750. * @private
  19751. * @type {Object}
  19752. */
  19753. this._optionBackup;
  19754. /**
  19755. * @private
  19756. * @type {Object}
  19757. */
  19758. this._newBaseOption;
  19759. }
  19760. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19761. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19762. // rawOption cloned and backuped when timeline changed, which does no
  19763. // good to performance. What's more, that both timeline and setOption
  19764. // method supply 'notMerge' brings complex and some problems.
  19765. // Consider this case:
  19766. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19767. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19768. OptionManager.prototype = {
  19769. constructor: OptionManager,
  19770. /**
  19771. * @public
  19772. * @param {Object} rawOption Raw option.
  19773. * @param {module:echarts/model/Global} ecModel
  19774. * @param {Array.<Function>} optionPreprocessorFuncs
  19775. * @return {Object} Init option
  19776. */
  19777. setOption: function (rawOption, optionPreprocessorFuncs) {
  19778. if (rawOption) {
  19779. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19780. each$1(normalizeToArray(rawOption.series), function (series) {
  19781. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19782. });
  19783. }
  19784. // Caution: some series modify option data, if do not clone,
  19785. // it should ensure that the repeat modify correctly
  19786. // (create a new object when modify itself).
  19787. rawOption = clone$3(rawOption);
  19788. // FIXME
  19789. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19790. var oldOptionBackup = this._optionBackup;
  19791. var newParsedOption = parseRawOption.call(
  19792. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19793. );
  19794. this._newBaseOption = newParsedOption.baseOption;
  19795. // For setOption at second time (using merge mode);
  19796. if (oldOptionBackup) {
  19797. // Only baseOption can be merged.
  19798. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19799. // For simplicity, timeline options and media options do not support merge,
  19800. // that is, if you `setOption` twice and both has timeline options, the latter
  19801. // timeline opitons will not be merged to the formers, but just substitude them.
  19802. if (newParsedOption.timelineOptions.length) {
  19803. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19804. }
  19805. if (newParsedOption.mediaList.length) {
  19806. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19807. }
  19808. if (newParsedOption.mediaDefault) {
  19809. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19810. }
  19811. }
  19812. else {
  19813. this._optionBackup = newParsedOption;
  19814. }
  19815. },
  19816. /**
  19817. * @param {boolean} isRecreate
  19818. * @return {Object}
  19819. */
  19820. mountOption: function (isRecreate) {
  19821. var optionBackup = this._optionBackup;
  19822. // TODO
  19823. // 如果没有reset功能则不clone。
  19824. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19825. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19826. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19827. this._currentMediaIndices = [];
  19828. return clone$3(isRecreate
  19829. // this._optionBackup.baseOption, which is created at the first `setOption`
  19830. // called, and is merged into every new option by inner method `mergeOption`
  19831. // each time `setOption` called, can be only used in `isRecreate`, because
  19832. // its reliability is under suspicion. In other cases option merge is
  19833. // performed by `model.mergeOption`.
  19834. ? optionBackup.baseOption : this._newBaseOption
  19835. );
  19836. },
  19837. /**
  19838. * @param {module:echarts/model/Global} ecModel
  19839. * @return {Object}
  19840. */
  19841. getTimelineOption: function (ecModel) {
  19842. var option;
  19843. var timelineOptions = this._timelineOptions;
  19844. if (timelineOptions.length) {
  19845. // getTimelineOption can only be called after ecModel inited,
  19846. // so we can get currentIndex from timelineModel.
  19847. var timelineModel = ecModel.getComponent('timeline');
  19848. if (timelineModel) {
  19849. option = clone$3(
  19850. timelineOptions[timelineModel.getCurrentIndex()],
  19851. true
  19852. );
  19853. }
  19854. }
  19855. return option;
  19856. },
  19857. /**
  19858. * @param {module:echarts/model/Global} ecModel
  19859. * @return {Array.<Object>}
  19860. */
  19861. getMediaOption: function (ecModel) {
  19862. var ecWidth = this._api.getWidth();
  19863. var ecHeight = this._api.getHeight();
  19864. var mediaList = this._mediaList;
  19865. var mediaDefault = this._mediaDefault;
  19866. var indices = [];
  19867. var result = [];
  19868. // No media defined.
  19869. if (!mediaList.length && !mediaDefault) {
  19870. return result;
  19871. }
  19872. // Multi media may be applied, the latter defined media has higher priority.
  19873. for (var i = 0, len = mediaList.length; i < len; i++) {
  19874. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19875. indices.push(i);
  19876. }
  19877. }
  19878. // FIXME
  19879. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  19880. if (!indices.length && mediaDefault) {
  19881. indices = [-1];
  19882. }
  19883. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19884. result = map$1(indices, function (index) {
  19885. return clone$3(
  19886. index === -1 ? mediaDefault.option : mediaList[index].option
  19887. );
  19888. });
  19889. }
  19890. // Otherwise return nothing.
  19891. this._currentMediaIndices = indices;
  19892. return result;
  19893. }
  19894. };
  19895. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  19896. var timelineOptions = [];
  19897. var mediaList = [];
  19898. var mediaDefault;
  19899. var baseOption;
  19900. // Compatible with ec2.
  19901. var timelineOpt = rawOption.timeline;
  19902. if (rawOption.baseOption) {
  19903. baseOption = rawOption.baseOption;
  19904. }
  19905. // For timeline
  19906. if (timelineOpt || rawOption.options) {
  19907. baseOption = baseOption || {};
  19908. timelineOptions = (rawOption.options || []).slice();
  19909. }
  19910. // For media query
  19911. if (rawOption.media) {
  19912. baseOption = baseOption || {};
  19913. var media = rawOption.media;
  19914. each$4(media, function (singleMedia) {
  19915. if (singleMedia && singleMedia.option) {
  19916. if (singleMedia.query) {
  19917. mediaList.push(singleMedia);
  19918. }
  19919. else if (!mediaDefault) {
  19920. // Use the first media default.
  19921. mediaDefault = singleMedia;
  19922. }
  19923. }
  19924. });
  19925. }
  19926. // For normal option
  19927. if (!baseOption) {
  19928. baseOption = rawOption;
  19929. }
  19930. // Set timelineOpt to baseOption in ec3,
  19931. // which is convenient for merge option.
  19932. if (!baseOption.timeline) {
  19933. baseOption.timeline = timelineOpt;
  19934. }
  19935. // Preprocess.
  19936. each$4([baseOption].concat(timelineOptions)
  19937. .concat(map(mediaList, function (media) {
  19938. return media.option;
  19939. })),
  19940. function (option) {
  19941. each$4(optionPreprocessorFuncs, function (preProcess) {
  19942. preProcess(option, isNew);
  19943. });
  19944. }
  19945. );
  19946. return {
  19947. baseOption: baseOption,
  19948. timelineOptions: timelineOptions,
  19949. mediaDefault: mediaDefault,
  19950. mediaList: mediaList
  19951. };
  19952. }
  19953. /**
  19954. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  19955. * Support: width, height, aspectRatio
  19956. * Can use max or min as prefix.
  19957. */
  19958. function applyMediaQuery(query, ecWidth, ecHeight) {
  19959. var realMap = {
  19960. width: ecWidth,
  19961. height: ecHeight,
  19962. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  19963. };
  19964. var applicatable = true;
  19965. each$1(query, function (value, attr) {
  19966. var matched = attr.match(QUERY_REG);
  19967. if (!matched || !matched[1] || !matched[2]) {
  19968. return;
  19969. }
  19970. var operator = matched[1];
  19971. var realAttr = matched[2].toLowerCase();
  19972. if (!compare(realMap[realAttr], value, operator)) {
  19973. applicatable = false;
  19974. }
  19975. });
  19976. return applicatable;
  19977. }
  19978. function compare(real, expect, operator) {
  19979. if (operator === 'min') {
  19980. return real >= expect;
  19981. }
  19982. else if (operator === 'max') {
  19983. return real <= expect;
  19984. }
  19985. else { // Equals
  19986. return real === expect;
  19987. }
  19988. }
  19989. function indicesEquals(indices1, indices2) {
  19990. // indices is always order by asc and has only finite number.
  19991. return indices1.join(',') === indices2.join(',');
  19992. }
  19993. /**
  19994. * Consider case:
  19995. * `chart.setOption(opt1);`
  19996. * Then user do some interaction like dataZoom, dataView changing.
  19997. * `chart.setOption(opt2);`
  19998. * Then user press 'reset button' in toolbox.
  19999. *
  20000. * After doing that all of the interaction effects should be reset, the
  20001. * chart should be the same as the result of invoke
  20002. * `chart.setOption(opt1); chart.setOption(opt2);`.
  20003. *
  20004. * Although it is not able ensure that
  20005. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  20006. * `chart.setOption(merge(opt1, opt2));` exactly,
  20007. * this might be the only simple way to implement that feature.
  20008. *
  20009. * MEMO: We've considered some other approaches:
  20010. * 1. Each model handle its self restoration but not uniform treatment.
  20011. * (Too complex in logic and error-prone)
  20012. * 2. Use a shadow ecModel. (Performace expensive)
  20013. */
  20014. function mergeOption(oldOption, newOption) {
  20015. newOption = newOption || {};
  20016. each$4(newOption, function (newCptOpt, mainType) {
  20017. if (newCptOpt == null) {
  20018. return;
  20019. }
  20020. var oldCptOpt = oldOption[mainType];
  20021. if (!ComponentModel.hasClass(mainType)) {
  20022. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  20023. }
  20024. else {
  20025. newCptOpt = normalizeToArray(newCptOpt);
  20026. oldCptOpt = normalizeToArray(oldCptOpt);
  20027. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  20028. oldOption[mainType] = map$1(mapResult, function (item) {
  20029. return (item.option && item.exist)
  20030. ? merge$1(item.exist, item.option, true)
  20031. : (item.exist || item.option);
  20032. });
  20033. }
  20034. });
  20035. }
  20036. /*
  20037. * Licensed to the Apache Software Foundation (ASF) under one
  20038. * or more contributor license agreements. See the NOTICE file
  20039. * distributed with this work for additional information
  20040. * regarding copyright ownership. The ASF licenses this file
  20041. * to you under the Apache License, Version 2.0 (the
  20042. * "License"); you may not use this file except in compliance
  20043. * with the License. You may obtain a copy of the License at
  20044. *
  20045. * http://www.apache.org/licenses/LICENSE-2.0
  20046. *
  20047. * Unless required by applicable law or agreed to in writing,
  20048. * software distributed under the License is distributed on an
  20049. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20050. * KIND, either express or implied. See the License for the
  20051. * specific language governing permissions and limitations
  20052. * under the License.
  20053. */
  20054. var each$5 = each$1;
  20055. var isObject$3 = isObject$1;
  20056. var POSSIBLE_STYLES = [
  20057. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  20058. 'chordStyle', 'label', 'labelLine'
  20059. ];
  20060. function compatEC2ItemStyle(opt) {
  20061. var itemStyleOpt = opt && opt.itemStyle;
  20062. if (!itemStyleOpt) {
  20063. return;
  20064. }
  20065. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  20066. var styleName = POSSIBLE_STYLES[i];
  20067. var normalItemStyleOpt = itemStyleOpt.normal;
  20068. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  20069. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  20070. opt[styleName] = opt[styleName] || {};
  20071. if (!opt[styleName].normal) {
  20072. opt[styleName].normal = normalItemStyleOpt[styleName];
  20073. }
  20074. else {
  20075. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  20076. }
  20077. normalItemStyleOpt[styleName] = null;
  20078. }
  20079. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  20080. opt[styleName] = opt[styleName] || {};
  20081. if (!opt[styleName].emphasis) {
  20082. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  20083. }
  20084. else {
  20085. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  20086. }
  20087. emphasisItemStyleOpt[styleName] = null;
  20088. }
  20089. }
  20090. }
  20091. function convertNormalEmphasis(opt, optType, useExtend) {
  20092. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  20093. var normalOpt = opt[optType].normal;
  20094. var emphasisOpt = opt[optType].emphasis;
  20095. if (normalOpt) {
  20096. // Timeline controlStyle has other properties besides normal and emphasis
  20097. if (useExtend) {
  20098. opt[optType].normal = opt[optType].emphasis = null;
  20099. defaults(opt[optType], normalOpt);
  20100. }
  20101. else {
  20102. opt[optType] = normalOpt;
  20103. }
  20104. }
  20105. if (emphasisOpt) {
  20106. opt.emphasis = opt.emphasis || {};
  20107. opt.emphasis[optType] = emphasisOpt;
  20108. }
  20109. }
  20110. }
  20111. function removeEC3NormalStatus(opt) {
  20112. convertNormalEmphasis(opt, 'itemStyle');
  20113. convertNormalEmphasis(opt, 'lineStyle');
  20114. convertNormalEmphasis(opt, 'areaStyle');
  20115. convertNormalEmphasis(opt, 'label');
  20116. convertNormalEmphasis(opt, 'labelLine');
  20117. // treemap
  20118. convertNormalEmphasis(opt, 'upperLabel');
  20119. // graph
  20120. convertNormalEmphasis(opt, 'edgeLabel');
  20121. }
  20122. function compatTextStyle(opt, propName) {
  20123. // Check whether is not object (string\null\undefined ...)
  20124. var labelOptSingle = isObject$3(opt) && opt[propName];
  20125. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  20126. if (textStyle) {
  20127. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  20128. var propName = TEXT_STYLE_OPTIONS[i];
  20129. if (textStyle.hasOwnProperty(propName)) {
  20130. labelOptSingle[propName] = textStyle[propName];
  20131. }
  20132. }
  20133. }
  20134. }
  20135. function compatEC3CommonStyles(opt) {
  20136. if (opt) {
  20137. removeEC3NormalStatus(opt);
  20138. compatTextStyle(opt, 'label');
  20139. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  20140. }
  20141. }
  20142. function processSeries(seriesOpt) {
  20143. if (!isObject$3(seriesOpt)) {
  20144. return;
  20145. }
  20146. compatEC2ItemStyle(seriesOpt);
  20147. removeEC3NormalStatus(seriesOpt);
  20148. compatTextStyle(seriesOpt, 'label');
  20149. // treemap
  20150. compatTextStyle(seriesOpt, 'upperLabel');
  20151. // graph
  20152. compatTextStyle(seriesOpt, 'edgeLabel');
  20153. if (seriesOpt.emphasis) {
  20154. compatTextStyle(seriesOpt.emphasis, 'label');
  20155. // treemap
  20156. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  20157. // graph
  20158. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  20159. }
  20160. var markPoint = seriesOpt.markPoint;
  20161. if (markPoint) {
  20162. compatEC2ItemStyle(markPoint);
  20163. compatEC3CommonStyles(markPoint);
  20164. }
  20165. var markLine = seriesOpt.markLine;
  20166. if (markLine) {
  20167. compatEC2ItemStyle(markLine);
  20168. compatEC3CommonStyles(markLine);
  20169. }
  20170. var markArea = seriesOpt.markArea;
  20171. if (markArea) {
  20172. compatEC3CommonStyles(markArea);
  20173. }
  20174. var data = seriesOpt.data;
  20175. // Break with ec3: if `setOption` again, there may be no `type` in option,
  20176. // then the backward compat based on option type will not be performed.
  20177. if (seriesOpt.type === 'graph') {
  20178. data = data || seriesOpt.nodes;
  20179. var edgeData = seriesOpt.links || seriesOpt.edges;
  20180. if (edgeData && !isTypedArray(edgeData)) {
  20181. for (var i = 0; i < edgeData.length; i++) {
  20182. compatEC3CommonStyles(edgeData[i]);
  20183. }
  20184. }
  20185. each$1(seriesOpt.categories, function (opt) {
  20186. removeEC3NormalStatus(opt);
  20187. });
  20188. }
  20189. if (data && !isTypedArray(data)) {
  20190. for (var i = 0; i < data.length; i++) {
  20191. compatEC3CommonStyles(data[i]);
  20192. }
  20193. }
  20194. // mark point data
  20195. var markPoint = seriesOpt.markPoint;
  20196. if (markPoint && markPoint.data) {
  20197. var mpData = markPoint.data;
  20198. for (var i = 0; i < mpData.length; i++) {
  20199. compatEC3CommonStyles(mpData[i]);
  20200. }
  20201. }
  20202. // mark line data
  20203. var markLine = seriesOpt.markLine;
  20204. if (markLine && markLine.data) {
  20205. var mlData = markLine.data;
  20206. for (var i = 0; i < mlData.length; i++) {
  20207. if (isArray(mlData[i])) {
  20208. compatEC3CommonStyles(mlData[i][0]);
  20209. compatEC3CommonStyles(mlData[i][1]);
  20210. }
  20211. else {
  20212. compatEC3CommonStyles(mlData[i]);
  20213. }
  20214. }
  20215. }
  20216. // Series
  20217. if (seriesOpt.type === 'gauge') {
  20218. compatTextStyle(seriesOpt, 'axisLabel');
  20219. compatTextStyle(seriesOpt, 'title');
  20220. compatTextStyle(seriesOpt, 'detail');
  20221. }
  20222. else if (seriesOpt.type === 'treemap') {
  20223. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  20224. each$1(seriesOpt.levels, function (opt) {
  20225. removeEC3NormalStatus(opt);
  20226. });
  20227. }
  20228. else if (seriesOpt.type === 'tree') {
  20229. removeEC3NormalStatus(seriesOpt.leaves);
  20230. }
  20231. // sunburst starts from ec4, so it does not need to compat levels.
  20232. }
  20233. function toArr(o) {
  20234. return isArray(o) ? o : o ? [o] : [];
  20235. }
  20236. function toObj(o) {
  20237. return (isArray(o) ? o[0] : o) || {};
  20238. }
  20239. var compatStyle = function (option, isTheme) {
  20240. each$5(toArr(option.series), function (seriesOpt) {
  20241. isObject$3(seriesOpt) && processSeries(seriesOpt);
  20242. });
  20243. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  20244. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  20245. each$5(
  20246. axes,
  20247. function (axisName) {
  20248. each$5(toArr(option[axisName]), function (axisOpt) {
  20249. if (axisOpt) {
  20250. compatTextStyle(axisOpt, 'axisLabel');
  20251. compatTextStyle(axisOpt.axisPointer, 'label');
  20252. }
  20253. });
  20254. }
  20255. );
  20256. each$5(toArr(option.parallel), function (parallelOpt) {
  20257. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  20258. compatTextStyle(parallelAxisDefault, 'axisLabel');
  20259. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  20260. });
  20261. each$5(toArr(option.calendar), function (calendarOpt) {
  20262. convertNormalEmphasis(calendarOpt, 'itemStyle');
  20263. compatTextStyle(calendarOpt, 'dayLabel');
  20264. compatTextStyle(calendarOpt, 'monthLabel');
  20265. compatTextStyle(calendarOpt, 'yearLabel');
  20266. });
  20267. // radar.name.textStyle
  20268. each$5(toArr(option.radar), function (radarOpt) {
  20269. compatTextStyle(radarOpt, 'name');
  20270. });
  20271. each$5(toArr(option.geo), function (geoOpt) {
  20272. if (isObject$3(geoOpt)) {
  20273. compatEC3CommonStyles(geoOpt);
  20274. each$5(toArr(geoOpt.regions), function (regionObj) {
  20275. compatEC3CommonStyles(regionObj);
  20276. });
  20277. }
  20278. });
  20279. each$5(toArr(option.timeline), function (timelineOpt) {
  20280. compatEC3CommonStyles(timelineOpt);
  20281. convertNormalEmphasis(timelineOpt, 'label');
  20282. convertNormalEmphasis(timelineOpt, 'itemStyle');
  20283. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  20284. var data = timelineOpt.data;
  20285. isArray(data) && each$1(data, function (item) {
  20286. if (isObject$1(item)) {
  20287. convertNormalEmphasis(item, 'label');
  20288. convertNormalEmphasis(item, 'itemStyle');
  20289. }
  20290. });
  20291. });
  20292. each$5(toArr(option.toolbox), function (toolboxOpt) {
  20293. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  20294. each$5(toolboxOpt.feature, function (featureOpt) {
  20295. convertNormalEmphasis(featureOpt, 'iconStyle');
  20296. });
  20297. });
  20298. compatTextStyle(toObj(option.axisPointer), 'label');
  20299. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  20300. };
  20301. /*
  20302. * Licensed to the Apache Software Foundation (ASF) under one
  20303. * or more contributor license agreements. See the NOTICE file
  20304. * distributed with this work for additional information
  20305. * regarding copyright ownership. The ASF licenses this file
  20306. * to you under the Apache License, Version 2.0 (the
  20307. * "License"); you may not use this file except in compliance
  20308. * with the License. You may obtain a copy of the License at
  20309. *
  20310. * http://www.apache.org/licenses/LICENSE-2.0
  20311. *
  20312. * Unless required by applicable law or agreed to in writing,
  20313. * software distributed under the License is distributed on an
  20314. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20315. * KIND, either express or implied. See the License for the
  20316. * specific language governing permissions and limitations
  20317. * under the License.
  20318. */
  20319. // Compatitable with 2.0
  20320. function get(opt, path) {
  20321. path = path.split(',');
  20322. var obj = opt;
  20323. for (var i = 0; i < path.length; i++) {
  20324. obj = obj && obj[path[i]];
  20325. if (obj == null) {
  20326. break;
  20327. }
  20328. }
  20329. return obj;
  20330. }
  20331. function set$1(opt, path, val, overwrite) {
  20332. path = path.split(',');
  20333. var obj = opt;
  20334. var key;
  20335. for (var i = 0; i < path.length - 1; i++) {
  20336. key = path[i];
  20337. if (obj[key] == null) {
  20338. obj[key] = {};
  20339. }
  20340. obj = obj[key];
  20341. }
  20342. if (overwrite || obj[path[i]] == null) {
  20343. obj[path[i]] = val;
  20344. }
  20345. }
  20346. function compatLayoutProperties(option) {
  20347. each$1(LAYOUT_PROPERTIES, function (prop) {
  20348. if (prop[0] in option && !(prop[1] in option)) {
  20349. option[prop[1]] = option[prop[0]];
  20350. }
  20351. });
  20352. }
  20353. var LAYOUT_PROPERTIES = [
  20354. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  20355. ];
  20356. var COMPATITABLE_COMPONENTS = [
  20357. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  20358. ];
  20359. var backwardCompat = function (option, isTheme) {
  20360. compatStyle(option, isTheme);
  20361. // Make sure series array for model initialization.
  20362. option.series = normalizeToArray(option.series);
  20363. each$1(option.series, function (seriesOpt) {
  20364. if (!isObject$1(seriesOpt)) {
  20365. return;
  20366. }
  20367. var seriesType = seriesOpt.type;
  20368. if (seriesType === 'line') {
  20369. if (seriesOpt.clipOverflow != null) {
  20370. seriesOpt.clip = seriesOpt.clipOverflow;
  20371. }
  20372. }
  20373. else if (seriesType === 'pie' || seriesType === 'gauge') {
  20374. if (seriesOpt.clockWise != null) {
  20375. seriesOpt.clockwise = seriesOpt.clockWise;
  20376. }
  20377. }
  20378. else if (seriesType === 'gauge') {
  20379. var pointerColor = get(seriesOpt, 'pointer.color');
  20380. pointerColor != null
  20381. && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  20382. }
  20383. compatLayoutProperties(seriesOpt);
  20384. });
  20385. // dataRange has changed to visualMap
  20386. if (option.dataRange) {
  20387. option.visualMap = option.dataRange;
  20388. }
  20389. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  20390. var options = option[componentName];
  20391. if (options) {
  20392. if (!isArray(options)) {
  20393. options = [options];
  20394. }
  20395. each$1(options, function (option) {
  20396. compatLayoutProperties(option);
  20397. });
  20398. }
  20399. });
  20400. };
  20401. /*
  20402. * Licensed to the Apache Software Foundation (ASF) under one
  20403. * or more contributor license agreements. See the NOTICE file
  20404. * distributed with this work for additional information
  20405. * regarding copyright ownership. The ASF licenses this file
  20406. * to you under the Apache License, Version 2.0 (the
  20407. * "License"); you may not use this file except in compliance
  20408. * with the License. You may obtain a copy of the License at
  20409. *
  20410. * http://www.apache.org/licenses/LICENSE-2.0
  20411. *
  20412. * Unless required by applicable law or agreed to in writing,
  20413. * software distributed under the License is distributed on an
  20414. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20415. * KIND, either express or implied. See the License for the
  20416. * specific language governing permissions and limitations
  20417. * under the License.
  20418. */
  20419. // (1) [Caution]: the logic is correct based on the premises:
  20420. // data processing stage is blocked in stream.
  20421. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  20422. // (2) Only register once when import repeatly.
  20423. // Should be executed after series filtered and before stack calculation.
  20424. var dataStack = function (ecModel) {
  20425. var stackInfoMap = createHashMap();
  20426. ecModel.eachSeries(function (seriesModel) {
  20427. var stack = seriesModel.get('stack');
  20428. // Compatibal: when `stack` is set as '', do not stack.
  20429. if (stack) {
  20430. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  20431. var data = seriesModel.getData();
  20432. var stackInfo = {
  20433. // Used for calculate axis extent automatically.
  20434. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  20435. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  20436. stackedDimension: data.getCalculationInfo('stackedDimension'),
  20437. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  20438. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  20439. data: data,
  20440. seriesModel: seriesModel
  20441. };
  20442. // If stacked on axis that do not support data stack.
  20443. if (!stackInfo.stackedDimension
  20444. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  20445. ) {
  20446. return;
  20447. }
  20448. stackInfoList.length && data.setCalculationInfo(
  20449. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  20450. );
  20451. stackInfoList.push(stackInfo);
  20452. }
  20453. });
  20454. stackInfoMap.each(calculateStack);
  20455. };
  20456. function calculateStack(stackInfoList) {
  20457. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  20458. var resultVal = [];
  20459. var resultNaN = [NaN, NaN];
  20460. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  20461. var targetData = targetStackInfo.data;
  20462. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  20463. // Should not write on raw data, because stack series model list changes
  20464. // depending on legend selection.
  20465. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  20466. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  20467. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  20468. // should also be NaN, to draw a appropriate belt area.
  20469. if (isNaN(sum)) {
  20470. return resultNaN;
  20471. }
  20472. var byValue;
  20473. var stackedDataRawIndex;
  20474. if (isStackedByIndex) {
  20475. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  20476. }
  20477. else {
  20478. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  20479. }
  20480. // If stackOver is NaN, chart view will render point on value start.
  20481. var stackedOver = NaN;
  20482. for (var j = idxInStack - 1; j >= 0; j--) {
  20483. var stackInfo = stackInfoList[j];
  20484. // Has been optimized by inverted indices on `stackedByDimension`.
  20485. if (!isStackedByIndex) {
  20486. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  20487. }
  20488. if (stackedDataRawIndex >= 0) {
  20489. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  20490. // Considering positive stack, negative stack and empty data
  20491. if ((sum >= 0 && val > 0) // Positive stack
  20492. || (sum <= 0 && val < 0) // Negative stack
  20493. ) {
  20494. sum += val;
  20495. stackedOver = val;
  20496. break;
  20497. }
  20498. }
  20499. }
  20500. resultVal[0] = sum;
  20501. resultVal[1] = stackedOver;
  20502. return resultVal;
  20503. });
  20504. targetData.hostModel.setData(newData);
  20505. // Update for consequent calculation
  20506. targetStackInfo.data = newData;
  20507. });
  20508. }
  20509. /*
  20510. * Licensed to the Apache Software Foundation (ASF) under one
  20511. * or more contributor license agreements. See the NOTICE file
  20512. * distributed with this work for additional information
  20513. * regarding copyright ownership. The ASF licenses this file
  20514. * to you under the Apache License, Version 2.0 (the
  20515. * "License"); you may not use this file except in compliance
  20516. * with the License. You may obtain a copy of the License at
  20517. *
  20518. * http://www.apache.org/licenses/LICENSE-2.0
  20519. *
  20520. * Unless required by applicable law or agreed to in writing,
  20521. * software distributed under the License is distributed on an
  20522. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20523. * KIND, either express or implied. See the License for the
  20524. * specific language governing permissions and limitations
  20525. * under the License.
  20526. */
  20527. // TODO
  20528. // ??? refactor? check the outer usage of data provider.
  20529. // merge with defaultDimValueGetter?
  20530. /**
  20531. * If normal array used, mutable chunk size is supported.
  20532. * If typed array used, chunk size must be fixed.
  20533. */
  20534. function DefaultDataProvider(source, dimSize) {
  20535. if (!Source.isInstance(source)) {
  20536. source = Source.seriesDataToSource(source);
  20537. }
  20538. this._source = source;
  20539. var data = this._data = source.data;
  20540. var sourceFormat = source.sourceFormat;
  20541. // Typed array. TODO IE10+?
  20542. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20543. if (__DEV__) {
  20544. if (dimSize == null) {
  20545. throw new Error('Typed array data must specify dimension size');
  20546. }
  20547. }
  20548. this._offset = 0;
  20549. this._dimSize = dimSize;
  20550. this._data = data;
  20551. }
  20552. var methods = providerMethods[
  20553. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  20554. ? sourceFormat + '_' + source.seriesLayoutBy
  20555. : sourceFormat
  20556. ];
  20557. if (__DEV__) {
  20558. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20559. }
  20560. extend(this, methods);
  20561. }
  20562. var providerProto = DefaultDataProvider.prototype;
  20563. // If data is pure without style configuration
  20564. providerProto.pure = false;
  20565. // If data is persistent and will not be released after use.
  20566. providerProto.persistent = true;
  20567. // ???! FIXME legacy data provider do not has method getSource
  20568. providerProto.getSource = function () {
  20569. return this._source;
  20570. };
  20571. var providerMethods = {
  20572. 'arrayRows_column': {
  20573. pure: true,
  20574. count: function () {
  20575. return Math.max(0, this._data.length - this._source.startIndex);
  20576. },
  20577. getItem: function (idx) {
  20578. return this._data[idx + this._source.startIndex];
  20579. },
  20580. appendData: appendDataSimply
  20581. },
  20582. 'arrayRows_row': {
  20583. pure: true,
  20584. count: function () {
  20585. var row = this._data[0];
  20586. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  20587. },
  20588. getItem: function (idx) {
  20589. idx += this._source.startIndex;
  20590. var item = [];
  20591. var data = this._data;
  20592. for (var i = 0; i < data.length; i++) {
  20593. var row = data[i];
  20594. item.push(row ? row[idx] : null);
  20595. }
  20596. return item;
  20597. },
  20598. appendData: function () {
  20599. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20600. }
  20601. },
  20602. 'objectRows': {
  20603. pure: true,
  20604. count: countSimply,
  20605. getItem: getItemSimply,
  20606. appendData: appendDataSimply
  20607. },
  20608. 'keyedColumns': {
  20609. pure: true,
  20610. count: function () {
  20611. var dimName = this._source.dimensionsDefine[0].name;
  20612. var col = this._data[dimName];
  20613. return col ? col.length : 0;
  20614. },
  20615. getItem: function (idx) {
  20616. var item = [];
  20617. var dims = this._source.dimensionsDefine;
  20618. for (var i = 0; i < dims.length; i++) {
  20619. var col = this._data[dims[i].name];
  20620. item.push(col ? col[idx] : null);
  20621. }
  20622. return item;
  20623. },
  20624. appendData: function (newData) {
  20625. var data = this._data;
  20626. each$1(newData, function (newCol, key) {
  20627. var oldCol = data[key] || (data[key] = []);
  20628. for (var i = 0; i < (newCol || []).length; i++) {
  20629. oldCol.push(newCol[i]);
  20630. }
  20631. });
  20632. }
  20633. },
  20634. 'original': {
  20635. count: countSimply,
  20636. getItem: getItemSimply,
  20637. appendData: appendDataSimply
  20638. },
  20639. 'typedArray': {
  20640. persistent: false,
  20641. pure: true,
  20642. count: function () {
  20643. return this._data ? (this._data.length / this._dimSize) : 0;
  20644. },
  20645. getItem: function (idx, out) {
  20646. idx = idx - this._offset;
  20647. out = out || [];
  20648. var offset = this._dimSize * idx;
  20649. for (var i = 0; i < this._dimSize; i++) {
  20650. out[i] = this._data[offset + i];
  20651. }
  20652. return out;
  20653. },
  20654. appendData: function (newData) {
  20655. if (__DEV__) {
  20656. assert$1(
  20657. isTypedArray(newData),
  20658. 'Added data must be TypedArray if data in initialization is TypedArray'
  20659. );
  20660. }
  20661. this._data = newData;
  20662. },
  20663. // Clean self if data is already used.
  20664. clean: function () {
  20665. // PENDING
  20666. this._offset += this.count();
  20667. this._data = null;
  20668. }
  20669. }
  20670. };
  20671. function countSimply() {
  20672. return this._data.length;
  20673. }
  20674. function getItemSimply(idx) {
  20675. return this._data[idx];
  20676. }
  20677. function appendDataSimply(newData) {
  20678. for (var i = 0; i < newData.length; i++) {
  20679. this._data.push(newData[i]);
  20680. }
  20681. }
  20682. var rawValueGetters = {
  20683. arrayRows: getRawValueSimply,
  20684. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20685. return dimIndex != null ? dataItem[dimName] : dataItem;
  20686. },
  20687. keyedColumns: getRawValueSimply,
  20688. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20689. // FIXME
  20690. // In some case (markpoint in geo (geo-map.html)), dataItem
  20691. // is {coord: [...]}
  20692. var value = getDataItemValue(dataItem);
  20693. return (dimIndex == null || !(value instanceof Array))
  20694. ? value
  20695. : value[dimIndex];
  20696. },
  20697. typedArray: getRawValueSimply
  20698. };
  20699. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20700. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20701. }
  20702. var defaultDimValueGetters = {
  20703. arrayRows: getDimValueSimply,
  20704. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20705. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20706. },
  20707. keyedColumns: getDimValueSimply,
  20708. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20709. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20710. // If dataItem is an plain object with no value field, the var `value`
  20711. // will be assigned with the object, but it will be tread correctly
  20712. // in the `convertDataValue`.
  20713. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20714. // If any dataItem is like { value: 10 }
  20715. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20716. this.hasItemOption = true;
  20717. }
  20718. return converDataValue(
  20719. (value instanceof Array)
  20720. ? value[dimIndex]
  20721. // If value is a single number or something else not array.
  20722. : value,
  20723. this._dimensionInfos[dimName]
  20724. );
  20725. },
  20726. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20727. return dataItem[dimIndex];
  20728. }
  20729. };
  20730. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20731. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20732. }
  20733. /**
  20734. * This helper method convert value in data.
  20735. * @param {string|number|Date} value
  20736. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20737. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20738. */
  20739. function converDataValue(value, dimInfo) {
  20740. // Performance sensitive.
  20741. var dimType = dimInfo && dimInfo.type;
  20742. if (dimType === 'ordinal') {
  20743. // If given value is a category string
  20744. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20745. return ordinalMeta
  20746. ? ordinalMeta.parseAndCollect(value)
  20747. : value;
  20748. }
  20749. if (dimType === 'time'
  20750. // spead up when using timestamp
  20751. && typeof value !== 'number'
  20752. && value != null
  20753. && value !== '-'
  20754. ) {
  20755. value = +parseDate(value);
  20756. }
  20757. // dimType defaults 'number'.
  20758. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20759. // parse to NaN.
  20760. return (value == null || value === '')
  20761. ? NaN
  20762. // If string (like '-'), using '+' parse to NaN
  20763. // If object, also parse to NaN
  20764. : +value;
  20765. }
  20766. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20767. // Consider persistent.
  20768. // Caution: why use raw value to display on label or tooltip?
  20769. // A reason is to avoid format. For example time value we do not know
  20770. // how to format is expected. More over, if stack is used, calculated
  20771. // value may be 0.91000000001, which have brings trouble to display.
  20772. // TODO: consider how to treat null/undefined/NaN when display?
  20773. /**
  20774. * @param {module:echarts/data/List} data
  20775. * @param {number} dataIndex
  20776. * @param {string|number} [dim] dimName or dimIndex
  20777. * @return {Array.<number>|string|number} can be null/undefined.
  20778. */
  20779. function retrieveRawValue(data, dataIndex, dim) {
  20780. if (!data) {
  20781. return;
  20782. }
  20783. // Consider data may be not persistent.
  20784. var dataItem = data.getRawDataItem(dataIndex);
  20785. if (dataItem == null) {
  20786. return;
  20787. }
  20788. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20789. var dimName;
  20790. var dimIndex;
  20791. var dimInfo = data.getDimensionInfo(dim);
  20792. if (dimInfo) {
  20793. dimName = dimInfo.name;
  20794. dimIndex = dimInfo.index;
  20795. }
  20796. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20797. }
  20798. /**
  20799. * Compatible with some cases (in pie, map) like:
  20800. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20801. * where only sourceFormat is 'original' and 'objectRows' supported.
  20802. *
  20803. * ??? TODO
  20804. * Supported detail options in data item when using 'arrayRows'.
  20805. *
  20806. * @param {module:echarts/data/List} data
  20807. * @param {number} dataIndex
  20808. * @param {string} attr like 'selected'
  20809. */
  20810. function retrieveRawAttr(data, dataIndex, attr) {
  20811. if (!data) {
  20812. return;
  20813. }
  20814. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20815. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20816. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20817. ) {
  20818. return;
  20819. }
  20820. var dataItem = data.getRawDataItem(dataIndex);
  20821. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20822. dataItem = null;
  20823. }
  20824. if (dataItem) {
  20825. return dataItem[attr];
  20826. }
  20827. }
  20828. /*
  20829. * Licensed to the Apache Software Foundation (ASF) under one
  20830. * or more contributor license agreements. See the NOTICE file
  20831. * distributed with this work for additional information
  20832. * regarding copyright ownership. The ASF licenses this file
  20833. * to you under the Apache License, Version 2.0 (the
  20834. * "License"); you may not use this file except in compliance
  20835. * with the License. You may obtain a copy of the License at
  20836. *
  20837. * http://www.apache.org/licenses/LICENSE-2.0
  20838. *
  20839. * Unless required by applicable law or agreed to in writing,
  20840. * software distributed under the License is distributed on an
  20841. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20842. * KIND, either express or implied. See the License for the
  20843. * specific language governing permissions and limitations
  20844. * under the License.
  20845. */
  20846. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20847. // PENDING A little ugly
  20848. var dataFormatMixin = {
  20849. /**
  20850. * Get params for formatter
  20851. * @param {number} dataIndex
  20852. * @param {string} [dataType]
  20853. * @return {Object}
  20854. */
  20855. getDataParams: function (dataIndex, dataType) {
  20856. var data = this.getData(dataType);
  20857. var rawValue = this.getRawValue(dataIndex, dataType);
  20858. var rawDataIndex = data.getRawIndex(dataIndex);
  20859. var name = data.getName(dataIndex);
  20860. var itemOpt = data.getRawDataItem(dataIndex);
  20861. var color = data.getItemVisual(dataIndex, 'color');
  20862. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  20863. var tooltipModel = this.ecModel.getComponent('tooltip');
  20864. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20865. var renderMode = getTooltipRenderMode(renderModeOption);
  20866. var mainType = this.mainType;
  20867. var isSeries = mainType === 'series';
  20868. var userOutput = data.userOutput;
  20869. return {
  20870. componentType: mainType,
  20871. componentSubType: this.subType,
  20872. componentIndex: this.componentIndex,
  20873. seriesType: isSeries ? this.subType : null,
  20874. seriesIndex: this.seriesIndex,
  20875. seriesId: isSeries ? this.id : null,
  20876. seriesName: isSeries ? this.name : null,
  20877. name: name,
  20878. dataIndex: rawDataIndex,
  20879. data: itemOpt,
  20880. dataType: dataType,
  20881. value: rawValue,
  20882. color: color,
  20883. borderColor: borderColor,
  20884. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  20885. encode: userOutput ? userOutput.encode : null,
  20886. marker: getTooltipMarker({
  20887. color: color,
  20888. renderMode: renderMode
  20889. }),
  20890. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20891. $vars: ['seriesName', 'name', 'value']
  20892. };
  20893. },
  20894. /**
  20895. * Format label
  20896. * @param {number} dataIndex
  20897. * @param {string} [status='normal'] 'normal' or 'emphasis'
  20898. * @param {string} [dataType]
  20899. * @param {number} [dimIndex] Only used in some chart that
  20900. * use formatter in different dimensions, like radar.
  20901. * @param {string} [labelProp='label']
  20902. * @return {string} If not formatter, return null/undefined
  20903. */
  20904. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  20905. status = status || 'normal';
  20906. var data = this.getData(dataType);
  20907. var itemModel = data.getItemModel(dataIndex);
  20908. var params = this.getDataParams(dataIndex, dataType);
  20909. if (dimIndex != null && (params.value instanceof Array)) {
  20910. params.value = params.value[dimIndex];
  20911. }
  20912. var formatter = itemModel.get(
  20913. status === 'normal'
  20914. ? [labelProp || 'label', 'formatter']
  20915. : [status, labelProp || 'label', 'formatter']
  20916. );
  20917. if (typeof formatter === 'function') {
  20918. params.status = status;
  20919. params.dimensionIndex = dimIndex;
  20920. return formatter(params);
  20921. }
  20922. else if (typeof formatter === 'string') {
  20923. var str = formatTpl(formatter, params);
  20924. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20925. // Do not support '}' in dim name util have to.
  20926. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  20927. var len = dim.length;
  20928. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  20929. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  20930. }
  20931. return retrieveRawValue(data, dataIndex, dim);
  20932. });
  20933. }
  20934. },
  20935. /**
  20936. * Get raw value in option
  20937. * @param {number} idx
  20938. * @param {string} [dataType]
  20939. * @return {Array|number|string}
  20940. */
  20941. getRawValue: function (idx, dataType) {
  20942. return retrieveRawValue(this.getData(dataType), idx);
  20943. },
  20944. /**
  20945. * Should be implemented.
  20946. * @param {number} dataIndex
  20947. * @param {boolean} [multipleSeries=false]
  20948. * @param {number} [dataType]
  20949. * @return {string} tooltip string
  20950. */
  20951. formatTooltip: function () {
  20952. // Empty function
  20953. }
  20954. };
  20955. /*
  20956. * Licensed to the Apache Software Foundation (ASF) under one
  20957. * or more contributor license agreements. See the NOTICE file
  20958. * distributed with this work for additional information
  20959. * regarding copyright ownership. The ASF licenses this file
  20960. * to you under the Apache License, Version 2.0 (the
  20961. * "License"); you may not use this file except in compliance
  20962. * with the License. You may obtain a copy of the License at
  20963. *
  20964. * http://www.apache.org/licenses/LICENSE-2.0
  20965. *
  20966. * Unless required by applicable law or agreed to in writing,
  20967. * software distributed under the License is distributed on an
  20968. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20969. * KIND, either express or implied. See the License for the
  20970. * specific language governing permissions and limitations
  20971. * under the License.
  20972. */
  20973. /**
  20974. * @param {Object} define
  20975. * @return See the return of `createTask`.
  20976. */
  20977. function createTask(define) {
  20978. return new Task(define);
  20979. }
  20980. /**
  20981. * @constructor
  20982. * @param {Object} define
  20983. * @param {Function} define.reset Custom reset
  20984. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  20985. * @param {Function} [define.count] count is used to determin data task.
  20986. * @param {Function} [define.onDirty] count is used to determin data task.
  20987. */
  20988. function Task(define) {
  20989. define = define || {};
  20990. this._reset = define.reset;
  20991. this._plan = define.plan;
  20992. this._count = define.count;
  20993. this._onDirty = define.onDirty;
  20994. this._dirty = true;
  20995. // Context must be specified implicitly, to
  20996. // avoid miss update context when model changed.
  20997. this.context;
  20998. }
  20999. var taskProto = Task.prototype;
  21000. /**
  21001. * @param {Object} performArgs
  21002. * @param {number} [performArgs.step] Specified step.
  21003. * @param {number} [performArgs.skip] Skip customer perform call.
  21004. * @param {number} [performArgs.modBy] Sampling window size.
  21005. * @param {number} [performArgs.modDataCount] Sampling count.
  21006. */
  21007. taskProto.perform = function (performArgs) {
  21008. var upTask = this._upstream;
  21009. var skip = performArgs && performArgs.skip;
  21010. // TODO some refactor.
  21011. // Pull data. Must pull data each time, because context.data
  21012. // may be updated by Series.setData.
  21013. if (this._dirty && upTask) {
  21014. var context = this.context;
  21015. context.data = context.outputData = upTask.context.outputData;
  21016. }
  21017. if (this.__pipeline) {
  21018. this.__pipeline.currentTask = this;
  21019. }
  21020. var planResult;
  21021. if (this._plan && !skip) {
  21022. planResult = this._plan(this.context);
  21023. }
  21024. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  21025. // elements uniformed distributed when progress, especially when moving or zooming.
  21026. var lastModBy = normalizeModBy(this._modBy);
  21027. var lastModDataCount = this._modDataCount || 0;
  21028. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  21029. var modDataCount = performArgs && performArgs.modDataCount || 0;
  21030. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  21031. planResult = 'reset';
  21032. }
  21033. function normalizeModBy(val) {
  21034. !(val >= 1) && (val = 1); // jshint ignore:line
  21035. return val;
  21036. }
  21037. var forceFirstProgress;
  21038. if (this._dirty || planResult === 'reset') {
  21039. this._dirty = false;
  21040. forceFirstProgress = reset(this, skip);
  21041. }
  21042. this._modBy = modBy;
  21043. this._modDataCount = modDataCount;
  21044. var step = performArgs && performArgs.step;
  21045. if (upTask) {
  21046. if (__DEV__) {
  21047. assert$1(upTask._outputDueEnd != null);
  21048. }
  21049. this._dueEnd = upTask._outputDueEnd;
  21050. }
  21051. // DataTask or overallTask
  21052. else {
  21053. if (__DEV__) {
  21054. assert$1(!this._progress || this._count);
  21055. }
  21056. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  21057. }
  21058. // Note: Stubs, that its host overall task let it has progress, has progress.
  21059. // If no progress, pass index from upstream to downstream each time plan called.
  21060. if (this._progress) {
  21061. var start = this._dueIndex;
  21062. var end = Math.min(
  21063. step != null ? this._dueIndex + step : Infinity,
  21064. this._dueEnd
  21065. );
  21066. if (!skip && (forceFirstProgress || start < end)) {
  21067. var progress = this._progress;
  21068. if (isArray(progress)) {
  21069. for (var i = 0; i < progress.length; i++) {
  21070. doProgress(this, progress[i], start, end, modBy, modDataCount);
  21071. }
  21072. }
  21073. else {
  21074. doProgress(this, progress, start, end, modBy, modDataCount);
  21075. }
  21076. }
  21077. this._dueIndex = end;
  21078. // If no `outputDueEnd`, assume that output data and
  21079. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  21080. var outputDueEnd = this._settedOutputEnd != null
  21081. ? this._settedOutputEnd : end;
  21082. if (__DEV__) {
  21083. // ??? Can not rollback.
  21084. assert$1(outputDueEnd >= this._outputDueEnd);
  21085. }
  21086. this._outputDueEnd = outputDueEnd;
  21087. }
  21088. else {
  21089. // (1) Some overall task has no progress.
  21090. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  21091. // This should always be performed so it can be passed to downstream.
  21092. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  21093. ? this._settedOutputEnd : this._dueEnd;
  21094. }
  21095. return this.unfinished();
  21096. };
  21097. var iterator = (function () {
  21098. var end;
  21099. var current;
  21100. var modBy;
  21101. var modDataCount;
  21102. var winCount;
  21103. var it = {
  21104. reset: function (s, e, sStep, sCount) {
  21105. current = s;
  21106. end = e;
  21107. modBy = sStep;
  21108. modDataCount = sCount;
  21109. winCount = Math.ceil(modDataCount / modBy);
  21110. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  21111. }
  21112. };
  21113. return it;
  21114. function sequentialNext() {
  21115. return current < end ? current++ : null;
  21116. }
  21117. function modNext() {
  21118. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  21119. var result = current >= end
  21120. ? null
  21121. : dataIndex < modDataCount
  21122. ? dataIndex
  21123. // If modDataCount is smaller than data.count() (consider `appendData` case),
  21124. // Use normal linear rendering mode.
  21125. : current;
  21126. current++;
  21127. return result;
  21128. }
  21129. })();
  21130. taskProto.dirty = function () {
  21131. this._dirty = true;
  21132. this._onDirty && this._onDirty(this.context);
  21133. };
  21134. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  21135. iterator.reset(start, end, modBy, modDataCount);
  21136. taskIns._callingProgress = progress;
  21137. taskIns._callingProgress({
  21138. start: start, end: end, count: end - start, next: iterator.next
  21139. }, taskIns.context);
  21140. }
  21141. function reset(taskIns, skip) {
  21142. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  21143. taskIns._settedOutputEnd = null;
  21144. var progress;
  21145. var forceFirstProgress;
  21146. if (!skip && taskIns._reset) {
  21147. progress = taskIns._reset(taskIns.context);
  21148. if (progress && progress.progress) {
  21149. forceFirstProgress = progress.forceFirstProgress;
  21150. progress = progress.progress;
  21151. }
  21152. // To simplify no progress checking, array must has item.
  21153. if (isArray(progress) && !progress.length) {
  21154. progress = null;
  21155. }
  21156. }
  21157. taskIns._progress = progress;
  21158. taskIns._modBy = taskIns._modDataCount = null;
  21159. var downstream = taskIns._downstream;
  21160. downstream && downstream.dirty();
  21161. return forceFirstProgress;
  21162. }
  21163. /**
  21164. * @return {boolean}
  21165. */
  21166. taskProto.unfinished = function () {
  21167. return this._progress && this._dueIndex < this._dueEnd;
  21168. };
  21169. /**
  21170. * @param {Object} downTask The downstream task.
  21171. * @return {Object} The downstream task.
  21172. */
  21173. taskProto.pipe = function (downTask) {
  21174. if (__DEV__) {
  21175. assert$1(downTask && !downTask._disposed && downTask !== this);
  21176. }
  21177. // If already downstream, do not dirty downTask.
  21178. if (this._downstream !== downTask || this._dirty) {
  21179. this._downstream = downTask;
  21180. downTask._upstream = this;
  21181. downTask.dirty();
  21182. }
  21183. };
  21184. taskProto.dispose = function () {
  21185. if (this._disposed) {
  21186. return;
  21187. }
  21188. this._upstream && (this._upstream._downstream = null);
  21189. this._downstream && (this._downstream._upstream = null);
  21190. this._dirty = false;
  21191. this._disposed = true;
  21192. };
  21193. taskProto.getUpstream = function () {
  21194. return this._upstream;
  21195. };
  21196. taskProto.getDownstream = function () {
  21197. return this._downstream;
  21198. };
  21199. taskProto.setOutputEnd = function (end) {
  21200. // This only happend in dataTask, dataZoom, map, currently.
  21201. // where dataZoom do not set end each time, but only set
  21202. // when reset. So we should record the setted end, in case
  21203. // that the stub of dataZoom perform again and earse the
  21204. // setted end by upstream.
  21205. this._outputDueEnd = this._settedOutputEnd = end;
  21206. };
  21207. ///////////////////////////////////////////////////////////
  21208. // For stream debug (Should be commented out after used!)
  21209. // Usage: printTask(this, 'begin');
  21210. // Usage: printTask(this, null, {someExtraProp});
  21211. // function printTask(task, prefix, extra) {
  21212. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  21213. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  21214. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  21215. // var props = [];
  21216. // if (task.__pipeline) {
  21217. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  21218. // props.push({text: 'idx', value: val});
  21219. // } else {
  21220. // var stubCount = 0;
  21221. // task.agentStubMap.each(() => stubCount++);
  21222. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  21223. // }
  21224. // props.push({text: 'uid', value: task.uidDebug});
  21225. // if (task.__pipeline) {
  21226. // props.push({text: 'pid', value: task.__pipeline.id});
  21227. // task.agent && props.push(
  21228. // {text: 'stubFor', value: task.agent.uidDebug}
  21229. // );
  21230. // }
  21231. // props.push(
  21232. // {text: 'dirty', value: task._dirty},
  21233. // {text: 'dueIndex', value: task._dueIndex},
  21234. // {text: 'dueEnd', value: task._dueEnd},
  21235. // {text: 'outputDueEnd', value: task._outputDueEnd}
  21236. // );
  21237. // if (extra) {
  21238. // Object.keys(extra).forEach(key => {
  21239. // props.push({text: key, value: extra[key]});
  21240. // });
  21241. // }
  21242. // var args = ['color: blue'];
  21243. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  21244. // args.push('color: black', 'color: red'),
  21245. // `${item.text}: %c${item.value}`
  21246. // )).join('%c, ');
  21247. // console.log.apply(console, [msg].concat(args));
  21248. // // console.log(this);
  21249. // }
  21250. /*
  21251. * Licensed to the Apache Software Foundation (ASF) under one
  21252. * or more contributor license agreements. See the NOTICE file
  21253. * distributed with this work for additional information
  21254. * regarding copyright ownership. The ASF licenses this file
  21255. * to you under the Apache License, Version 2.0 (the
  21256. * "License"); you may not use this file except in compliance
  21257. * with the License. You may obtain a copy of the License at
  21258. *
  21259. * http://www.apache.org/licenses/LICENSE-2.0
  21260. *
  21261. * Unless required by applicable law or agreed to in writing,
  21262. * software distributed under the License is distributed on an
  21263. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21264. * KIND, either express or implied. See the License for the
  21265. * specific language governing permissions and limitations
  21266. * under the License.
  21267. */
  21268. var inner$4 = makeInner();
  21269. var SeriesModel = ComponentModel.extend({
  21270. type: 'series.__base__',
  21271. /**
  21272. * @readOnly
  21273. */
  21274. seriesIndex: 0,
  21275. // coodinateSystem will be injected in the echarts/CoordinateSystem
  21276. coordinateSystem: null,
  21277. /**
  21278. * @type {Object}
  21279. * @protected
  21280. */
  21281. defaultOption: null,
  21282. /**
  21283. * legend visual provider to the legend component
  21284. * @type {Object}
  21285. */
  21286. // PENDING
  21287. legendVisualProvider: null,
  21288. /**
  21289. * Access path of color for visual
  21290. */
  21291. visualColorAccessPath: 'itemStyle.color',
  21292. /**
  21293. * Access path of borderColor for visual
  21294. */
  21295. visualBorderColorAccessPath: 'itemStyle.borderColor',
  21296. /**
  21297. * Support merge layout params.
  21298. * Only support 'box' now (left/right/top/bottom/width/height).
  21299. * @type {string|Object} Object can be {ignoreSize: true}
  21300. * @readOnly
  21301. */
  21302. layoutMode: null,
  21303. init: function (option, parentModel, ecModel, extraOpt) {
  21304. /**
  21305. * @type {number}
  21306. * @readOnly
  21307. */
  21308. this.seriesIndex = this.componentIndex;
  21309. this.dataTask = createTask({
  21310. count: dataTaskCount,
  21311. reset: dataTaskReset
  21312. });
  21313. this.dataTask.context = {model: this};
  21314. this.mergeDefaultAndTheme(option, ecModel);
  21315. prepareSource(this);
  21316. var data = this.getInitialData(option, ecModel);
  21317. wrapData(data, this);
  21318. this.dataTask.context.data = data;
  21319. if (__DEV__) {
  21320. assert$1(data, 'getInitialData returned invalid data.');
  21321. }
  21322. /**
  21323. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  21324. * @private
  21325. */
  21326. inner$4(this).dataBeforeProcessed = data;
  21327. // If we reverse the order (make data firstly, and then make
  21328. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21329. // cause data.graph.data !== data when using
  21330. // module:echarts/data/Graph or module:echarts/data/Tree.
  21331. // See module:echarts/data/helper/linkList
  21332. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21333. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21334. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21335. // Call `seriesModel.getRawData()` instead.
  21336. // this.restoreData();
  21337. autoSeriesName(this);
  21338. },
  21339. /**
  21340. * Util for merge default and theme to option
  21341. * @param {Object} option
  21342. * @param {module:echarts/model/Global} ecModel
  21343. */
  21344. mergeDefaultAndTheme: function (option, ecModel) {
  21345. var layoutMode = this.layoutMode;
  21346. var inputPositionParams = layoutMode
  21347. ? getLayoutParams(option) : {};
  21348. // Backward compat: using subType on theme.
  21349. // But if name duplicate between series subType
  21350. // (for example: parallel) add component mainType,
  21351. // add suffix 'Series'.
  21352. var themeSubType = this.subType;
  21353. if (ComponentModel.hasClass(themeSubType)) {
  21354. themeSubType += 'Series';
  21355. }
  21356. merge(
  21357. option,
  21358. ecModel.getTheme().get(this.subType)
  21359. );
  21360. merge(option, this.getDefaultOption());
  21361. // Default label emphasis `show`
  21362. defaultEmphasis(option, 'label', ['show']);
  21363. this.fillDataTextStyle(option.data);
  21364. if (layoutMode) {
  21365. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21366. }
  21367. },
  21368. mergeOption: function (newSeriesOption, ecModel) {
  21369. // this.settingTask.dirty();
  21370. newSeriesOption = merge(this.option, newSeriesOption, true);
  21371. this.fillDataTextStyle(newSeriesOption.data);
  21372. var layoutMode = this.layoutMode;
  21373. if (layoutMode) {
  21374. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21375. }
  21376. prepareSource(this);
  21377. var data = this.getInitialData(newSeriesOption, ecModel);
  21378. wrapData(data, this);
  21379. this.dataTask.dirty();
  21380. this.dataTask.context.data = data;
  21381. inner$4(this).dataBeforeProcessed = data;
  21382. autoSeriesName(this);
  21383. },
  21384. fillDataTextStyle: function (data) {
  21385. // Default data label emphasis `show`
  21386. // FIXME Tree structure data ?
  21387. // FIXME Performance ?
  21388. if (data && !isTypedArray(data)) {
  21389. var props = ['show'];
  21390. for (var i = 0; i < data.length; i++) {
  21391. if (data[i] && data[i].label) {
  21392. defaultEmphasis(data[i], 'label', props);
  21393. }
  21394. }
  21395. }
  21396. },
  21397. /**
  21398. * Init a data structure from data related option in series
  21399. * Must be overwritten
  21400. */
  21401. getInitialData: function () {},
  21402. /**
  21403. * Append data to list
  21404. * @param {Object} params
  21405. * @param {Array|TypedArray} params.data
  21406. */
  21407. appendData: function (params) {
  21408. // FIXME ???
  21409. // (1) If data from dataset, forbidden append.
  21410. // (2) support append data of dataset.
  21411. var data = this.getRawData();
  21412. data.appendData(params.data);
  21413. },
  21414. /**
  21415. * Consider some method like `filter`, `map` need make new data,
  21416. * We should make sure that `seriesModel.getData()` get correct
  21417. * data in the stream procedure. So we fetch data from upstream
  21418. * each time `task.perform` called.
  21419. * @param {string} [dataType]
  21420. * @return {module:echarts/data/List}
  21421. */
  21422. getData: function (dataType) {
  21423. var task = getCurrentTask(this);
  21424. if (task) {
  21425. var data = task.context.data;
  21426. return dataType == null ? data : data.getLinkedData(dataType);
  21427. }
  21428. else {
  21429. // When series is not alive (that may happen when click toolbox
  21430. // restore or setOption with not merge mode), series data may
  21431. // be still need to judge animation or something when graphic
  21432. // elements want to know whether fade out.
  21433. return inner$4(this).data;
  21434. }
  21435. },
  21436. /**
  21437. * @param {module:echarts/data/List} data
  21438. */
  21439. setData: function (data) {
  21440. var task = getCurrentTask(this);
  21441. if (task) {
  21442. var context = task.context;
  21443. // Consider case: filter, data sample.
  21444. if (context.data !== data && task.modifyOutputEnd) {
  21445. task.setOutputEnd(data.count());
  21446. }
  21447. context.outputData = data;
  21448. // Caution: setData should update context.data,
  21449. // Because getData may be called multiply in a
  21450. // single stage and expect to get the data just
  21451. // set. (For example, AxisProxy, x y both call
  21452. // getData and setDate sequentially).
  21453. // So the context.data should be fetched from
  21454. // upstream each time when a stage starts to be
  21455. // performed.
  21456. if (task !== this.dataTask) {
  21457. context.data = data;
  21458. }
  21459. }
  21460. inner$4(this).data = data;
  21461. },
  21462. /**
  21463. * @see {module:echarts/data/helper/sourceHelper#getSource}
  21464. * @return {module:echarts/data/Source} source
  21465. */
  21466. getSource: function () {
  21467. return getSource(this);
  21468. },
  21469. /**
  21470. * Get data before processed
  21471. * @return {module:echarts/data/List}
  21472. */
  21473. getRawData: function () {
  21474. return inner$4(this).dataBeforeProcessed;
  21475. },
  21476. /**
  21477. * Get base axis if has coordinate system and has axis.
  21478. * By default use coordSys.getBaseAxis();
  21479. * Can be overrided for some chart.
  21480. * @return {type} description
  21481. */
  21482. getBaseAxis: function () {
  21483. var coordSys = this.coordinateSystem;
  21484. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21485. },
  21486. // FIXME
  21487. /**
  21488. * Default tooltip formatter
  21489. *
  21490. * @param {number} dataIndex
  21491. * @param {boolean} [multipleSeries=false]
  21492. * @param {number} [dataType]
  21493. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  21494. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21495. * string is used as DOM HTML content.
  21496. * 'richText' is used for rendering tooltip in rich text form, for those where
  21497. * DOM operation is not supported.
  21498. * @return {Object} formatted tooltip with `html` and `markers`
  21499. */
  21500. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  21501. var series = this;
  21502. renderMode = renderMode || 'html';
  21503. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  21504. var isRichText = renderMode === 'richText';
  21505. var markers = {};
  21506. var markerId = 0;
  21507. function formatArrayValue(value) {
  21508. // ??? TODO refactor these logic.
  21509. // check: category-no-encode-has-axis-data in dataset.html
  21510. var vertially = reduce(value, function (vertially, val, idx) {
  21511. var dimItem = data.getDimensionInfo(idx);
  21512. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21513. }, 0);
  21514. var result = [];
  21515. tooltipDims.length
  21516. ? each$1(tooltipDims, function (dim) {
  21517. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21518. })
  21519. // By default, all dims is used on tooltip.
  21520. : each$1(value, setEachItem);
  21521. function setEachItem(val, dim) {
  21522. var dimInfo = data.getDimensionInfo(dim);
  21523. // If `dimInfo.tooltip` is not set, show tooltip.
  21524. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21525. return;
  21526. }
  21527. var dimType = dimInfo.type;
  21528. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  21529. var dimHead = getTooltipMarker({
  21530. color: color,
  21531. type: 'subItem',
  21532. renderMode: renderMode,
  21533. markerId: markName
  21534. });
  21535. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  21536. var valStr = (vertially
  21537. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  21538. : ''
  21539. )
  21540. // FIXME should not format time for raw data?
  21541. + encodeHTML(dimType === 'ordinal'
  21542. ? val + ''
  21543. : dimType === 'time'
  21544. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  21545. : addCommas(val)
  21546. );
  21547. valStr && result.push(valStr);
  21548. if (isRichText) {
  21549. markers[markName] = color;
  21550. ++markerId;
  21551. }
  21552. }
  21553. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  21554. var content = newLine + result.join(newLine || ', ');
  21555. return {
  21556. renderMode: renderMode,
  21557. content: content,
  21558. style: markers
  21559. };
  21560. }
  21561. function formatSingleValue(val) {
  21562. // return encodeHTML(addCommas(val));
  21563. return {
  21564. renderMode: renderMode,
  21565. content: encodeHTML(addCommas(val)),
  21566. style: markers
  21567. };
  21568. }
  21569. var data = this.getData();
  21570. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  21571. var tooltipDimLen = tooltipDims.length;
  21572. var value = this.getRawValue(dataIndex);
  21573. var isValueArr = isArray(value);
  21574. var color = data.getItemVisual(dataIndex, 'color');
  21575. if (isObject$1(color) && color.colorStops) {
  21576. color = (color.colorStops[0] || {}).color;
  21577. }
  21578. color = color || 'transparent';
  21579. // Complicated rule for pretty tooltip.
  21580. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  21581. ? formatArrayValue(value)
  21582. : tooltipDimLen
  21583. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  21584. : formatSingleValue(isValueArr ? value[0] : value);
  21585. var content = formattedValue.content;
  21586. var markName = series.seriesIndex + 'at' + markerId;
  21587. var colorEl = getTooltipMarker({
  21588. color: color,
  21589. type: 'item',
  21590. renderMode: renderMode,
  21591. markerId: markName
  21592. });
  21593. markers[markName] = color;
  21594. ++markerId;
  21595. var name = data.getName(dataIndex);
  21596. var seriesName = this.name;
  21597. if (!isNameSpecified(this)) {
  21598. seriesName = '';
  21599. }
  21600. seriesName = seriesName
  21601. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  21602. : '';
  21603. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  21604. var html = !multipleSeries
  21605. ? seriesName + colorStr
  21606. + (name
  21607. ? encodeHTML(name) + ': ' + content
  21608. : content
  21609. )
  21610. : colorStr + seriesName + content;
  21611. return {
  21612. html: html,
  21613. markers: markers
  21614. };
  21615. },
  21616. /**
  21617. * @return {boolean}
  21618. */
  21619. isAnimationEnabled: function () {
  21620. if (env$1.node) {
  21621. return false;
  21622. }
  21623. var animationEnabled = this.getShallow('animation');
  21624. if (animationEnabled) {
  21625. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21626. animationEnabled = false;
  21627. }
  21628. }
  21629. return animationEnabled;
  21630. },
  21631. restoreData: function () {
  21632. this.dataTask.dirty();
  21633. },
  21634. getColorFromPalette: function (name, scope, requestColorNum) {
  21635. var ecModel = this.ecModel;
  21636. // PENDING
  21637. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  21638. if (!color) {
  21639. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21640. }
  21641. return color;
  21642. },
  21643. /**
  21644. * Use `data.mapDimension(coordDim, true)` instead.
  21645. * @deprecated
  21646. */
  21647. coordDimToDataDim: function (coordDim) {
  21648. return this.getRawData().mapDimension(coordDim, true);
  21649. },
  21650. /**
  21651. * Get progressive rendering count each step
  21652. * @return {number}
  21653. */
  21654. getProgressive: function () {
  21655. return this.get('progressive');
  21656. },
  21657. /**
  21658. * Get progressive rendering count each step
  21659. * @return {number}
  21660. */
  21661. getProgressiveThreshold: function () {
  21662. return this.get('progressiveThreshold');
  21663. },
  21664. /**
  21665. * Get data indices for show tooltip content. See tooltip.
  21666. * @abstract
  21667. * @param {Array.<string>|string} dim
  21668. * @param {Array.<number>} value
  21669. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21670. * @return {Object} {dataIndices, nestestValue}.
  21671. */
  21672. getAxisTooltipData: null,
  21673. /**
  21674. * See tooltip.
  21675. * @abstract
  21676. * @param {number} dataIndex
  21677. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21678. */
  21679. getTooltipPosition: null,
  21680. /**
  21681. * @see {module:echarts/stream/Scheduler}
  21682. */
  21683. pipeTask: null,
  21684. /**
  21685. * Convinient for override in extended class.
  21686. * @protected
  21687. * @type {Function}
  21688. */
  21689. preventIncremental: null,
  21690. /**
  21691. * @public
  21692. * @readOnly
  21693. * @type {Object}
  21694. */
  21695. pipelineContext: null
  21696. });
  21697. mixin(SeriesModel, dataFormatMixin);
  21698. mixin(SeriesModel, colorPaletteMixin);
  21699. /**
  21700. * MUST be called after `prepareSource` called
  21701. * Here we need to make auto series, especially for auto legend. But we
  21702. * do not modify series.name in option to avoid side effects.
  21703. */
  21704. function autoSeriesName(seriesModel) {
  21705. // User specified name has higher priority, otherwise it may cause
  21706. // series can not be queried unexpectedly.
  21707. var name = seriesModel.name;
  21708. if (!isNameSpecified(seriesModel)) {
  21709. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21710. }
  21711. }
  21712. function getSeriesAutoName(seriesModel) {
  21713. var data = seriesModel.getRawData();
  21714. var dataDims = data.mapDimension('seriesName', true);
  21715. var nameArr = [];
  21716. each$1(dataDims, function (dataDim) {
  21717. var dimInfo = data.getDimensionInfo(dataDim);
  21718. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21719. });
  21720. return nameArr.join(' ');
  21721. }
  21722. function dataTaskCount(context) {
  21723. return context.model.getRawData().count();
  21724. }
  21725. function dataTaskReset(context) {
  21726. var seriesModel = context.model;
  21727. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21728. return dataTaskProgress;
  21729. }
  21730. function dataTaskProgress(param, context) {
  21731. // Avoid repead cloneShallow when data just created in reset.
  21732. if (param.end > context.outputData.count()) {
  21733. context.model.getRawData().cloneShallow(context.outputData);
  21734. }
  21735. }
  21736. // TODO refactor
  21737. function wrapData(data, seriesModel) {
  21738. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21739. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21740. });
  21741. }
  21742. function onDataSelfChange(seriesModel) {
  21743. var task = getCurrentTask(seriesModel);
  21744. if (task) {
  21745. // Consider case: filter, selectRange
  21746. task.setOutputEnd(this.count());
  21747. }
  21748. }
  21749. function getCurrentTask(seriesModel) {
  21750. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21751. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21752. if (pipeline) {
  21753. // When pipline finished, the currrentTask keep the last
  21754. // task (renderTask).
  21755. var task = pipeline.currentTask;
  21756. if (task) {
  21757. var agentStubMap = task.agentStubMap;
  21758. if (agentStubMap) {
  21759. task = agentStubMap.get(seriesModel.uid);
  21760. }
  21761. }
  21762. return task;
  21763. }
  21764. }
  21765. /*
  21766. * Licensed to the Apache Software Foundation (ASF) under one
  21767. * or more contributor license agreements. See the NOTICE file
  21768. * distributed with this work for additional information
  21769. * regarding copyright ownership. The ASF licenses this file
  21770. * to you under the Apache License, Version 2.0 (the
  21771. * "License"); you may not use this file except in compliance
  21772. * with the License. You may obtain a copy of the License at
  21773. *
  21774. * http://www.apache.org/licenses/LICENSE-2.0
  21775. *
  21776. * Unless required by applicable law or agreed to in writing,
  21777. * software distributed under the License is distributed on an
  21778. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21779. * KIND, either express or implied. See the License for the
  21780. * specific language governing permissions and limitations
  21781. * under the License.
  21782. */
  21783. var Component$1 = function () {
  21784. /**
  21785. * @type {module:zrender/container/Group}
  21786. * @readOnly
  21787. */
  21788. this.group = new Group();
  21789. /**
  21790. * @type {string}
  21791. * @readOnly
  21792. */
  21793. this.uid = getUID('viewComponent');
  21794. };
  21795. Component$1.prototype = {
  21796. constructor: Component$1,
  21797. init: function (ecModel, api) {},
  21798. render: function (componentModel, ecModel, api, payload) {},
  21799. dispose: function () {},
  21800. /**
  21801. * @param {string} eventType
  21802. * @param {Object} query
  21803. * @param {module:zrender/Element} targetEl
  21804. * @param {Object} packedEvent
  21805. * @return {boolen} Pass only when return `true`.
  21806. */
  21807. filterForExposedEvent: null
  21808. };
  21809. var componentProto = Component$1.prototype;
  21810. componentProto.updateView =
  21811. componentProto.updateLayout =
  21812. componentProto.updateVisual =
  21813. function (seriesModel, ecModel, api, payload) {
  21814. // Do nothing;
  21815. };
  21816. // Enable Component.extend.
  21817. enableClassExtend(Component$1);
  21818. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21819. enableClassManagement(Component$1, {registerWhenExtend: true});
  21820. /*
  21821. * Licensed to the Apache Software Foundation (ASF) under one
  21822. * or more contributor license agreements. See the NOTICE file
  21823. * distributed with this work for additional information
  21824. * regarding copyright ownership. The ASF licenses this file
  21825. * to you under the Apache License, Version 2.0 (the
  21826. * "License"); you may not use this file except in compliance
  21827. * with the License. You may obtain a copy of the License at
  21828. *
  21829. * http://www.apache.org/licenses/LICENSE-2.0
  21830. *
  21831. * Unless required by applicable law or agreed to in writing,
  21832. * software distributed under the License is distributed on an
  21833. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21834. * KIND, either express or implied. See the License for the
  21835. * specific language governing permissions and limitations
  21836. * under the License.
  21837. */
  21838. /**
  21839. * @return {string} If large mode changed, return string 'reset';
  21840. */
  21841. var createRenderPlanner = function () {
  21842. var inner = makeInner();
  21843. return function (seriesModel) {
  21844. var fields = inner(seriesModel);
  21845. var pipelineContext = seriesModel.pipelineContext;
  21846. var originalLarge = fields.large;
  21847. var originalProgressive = fields.progressiveRender;
  21848. var large = fields.large = pipelineContext.large;
  21849. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  21850. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21851. };
  21852. };
  21853. /*
  21854. * Licensed to the Apache Software Foundation (ASF) under one
  21855. * or more contributor license agreements. See the NOTICE file
  21856. * distributed with this work for additional information
  21857. * regarding copyright ownership. The ASF licenses this file
  21858. * to you under the Apache License, Version 2.0 (the
  21859. * "License"); you may not use this file except in compliance
  21860. * with the License. You may obtain a copy of the License at
  21861. *
  21862. * http://www.apache.org/licenses/LICENSE-2.0
  21863. *
  21864. * Unless required by applicable law or agreed to in writing,
  21865. * software distributed under the License is distributed on an
  21866. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21867. * KIND, either express or implied. See the License for the
  21868. * specific language governing permissions and limitations
  21869. * under the License.
  21870. */
  21871. var inner$5 = makeInner();
  21872. var renderPlanner = createRenderPlanner();
  21873. function Chart() {
  21874. /**
  21875. * @type {module:zrender/container/Group}
  21876. * @readOnly
  21877. */
  21878. this.group = new Group();
  21879. /**
  21880. * @type {string}
  21881. * @readOnly
  21882. */
  21883. this.uid = getUID('viewChart');
  21884. this.renderTask = createTask({
  21885. plan: renderTaskPlan,
  21886. reset: renderTaskReset
  21887. });
  21888. this.renderTask.context = {view: this};
  21889. }
  21890. Chart.prototype = {
  21891. type: 'chart',
  21892. /**
  21893. * Init the chart.
  21894. * @param {module:echarts/model/Global} ecModel
  21895. * @param {module:echarts/ExtensionAPI} api
  21896. */
  21897. init: function (ecModel, api) {},
  21898. /**
  21899. * Render the chart.
  21900. * @param {module:echarts/model/Series} seriesModel
  21901. * @param {module:echarts/model/Global} ecModel
  21902. * @param {module:echarts/ExtensionAPI} api
  21903. * @param {Object} payload
  21904. */
  21905. render: function (seriesModel, ecModel, api, payload) {},
  21906. /**
  21907. * Highlight series or specified data item.
  21908. * @param {module:echarts/model/Series} seriesModel
  21909. * @param {module:echarts/model/Global} ecModel
  21910. * @param {module:echarts/ExtensionAPI} api
  21911. * @param {Object} payload
  21912. */
  21913. highlight: function (seriesModel, ecModel, api, payload) {
  21914. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  21915. },
  21916. /**
  21917. * Downplay series or specified data item.
  21918. * @param {module:echarts/model/Series} seriesModel
  21919. * @param {module:echarts/model/Global} ecModel
  21920. * @param {module:echarts/ExtensionAPI} api
  21921. * @param {Object} payload
  21922. */
  21923. downplay: function (seriesModel, ecModel, api, payload) {
  21924. toggleHighlight(seriesModel.getData(), payload, 'normal');
  21925. },
  21926. /**
  21927. * Remove self.
  21928. * @param {module:echarts/model/Global} ecModel
  21929. * @param {module:echarts/ExtensionAPI} api
  21930. */
  21931. remove: function (ecModel, api) {
  21932. this.group.removeAll();
  21933. },
  21934. /**
  21935. * Dispose self.
  21936. * @param {module:echarts/model/Global} ecModel
  21937. * @param {module:echarts/ExtensionAPI} api
  21938. */
  21939. dispose: function () {},
  21940. /**
  21941. * Rendering preparation in progressive mode.
  21942. * @param {module:echarts/model/Series} seriesModel
  21943. * @param {module:echarts/model/Global} ecModel
  21944. * @param {module:echarts/ExtensionAPI} api
  21945. * @param {Object} payload
  21946. */
  21947. incrementalPrepareRender: null,
  21948. /**
  21949. * Render in progressive mode.
  21950. * @param {Object} params See taskParams in `stream/task.js`
  21951. * @param {module:echarts/model/Series} seriesModel
  21952. * @param {module:echarts/model/Global} ecModel
  21953. * @param {module:echarts/ExtensionAPI} api
  21954. * @param {Object} payload
  21955. */
  21956. incrementalRender: null,
  21957. /**
  21958. * Update transform directly.
  21959. * @param {module:echarts/model/Series} seriesModel
  21960. * @param {module:echarts/model/Global} ecModel
  21961. * @param {module:echarts/ExtensionAPI} api
  21962. * @param {Object} payload
  21963. * @return {Object} {update: true}
  21964. */
  21965. updateTransform: null,
  21966. /**
  21967. * The view contains the given point.
  21968. * @interface
  21969. * @param {Array.<number>} point
  21970. * @return {boolean}
  21971. */
  21972. // containPoint: function () {}
  21973. /**
  21974. * @param {string} eventType
  21975. * @param {Object} query
  21976. * @param {module:zrender/Element} targetEl
  21977. * @param {Object} packedEvent
  21978. * @return {boolen} Pass only when return `true`.
  21979. */
  21980. filterForExposedEvent: null
  21981. };
  21982. var chartProto = Chart.prototype;
  21983. chartProto.updateView =
  21984. chartProto.updateLayout =
  21985. chartProto.updateVisual =
  21986. function (seriesModel, ecModel, api, payload) {
  21987. this.render(seriesModel, ecModel, api, payload);
  21988. };
  21989. /**
  21990. * Set state of single element
  21991. * @param {module:zrender/Element} el
  21992. * @param {string} state 'normal'|'emphasis'
  21993. * @param {number} highlightDigit
  21994. */
  21995. function elSetState(el, state, highlightDigit) {
  21996. if (el) {
  21997. el.trigger(state, highlightDigit);
  21998. if (el.isGroup
  21999. // Simple optimize.
  22000. && !isHighDownDispatcher(el)
  22001. ) {
  22002. for (var i = 0, len = el.childCount(); i < len; i++) {
  22003. elSetState(el.childAt(i), state, highlightDigit);
  22004. }
  22005. }
  22006. }
  22007. }
  22008. /**
  22009. * @param {module:echarts/data/List} data
  22010. * @param {Object} payload
  22011. * @param {string} state 'normal'|'emphasis'
  22012. */
  22013. function toggleHighlight(data, payload, state) {
  22014. var dataIndex = queryDataIndex(data, payload);
  22015. var highlightDigit = (payload && payload.highlightKey != null)
  22016. ? getHighlightDigit(payload.highlightKey)
  22017. : null;
  22018. if (dataIndex != null) {
  22019. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  22020. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22021. });
  22022. }
  22023. else {
  22024. data.eachItemGraphicEl(function (el) {
  22025. elSetState(el, state, highlightDigit);
  22026. });
  22027. }
  22028. }
  22029. // Enable Chart.extend.
  22030. enableClassExtend(Chart, ['dispose']);
  22031. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  22032. enableClassManagement(Chart, {registerWhenExtend: true});
  22033. Chart.markUpdateMethod = function (payload, methodName) {
  22034. inner$5(payload).updateMethod = methodName;
  22035. };
  22036. function renderTaskPlan(context) {
  22037. return renderPlanner(context.model);
  22038. }
  22039. function renderTaskReset(context) {
  22040. var seriesModel = context.model;
  22041. var ecModel = context.ecModel;
  22042. var api = context.api;
  22043. var payload = context.payload;
  22044. // ???! remove updateView updateVisual
  22045. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22046. var view = context.view;
  22047. var updateMethod = payload && inner$5(payload).updateMethod;
  22048. var methodName = progressiveRender
  22049. ? 'incrementalPrepareRender'
  22050. : (updateMethod && view[updateMethod])
  22051. ? updateMethod
  22052. // `appendData` is also supported when data amount
  22053. // is less than progressive threshold.
  22054. : 'render';
  22055. if (methodName !== 'render') {
  22056. view[methodName](seriesModel, ecModel, api, payload);
  22057. }
  22058. return progressMethodMap[methodName];
  22059. }
  22060. var progressMethodMap = {
  22061. incrementalPrepareRender: {
  22062. progress: function (params, context) {
  22063. context.view.incrementalRender(
  22064. params, context.model, context.ecModel, context.api, context.payload
  22065. );
  22066. }
  22067. },
  22068. render: {
  22069. // Put view.render in `progress` to support appendData. But in this case
  22070. // view.render should not be called in reset, otherwise it will be called
  22071. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22072. // in any cases.
  22073. forceFirstProgress: true,
  22074. progress: function (params, context) {
  22075. context.view.render(
  22076. context.model, context.ecModel, context.api, context.payload
  22077. );
  22078. }
  22079. }
  22080. };
  22081. /*
  22082. * Licensed to the Apache Software Foundation (ASF) under one
  22083. * or more contributor license agreements. See the NOTICE file
  22084. * distributed with this work for additional information
  22085. * regarding copyright ownership. The ASF licenses this file
  22086. * to you under the Apache License, Version 2.0 (the
  22087. * "License"); you may not use this file except in compliance
  22088. * with the License. You may obtain a copy of the License at
  22089. *
  22090. * http://www.apache.org/licenses/LICENSE-2.0
  22091. *
  22092. * Unless required by applicable law or agreed to in writing,
  22093. * software distributed under the License is distributed on an
  22094. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22095. * KIND, either express or implied. See the License for the
  22096. * specific language governing permissions and limitations
  22097. * under the License.
  22098. */
  22099. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22100. var RATE = '\0__throttleRate';
  22101. var THROTTLE_TYPE = '\0__throttleType';
  22102. /**
  22103. * @public
  22104. * @param {(Function)} fn
  22105. * @param {number} [delay=0] Unit: ms.
  22106. * @param {boolean} [debounce=false]
  22107. * true: If call interval less than `delay`, only the last call works.
  22108. * false: If call interval less than `delay, call works on fixed rate.
  22109. * @return {(Function)} throttled fn.
  22110. */
  22111. function throttle(fn, delay, debounce) {
  22112. var currCall;
  22113. var lastCall = 0;
  22114. var lastExec = 0;
  22115. var timer = null;
  22116. var diff;
  22117. var scope;
  22118. var args;
  22119. var debounceNextCall;
  22120. delay = delay || 0;
  22121. function exec() {
  22122. lastExec = (new Date()).getTime();
  22123. timer = null;
  22124. fn.apply(scope, args || []);
  22125. }
  22126. var cb = function () {
  22127. currCall = (new Date()).getTime();
  22128. scope = this;
  22129. args = arguments;
  22130. var thisDelay = debounceNextCall || delay;
  22131. var thisDebounce = debounceNextCall || debounce;
  22132. debounceNextCall = null;
  22133. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22134. clearTimeout(timer);
  22135. // Here we should make sure that: the `exec` SHOULD NOT be called later
  22136. // than a new call of `cb`, that is, preserving the command order. Consider
  22137. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22138. // happens, either the `exec` is called dierectly, or the call is delayed.
  22139. // But the delayed call should never be later than next call of `cb`. Under
  22140. // this assurance, we can simply update view state each time `dispatchAction`
  22141. // triggered by user roaming, but not need to add extra code to avoid the
  22142. // state being "rolled-back".
  22143. if (thisDebounce) {
  22144. timer = setTimeout(exec, thisDelay);
  22145. }
  22146. else {
  22147. if (diff >= 0) {
  22148. exec();
  22149. }
  22150. else {
  22151. timer = setTimeout(exec, -diff);
  22152. }
  22153. }
  22154. lastCall = currCall;
  22155. };
  22156. /**
  22157. * Clear throttle.
  22158. * @public
  22159. */
  22160. cb.clear = function () {
  22161. if (timer) {
  22162. clearTimeout(timer);
  22163. timer = null;
  22164. }
  22165. };
  22166. /**
  22167. * Enable debounce once.
  22168. */
  22169. cb.debounceNextCall = function (debounceDelay) {
  22170. debounceNextCall = debounceDelay;
  22171. };
  22172. return cb;
  22173. }
  22174. /**
  22175. * Create throttle method or update throttle rate.
  22176. *
  22177. * @example
  22178. * ComponentView.prototype.render = function () {
  22179. * ...
  22180. * throttle.createOrUpdate(
  22181. * this,
  22182. * '_dispatchAction',
  22183. * this.model.get('throttle'),
  22184. * 'fixRate'
  22185. * );
  22186. * };
  22187. * ComponentView.prototype.remove = function () {
  22188. * throttle.clear(this, '_dispatchAction');
  22189. * };
  22190. * ComponentView.prototype.dispose = function () {
  22191. * throttle.clear(this, '_dispatchAction');
  22192. * };
  22193. *
  22194. * @public
  22195. * @param {Object} obj
  22196. * @param {string} fnAttr
  22197. * @param {number} [rate]
  22198. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  22199. * @return {Function} throttled function.
  22200. */
  22201. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22202. var fn = obj[fnAttr];
  22203. if (!fn) {
  22204. return;
  22205. }
  22206. var originFn = fn[ORIGIN_METHOD] || fn;
  22207. var lastThrottleType = fn[THROTTLE_TYPE];
  22208. var lastRate = fn[RATE];
  22209. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22210. if (rate == null || !throttleType) {
  22211. return (obj[fnAttr] = originFn);
  22212. }
  22213. fn = obj[fnAttr] = throttle(
  22214. originFn, rate, throttleType === 'debounce'
  22215. );
  22216. fn[ORIGIN_METHOD] = originFn;
  22217. fn[THROTTLE_TYPE] = throttleType;
  22218. fn[RATE] = rate;
  22219. }
  22220. return fn;
  22221. }
  22222. /**
  22223. * Clear throttle. Example see throttle.createOrUpdate.
  22224. *
  22225. * @public
  22226. * @param {Object} obj
  22227. * @param {string} fnAttr
  22228. */
  22229. function clear(obj, fnAttr) {
  22230. var fn = obj[fnAttr];
  22231. if (fn && fn[ORIGIN_METHOD]) {
  22232. obj[fnAttr] = fn[ORIGIN_METHOD];
  22233. }
  22234. }
  22235. /*
  22236. * Licensed to the Apache Software Foundation (ASF) under one
  22237. * or more contributor license agreements. See the NOTICE file
  22238. * distributed with this work for additional information
  22239. * regarding copyright ownership. The ASF licenses this file
  22240. * to you under the Apache License, Version 2.0 (the
  22241. * "License"); you may not use this file except in compliance
  22242. * with the License. You may obtain a copy of the License at
  22243. *
  22244. * http://www.apache.org/licenses/LICENSE-2.0
  22245. *
  22246. * Unless required by applicable law or agreed to in writing,
  22247. * software distributed under the License is distributed on an
  22248. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22249. * KIND, either express or implied. See the License for the
  22250. * specific language governing permissions and limitations
  22251. * under the License.
  22252. */
  22253. var seriesColor = {
  22254. createOnAllSeries: true,
  22255. performRawSeries: true,
  22256. reset: function (seriesModel, ecModel) {
  22257. var data = seriesModel.getData();
  22258. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  22259. // Set in itemStyle
  22260. var color = seriesModel.get(colorAccessPath);
  22261. var colorCallback = (isFunction$1(color) && !(color instanceof Gradient))
  22262. ? color : null;
  22263. // Default color
  22264. if (!color || colorCallback) {
  22265. color = seriesModel.getColorFromPalette(
  22266. // TODO series count changed.
  22267. seriesModel.name, null, ecModel.getSeriesCount()
  22268. );
  22269. }
  22270. data.setVisual('color', color);
  22271. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  22272. var borderColor = seriesModel.get(borderColorAccessPath);
  22273. data.setVisual('borderColor', borderColor);
  22274. // Only visible series has each data be visual encoded
  22275. if (!ecModel.isSeriesFiltered(seriesModel)) {
  22276. if (colorCallback) {
  22277. data.each(function (idx) {
  22278. data.setItemVisual(
  22279. idx, 'color', colorCallback(seriesModel.getDataParams(idx))
  22280. );
  22281. });
  22282. }
  22283. // itemStyle in each data item
  22284. var dataEach = function (data, idx) {
  22285. var itemModel = data.getItemModel(idx);
  22286. var color = itemModel.get(colorAccessPath, true);
  22287. var borderColor = itemModel.get(borderColorAccessPath, true);
  22288. if (color != null) {
  22289. data.setItemVisual(idx, 'color', color);
  22290. }
  22291. if (borderColor != null) {
  22292. data.setItemVisual(idx, 'borderColor', borderColor);
  22293. }
  22294. };
  22295. return { dataEach: data.hasItemOption ? dataEach : null };
  22296. }
  22297. }
  22298. };
  22299. /*
  22300. * Licensed to the Apache Software Foundation (ASF) under one
  22301. * or more contributor license agreements. See the NOTICE file
  22302. * distributed with this work for additional information
  22303. * regarding copyright ownership. The ASF licenses this file
  22304. * to you under the Apache License, Version 2.0 (the
  22305. * "License"); you may not use this file except in compliance
  22306. * with the License. You may obtain a copy of the License at
  22307. *
  22308. * http://www.apache.org/licenses/LICENSE-2.0
  22309. *
  22310. * Unless required by applicable law or agreed to in writing,
  22311. * software distributed under the License is distributed on an
  22312. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22313. * KIND, either express or implied. See the License for the
  22314. * specific language governing permissions and limitations
  22315. * under the License.
  22316. */
  22317. /**
  22318. * Language: English.
  22319. */
  22320. var lang = {
  22321. legend: {
  22322. selector: {
  22323. all: 'All',
  22324. inverse: 'Inv'
  22325. }
  22326. },
  22327. toolbox: {
  22328. brush: {
  22329. title: {
  22330. rect: 'Box Select',
  22331. polygon: 'Lasso Select',
  22332. lineX: 'Horizontally Select',
  22333. lineY: 'Vertically Select',
  22334. keep: 'Keep Selections',
  22335. clear: 'Clear Selections'
  22336. }
  22337. },
  22338. dataView: {
  22339. title: 'Data View',
  22340. lang: ['Data View', 'Close', 'Refresh']
  22341. },
  22342. dataZoom: {
  22343. title: {
  22344. zoom: 'Zoom',
  22345. back: 'Zoom Reset'
  22346. }
  22347. },
  22348. magicType: {
  22349. title: {
  22350. line: 'Switch to Line Chart',
  22351. bar: 'Switch to Bar Chart',
  22352. stack: 'Stack',
  22353. tiled: 'Tile'
  22354. }
  22355. },
  22356. restore: {
  22357. title: 'Restore'
  22358. },
  22359. saveAsImage: {
  22360. title: 'Save as Image',
  22361. lang: ['Right Click to Save Image']
  22362. }
  22363. },
  22364. aria: {
  22365. general: {
  22366. withTitle: 'This is a chart about "{title}"',
  22367. withoutTitle: 'This is a chart'
  22368. },
  22369. series: {
  22370. single: {
  22371. prefix: '',
  22372. withName: ' with type {seriesType} named {seriesName}.',
  22373. withoutName: ' with type {seriesType}.'
  22374. },
  22375. multiple: {
  22376. prefix: '. It consists of {seriesCount} series count.',
  22377. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  22378. withoutName: ' The {seriesId} series is a {seriesType}.',
  22379. separator: {
  22380. middle: '',
  22381. end: ''
  22382. }
  22383. }
  22384. },
  22385. data: {
  22386. allData: 'The data is as follows: ',
  22387. partialData: 'The first {displayCnt} items are: ',
  22388. withName: 'the data for {name} is {value}',
  22389. withoutName: '{value}',
  22390. separator: {
  22391. middle: ',',
  22392. end: '.'
  22393. }
  22394. }
  22395. }
  22396. };
  22397. /*
  22398. * Licensed to the Apache Software Foundation (ASF) under one
  22399. * or more contributor license agreements. See the NOTICE file
  22400. * distributed with this work for additional information
  22401. * regarding copyright ownership. The ASF licenses this file
  22402. * to you under the Apache License, Version 2.0 (the
  22403. * "License"); you may not use this file except in compliance
  22404. * with the License. You may obtain a copy of the License at
  22405. *
  22406. * http://www.apache.org/licenses/LICENSE-2.0
  22407. *
  22408. * Unless required by applicable law or agreed to in writing,
  22409. * software distributed under the License is distributed on an
  22410. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22411. * KIND, either express or implied. See the License for the
  22412. * specific language governing permissions and limitations
  22413. * under the License.
  22414. */
  22415. var aria = function (dom, ecModel) {
  22416. var ariaModel = ecModel.getModel('aria');
  22417. if (!ariaModel.get('show')) {
  22418. return;
  22419. }
  22420. else if (ariaModel.get('description')) {
  22421. dom.setAttribute('aria-label', ariaModel.get('description'));
  22422. return;
  22423. }
  22424. var seriesCnt = 0;
  22425. ecModel.eachSeries(function (seriesModel, idx) {
  22426. ++seriesCnt;
  22427. }, this);
  22428. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  22429. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  22430. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  22431. var ariaLabel;
  22432. if (seriesCnt < 1) {
  22433. // No series, no aria label
  22434. return;
  22435. }
  22436. else {
  22437. var title = getTitle();
  22438. if (title) {
  22439. ariaLabel = replace(getConfig('general.withTitle'), {
  22440. title: title
  22441. });
  22442. }
  22443. else {
  22444. ariaLabel = getConfig('general.withoutTitle');
  22445. }
  22446. var seriesLabels = [];
  22447. var prefix = seriesCnt > 1
  22448. ? 'series.multiple.prefix'
  22449. : 'series.single.prefix';
  22450. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  22451. ecModel.eachSeries(function (seriesModel, idx) {
  22452. if (idx < displaySeriesCnt) {
  22453. var seriesLabel;
  22454. var seriesName = seriesModel.get('name');
  22455. var seriesTpl = 'series.'
  22456. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  22457. seriesLabel = getConfig(seriesName
  22458. ? seriesTpl + 'withName'
  22459. : seriesTpl + 'withoutName');
  22460. seriesLabel = replace(seriesLabel, {
  22461. seriesId: seriesModel.seriesIndex,
  22462. seriesName: seriesModel.get('name'),
  22463. seriesType: getSeriesTypeName(seriesModel.subType)
  22464. });
  22465. var data = seriesModel.getData();
  22466. window.data = data;
  22467. if (data.count() > maxDataCnt) {
  22468. // Show part of data
  22469. seriesLabel += replace(getConfig('data.partialData'), {
  22470. displayCnt: maxDataCnt
  22471. });
  22472. }
  22473. else {
  22474. seriesLabel += getConfig('data.allData');
  22475. }
  22476. var dataLabels = [];
  22477. for (var i = 0; i < data.count(); i++) {
  22478. if (i < maxDataCnt) {
  22479. var name = data.getName(i);
  22480. var value = retrieveRawValue(data, i);
  22481. dataLabels.push(
  22482. replace(
  22483. name
  22484. ? getConfig('data.withName')
  22485. : getConfig('data.withoutName'),
  22486. {
  22487. name: name,
  22488. value: value
  22489. }
  22490. )
  22491. );
  22492. }
  22493. }
  22494. seriesLabel += dataLabels
  22495. .join(getConfig('data.separator.middle'))
  22496. + getConfig('data.separator.end');
  22497. seriesLabels.push(seriesLabel);
  22498. }
  22499. });
  22500. ariaLabel += seriesLabels
  22501. .join(getConfig('series.multiple.separator.middle'))
  22502. + getConfig('series.multiple.separator.end');
  22503. dom.setAttribute('aria-label', ariaLabel);
  22504. }
  22505. function replace(str, keyValues) {
  22506. if (typeof str !== 'string') {
  22507. return str;
  22508. }
  22509. var result = str;
  22510. each$1(keyValues, function (value, key) {
  22511. result = result.replace(
  22512. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  22513. value
  22514. );
  22515. });
  22516. return result;
  22517. }
  22518. function getConfig(path) {
  22519. var userConfig = ariaModel.get(path);
  22520. if (userConfig == null) {
  22521. var pathArr = path.split('.');
  22522. var result = lang.aria;
  22523. for (var i = 0; i < pathArr.length; ++i) {
  22524. result = result[pathArr[i]];
  22525. }
  22526. return result;
  22527. }
  22528. else {
  22529. return userConfig;
  22530. }
  22531. }
  22532. function getTitle() {
  22533. var title = ecModel.getModel('title').option;
  22534. if (title && title.length) {
  22535. title = title[0];
  22536. }
  22537. return title && title.text;
  22538. }
  22539. function getSeriesTypeName(type) {
  22540. return lang.series.typeNames[type] || '自定义图';
  22541. }
  22542. };
  22543. /*
  22544. * Licensed to the Apache Software Foundation (ASF) under one
  22545. * or more contributor license agreements. See the NOTICE file
  22546. * distributed with this work for additional information
  22547. * regarding copyright ownership. The ASF licenses this file
  22548. * to you under the Apache License, Version 2.0 (the
  22549. * "License"); you may not use this file except in compliance
  22550. * with the License. You may obtain a copy of the License at
  22551. *
  22552. * http://www.apache.org/licenses/LICENSE-2.0
  22553. *
  22554. * Unless required by applicable law or agreed to in writing,
  22555. * software distributed under the License is distributed on an
  22556. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22557. * KIND, either express or implied. See the License for the
  22558. * specific language governing permissions and limitations
  22559. * under the License.
  22560. */
  22561. var PI$1 = Math.PI;
  22562. /**
  22563. * @param {module:echarts/ExtensionAPI} api
  22564. * @param {Object} [opts]
  22565. * @param {string} [opts.text]
  22566. * @param {string} [opts.color]
  22567. * @param {string} [opts.textColor]
  22568. * @return {module:zrender/Element}
  22569. */
  22570. var loadingDefault = function (api, opts) {
  22571. opts = opts || {};
  22572. defaults(opts, {
  22573. text: 'loading',
  22574. color: '#c23531',
  22575. textColor: '#000',
  22576. maskColor: 'rgba(255, 255, 255, 0.8)',
  22577. zlevel: 0
  22578. });
  22579. var mask = new Rect({
  22580. style: {
  22581. fill: opts.maskColor
  22582. },
  22583. zlevel: opts.zlevel,
  22584. z: 10000
  22585. });
  22586. var arc = new Arc({
  22587. shape: {
  22588. startAngle: -PI$1 / 2,
  22589. endAngle: -PI$1 / 2 + 0.1,
  22590. r: 10
  22591. },
  22592. style: {
  22593. stroke: opts.color,
  22594. lineCap: 'round',
  22595. lineWidth: 5
  22596. },
  22597. zlevel: opts.zlevel,
  22598. z: 10001
  22599. });
  22600. var labelRect = new Rect({
  22601. style: {
  22602. fill: 'none',
  22603. text: opts.text,
  22604. textPosition: 'right',
  22605. textDistance: 10,
  22606. textFill: opts.textColor
  22607. },
  22608. zlevel: opts.zlevel,
  22609. z: 10001
  22610. });
  22611. arc.animateShape(true)
  22612. .when(1000, {
  22613. endAngle: PI$1 * 3 / 2
  22614. })
  22615. .start('circularInOut');
  22616. arc.animateShape(true)
  22617. .when(1000, {
  22618. startAngle: PI$1 * 3 / 2
  22619. })
  22620. .delay(300)
  22621. .start('circularInOut');
  22622. var group = new Group();
  22623. group.add(arc);
  22624. group.add(labelRect);
  22625. group.add(mask);
  22626. // Inject resize
  22627. group.resize = function () {
  22628. var cx = api.getWidth() / 2;
  22629. var cy = api.getHeight() / 2;
  22630. arc.setShape({
  22631. cx: cx,
  22632. cy: cy
  22633. });
  22634. var r = arc.shape.r;
  22635. labelRect.setShape({
  22636. x: cx - r,
  22637. y: cy - r,
  22638. width: r * 2,
  22639. height: r * 2
  22640. });
  22641. mask.setShape({
  22642. x: 0,
  22643. y: 0,
  22644. width: api.getWidth(),
  22645. height: api.getHeight()
  22646. });
  22647. };
  22648. group.resize();
  22649. return group;
  22650. };
  22651. /*
  22652. * Licensed to the Apache Software Foundation (ASF) under one
  22653. * or more contributor license agreements. See the NOTICE file
  22654. * distributed with this work for additional information
  22655. * regarding copyright ownership. The ASF licenses this file
  22656. * to you under the Apache License, Version 2.0 (the
  22657. * "License"); you may not use this file except in compliance
  22658. * with the License. You may obtain a copy of the License at
  22659. *
  22660. * http://www.apache.org/licenses/LICENSE-2.0
  22661. *
  22662. * Unless required by applicable law or agreed to in writing,
  22663. * software distributed under the License is distributed on an
  22664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22665. * KIND, either express or implied. See the License for the
  22666. * specific language governing permissions and limitations
  22667. * under the License.
  22668. */
  22669. /**
  22670. * @module echarts/stream/Scheduler
  22671. */
  22672. /**
  22673. * @constructor
  22674. */
  22675. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22676. this.ecInstance = ecInstance;
  22677. this.api = api;
  22678. this.unfinished;
  22679. // Fix current processors in case that in some rear cases that
  22680. // processors might be registered after echarts instance created.
  22681. // Register processors incrementally for a echarts instance is
  22682. // not supported by this stream architecture.
  22683. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22684. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22685. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22686. /**
  22687. * @private
  22688. * @type {
  22689. * [handlerUID: string]: {
  22690. * seriesTaskMap?: {
  22691. * [seriesUID: string]: Task
  22692. * },
  22693. * overallTask?: Task
  22694. * }
  22695. * }
  22696. */
  22697. this._stageTaskMap = createHashMap();
  22698. }
  22699. var proto = Scheduler.prototype;
  22700. /**
  22701. * @param {module:echarts/model/Global} ecModel
  22702. * @param {Object} payload
  22703. */
  22704. proto.restoreData = function (ecModel, payload) {
  22705. // TODO: Only restroe needed series and components, but not all components.
  22706. // Currently `restoreData` of all of the series and component will be called.
  22707. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22708. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22709. // and some components like coordinate system, axes, dataZoom, visualMap only
  22710. // need their target series refresh.
  22711. // (1) If we are implementing this feature some day, we should consider these cases:
  22712. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22713. // on the settings of `dataZoom`), it should be re-performed if the component
  22714. // is modified by `setOption`.
  22715. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22716. // it should be re-performed when the result array of `getTargetSeries` changed.
  22717. // We use `dependencies` to cover these issues.
  22718. // (3) How to update target series when coordinate system related components modified.
  22719. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22720. // and this case all of the tasks will be set as dirty.
  22721. ecModel.restoreData(payload);
  22722. // Theoretically an overall task not only depends on each of its target series, but also
  22723. // depends on all of the series.
  22724. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22725. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22726. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22727. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22728. // probably cause state chaos (consider `dataZoomProcessor`).
  22729. this._stageTaskMap.each(function (taskRecord) {
  22730. var overallTask = taskRecord.overallTask;
  22731. overallTask && overallTask.dirty();
  22732. });
  22733. };
  22734. // If seriesModel provided, incremental threshold is check by series data.
  22735. proto.getPerformArgs = function (task, isBlock) {
  22736. // For overall task
  22737. if (!task.__pipeline) {
  22738. return;
  22739. }
  22740. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22741. var pCtx = pipeline.context;
  22742. var incremental = !isBlock
  22743. && pipeline.progressiveEnabled
  22744. && (!pCtx || pCtx.progressiveRender)
  22745. && task.__idxInPipeline > pipeline.blockIndex;
  22746. var step = incremental ? pipeline.step : null;
  22747. var modDataCount = pCtx && pCtx.modDataCount;
  22748. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22749. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22750. };
  22751. proto.getPipeline = function (pipelineId) {
  22752. return this._pipelineMap.get(pipelineId);
  22753. };
  22754. /**
  22755. * Current, progressive rendering starts from visual and layout.
  22756. * Always detect render mode in the same stage, avoiding that incorrect
  22757. * detection caused by data filtering.
  22758. * Caution:
  22759. * `updateStreamModes` use `seriesModel.getData()`.
  22760. */
  22761. proto.updateStreamModes = function (seriesModel, view) {
  22762. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22763. var data = seriesModel.getData();
  22764. var dataLen = data.count();
  22765. // `progressiveRender` means that can render progressively in each
  22766. // animation frame. Note that some types of series do not provide
  22767. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22768. // use the term `incremental` but not `progressive` to describe the
  22769. // case that `chart.appendData`.
  22770. var progressiveRender = pipeline.progressiveEnabled
  22771. && view.incrementalPrepareRender
  22772. && dataLen >= pipeline.threshold;
  22773. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22774. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22775. // see `test/candlestick-large3.html`
  22776. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22777. seriesModel.pipelineContext = pipeline.context = {
  22778. progressiveRender: progressiveRender,
  22779. modDataCount: modDataCount,
  22780. large: large
  22781. };
  22782. };
  22783. proto.restorePipelines = function (ecModel) {
  22784. var scheduler = this;
  22785. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22786. ecModel.eachSeries(function (seriesModel) {
  22787. var progressive = seriesModel.getProgressive();
  22788. var pipelineId = seriesModel.uid;
  22789. pipelineMap.set(pipelineId, {
  22790. id: pipelineId,
  22791. head: null,
  22792. tail: null,
  22793. threshold: seriesModel.getProgressiveThreshold(),
  22794. progressiveEnabled: progressive
  22795. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22796. blockIndex: -1,
  22797. step: Math.round(progressive || 700),
  22798. count: 0
  22799. });
  22800. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22801. });
  22802. };
  22803. proto.prepareStageTasks = function () {
  22804. var stageTaskMap = this._stageTaskMap;
  22805. var ecModel = this.ecInstance.getModel();
  22806. var api = this.api;
  22807. each$1(this._allHandlers, function (handler) {
  22808. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22809. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22810. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22811. }, this);
  22812. };
  22813. proto.prepareView = function (view, model, ecModel, api) {
  22814. var renderTask = view.renderTask;
  22815. var context = renderTask.context;
  22816. context.model = model;
  22817. context.ecModel = ecModel;
  22818. context.api = api;
  22819. renderTask.__block = !view.incrementalPrepareRender;
  22820. pipe(this, model, renderTask);
  22821. };
  22822. proto.performDataProcessorTasks = function (ecModel, payload) {
  22823. // If we do not use `block` here, it should be considered when to update modes.
  22824. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22825. };
  22826. // opt
  22827. // opt.visualType: 'visual' or 'layout'
  22828. // opt.setDirty
  22829. proto.performVisualTasks = function (ecModel, payload, opt) {
  22830. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22831. };
  22832. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22833. opt = opt || {};
  22834. var unfinished;
  22835. each$1(stageHandlers, function (stageHandler, idx) {
  22836. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22837. return;
  22838. }
  22839. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22840. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22841. var overallTask = stageHandlerRecord.overallTask;
  22842. if (overallTask) {
  22843. var overallNeedDirty;
  22844. var agentStubMap = overallTask.agentStubMap;
  22845. agentStubMap.each(function (stub) {
  22846. if (needSetDirty(opt, stub)) {
  22847. stub.dirty();
  22848. overallNeedDirty = true;
  22849. }
  22850. });
  22851. overallNeedDirty && overallTask.dirty();
  22852. updatePayload(overallTask, payload);
  22853. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22854. // Execute stubs firstly, which may set the overall task dirty,
  22855. // then execute the overall task. And stub will call seriesModel.setData,
  22856. // which ensures that in the overallTask seriesModel.getData() will not
  22857. // return incorrect data.
  22858. agentStubMap.each(function (stub) {
  22859. stub.perform(performArgs);
  22860. });
  22861. unfinished |= overallTask.perform(performArgs);
  22862. }
  22863. else if (seriesTaskMap) {
  22864. seriesTaskMap.each(function (task, pipelineId) {
  22865. if (needSetDirty(opt, task)) {
  22866. task.dirty();
  22867. }
  22868. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22869. performArgs.skip = !stageHandler.performRawSeries
  22870. && ecModel.isSeriesFiltered(task.context.model);
  22871. updatePayload(task, payload);
  22872. unfinished |= task.perform(performArgs);
  22873. });
  22874. }
  22875. });
  22876. function needSetDirty(opt, task) {
  22877. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22878. }
  22879. scheduler.unfinished |= unfinished;
  22880. }
  22881. proto.performSeriesTasks = function (ecModel) {
  22882. var unfinished;
  22883. ecModel.eachSeries(function (seriesModel) {
  22884. // Progress to the end for dataInit and dataRestore.
  22885. unfinished |= seriesModel.dataTask.perform();
  22886. });
  22887. this.unfinished |= unfinished;
  22888. };
  22889. proto.plan = function () {
  22890. // Travel pipelines, check block.
  22891. this._pipelineMap.each(function (pipeline) {
  22892. var task = pipeline.tail;
  22893. do {
  22894. if (task.__block) {
  22895. pipeline.blockIndex = task.__idxInPipeline;
  22896. break;
  22897. }
  22898. task = task.getUpstream();
  22899. }
  22900. while (task);
  22901. });
  22902. };
  22903. var updatePayload = proto.updatePayload = function (task, payload) {
  22904. payload !== 'remain' && (task.context.payload = payload);
  22905. };
  22906. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22907. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  22908. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  22909. var seriesType = stageHandler.seriesType;
  22910. var getTargetSeries = stageHandler.getTargetSeries;
  22911. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22912. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22913. // it works but it may cause other irrelevant charts blocked.
  22914. if (stageHandler.createOnAllSeries) {
  22915. ecModel.eachRawSeries(create);
  22916. }
  22917. else if (seriesType) {
  22918. ecModel.eachRawSeriesByType(seriesType, create);
  22919. }
  22920. else if (getTargetSeries) {
  22921. getTargetSeries(ecModel, api).each(create);
  22922. }
  22923. function create(seriesModel) {
  22924. var pipelineId = seriesModel.uid;
  22925. // Init tasks for each seriesModel only once.
  22926. // Reuse original task instance.
  22927. var task = seriesTaskMap.get(pipelineId)
  22928. || seriesTaskMap.set(pipelineId, createTask({
  22929. plan: seriesTaskPlan,
  22930. reset: seriesTaskReset,
  22931. count: seriesTaskCount
  22932. }));
  22933. task.context = {
  22934. model: seriesModel,
  22935. ecModel: ecModel,
  22936. api: api,
  22937. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22938. plan: stageHandler.plan,
  22939. reset: stageHandler.reset,
  22940. scheduler: scheduler
  22941. };
  22942. pipe(scheduler, seriesModel, task);
  22943. }
  22944. // Clear unused series tasks.
  22945. var pipelineMap = scheduler._pipelineMap;
  22946. seriesTaskMap.each(function (task, pipelineId) {
  22947. if (!pipelineMap.get(pipelineId)) {
  22948. task.dispose();
  22949. seriesTaskMap.removeKey(pipelineId);
  22950. }
  22951. });
  22952. }
  22953. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22954. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  22955. // For overall task, the function only be called on reset stage.
  22956. || createTask({reset: overallTaskReset});
  22957. overallTask.context = {
  22958. ecModel: ecModel,
  22959. api: api,
  22960. overallReset: stageHandler.overallReset,
  22961. scheduler: scheduler
  22962. };
  22963. // Reuse orignal stubs.
  22964. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  22965. var seriesType = stageHandler.seriesType;
  22966. var getTargetSeries = stageHandler.getTargetSeries;
  22967. var overallProgress = true;
  22968. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  22969. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22970. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22971. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22972. // we set the pipeline block.
  22973. if (seriesType) {
  22974. ecModel.eachRawSeriesByType(seriesType, createStub);
  22975. }
  22976. else if (getTargetSeries) {
  22977. getTargetSeries(ecModel, api).each(createStub);
  22978. }
  22979. // Otherwise, (usually it is legancy case), the overall task will only be
  22980. // executed when upstream dirty. Otherwise the progressive rendering of all
  22981. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22982. // dirty info from upsteam.
  22983. else {
  22984. overallProgress = false;
  22985. each$1(ecModel.getSeries(), createStub);
  22986. }
  22987. function createStub(seriesModel) {
  22988. var pipelineId = seriesModel.uid;
  22989. var stub = agentStubMap.get(pipelineId);
  22990. if (!stub) {
  22991. stub = agentStubMap.set(pipelineId, createTask(
  22992. {reset: stubReset, onDirty: stubOnDirty}
  22993. ));
  22994. // When the result of `getTargetSeries` changed, the overallTask
  22995. // should be set as dirty and re-performed.
  22996. overallTask.dirty();
  22997. }
  22998. stub.context = {
  22999. model: seriesModel,
  23000. overallProgress: overallProgress,
  23001. modifyOutputEnd: modifyOutputEnd
  23002. };
  23003. stub.agent = overallTask;
  23004. stub.__block = overallProgress;
  23005. pipe(scheduler, seriesModel, stub);
  23006. }
  23007. // Clear unused stubs.
  23008. var pipelineMap = scheduler._pipelineMap;
  23009. agentStubMap.each(function (stub, pipelineId) {
  23010. if (!pipelineMap.get(pipelineId)) {
  23011. stub.dispose();
  23012. // When the result of `getTargetSeries` changed, the overallTask
  23013. // should be set as dirty and re-performed.
  23014. overallTask.dirty();
  23015. agentStubMap.removeKey(pipelineId);
  23016. }
  23017. });
  23018. }
  23019. function overallTaskReset(context) {
  23020. context.overallReset(
  23021. context.ecModel, context.api, context.payload
  23022. );
  23023. }
  23024. function stubReset(context, upstreamContext) {
  23025. return context.overallProgress && stubProgress;
  23026. }
  23027. function stubProgress() {
  23028. this.agent.dirty();
  23029. this.getDownstream().dirty();
  23030. }
  23031. function stubOnDirty() {
  23032. this.agent && this.agent.dirty();
  23033. }
  23034. function seriesTaskPlan(context) {
  23035. return context.plan && context.plan(
  23036. context.model, context.ecModel, context.api, context.payload
  23037. );
  23038. }
  23039. function seriesTaskReset(context) {
  23040. if (context.useClearVisual) {
  23041. context.data.clearAllVisual();
  23042. }
  23043. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  23044. context.model, context.ecModel, context.api, context.payload
  23045. ));
  23046. return resetDefines.length > 1
  23047. ? map(resetDefines, function (v, idx) {
  23048. return makeSeriesTaskProgress(idx);
  23049. })
  23050. : singleSeriesTaskProgress;
  23051. }
  23052. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23053. function makeSeriesTaskProgress(resetDefineIdx) {
  23054. return function (params, context) {
  23055. var data = context.data;
  23056. var resetDefine = context.resetDefines[resetDefineIdx];
  23057. if (resetDefine && resetDefine.dataEach) {
  23058. for (var i = params.start; i < params.end; i++) {
  23059. resetDefine.dataEach(data, i);
  23060. }
  23061. }
  23062. else if (resetDefine && resetDefine.progress) {
  23063. resetDefine.progress(params, data);
  23064. }
  23065. };
  23066. }
  23067. function seriesTaskCount(context) {
  23068. return context.data.count();
  23069. }
  23070. function pipe(scheduler, seriesModel, task) {
  23071. var pipelineId = seriesModel.uid;
  23072. var pipeline = scheduler._pipelineMap.get(pipelineId);
  23073. !pipeline.head && (pipeline.head = task);
  23074. pipeline.tail && pipeline.tail.pipe(task);
  23075. pipeline.tail = task;
  23076. task.__idxInPipeline = pipeline.count++;
  23077. task.__pipeline = pipeline;
  23078. }
  23079. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23080. if (isFunction$1(stageHandler)) {
  23081. stageHandler = {
  23082. overallReset: stageHandler,
  23083. seriesType: detectSeriseType(stageHandler)
  23084. };
  23085. }
  23086. stageHandler.uid = getUID('stageHandler');
  23087. visualType && (stageHandler.visualType = visualType);
  23088. return stageHandler;
  23089. };
  23090. /**
  23091. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23092. * To ensure that they can work normally, they should work in block mode, that is,
  23093. * they should not be started util the previous tasks finished. So they cause the
  23094. * progressive rendering disabled. We try to detect the series type, to narrow down
  23095. * the block range to only the series type they concern, but not all series.
  23096. */
  23097. function detectSeriseType(legacyFunc) {
  23098. seriesType = null;
  23099. try {
  23100. // Assume there is no async when calling `eachSeriesByType`.
  23101. legacyFunc(ecModelMock, apiMock);
  23102. }
  23103. catch (e) {
  23104. }
  23105. return seriesType;
  23106. }
  23107. var ecModelMock = {};
  23108. var apiMock = {};
  23109. var seriesType;
  23110. mockMethods(ecModelMock, GlobalModel);
  23111. mockMethods(apiMock, ExtensionAPI);
  23112. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23113. seriesType = type;
  23114. };
  23115. ecModelMock.eachComponent = function (cond) {
  23116. if (cond.mainType === 'series' && cond.subType) {
  23117. seriesType = cond.subType;
  23118. }
  23119. };
  23120. function mockMethods(target, Clz) {
  23121. /* eslint-disable */
  23122. for (var name in Clz.prototype) {
  23123. // Do not use hasOwnProperty
  23124. target[name] = noop;
  23125. }
  23126. /* eslint-enable */
  23127. }
  23128. /*
  23129. * Licensed to the Apache Software Foundation (ASF) under one
  23130. * or more contributor license agreements. See the NOTICE file
  23131. * distributed with this work for additional information
  23132. * regarding copyright ownership. The ASF licenses this file
  23133. * to you under the Apache License, Version 2.0 (the
  23134. * "License"); you may not use this file except in compliance
  23135. * with the License. You may obtain a copy of the License at
  23136. *
  23137. * http://www.apache.org/licenses/LICENSE-2.0
  23138. *
  23139. * Unless required by applicable law or agreed to in writing,
  23140. * software distributed under the License is distributed on an
  23141. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23142. * KIND, either express or implied. See the License for the
  23143. * specific language governing permissions and limitations
  23144. * under the License.
  23145. */
  23146. var colorAll = [
  23147. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  23148. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  23149. ];
  23150. var lightTheme = {
  23151. color: colorAll,
  23152. colorLayer: [
  23153. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  23154. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  23155. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  23156. colorAll
  23157. ]
  23158. };
  23159. /*
  23160. * Licensed to the Apache Software Foundation (ASF) under one
  23161. * or more contributor license agreements. See the NOTICE file
  23162. * distributed with this work for additional information
  23163. * regarding copyright ownership. The ASF licenses this file
  23164. * to you under the Apache License, Version 2.0 (the
  23165. * "License"); you may not use this file except in compliance
  23166. * with the License. You may obtain a copy of the License at
  23167. *
  23168. * http://www.apache.org/licenses/LICENSE-2.0
  23169. *
  23170. * Unless required by applicable law or agreed to in writing,
  23171. * software distributed under the License is distributed on an
  23172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23173. * KIND, either express or implied. See the License for the
  23174. * specific language governing permissions and limitations
  23175. * under the License.
  23176. */
  23177. var contrastColor = '#eee';
  23178. var axisCommon = function () {
  23179. return {
  23180. axisLine: {
  23181. lineStyle: {
  23182. color: contrastColor
  23183. }
  23184. },
  23185. axisTick: {
  23186. lineStyle: {
  23187. color: contrastColor
  23188. }
  23189. },
  23190. axisLabel: {
  23191. textStyle: {
  23192. color: contrastColor
  23193. }
  23194. },
  23195. splitLine: {
  23196. lineStyle: {
  23197. type: 'dashed',
  23198. color: '#aaa'
  23199. }
  23200. },
  23201. splitArea: {
  23202. areaStyle: {
  23203. color: contrastColor
  23204. }
  23205. }
  23206. };
  23207. };
  23208. var colorPalette = [
  23209. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  23210. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  23211. ];
  23212. var theme = {
  23213. color: colorPalette,
  23214. backgroundColor: '#333',
  23215. tooltip: {
  23216. axisPointer: {
  23217. lineStyle: {
  23218. color: contrastColor
  23219. },
  23220. crossStyle: {
  23221. color: contrastColor
  23222. },
  23223. label: {
  23224. color: '#000'
  23225. }
  23226. }
  23227. },
  23228. legend: {
  23229. textStyle: {
  23230. color: contrastColor
  23231. }
  23232. },
  23233. textStyle: {
  23234. color: contrastColor
  23235. },
  23236. title: {
  23237. textStyle: {
  23238. color: contrastColor
  23239. }
  23240. },
  23241. toolbox: {
  23242. iconStyle: {
  23243. normal: {
  23244. borderColor: contrastColor
  23245. }
  23246. }
  23247. },
  23248. dataZoom: {
  23249. textStyle: {
  23250. color: contrastColor
  23251. }
  23252. },
  23253. visualMap: {
  23254. textStyle: {
  23255. color: contrastColor
  23256. }
  23257. },
  23258. timeline: {
  23259. lineStyle: {
  23260. color: contrastColor
  23261. },
  23262. itemStyle: {
  23263. normal: {
  23264. color: colorPalette[1]
  23265. }
  23266. },
  23267. label: {
  23268. normal: {
  23269. textStyle: {
  23270. color: contrastColor
  23271. }
  23272. }
  23273. },
  23274. controlStyle: {
  23275. normal: {
  23276. color: contrastColor,
  23277. borderColor: contrastColor
  23278. }
  23279. }
  23280. },
  23281. timeAxis: axisCommon(),
  23282. logAxis: axisCommon(),
  23283. valueAxis: axisCommon(),
  23284. categoryAxis: axisCommon(),
  23285. line: {
  23286. symbol: 'circle'
  23287. },
  23288. graph: {
  23289. color: colorPalette
  23290. },
  23291. gauge: {
  23292. title: {
  23293. textStyle: {
  23294. color: contrastColor
  23295. }
  23296. }
  23297. },
  23298. candlestick: {
  23299. itemStyle: {
  23300. normal: {
  23301. color: '#FD1050',
  23302. color0: '#0CF49B',
  23303. borderColor: '#FD1050',
  23304. borderColor0: '#0CF49B'
  23305. }
  23306. }
  23307. }
  23308. };
  23309. theme.categoryAxis.splitLine.show = false;
  23310. /*
  23311. * Licensed to the Apache Software Foundation (ASF) under one
  23312. * or more contributor license agreements. See the NOTICE file
  23313. * distributed with this work for additional information
  23314. * regarding copyright ownership. The ASF licenses this file
  23315. * to you under the Apache License, Version 2.0 (the
  23316. * "License"); you may not use this file except in compliance
  23317. * with the License. You may obtain a copy of the License at
  23318. *
  23319. * http://www.apache.org/licenses/LICENSE-2.0
  23320. *
  23321. * Unless required by applicable law or agreed to in writing,
  23322. * software distributed under the License is distributed on an
  23323. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23324. * KIND, either express or implied. See the License for the
  23325. * specific language governing permissions and limitations
  23326. * under the License.
  23327. */
  23328. /**
  23329. * This module is imported by echarts directly.
  23330. *
  23331. * Notice:
  23332. * Always keep this file exists for backward compatibility.
  23333. * Because before 4.1.0, dataset is an optional component,
  23334. * some users may import this module manually.
  23335. */
  23336. ComponentModel.extend({
  23337. type: 'dataset',
  23338. /**
  23339. * @protected
  23340. */
  23341. defaultOption: {
  23342. // 'row', 'column'
  23343. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  23344. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  23345. sourceHeader: null,
  23346. dimensions: null,
  23347. source: null
  23348. },
  23349. optionUpdated: function () {
  23350. detectSourceFormat(this);
  23351. }
  23352. });
  23353. Component$1.extend({
  23354. type: 'dataset'
  23355. });
  23356. /**
  23357. * 椭圆形状
  23358. * @module zrender/graphic/shape/Ellipse
  23359. */
  23360. var Ellipse = Path.extend({
  23361. type: 'ellipse',
  23362. shape: {
  23363. cx: 0, cy: 0,
  23364. rx: 0, ry: 0
  23365. },
  23366. buildPath: function (ctx, shape) {
  23367. var k = 0.5522848;
  23368. var x = shape.cx;
  23369. var y = shape.cy;
  23370. var a = shape.rx;
  23371. var b = shape.ry;
  23372. var ox = a * k; // 水平控制点偏移量
  23373. var oy = b * k; // 垂直控制点偏移量
  23374. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  23375. ctx.moveTo(x - a, y);
  23376. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  23377. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  23378. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  23379. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  23380. ctx.closePath();
  23381. }
  23382. });
  23383. // import RadialGradient from '../graphic/RadialGradient';
  23384. // import Pattern from '../graphic/Pattern';
  23385. // import * as vector from '../core/vector';
  23386. // Most of the values can be separated by comma and/or white space.
  23387. var DILIMITER_REG = /[\s,]+/;
  23388. /**
  23389. * For big svg string, this method might be time consuming.
  23390. *
  23391. * @param {string} svg xml string
  23392. * @return {Object} xml root.
  23393. */
  23394. function parseXML(svg) {
  23395. if (isString(svg)) {
  23396. var parser = new DOMParser();
  23397. svg = parser.parseFromString(svg, 'text/xml');
  23398. }
  23399. // Document node. If using $.get, doc node may be input.
  23400. if (svg.nodeType === 9) {
  23401. svg = svg.firstChild;
  23402. }
  23403. // nodeName of <!DOCTYPE svg> is also 'svg'.
  23404. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  23405. svg = svg.nextSibling;
  23406. }
  23407. return svg;
  23408. }
  23409. function SVGParser() {
  23410. this._defs = {};
  23411. this._root = null;
  23412. this._isDefine = false;
  23413. this._isText = false;
  23414. }
  23415. SVGParser.prototype.parse = function (xml, opt) {
  23416. opt = opt || {};
  23417. var svg = parseXML(xml);
  23418. if (!svg) {
  23419. throw new Error('Illegal svg');
  23420. }
  23421. var root = new Group();
  23422. this._root = root;
  23423. // parse view port
  23424. var viewBox = svg.getAttribute('viewBox') || '';
  23425. // If width/height not specified, means "100%" of `opt.width/height`.
  23426. // TODO: Other percent value not supported yet.
  23427. var width = parseFloat(svg.getAttribute('width') || opt.width);
  23428. var height = parseFloat(svg.getAttribute('height') || opt.height);
  23429. // If width/height not specified, set as null for output.
  23430. isNaN(width) && (width = null);
  23431. isNaN(height) && (height = null);
  23432. // Apply inline style on svg element.
  23433. parseAttributes(svg, root, null, true);
  23434. var child = svg.firstChild;
  23435. while (child) {
  23436. this._parseNode(child, root);
  23437. child = child.nextSibling;
  23438. }
  23439. var viewBoxRect;
  23440. var viewBoxTransform;
  23441. if (viewBox) {
  23442. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  23443. // Some invalid case like viewBox: 'none'.
  23444. if (viewBoxArr.length >= 4) {
  23445. viewBoxRect = {
  23446. x: parseFloat(viewBoxArr[0] || 0),
  23447. y: parseFloat(viewBoxArr[1] || 0),
  23448. width: parseFloat(viewBoxArr[2]),
  23449. height: parseFloat(viewBoxArr[3])
  23450. };
  23451. }
  23452. }
  23453. if (viewBoxRect && width != null && height != null) {
  23454. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  23455. if (!opt.ignoreViewBox) {
  23456. // If set transform on the output group, it probably bring trouble when
  23457. // some users only intend to show the clipped content inside the viewBox,
  23458. // but not intend to transform the output group. So we keep the output
  23459. // group no transform. If the user intend to use the viewBox as a
  23460. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  23461. // manually according to the viewBox info in the output of this method.
  23462. var elRoot = root;
  23463. root = new Group();
  23464. root.add(elRoot);
  23465. elRoot.scale = viewBoxTransform.scale.slice();
  23466. elRoot.position = viewBoxTransform.position.slice();
  23467. }
  23468. }
  23469. // Some shapes might be overflow the viewport, which should be
  23470. // clipped despite whether the viewBox is used, as the SVG does.
  23471. if (!opt.ignoreRootClip && width != null && height != null) {
  23472. root.setClipPath(new Rect({
  23473. shape: {x: 0, y: 0, width: width, height: height}
  23474. }));
  23475. }
  23476. // Set width/height on group just for output the viewport size.
  23477. return {
  23478. root: root,
  23479. width: width,
  23480. height: height,
  23481. viewBoxRect: viewBoxRect,
  23482. viewBoxTransform: viewBoxTransform
  23483. };
  23484. };
  23485. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  23486. var nodeName = xmlNode.nodeName.toLowerCase();
  23487. // TODO
  23488. // support <style>...</style> in svg, where nodeName is 'style',
  23489. // CSS classes is defined globally wherever the style tags are declared.
  23490. if (nodeName === 'defs') {
  23491. // define flag
  23492. this._isDefine = true;
  23493. }
  23494. else if (nodeName === 'text') {
  23495. this._isText = true;
  23496. }
  23497. var el;
  23498. if (this._isDefine) {
  23499. var parser = defineParsers[nodeName];
  23500. if (parser) {
  23501. var def = parser.call(this, xmlNode);
  23502. var id = xmlNode.getAttribute('id');
  23503. if (id) {
  23504. this._defs[id] = def;
  23505. }
  23506. }
  23507. }
  23508. else {
  23509. var parser = nodeParsers[nodeName];
  23510. if (parser) {
  23511. el = parser.call(this, xmlNode, parentGroup);
  23512. parentGroup.add(el);
  23513. }
  23514. }
  23515. var child = xmlNode.firstChild;
  23516. while (child) {
  23517. if (child.nodeType === 1) {
  23518. this._parseNode(child, el);
  23519. }
  23520. // Is text
  23521. if (child.nodeType === 3 && this._isText) {
  23522. this._parseText(child, el);
  23523. }
  23524. child = child.nextSibling;
  23525. }
  23526. // Quit define
  23527. if (nodeName === 'defs') {
  23528. this._isDefine = false;
  23529. }
  23530. else if (nodeName === 'text') {
  23531. this._isText = false;
  23532. }
  23533. };
  23534. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  23535. if (xmlNode.nodeType === 1) {
  23536. var dx = xmlNode.getAttribute('dx') || 0;
  23537. var dy = xmlNode.getAttribute('dy') || 0;
  23538. this._textX += parseFloat(dx);
  23539. this._textY += parseFloat(dy);
  23540. }
  23541. var text = new Text({
  23542. style: {
  23543. text: xmlNode.textContent,
  23544. transformText: true
  23545. },
  23546. position: [this._textX || 0, this._textY || 0]
  23547. });
  23548. inheritStyle(parentGroup, text);
  23549. parseAttributes(xmlNode, text, this._defs);
  23550. var fontSize = text.style.fontSize;
  23551. if (fontSize && fontSize < 9) {
  23552. // PENDING
  23553. text.style.fontSize = 9;
  23554. text.scale = text.scale || [1, 1];
  23555. text.scale[0] *= fontSize / 9;
  23556. text.scale[1] *= fontSize / 9;
  23557. }
  23558. var rect = text.getBoundingRect();
  23559. this._textX += rect.width;
  23560. parentGroup.add(text);
  23561. return text;
  23562. };
  23563. var nodeParsers = {
  23564. 'g': function (xmlNode, parentGroup) {
  23565. var g = new Group();
  23566. inheritStyle(parentGroup, g);
  23567. parseAttributes(xmlNode, g, this._defs);
  23568. return g;
  23569. },
  23570. 'rect': function (xmlNode, parentGroup) {
  23571. var rect = new Rect();
  23572. inheritStyle(parentGroup, rect);
  23573. parseAttributes(xmlNode, rect, this._defs);
  23574. rect.setShape({
  23575. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23576. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23577. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23578. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23579. });
  23580. // console.log(xmlNode.getAttribute('transform'));
  23581. // console.log(rect.transform);
  23582. return rect;
  23583. },
  23584. 'circle': function (xmlNode, parentGroup) {
  23585. var circle = new Circle();
  23586. inheritStyle(parentGroup, circle);
  23587. parseAttributes(xmlNode, circle, this._defs);
  23588. circle.setShape({
  23589. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23590. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23591. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23592. });
  23593. return circle;
  23594. },
  23595. 'line': function (xmlNode, parentGroup) {
  23596. var line = new Line();
  23597. inheritStyle(parentGroup, line);
  23598. parseAttributes(xmlNode, line, this._defs);
  23599. line.setShape({
  23600. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23601. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23602. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23603. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23604. });
  23605. return line;
  23606. },
  23607. 'ellipse': function (xmlNode, parentGroup) {
  23608. var ellipse = new Ellipse();
  23609. inheritStyle(parentGroup, ellipse);
  23610. parseAttributes(xmlNode, ellipse, this._defs);
  23611. ellipse.setShape({
  23612. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23613. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23614. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23615. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23616. });
  23617. return ellipse;
  23618. },
  23619. 'polygon': function (xmlNode, parentGroup) {
  23620. var points = xmlNode.getAttribute('points');
  23621. if (points) {
  23622. points = parsePoints(points);
  23623. }
  23624. var polygon = new Polygon({
  23625. shape: {
  23626. points: points || []
  23627. }
  23628. });
  23629. inheritStyle(parentGroup, polygon);
  23630. parseAttributes(xmlNode, polygon, this._defs);
  23631. return polygon;
  23632. },
  23633. 'polyline': function (xmlNode, parentGroup) {
  23634. var path = new Path();
  23635. inheritStyle(parentGroup, path);
  23636. parseAttributes(xmlNode, path, this._defs);
  23637. var points = xmlNode.getAttribute('points');
  23638. if (points) {
  23639. points = parsePoints(points);
  23640. }
  23641. var polyline = new Polyline({
  23642. shape: {
  23643. points: points || []
  23644. }
  23645. });
  23646. return polyline;
  23647. },
  23648. 'image': function (xmlNode, parentGroup) {
  23649. var img = new ZImage();
  23650. inheritStyle(parentGroup, img);
  23651. parseAttributes(xmlNode, img, this._defs);
  23652. img.setStyle({
  23653. image: xmlNode.getAttribute('xlink:href'),
  23654. x: xmlNode.getAttribute('x'),
  23655. y: xmlNode.getAttribute('y'),
  23656. width: xmlNode.getAttribute('width'),
  23657. height: xmlNode.getAttribute('height')
  23658. });
  23659. return img;
  23660. },
  23661. 'text': function (xmlNode, parentGroup) {
  23662. var x = xmlNode.getAttribute('x') || 0;
  23663. var y = xmlNode.getAttribute('y') || 0;
  23664. var dx = xmlNode.getAttribute('dx') || 0;
  23665. var dy = xmlNode.getAttribute('dy') || 0;
  23666. this._textX = parseFloat(x) + parseFloat(dx);
  23667. this._textY = parseFloat(y) + parseFloat(dy);
  23668. var g = new Group();
  23669. inheritStyle(parentGroup, g);
  23670. parseAttributes(xmlNode, g, this._defs);
  23671. return g;
  23672. },
  23673. 'tspan': function (xmlNode, parentGroup) {
  23674. var x = xmlNode.getAttribute('x');
  23675. var y = xmlNode.getAttribute('y');
  23676. if (x != null) {
  23677. // new offset x
  23678. this._textX = parseFloat(x);
  23679. }
  23680. if (y != null) {
  23681. // new offset y
  23682. this._textY = parseFloat(y);
  23683. }
  23684. var dx = xmlNode.getAttribute('dx') || 0;
  23685. var dy = xmlNode.getAttribute('dy') || 0;
  23686. var g = new Group();
  23687. inheritStyle(parentGroup, g);
  23688. parseAttributes(xmlNode, g, this._defs);
  23689. this._textX += dx;
  23690. this._textY += dy;
  23691. return g;
  23692. },
  23693. 'path': function (xmlNode, parentGroup) {
  23694. // TODO svg fill rule
  23695. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23696. // path.style.globalCompositeOperation = 'xor';
  23697. var d = xmlNode.getAttribute('d') || '';
  23698. // Performance sensitive.
  23699. var path = createFromString(d);
  23700. inheritStyle(parentGroup, path);
  23701. parseAttributes(xmlNode, path, this._defs);
  23702. return path;
  23703. }
  23704. };
  23705. var defineParsers = {
  23706. 'lineargradient': function (xmlNode) {
  23707. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23708. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23709. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23710. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23711. var gradient = new LinearGradient(x1, y1, x2, y2);
  23712. _parseGradientColorStops(xmlNode, gradient);
  23713. return gradient;
  23714. },
  23715. 'radialgradient': function (xmlNode) {
  23716. }
  23717. };
  23718. function _parseGradientColorStops(xmlNode, gradient) {
  23719. var stop = xmlNode.firstChild;
  23720. while (stop) {
  23721. if (stop.nodeType === 1) {
  23722. var offset = stop.getAttribute('offset');
  23723. if (offset.indexOf('%') > 0) { // percentage
  23724. offset = parseInt(offset, 10) / 100;
  23725. }
  23726. else if (offset) { // number from 0 to 1
  23727. offset = parseFloat(offset);
  23728. }
  23729. else {
  23730. offset = 0;
  23731. }
  23732. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23733. gradient.addColorStop(offset, stopColor);
  23734. }
  23735. stop = stop.nextSibling;
  23736. }
  23737. }
  23738. function inheritStyle(parent, child) {
  23739. if (parent && parent.__inheritedStyle) {
  23740. if (!child.__inheritedStyle) {
  23741. child.__inheritedStyle = {};
  23742. }
  23743. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23744. }
  23745. }
  23746. function parsePoints(pointsString) {
  23747. var list = trim(pointsString).split(DILIMITER_REG);
  23748. var points = [];
  23749. for (var i = 0; i < list.length; i += 2) {
  23750. var x = parseFloat(list[i]);
  23751. var y = parseFloat(list[i + 1]);
  23752. points.push([x, y]);
  23753. }
  23754. return points;
  23755. }
  23756. var attributesMap = {
  23757. 'fill': 'fill',
  23758. 'stroke': 'stroke',
  23759. 'stroke-width': 'lineWidth',
  23760. 'opacity': 'opacity',
  23761. 'fill-opacity': 'fillOpacity',
  23762. 'stroke-opacity': 'strokeOpacity',
  23763. 'stroke-dasharray': 'lineDash',
  23764. 'stroke-dashoffset': 'lineDashOffset',
  23765. 'stroke-linecap': 'lineCap',
  23766. 'stroke-linejoin': 'lineJoin',
  23767. 'stroke-miterlimit': 'miterLimit',
  23768. 'font-family': 'fontFamily',
  23769. 'font-size': 'fontSize',
  23770. 'font-style': 'fontStyle',
  23771. 'font-weight': 'fontWeight',
  23772. 'text-align': 'textAlign',
  23773. 'alignment-baseline': 'textBaseline'
  23774. };
  23775. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23776. var zrStyle = el.__inheritedStyle || {};
  23777. var isTextEl = el.type === 'text';
  23778. // TODO Shadow
  23779. if (xmlNode.nodeType === 1) {
  23780. parseTransformAttribute(xmlNode, el);
  23781. extend(zrStyle, parseStyleAttribute(xmlNode));
  23782. if (!onlyInlineStyle) {
  23783. for (var svgAttrName in attributesMap) {
  23784. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23785. var attrValue = xmlNode.getAttribute(svgAttrName);
  23786. if (attrValue != null) {
  23787. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23788. }
  23789. }
  23790. }
  23791. }
  23792. }
  23793. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23794. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23795. el.style = el.style || new Style();
  23796. var elStyle = el.style;
  23797. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23798. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23799. each$1([
  23800. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23801. ], function (propName) {
  23802. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23803. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23804. });
  23805. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23806. zrStyle.textBaseline = 'alphabetic';
  23807. }
  23808. if (zrStyle.textBaseline === 'alphabetic') {
  23809. zrStyle.textBaseline = 'bottom';
  23810. }
  23811. if (zrStyle.textAlign === 'start') {
  23812. zrStyle.textAlign = 'left';
  23813. }
  23814. if (zrStyle.textAlign === 'end') {
  23815. zrStyle.textAlign = 'right';
  23816. }
  23817. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23818. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23819. ], function (propName) {
  23820. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23821. });
  23822. if (zrStyle.lineDash) {
  23823. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23824. }
  23825. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23826. // enable stroke
  23827. el[elStrokeProp] = true;
  23828. }
  23829. el.__inheritedStyle = zrStyle;
  23830. }
  23831. var urlRegex = /url\(\s*#(.*?)\)/;
  23832. function getPaint(str, defs) {
  23833. // if (str === 'none') {
  23834. // return;
  23835. // }
  23836. var urlMatch = defs && str && str.match(urlRegex);
  23837. if (urlMatch) {
  23838. var url = trim(urlMatch[1]);
  23839. var def = defs[url];
  23840. return def;
  23841. }
  23842. return str;
  23843. }
  23844. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23845. function parseTransformAttribute(xmlNode, node) {
  23846. var transform = xmlNode.getAttribute('transform');
  23847. if (transform) {
  23848. transform = transform.replace(/,/g, ' ');
  23849. var m = null;
  23850. var transformOps = [];
  23851. transform.replace(transformRegex, function (str, type, value) {
  23852. transformOps.push(type, value);
  23853. });
  23854. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23855. var value = transformOps[i];
  23856. var type = transformOps[i - 1];
  23857. m = m || create$1();
  23858. switch (type) {
  23859. case 'translate':
  23860. value = trim(value).split(DILIMITER_REG);
  23861. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23862. break;
  23863. case 'scale':
  23864. value = trim(value).split(DILIMITER_REG);
  23865. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23866. break;
  23867. case 'rotate':
  23868. value = trim(value).split(DILIMITER_REG);
  23869. rotate(m, m, parseFloat(value[0]));
  23870. break;
  23871. case 'skew':
  23872. value = trim(value).split(DILIMITER_REG);
  23873. console.warn('Skew transform is not supported yet');
  23874. break;
  23875. case 'matrix':
  23876. var value = trim(value).split(DILIMITER_REG);
  23877. m[0] = parseFloat(value[0]);
  23878. m[1] = parseFloat(value[1]);
  23879. m[2] = parseFloat(value[2]);
  23880. m[3] = parseFloat(value[3]);
  23881. m[4] = parseFloat(value[4]);
  23882. m[5] = parseFloat(value[5]);
  23883. break;
  23884. }
  23885. }
  23886. node.setLocalTransform(m);
  23887. }
  23888. }
  23889. // Value may contain space.
  23890. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23891. function parseStyleAttribute(xmlNode) {
  23892. var style = xmlNode.getAttribute('style');
  23893. var result = {};
  23894. if (!style) {
  23895. return result;
  23896. }
  23897. var styleList = {};
  23898. styleRegex.lastIndex = 0;
  23899. var styleRegResult;
  23900. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23901. styleList[styleRegResult[1]] = styleRegResult[2];
  23902. }
  23903. for (var svgAttrName in attributesMap) {
  23904. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  23905. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  23906. }
  23907. }
  23908. return result;
  23909. }
  23910. /**
  23911. * @param {Array.<number>} viewBoxRect
  23912. * @param {number} width
  23913. * @param {number} height
  23914. * @return {Object} {scale, position}
  23915. */
  23916. function makeViewBoxTransform(viewBoxRect, width, height) {
  23917. var scaleX = width / viewBoxRect.width;
  23918. var scaleY = height / viewBoxRect.height;
  23919. var scale = Math.min(scaleX, scaleY);
  23920. // preserveAspectRatio 'xMidYMid'
  23921. var viewBoxScale = [scale, scale];
  23922. var viewBoxPosition = [
  23923. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  23924. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  23925. ];
  23926. return {
  23927. scale: viewBoxScale,
  23928. position: viewBoxPosition
  23929. };
  23930. }
  23931. /**
  23932. * @param {string|XMLElement} xml
  23933. * @param {Object} [opt]
  23934. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  23935. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  23936. * @param {boolean} [opt.ignoreViewBox]
  23937. * @param {boolean} [opt.ignoreRootClip]
  23938. * @return {Object} result:
  23939. * {
  23940. * root: Group, The root of the the result tree of zrender shapes,
  23941. * width: number, the viewport width of the SVG,
  23942. * height: number, the viewport height of the SVG,
  23943. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  23944. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  23945. * }
  23946. */
  23947. /*
  23948. * Licensed to the Apache Software Foundation (ASF) under one
  23949. * or more contributor license agreements. See the NOTICE file
  23950. * distributed with this work for additional information
  23951. * regarding copyright ownership. The ASF licenses this file
  23952. * to you under the Apache License, Version 2.0 (the
  23953. * "License"); you may not use this file except in compliance
  23954. * with the License. You may obtain a copy of the License at
  23955. *
  23956. * http://www.apache.org/licenses/LICENSE-2.0
  23957. *
  23958. * Unless required by applicable law or agreed to in writing,
  23959. * software distributed under the License is distributed on an
  23960. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23961. * KIND, either express or implied. See the License for the
  23962. * specific language governing permissions and limitations
  23963. * under the License.
  23964. */
  23965. var storage = createHashMap();
  23966. // For minimize the code size of common echarts package,
  23967. // do not put too much logic in this module.
  23968. var mapDataStorage = {
  23969. // The format of record: see `echarts.registerMap`.
  23970. // Compatible with previous `echarts.registerMap`.
  23971. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  23972. var records;
  23973. if (isArray(rawGeoJson)) {
  23974. records = rawGeoJson;
  23975. }
  23976. else if (rawGeoJson.svg) {
  23977. records = [{
  23978. type: 'svg',
  23979. source: rawGeoJson.svg,
  23980. specialAreas: rawGeoJson.specialAreas
  23981. }];
  23982. }
  23983. else {
  23984. // Backward compatibility.
  23985. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  23986. rawSpecialAreas = rawGeoJson.specialAreas;
  23987. rawGeoJson = rawGeoJson.geoJson;
  23988. }
  23989. records = [{
  23990. type: 'geoJSON',
  23991. source: rawGeoJson,
  23992. specialAreas: rawSpecialAreas
  23993. }];
  23994. }
  23995. each$1(records, function (record) {
  23996. var type = record.type;
  23997. type === 'geoJson' && (type = record.type = 'geoJSON');
  23998. var parse = parsers[type];
  23999. if (__DEV__) {
  24000. assert$1(parse, 'Illegal map type: ' + type);
  24001. }
  24002. parse(record);
  24003. });
  24004. return storage.set(mapName, records);
  24005. },
  24006. retrieveMap: function (mapName) {
  24007. return storage.get(mapName);
  24008. }
  24009. };
  24010. var parsers = {
  24011. geoJSON: function (record) {
  24012. var source = record.source;
  24013. record.geoJSON = !isString(source)
  24014. ? source
  24015. : (typeof JSON !== 'undefined' && JSON.parse)
  24016. ? JSON.parse(source)
  24017. : (new Function('return (' + source + ');'))();
  24018. },
  24019. // Only perform parse to XML object here, which might be time
  24020. // consiming for large SVG.
  24021. // Although convert XML to zrender element is also time consiming,
  24022. // if we do it here, the clone of zrender elements has to be
  24023. // required. So we do it once for each geo instance, util real
  24024. // performance issues call for optimizing it.
  24025. svg: function (record) {
  24026. record.svgXML = parseXML(record.source);
  24027. }
  24028. };
  24029. /*
  24030. * Licensed to the Apache Software Foundation (ASF) under one
  24031. * or more contributor license agreements. See the NOTICE file
  24032. * distributed with this work for additional information
  24033. * regarding copyright ownership. The ASF licenses this file
  24034. * to you under the Apache License, Version 2.0 (the
  24035. * "License"); you may not use this file except in compliance
  24036. * with the License. You may obtain a copy of the License at
  24037. *
  24038. * http://www.apache.org/licenses/LICENSE-2.0
  24039. *
  24040. * Unless required by applicable law or agreed to in writing,
  24041. * software distributed under the License is distributed on an
  24042. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24043. * KIND, either express or implied. See the License for the
  24044. * specific language governing permissions and limitations
  24045. * under the License.
  24046. */
  24047. var assert = assert$1;
  24048. var each = each$1;
  24049. var isFunction = isFunction$1;
  24050. var isObject = isObject$1;
  24051. var parseClassType = ComponentModel.parseClassType;
  24052. var version = '4.6.0';
  24053. var dependencies = {
  24054. zrender: '4.2.0'
  24055. };
  24056. var TEST_FRAME_REMAIN_TIME = 1;
  24057. var PRIORITY_PROCESSOR_FILTER = 1000;
  24058. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  24059. var PRIORITY_PROCESSOR_DATASTACK = 900;
  24060. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24061. var PRIORITY_VISUAL_LAYOUT = 1000;
  24062. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24063. var PRIORITY_VISUAL_GLOBAL = 2000;
  24064. var PRIORITY_VISUAL_CHART = 3000;
  24065. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  24066. var PRIORITY_VISUAL_COMPONENT = 4000;
  24067. // FIXME
  24068. // necessary?
  24069. var PRIORITY_VISUAL_BRUSH = 5000;
  24070. var PRIORITY = {
  24071. PROCESSOR: {
  24072. FILTER: PRIORITY_PROCESSOR_FILTER,
  24073. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24074. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24075. },
  24076. VISUAL: {
  24077. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24078. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24079. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24080. CHART: PRIORITY_VISUAL_CHART,
  24081. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24082. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24083. BRUSH: PRIORITY_VISUAL_BRUSH
  24084. }
  24085. };
  24086. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24087. // where they must not be invoked nestedly, except the only case: invoke
  24088. // dispatchAction with updateMethod "none" in main process.
  24089. // This flag is used to carry out this rule.
  24090. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24091. var IN_MAIN_PROCESS = '__flagInMainProcess';
  24092. var OPTION_UPDATED = '__optionUpdated';
  24093. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24094. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  24095. return function (eventName, handler, context) {
  24096. if (!ignoreDisposed && this._disposed) {
  24097. disposedWarning(this.id);
  24098. return;
  24099. }
  24100. // Event name is all lowercase
  24101. eventName = eventName && eventName.toLowerCase();
  24102. Eventful.prototype[method].call(this, eventName, handler, context);
  24103. };
  24104. }
  24105. /**
  24106. * @module echarts~MessageCenter
  24107. */
  24108. function MessageCenter() {
  24109. Eventful.call(this);
  24110. }
  24111. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  24112. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  24113. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  24114. mixin(MessageCenter, Eventful);
  24115. /**
  24116. * @module echarts~ECharts
  24117. */
  24118. function ECharts(dom, theme$$1, opts) {
  24119. opts = opts || {};
  24120. // Get theme by name
  24121. if (typeof theme$$1 === 'string') {
  24122. theme$$1 = themeStorage[theme$$1];
  24123. }
  24124. /**
  24125. * @type {string}
  24126. */
  24127. this.id;
  24128. /**
  24129. * Group id
  24130. * @type {string}
  24131. */
  24132. this.group;
  24133. /**
  24134. * @type {HTMLElement}
  24135. * @private
  24136. */
  24137. this._dom = dom;
  24138. var defaultRenderer = 'canvas';
  24139. if (__DEV__) {
  24140. defaultRenderer = (
  24141. typeof window === 'undefined' ? global : window
  24142. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24143. }
  24144. /**
  24145. * @type {module:zrender/ZRender}
  24146. * @private
  24147. */
  24148. var zr = this._zr = init$1(dom, {
  24149. renderer: opts.renderer || defaultRenderer,
  24150. devicePixelRatio: opts.devicePixelRatio,
  24151. width: opts.width,
  24152. height: opts.height
  24153. });
  24154. /**
  24155. * Expect 60 fps.
  24156. * @type {Function}
  24157. * @private
  24158. */
  24159. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24160. var theme$$1 = clone(theme$$1);
  24161. theme$$1 && backwardCompat(theme$$1, true);
  24162. /**
  24163. * @type {Object}
  24164. * @private
  24165. */
  24166. this._theme = theme$$1;
  24167. /**
  24168. * @type {Array.<module:echarts/view/Chart>}
  24169. * @private
  24170. */
  24171. this._chartsViews = [];
  24172. /**
  24173. * @type {Object.<string, module:echarts/view/Chart>}
  24174. * @private
  24175. */
  24176. this._chartsMap = {};
  24177. /**
  24178. * @type {Array.<module:echarts/view/Component>}
  24179. * @private
  24180. */
  24181. this._componentsViews = [];
  24182. /**
  24183. * @type {Object.<string, module:echarts/view/Component>}
  24184. * @private
  24185. */
  24186. this._componentsMap = {};
  24187. /**
  24188. * @type {module:echarts/CoordinateSystem}
  24189. * @private
  24190. */
  24191. this._coordSysMgr = new CoordinateSystemManager();
  24192. /**
  24193. * @type {module:echarts/ExtensionAPI}
  24194. * @private
  24195. */
  24196. var api = this._api = createExtensionAPI(this);
  24197. // Sort on demand
  24198. function prioritySortFunc(a, b) {
  24199. return a.__prio - b.__prio;
  24200. }
  24201. sort(visualFuncs, prioritySortFunc);
  24202. sort(dataProcessorFuncs, prioritySortFunc);
  24203. /**
  24204. * @type {module:echarts/stream/Scheduler}
  24205. */
  24206. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  24207. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  24208. /**
  24209. * @type {module:echarts~MessageCenter}
  24210. * @private
  24211. */
  24212. this._messageCenter = new MessageCenter();
  24213. // Init mouse events
  24214. this._initEvents();
  24215. // In case some people write `window.onresize = chart.resize`
  24216. this.resize = bind(this.resize, this);
  24217. // Can't dispatch action during rendering procedure
  24218. this._pendingActions = [];
  24219. zr.animation.on('frame', this._onframe, this);
  24220. bindRenderedEvent(zr, this);
  24221. // ECharts instance can be used as value.
  24222. setAsPrimitive(this);
  24223. }
  24224. var echartsProto = ECharts.prototype;
  24225. echartsProto._onframe = function () {
  24226. if (this._disposed) {
  24227. return;
  24228. }
  24229. var scheduler = this._scheduler;
  24230. // Lazy update
  24231. if (this[OPTION_UPDATED]) {
  24232. var silent = this[OPTION_UPDATED].silent;
  24233. this[IN_MAIN_PROCESS] = true;
  24234. prepare(this);
  24235. updateMethods.update.call(this);
  24236. this[IN_MAIN_PROCESS] = false;
  24237. this[OPTION_UPDATED] = false;
  24238. flushPendingActions.call(this, silent);
  24239. triggerUpdatedEvent.call(this, silent);
  24240. }
  24241. // Avoid do both lazy update and progress in one frame.
  24242. else if (scheduler.unfinished) {
  24243. // Stream progress.
  24244. var remainTime = TEST_FRAME_REMAIN_TIME;
  24245. var ecModel = this._model;
  24246. var api = this._api;
  24247. scheduler.unfinished = false;
  24248. do {
  24249. var startTime = +new Date();
  24250. scheduler.performSeriesTasks(ecModel);
  24251. // Currently dataProcessorFuncs do not check threshold.
  24252. scheduler.performDataProcessorTasks(ecModel);
  24253. updateStreamModes(this, ecModel);
  24254. // Do not update coordinate system here. Because that coord system update in
  24255. // each frame is not a good user experience. So we follow the rule that
  24256. // the extent of the coordinate system is determin in the first frame (the
  24257. // frame is executed immedietely after task reset.
  24258. // this._coordSysMgr.update(ecModel, api);
  24259. // console.log('--- ec frame visual ---', remainTime);
  24260. scheduler.performVisualTasks(ecModel);
  24261. renderSeries(this, this._model, api, 'remain');
  24262. remainTime -= (+new Date() - startTime);
  24263. }
  24264. while (remainTime > 0 && scheduler.unfinished);
  24265. // Call flush explicitly for trigger finished event.
  24266. if (!scheduler.unfinished) {
  24267. this._zr.flush();
  24268. }
  24269. // Else, zr flushing be ensue within the same frame,
  24270. // because zr flushing is after onframe event.
  24271. }
  24272. };
  24273. /**
  24274. * @return {HTMLElement}
  24275. */
  24276. echartsProto.getDom = function () {
  24277. return this._dom;
  24278. };
  24279. /**
  24280. * @return {module:zrender~ZRender}
  24281. */
  24282. echartsProto.getZr = function () {
  24283. return this._zr;
  24284. };
  24285. /**
  24286. * Usage:
  24287. * chart.setOption(option, notMerge, lazyUpdate);
  24288. * chart.setOption(option, {
  24289. * notMerge: ...,
  24290. * lazyUpdate: ...,
  24291. * silent: ...
  24292. * });
  24293. *
  24294. * @param {Object} option
  24295. * @param {Object|boolean} [opts] opts or notMerge.
  24296. * @param {boolean} [opts.notMerge=false]
  24297. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  24298. */
  24299. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  24300. if (__DEV__) {
  24301. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  24302. }
  24303. if (this._disposed) {
  24304. disposedWarning(this.id);
  24305. return;
  24306. }
  24307. var silent;
  24308. if (isObject(notMerge)) {
  24309. lazyUpdate = notMerge.lazyUpdate;
  24310. silent = notMerge.silent;
  24311. notMerge = notMerge.notMerge;
  24312. }
  24313. this[IN_MAIN_PROCESS] = true;
  24314. if (!this._model || notMerge) {
  24315. var optionManager = new OptionManager(this._api);
  24316. var theme$$1 = this._theme;
  24317. var ecModel = this._model = new GlobalModel();
  24318. ecModel.scheduler = this._scheduler;
  24319. ecModel.init(null, null, theme$$1, optionManager);
  24320. }
  24321. this._model.setOption(option, optionPreprocessorFuncs);
  24322. if (lazyUpdate) {
  24323. this[OPTION_UPDATED] = {silent: silent};
  24324. this[IN_MAIN_PROCESS] = false;
  24325. }
  24326. else {
  24327. prepare(this);
  24328. updateMethods.update.call(this);
  24329. // Ensure zr refresh sychronously, and then pixel in canvas can be
  24330. // fetched after `setOption`.
  24331. this._zr.flush();
  24332. this[OPTION_UPDATED] = false;
  24333. this[IN_MAIN_PROCESS] = false;
  24334. flushPendingActions.call(this, silent);
  24335. triggerUpdatedEvent.call(this, silent);
  24336. }
  24337. };
  24338. /**
  24339. * @DEPRECATED
  24340. */
  24341. echartsProto.setTheme = function () {
  24342. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  24343. };
  24344. /**
  24345. * @return {module:echarts/model/Global}
  24346. */
  24347. echartsProto.getModel = function () {
  24348. return this._model;
  24349. };
  24350. /**
  24351. * @return {Object}
  24352. */
  24353. echartsProto.getOption = function () {
  24354. return this._model && this._model.getOption();
  24355. };
  24356. /**
  24357. * @return {number}
  24358. */
  24359. echartsProto.getWidth = function () {
  24360. return this._zr.getWidth();
  24361. };
  24362. /**
  24363. * @return {number}
  24364. */
  24365. echartsProto.getHeight = function () {
  24366. return this._zr.getHeight();
  24367. };
  24368. /**
  24369. * @return {number}
  24370. */
  24371. echartsProto.getDevicePixelRatio = function () {
  24372. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  24373. };
  24374. /**
  24375. * Get canvas which has all thing rendered
  24376. * @param {Object} opts
  24377. * @param {string} [opts.backgroundColor]
  24378. * @return {string}
  24379. */
  24380. echartsProto.getRenderedCanvas = function (opts) {
  24381. if (!env$1.canvasSupported) {
  24382. return;
  24383. }
  24384. opts = opts || {};
  24385. opts.pixelRatio = opts.pixelRatio || 1;
  24386. opts.backgroundColor = opts.backgroundColor
  24387. || this._model.get('backgroundColor');
  24388. var zr = this._zr;
  24389. // var list = zr.storage.getDisplayList();
  24390. // Stop animations
  24391. // Never works before in init animation, so remove it.
  24392. // zrUtil.each(list, function (el) {
  24393. // el.stopAnimation(true);
  24394. // });
  24395. return zr.painter.getRenderedCanvas(opts);
  24396. };
  24397. /**
  24398. * Get svg data url
  24399. * @return {string}
  24400. */
  24401. echartsProto.getSvgDataUrl = function () {
  24402. if (!env$1.svgSupported) {
  24403. return;
  24404. }
  24405. var zr = this._zr;
  24406. var list = zr.storage.getDisplayList();
  24407. // Stop animations
  24408. each$1(list, function (el) {
  24409. el.stopAnimation(true);
  24410. });
  24411. return zr.painter.pathToDataUrl();
  24412. };
  24413. /**
  24414. * @return {string}
  24415. * @param {Object} opts
  24416. * @param {string} [opts.type='png']
  24417. * @param {string} [opts.pixelRatio=1]
  24418. * @param {string} [opts.backgroundColor]
  24419. * @param {string} [opts.excludeComponents]
  24420. */
  24421. echartsProto.getDataURL = function (opts) {
  24422. if (this._disposed) {
  24423. disposedWarning(this.id);
  24424. return;
  24425. }
  24426. opts = opts || {};
  24427. var excludeComponents = opts.excludeComponents;
  24428. var ecModel = this._model;
  24429. var excludesComponentViews = [];
  24430. var self = this;
  24431. each(excludeComponents, function (componentType) {
  24432. ecModel.eachComponent({
  24433. mainType: componentType
  24434. }, function (component) {
  24435. var view = self._componentsMap[component.__viewId];
  24436. if (!view.group.ignore) {
  24437. excludesComponentViews.push(view);
  24438. view.group.ignore = true;
  24439. }
  24440. });
  24441. });
  24442. var url = this._zr.painter.getType() === 'svg'
  24443. ? this.getSvgDataUrl()
  24444. : this.getRenderedCanvas(opts).toDataURL(
  24445. 'image/' + (opts && opts.type || 'png')
  24446. );
  24447. each(excludesComponentViews, function (view) {
  24448. view.group.ignore = false;
  24449. });
  24450. return url;
  24451. };
  24452. /**
  24453. * @return {string}
  24454. * @param {Object} opts
  24455. * @param {string} [opts.type='png']
  24456. * @param {string} [opts.pixelRatio=1]
  24457. * @param {string} [opts.backgroundColor]
  24458. */
  24459. echartsProto.getConnectedDataURL = function (opts) {
  24460. if (this._disposed) {
  24461. disposedWarning(this.id);
  24462. return;
  24463. }
  24464. if (!env$1.canvasSupported) {
  24465. return;
  24466. }
  24467. var groupId = this.group;
  24468. var mathMin = Math.min;
  24469. var mathMax = Math.max;
  24470. var MAX_NUMBER = Infinity;
  24471. if (connectedGroups[groupId]) {
  24472. var left = MAX_NUMBER;
  24473. var top = MAX_NUMBER;
  24474. var right = -MAX_NUMBER;
  24475. var bottom = -MAX_NUMBER;
  24476. var canvasList = [];
  24477. var dpr = (opts && opts.pixelRatio) || 1;
  24478. each$1(instances, function (chart, id) {
  24479. if (chart.group === groupId) {
  24480. var canvas = chart.getRenderedCanvas(
  24481. clone(opts)
  24482. );
  24483. var boundingRect = chart.getDom().getBoundingClientRect();
  24484. left = mathMin(boundingRect.left, left);
  24485. top = mathMin(boundingRect.top, top);
  24486. right = mathMax(boundingRect.right, right);
  24487. bottom = mathMax(boundingRect.bottom, bottom);
  24488. canvasList.push({
  24489. dom: canvas,
  24490. left: boundingRect.left,
  24491. top: boundingRect.top
  24492. });
  24493. }
  24494. });
  24495. left *= dpr;
  24496. top *= dpr;
  24497. right *= dpr;
  24498. bottom *= dpr;
  24499. var width = right - left;
  24500. var height = bottom - top;
  24501. var targetCanvas = createCanvas();
  24502. targetCanvas.width = width;
  24503. targetCanvas.height = height;
  24504. var zr = init$1(targetCanvas);
  24505. // Background between the charts
  24506. if (opts.connectedBackgroundColor) {
  24507. zr.add(new Rect({
  24508. shape: {
  24509. x: 0,
  24510. y: 0,
  24511. width: width,
  24512. height: height
  24513. },
  24514. style: {
  24515. fill: opts.connectedBackgroundColor
  24516. }
  24517. }));
  24518. }
  24519. each(canvasList, function (item) {
  24520. var img = new ZImage({
  24521. style: {
  24522. x: item.left * dpr - left,
  24523. y: item.top * dpr - top,
  24524. image: item.dom
  24525. }
  24526. });
  24527. zr.add(img);
  24528. });
  24529. zr.refreshImmediately();
  24530. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24531. }
  24532. else {
  24533. return this.getDataURL(opts);
  24534. }
  24535. };
  24536. /**
  24537. * Convert from logical coordinate system to pixel coordinate system.
  24538. * See CoordinateSystem#convertToPixel.
  24539. * @param {string|Object} finder
  24540. * If string, e.g., 'geo', means {geoIndex: 0}.
  24541. * If Object, could contain some of these properties below:
  24542. * {
  24543. * seriesIndex / seriesId / seriesName,
  24544. * geoIndex / geoId, geoName,
  24545. * bmapIndex / bmapId / bmapName,
  24546. * xAxisIndex / xAxisId / xAxisName,
  24547. * yAxisIndex / yAxisId / yAxisName,
  24548. * gridIndex / gridId / gridName,
  24549. * ... (can be extended)
  24550. * }
  24551. * @param {Array|number} value
  24552. * @return {Array|number} result
  24553. */
  24554. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  24555. /**
  24556. * Convert from pixel coordinate system to logical coordinate system.
  24557. * See CoordinateSystem#convertFromPixel.
  24558. * @param {string|Object} finder
  24559. * If string, e.g., 'geo', means {geoIndex: 0}.
  24560. * If Object, could contain some of these properties below:
  24561. * {
  24562. * seriesIndex / seriesId / seriesName,
  24563. * geoIndex / geoId / geoName,
  24564. * bmapIndex / bmapId / bmapName,
  24565. * xAxisIndex / xAxisId / xAxisName,
  24566. * yAxisIndex / yAxisId / yAxisName
  24567. * gridIndex / gridId / gridName,
  24568. * ... (can be extended)
  24569. * }
  24570. * @param {Array|number} value
  24571. * @return {Array|number} result
  24572. */
  24573. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24574. function doConvertPixel(methodName, finder, value) {
  24575. if (this._disposed) {
  24576. disposedWarning(this.id);
  24577. return;
  24578. }
  24579. var ecModel = this._model;
  24580. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24581. var result;
  24582. finder = parseFinder(ecModel, finder);
  24583. for (var i = 0; i < coordSysList.length; i++) {
  24584. var coordSys = coordSysList[i];
  24585. if (coordSys[methodName]
  24586. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24587. ) {
  24588. return result;
  24589. }
  24590. }
  24591. if (__DEV__) {
  24592. console.warn(
  24593. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24594. );
  24595. }
  24596. }
  24597. /**
  24598. * Is the specified coordinate systems or components contain the given pixel point.
  24599. * @param {string|Object} finder
  24600. * If string, e.g., 'geo', means {geoIndex: 0}.
  24601. * If Object, could contain some of these properties below:
  24602. * {
  24603. * seriesIndex / seriesId / seriesName,
  24604. * geoIndex / geoId / geoName,
  24605. * bmapIndex / bmapId / bmapName,
  24606. * xAxisIndex / xAxisId / xAxisName,
  24607. * yAxisIndex / yAxisId / yAxisName,
  24608. * gridIndex / gridId / gridName,
  24609. * ... (can be extended)
  24610. * }
  24611. * @param {Array|number} value
  24612. * @return {boolean} result
  24613. */
  24614. echartsProto.containPixel = function (finder, value) {
  24615. if (this._disposed) {
  24616. disposedWarning(this.id);
  24617. return;
  24618. }
  24619. var ecModel = this._model;
  24620. var result;
  24621. finder = parseFinder(ecModel, finder);
  24622. each$1(finder, function (models, key) {
  24623. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24624. var coordSys = model.coordinateSystem;
  24625. if (coordSys && coordSys.containPoint) {
  24626. result |= !!coordSys.containPoint(value);
  24627. }
  24628. else if (key === 'seriesModels') {
  24629. var view = this._chartsMap[model.__viewId];
  24630. if (view && view.containPoint) {
  24631. result |= view.containPoint(value, model);
  24632. }
  24633. else {
  24634. if (__DEV__) {
  24635. console.warn(key + ': ' + (view
  24636. ? 'The found component do not support containPoint.'
  24637. : 'No view mapping to the found component.'
  24638. ));
  24639. }
  24640. }
  24641. }
  24642. else {
  24643. if (__DEV__) {
  24644. console.warn(key + ': containPoint is not supported');
  24645. }
  24646. }
  24647. }, this);
  24648. }, this);
  24649. return !!result;
  24650. };
  24651. /**
  24652. * Get visual from series or data.
  24653. * @param {string|Object} finder
  24654. * If string, e.g., 'series', means {seriesIndex: 0}.
  24655. * If Object, could contain some of these properties below:
  24656. * {
  24657. * seriesIndex / seriesId / seriesName,
  24658. * dataIndex / dataIndexInside
  24659. * }
  24660. * If dataIndex is not specified, series visual will be fetched,
  24661. * but not data item visual.
  24662. * If all of seriesIndex, seriesId, seriesName are not specified,
  24663. * visual will be fetched from first series.
  24664. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24665. */
  24666. echartsProto.getVisual = function (finder, visualType) {
  24667. var ecModel = this._model;
  24668. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24669. var seriesModel = finder.seriesModel;
  24670. if (__DEV__) {
  24671. if (!seriesModel) {
  24672. console.warn('There is no specified seires model');
  24673. }
  24674. }
  24675. var data = seriesModel.getData();
  24676. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24677. ? finder.dataIndexInside
  24678. : finder.hasOwnProperty('dataIndex')
  24679. ? data.indexOfRawIndex(finder.dataIndex)
  24680. : null;
  24681. return dataIndexInside != null
  24682. ? data.getItemVisual(dataIndexInside, visualType)
  24683. : data.getVisual(visualType);
  24684. };
  24685. /**
  24686. * Get view of corresponding component model
  24687. * @param {module:echarts/model/Component} componentModel
  24688. * @return {module:echarts/view/Component}
  24689. */
  24690. echartsProto.getViewOfComponentModel = function (componentModel) {
  24691. return this._componentsMap[componentModel.__viewId];
  24692. };
  24693. /**
  24694. * Get view of corresponding series model
  24695. * @param {module:echarts/model/Series} seriesModel
  24696. * @return {module:echarts/view/Chart}
  24697. */
  24698. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24699. return this._chartsMap[seriesModel.__viewId];
  24700. };
  24701. var updateMethods = {
  24702. prepareAndUpdate: function (payload) {
  24703. prepare(this);
  24704. updateMethods.update.call(this, payload);
  24705. },
  24706. /**
  24707. * @param {Object} payload
  24708. * @private
  24709. */
  24710. update: function (payload) {
  24711. // console.profile && console.profile('update');
  24712. var ecModel = this._model;
  24713. var api = this._api;
  24714. var zr = this._zr;
  24715. var coordSysMgr = this._coordSysMgr;
  24716. var scheduler = this._scheduler;
  24717. // update before setOption
  24718. if (!ecModel) {
  24719. return;
  24720. }
  24721. scheduler.restoreData(ecModel, payload);
  24722. scheduler.performSeriesTasks(ecModel);
  24723. // TODO
  24724. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24725. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24726. // Create new coordinate system each update
  24727. // In LineView may save the old coordinate system and use it to get the orignal point
  24728. coordSysMgr.create(ecModel, api);
  24729. scheduler.performDataProcessorTasks(ecModel, payload);
  24730. // Current stream render is not supported in data process. So we can update
  24731. // stream modes after data processing, where the filtered data is used to
  24732. // deteming whether use progressive rendering.
  24733. updateStreamModes(this, ecModel);
  24734. // We update stream modes before coordinate system updated, then the modes info
  24735. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24736. // the drawback is the full coord info can not be fetched. Fortunately this full
  24737. // coord is not requied in stream mode updater currently.
  24738. coordSysMgr.update(ecModel, api);
  24739. clearColorPalette(ecModel);
  24740. scheduler.performVisualTasks(ecModel, payload);
  24741. render(this, ecModel, api, payload);
  24742. // Set background
  24743. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24744. // In IE8
  24745. if (!env$1.canvasSupported) {
  24746. var colorArr = parse(backgroundColor);
  24747. backgroundColor = stringify(colorArr, 'rgb');
  24748. if (colorArr[3] === 0) {
  24749. backgroundColor = 'transparent';
  24750. }
  24751. }
  24752. else {
  24753. zr.setBackgroundColor(backgroundColor);
  24754. }
  24755. performPostUpdateFuncs(ecModel, api);
  24756. // console.profile && console.profileEnd('update');
  24757. },
  24758. /**
  24759. * @param {Object} payload
  24760. * @private
  24761. */
  24762. updateTransform: function (payload) {
  24763. var ecModel = this._model;
  24764. var ecIns = this;
  24765. var api = this._api;
  24766. // update before setOption
  24767. if (!ecModel) {
  24768. return;
  24769. }
  24770. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24771. var componentDirtyList = [];
  24772. ecModel.eachComponent(function (componentType, componentModel) {
  24773. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24774. if (componentView && componentView.__alive) {
  24775. if (componentView.updateTransform) {
  24776. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24777. result && result.update && componentDirtyList.push(componentView);
  24778. }
  24779. else {
  24780. componentDirtyList.push(componentView);
  24781. }
  24782. }
  24783. });
  24784. var seriesDirtyMap = createHashMap();
  24785. ecModel.eachSeries(function (seriesModel) {
  24786. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24787. if (chartView.updateTransform) {
  24788. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24789. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24790. }
  24791. else {
  24792. seriesDirtyMap.set(seriesModel.uid, 1);
  24793. }
  24794. });
  24795. clearColorPalette(ecModel);
  24796. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24797. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24798. this._scheduler.performVisualTasks(
  24799. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24800. );
  24801. // Currently, not call render of components. Geo render cost a lot.
  24802. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24803. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24804. performPostUpdateFuncs(ecModel, this._api);
  24805. },
  24806. /**
  24807. * @param {Object} payload
  24808. * @private
  24809. */
  24810. updateView: function (payload) {
  24811. var ecModel = this._model;
  24812. // update before setOption
  24813. if (!ecModel) {
  24814. return;
  24815. }
  24816. Chart.markUpdateMethod(payload, 'updateView');
  24817. clearColorPalette(ecModel);
  24818. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24819. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24820. render(this, this._model, this._api, payload);
  24821. performPostUpdateFuncs(ecModel, this._api);
  24822. },
  24823. /**
  24824. * @param {Object} payload
  24825. * @private
  24826. */
  24827. updateVisual: function (payload) {
  24828. updateMethods.update.call(this, payload);
  24829. // var ecModel = this._model;
  24830. // // update before setOption
  24831. // if (!ecModel) {
  24832. // return;
  24833. // }
  24834. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24835. // clearColorPalette(ecModel);
  24836. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24837. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24838. // render(this, this._model, this._api, payload);
  24839. // performPostUpdateFuncs(ecModel, this._api);
  24840. },
  24841. /**
  24842. * @param {Object} payload
  24843. * @private
  24844. */
  24845. updateLayout: function (payload) {
  24846. updateMethods.update.call(this, payload);
  24847. // var ecModel = this._model;
  24848. // // update before setOption
  24849. // if (!ecModel) {
  24850. // return;
  24851. // }
  24852. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24853. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24854. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24855. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24856. // render(this, this._model, this._api, payload);
  24857. // performPostUpdateFuncs(ecModel, this._api);
  24858. }
  24859. };
  24860. function prepare(ecIns) {
  24861. var ecModel = ecIns._model;
  24862. var scheduler = ecIns._scheduler;
  24863. scheduler.restorePipelines(ecModel);
  24864. scheduler.prepareStageTasks();
  24865. prepareView(ecIns, 'component', ecModel, scheduler);
  24866. prepareView(ecIns, 'chart', ecModel, scheduler);
  24867. scheduler.plan();
  24868. }
  24869. /**
  24870. * @private
  24871. */
  24872. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24873. var ecModel = ecIns._model;
  24874. // broadcast
  24875. if (!mainType) {
  24876. // FIXME
  24877. // Chart will not be update directly here, except set dirty.
  24878. // But there is no such scenario now.
  24879. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24880. return;
  24881. }
  24882. var query = {};
  24883. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24884. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24885. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24886. var condition = {mainType: mainType, query: query};
  24887. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24888. var excludeSeriesId = payload.excludeSeriesId;
  24889. if (excludeSeriesId != null) {
  24890. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24891. }
  24892. // If dispatchAction before setOption, do nothing.
  24893. ecModel && ecModel.eachComponent(condition, function (model) {
  24894. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24895. callView(ecIns[
  24896. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24897. ][model.__viewId]);
  24898. }
  24899. }, ecIns);
  24900. function callView(view) {
  24901. view && view.__alive && view[method] && view[method](
  24902. view.__model, ecModel, ecIns._api, payload
  24903. );
  24904. }
  24905. }
  24906. /**
  24907. * Resize the chart
  24908. * @param {Object} opts
  24909. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  24910. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  24911. * @param {boolean} [opts.silent=false]
  24912. */
  24913. echartsProto.resize = function (opts) {
  24914. if (__DEV__) {
  24915. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  24916. }
  24917. if (this._disposed) {
  24918. disposedWarning(this.id);
  24919. return;
  24920. }
  24921. this._zr.resize(opts);
  24922. var ecModel = this._model;
  24923. // Resize loading effect
  24924. this._loadingFX && this._loadingFX.resize();
  24925. if (!ecModel) {
  24926. return;
  24927. }
  24928. var optionChanged = ecModel.resetOption('media');
  24929. var silent = opts && opts.silent;
  24930. this[IN_MAIN_PROCESS] = true;
  24931. optionChanged && prepare(this);
  24932. updateMethods.update.call(this);
  24933. this[IN_MAIN_PROCESS] = false;
  24934. flushPendingActions.call(this, silent);
  24935. triggerUpdatedEvent.call(this, silent);
  24936. };
  24937. function updateStreamModes(ecIns, ecModel) {
  24938. var chartsMap = ecIns._chartsMap;
  24939. var scheduler = ecIns._scheduler;
  24940. ecModel.eachSeries(function (seriesModel) {
  24941. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  24942. });
  24943. }
  24944. /**
  24945. * Show loading effect
  24946. * @param {string} [name='default']
  24947. * @param {Object} [cfg]
  24948. */
  24949. echartsProto.showLoading = function (name, cfg) {
  24950. if (this._disposed) {
  24951. disposedWarning(this.id);
  24952. return;
  24953. }
  24954. if (isObject(name)) {
  24955. cfg = name;
  24956. name = '';
  24957. }
  24958. name = name || 'default';
  24959. this.hideLoading();
  24960. if (!loadingEffects[name]) {
  24961. if (__DEV__) {
  24962. console.warn('Loading effects ' + name + ' not exists.');
  24963. }
  24964. return;
  24965. }
  24966. var el = loadingEffects[name](this._api, cfg);
  24967. var zr = this._zr;
  24968. this._loadingFX = el;
  24969. zr.add(el);
  24970. };
  24971. /**
  24972. * Hide loading effect
  24973. */
  24974. echartsProto.hideLoading = function () {
  24975. if (this._disposed) {
  24976. disposedWarning(this.id);
  24977. return;
  24978. }
  24979. this._loadingFX && this._zr.remove(this._loadingFX);
  24980. this._loadingFX = null;
  24981. };
  24982. /**
  24983. * @param {Object} eventObj
  24984. * @return {Object}
  24985. */
  24986. echartsProto.makeActionFromEvent = function (eventObj) {
  24987. var payload = extend({}, eventObj);
  24988. payload.type = eventActionMap[eventObj.type];
  24989. return payload;
  24990. };
  24991. /**
  24992. * @pubilc
  24993. * @param {Object} payload
  24994. * @param {string} [payload.type] Action type
  24995. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  24996. * @param {boolean} [opt.silent=false] Whether trigger events.
  24997. * @param {boolean} [opt.flush=undefined]
  24998. * true: Flush immediately, and then pixel in canvas can be fetched
  24999. * immediately. Caution: it might affect performance.
  25000. * false: Not flush.
  25001. * undefined: Auto decide whether perform flush.
  25002. */
  25003. echartsProto.dispatchAction = function (payload, opt) {
  25004. if (this._disposed) {
  25005. disposedWarning(this.id);
  25006. return;
  25007. }
  25008. if (!isObject(opt)) {
  25009. opt = {silent: !!opt};
  25010. }
  25011. if (!actions[payload.type]) {
  25012. return;
  25013. }
  25014. // Avoid dispatch action before setOption. Especially in `connect`.
  25015. if (!this._model) {
  25016. return;
  25017. }
  25018. // May dispatchAction in rendering procedure
  25019. if (this[IN_MAIN_PROCESS]) {
  25020. this._pendingActions.push(payload);
  25021. return;
  25022. }
  25023. doDispatchAction.call(this, payload, opt.silent);
  25024. if (opt.flush) {
  25025. this._zr.flush(true);
  25026. }
  25027. else if (opt.flush !== false && env$1.browser.weChat) {
  25028. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25029. // hang when sliding page (on touch event), which cause that zr does not
  25030. // refresh util user interaction finished, which is not expected.
  25031. // But `dispatchAction` may be called too frequently when pan on touch
  25032. // screen, which impacts performance if do not throttle them.
  25033. this._throttledZrFlush();
  25034. }
  25035. flushPendingActions.call(this, opt.silent);
  25036. triggerUpdatedEvent.call(this, opt.silent);
  25037. };
  25038. function doDispatchAction(payload, silent) {
  25039. var payloadType = payload.type;
  25040. var escapeConnect = payload.escapeConnect;
  25041. var actionWrap = actions[payloadType];
  25042. var actionInfo = actionWrap.actionInfo;
  25043. var cptType = (actionInfo.update || 'update').split(':');
  25044. var updateMethod = cptType.pop();
  25045. cptType = cptType[0] != null && parseClassType(cptType[0]);
  25046. this[IN_MAIN_PROCESS] = true;
  25047. var payloads = [payload];
  25048. var batched = false;
  25049. // Batch action
  25050. if (payload.batch) {
  25051. batched = true;
  25052. payloads = map(payload.batch, function (item) {
  25053. item = defaults(extend({}, item), payload);
  25054. item.batch = null;
  25055. return item;
  25056. });
  25057. }
  25058. var eventObjBatch = [];
  25059. var eventObj;
  25060. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  25061. each(payloads, function (batchItem) {
  25062. // Action can specify the event by return it.
  25063. eventObj = actionWrap.action(batchItem, this._model, this._api);
  25064. // Emit event outside
  25065. eventObj = eventObj || extend({}, batchItem);
  25066. // Convert type to eventType
  25067. eventObj.type = actionInfo.event || eventObj.type;
  25068. eventObjBatch.push(eventObj);
  25069. // light update does not perform data process, layout and visual.
  25070. if (isHighDown) {
  25071. // method, payload, mainType, subType
  25072. updateDirectly(this, updateMethod, batchItem, 'series');
  25073. }
  25074. else if (cptType) {
  25075. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  25076. }
  25077. }, this);
  25078. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  25079. // Still dirty
  25080. if (this[OPTION_UPDATED]) {
  25081. // FIXME Pass payload ?
  25082. prepare(this);
  25083. updateMethods.update.call(this, payload);
  25084. this[OPTION_UPDATED] = false;
  25085. }
  25086. else {
  25087. updateMethods[updateMethod].call(this, payload);
  25088. }
  25089. }
  25090. // Follow the rule of action batch
  25091. if (batched) {
  25092. eventObj = {
  25093. type: actionInfo.event || payloadType,
  25094. escapeConnect: escapeConnect,
  25095. batch: eventObjBatch
  25096. };
  25097. }
  25098. else {
  25099. eventObj = eventObjBatch[0];
  25100. }
  25101. this[IN_MAIN_PROCESS] = false;
  25102. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  25103. }
  25104. function flushPendingActions(silent) {
  25105. var pendingActions = this._pendingActions;
  25106. while (pendingActions.length) {
  25107. var payload = pendingActions.shift();
  25108. doDispatchAction.call(this, payload, silent);
  25109. }
  25110. }
  25111. function triggerUpdatedEvent(silent) {
  25112. !silent && this.trigger('updated');
  25113. }
  25114. /**
  25115. * Event `rendered` is triggered when zr
  25116. * rendered. It is useful for realtime
  25117. * snapshot (reflect animation).
  25118. *
  25119. * Event `finished` is triggered when:
  25120. * (1) zrender rendering finished.
  25121. * (2) initial animation finished.
  25122. * (3) progressive rendering finished.
  25123. * (4) no pending action.
  25124. * (5) no delayed setOption needs to be processed.
  25125. */
  25126. function bindRenderedEvent(zr, ecIns) {
  25127. zr.on('rendered', function () {
  25128. ecIns.trigger('rendered');
  25129. // The `finished` event should not be triggered repeatly,
  25130. // so it should only be triggered when rendering indeed happend
  25131. // in zrender. (Consider the case that dipatchAction is keep
  25132. // triggering when mouse move).
  25133. if (
  25134. // Although zr is dirty if initial animation is not finished
  25135. // and this checking is called on frame, we also check
  25136. // animation finished for robustness.
  25137. zr.animation.isFinished()
  25138. && !ecIns[OPTION_UPDATED]
  25139. && !ecIns._scheduler.unfinished
  25140. && !ecIns._pendingActions.length
  25141. ) {
  25142. ecIns.trigger('finished');
  25143. }
  25144. });
  25145. }
  25146. /**
  25147. * @param {Object} params
  25148. * @param {number} params.seriesIndex
  25149. * @param {Array|TypedArray} params.data
  25150. */
  25151. echartsProto.appendData = function (params) {
  25152. if (this._disposed) {
  25153. disposedWarning(this.id);
  25154. return;
  25155. }
  25156. var seriesIndex = params.seriesIndex;
  25157. var ecModel = this.getModel();
  25158. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25159. if (__DEV__) {
  25160. assert(params.data && seriesModel);
  25161. }
  25162. seriesModel.appendData(params);
  25163. // Note: `appendData` does not support that update extent of coordinate
  25164. // system, util some scenario require that. In the expected usage of
  25165. // `appendData`, the initial extent of coordinate system should better
  25166. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25167. // the extent changed while `appendData`, the location of the painted
  25168. // graphic elements have to be changed, which make the usage of
  25169. // `appendData` meaningless.
  25170. this._scheduler.unfinished = true;
  25171. };
  25172. /**
  25173. * Register event
  25174. * @method
  25175. */
  25176. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  25177. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  25178. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  25179. /**
  25180. * Prepare view instances of charts and components
  25181. * @param {module:echarts/model/Global} ecModel
  25182. * @private
  25183. */
  25184. function prepareView(ecIns, type, ecModel, scheduler) {
  25185. var isComponent = type === 'component';
  25186. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25187. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25188. var zr = ecIns._zr;
  25189. var api = ecIns._api;
  25190. for (var i = 0; i < viewList.length; i++) {
  25191. viewList[i].__alive = false;
  25192. }
  25193. isComponent
  25194. ? ecModel.eachComponent(function (componentType, model) {
  25195. componentType !== 'series' && doPrepare(model);
  25196. })
  25197. : ecModel.eachSeries(doPrepare);
  25198. function doPrepare(model) {
  25199. // Consider: id same and type changed.
  25200. var viewId = '_ec_' + model.id + '_' + model.type;
  25201. var view = viewMap[viewId];
  25202. if (!view) {
  25203. var classType = parseClassType(model.type);
  25204. var Clazz = isComponent
  25205. ? Component$1.getClass(classType.main, classType.sub)
  25206. : Chart.getClass(classType.sub);
  25207. if (__DEV__) {
  25208. assert(Clazz, classType.sub + ' does not exist.');
  25209. }
  25210. view = new Clazz();
  25211. view.init(ecModel, api);
  25212. viewMap[viewId] = view;
  25213. viewList.push(view);
  25214. zr.add(view.group);
  25215. }
  25216. model.__viewId = view.__id = viewId;
  25217. view.__alive = true;
  25218. view.__model = model;
  25219. view.group.__ecComponentInfo = {
  25220. mainType: model.mainType,
  25221. index: model.componentIndex
  25222. };
  25223. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25224. }
  25225. for (var i = 0; i < viewList.length;) {
  25226. var view = viewList[i];
  25227. if (!view.__alive) {
  25228. !isComponent && view.renderTask.dispose();
  25229. zr.remove(view.group);
  25230. view.dispose(ecModel, api);
  25231. viewList.splice(i, 1);
  25232. delete viewMap[view.__id];
  25233. view.__id = view.group.__ecComponentInfo = null;
  25234. }
  25235. else {
  25236. i++;
  25237. }
  25238. }
  25239. }
  25240. // /**
  25241. // * Encode visual infomation from data after data processing
  25242. // *
  25243. // * @param {module:echarts/model/Global} ecModel
  25244. // * @param {object} layout
  25245. // * @param {boolean} [layoutFilter] `true`: only layout,
  25246. // * `false`: only not layout,
  25247. // * `null`/`undefined`: all.
  25248. // * @param {string} taskBaseTag
  25249. // * @private
  25250. // */
  25251. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  25252. // each(visualFuncs, function (visual, index) {
  25253. // var isLayout = visual.isLayout;
  25254. // if (layoutFilter == null
  25255. // || (layoutFilter === false && !isLayout)
  25256. // || (layoutFilter === true && isLayout)
  25257. // ) {
  25258. // visual.func(ecModel, api, payload);
  25259. // }
  25260. // });
  25261. // }
  25262. function clearColorPalette(ecModel) {
  25263. ecModel.clearColorPalette();
  25264. ecModel.eachSeries(function (seriesModel) {
  25265. seriesModel.clearColorPalette();
  25266. });
  25267. }
  25268. function render(ecIns, ecModel, api, payload) {
  25269. renderComponents(ecIns, ecModel, api, payload);
  25270. each(ecIns._chartsViews, function (chart) {
  25271. chart.__alive = false;
  25272. });
  25273. renderSeries(ecIns, ecModel, api, payload);
  25274. // Remove groups of unrendered charts
  25275. each(ecIns._chartsViews, function (chart) {
  25276. if (!chart.__alive) {
  25277. chart.remove(ecModel, api);
  25278. }
  25279. });
  25280. }
  25281. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  25282. each(dirtyList || ecIns._componentsViews, function (componentView) {
  25283. var componentModel = componentView.__model;
  25284. componentView.render(componentModel, ecModel, api, payload);
  25285. updateZ(componentModel, componentView);
  25286. });
  25287. }
  25288. /**
  25289. * Render each chart and component
  25290. * @private
  25291. */
  25292. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  25293. // Render all charts
  25294. var scheduler = ecIns._scheduler;
  25295. var unfinished;
  25296. ecModel.eachSeries(function (seriesModel) {
  25297. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25298. chartView.__alive = true;
  25299. var renderTask = chartView.renderTask;
  25300. scheduler.updatePayload(renderTask, payload);
  25301. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  25302. renderTask.dirty();
  25303. }
  25304. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  25305. chartView.group.silent = !!seriesModel.get('silent');
  25306. updateZ(seriesModel, chartView);
  25307. updateBlend(seriesModel, chartView);
  25308. });
  25309. scheduler.unfinished |= unfinished;
  25310. // If use hover layer
  25311. updateHoverLayerStatus(ecIns, ecModel);
  25312. // Add aria
  25313. aria(ecIns._zr.dom, ecModel);
  25314. }
  25315. function performPostUpdateFuncs(ecModel, api) {
  25316. each(postUpdateFuncs, function (func) {
  25317. func(ecModel, api);
  25318. });
  25319. }
  25320. var MOUSE_EVENT_NAMES = [
  25321. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  25322. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  25323. ];
  25324. /**
  25325. * @private
  25326. */
  25327. echartsProto._initEvents = function () {
  25328. each(MOUSE_EVENT_NAMES, function (eveName) {
  25329. var handler = function (e) {
  25330. var ecModel = this.getModel();
  25331. var el = e.target;
  25332. var params;
  25333. var isGlobalOut = eveName === 'globalout';
  25334. // no e.target when 'globalout'.
  25335. if (isGlobalOut) {
  25336. params = {};
  25337. }
  25338. else if (el && el.dataIndex != null) {
  25339. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  25340. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  25341. }
  25342. // If element has custom eventData of components
  25343. else if (el && el.eventData) {
  25344. params = extend({}, el.eventData);
  25345. }
  25346. // Contract: if params prepared in mouse event,
  25347. // these properties must be specified:
  25348. // {
  25349. // componentType: string (component main type)
  25350. // componentIndex: number
  25351. // }
  25352. // Otherwise event query can not work.
  25353. if (params) {
  25354. var componentType = params.componentType;
  25355. var componentIndex = params.componentIndex;
  25356. // Special handling for historic reason: when trigger by
  25357. // markLine/markPoint/markArea, the componentType is
  25358. // 'markLine'/'markPoint'/'markArea', but we should better
  25359. // enable them to be queried by seriesIndex, since their
  25360. // option is set in each series.
  25361. if (componentType === 'markLine'
  25362. || componentType === 'markPoint'
  25363. || componentType === 'markArea'
  25364. ) {
  25365. componentType = 'series';
  25366. componentIndex = params.seriesIndex;
  25367. }
  25368. var model = componentType && componentIndex != null
  25369. && ecModel.getComponent(componentType, componentIndex);
  25370. var view = model && this[
  25371. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25372. ][model.__viewId];
  25373. if (__DEV__) {
  25374. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25375. // be missed, otherwise there is no way to distinguish source component.
  25376. // See `dataFormat.getDataParams`.
  25377. if (!isGlobalOut && !(model && view)) {
  25378. console.warn('model or view can not be found by params');
  25379. }
  25380. }
  25381. params.event = e;
  25382. params.type = eveName;
  25383. this._ecEventProcessor.eventInfo = {
  25384. targetEl: el,
  25385. packedEvent: params,
  25386. model: model,
  25387. view: view
  25388. };
  25389. this.trigger(eveName, params);
  25390. }
  25391. };
  25392. // Consider that some component (like tooltip, brush, ...)
  25393. // register zr event handler, but user event handler might
  25394. // do anything, such as call `setOption` or `dispatchAction`,
  25395. // which probably update any of the content and probably
  25396. // cause problem if it is called previous other inner handlers.
  25397. handler.zrEventfulCallAtLast = true;
  25398. this._zr.on(eveName, handler, this);
  25399. }, this);
  25400. each(eventActionMap, function (actionType, eventType) {
  25401. this._messageCenter.on(eventType, function (event) {
  25402. this.trigger(eventType, event);
  25403. }, this);
  25404. }, this);
  25405. };
  25406. /**
  25407. * @return {boolean}
  25408. */
  25409. echartsProto.isDisposed = function () {
  25410. return this._disposed;
  25411. };
  25412. /**
  25413. * Clear
  25414. */
  25415. echartsProto.clear = function () {
  25416. if (this._disposed) {
  25417. disposedWarning(this.id);
  25418. return;
  25419. }
  25420. this.setOption({ series: [] }, true);
  25421. };
  25422. /**
  25423. * Dispose instance
  25424. */
  25425. echartsProto.dispose = function () {
  25426. if (this._disposed) {
  25427. disposedWarning(this.id);
  25428. return;
  25429. }
  25430. this._disposed = true;
  25431. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25432. var api = this._api;
  25433. var ecModel = this._model;
  25434. each(this._componentsViews, function (component) {
  25435. component.dispose(ecModel, api);
  25436. });
  25437. each(this._chartsViews, function (chart) {
  25438. chart.dispose(ecModel, api);
  25439. });
  25440. // Dispose after all views disposed
  25441. this._zr.dispose();
  25442. delete instances[this.id];
  25443. };
  25444. mixin(ECharts, Eventful);
  25445. function disposedWarning(id) {
  25446. if (__DEV__) {
  25447. console.warn('Instance ' + id + ' has been disposed');
  25448. }
  25449. }
  25450. function updateHoverLayerStatus(ecIns, ecModel) {
  25451. var zr = ecIns._zr;
  25452. var storage = zr.storage;
  25453. var elCount = 0;
  25454. storage.traverse(function (el) {
  25455. elCount++;
  25456. });
  25457. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  25458. ecModel.eachSeries(function (seriesModel) {
  25459. if (seriesModel.preventUsingHoverLayer) {
  25460. return;
  25461. }
  25462. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25463. if (chartView.__alive) {
  25464. chartView.group.traverse(function (el) {
  25465. // Don't switch back.
  25466. el.useHoverLayer = true;
  25467. });
  25468. }
  25469. });
  25470. }
  25471. }
  25472. /**
  25473. * Update chart progressive and blend.
  25474. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25475. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25476. */
  25477. function updateBlend(seriesModel, chartView) {
  25478. var blendMode = seriesModel.get('blendMode') || null;
  25479. if (__DEV__) {
  25480. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  25481. console.warn('Only canvas support blendMode');
  25482. }
  25483. }
  25484. chartView.group.traverse(function (el) {
  25485. // FIXME marker and other components
  25486. if (!el.isGroup) {
  25487. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  25488. if (el.style.blend !== blendMode) {
  25489. el.setStyle('blend', blendMode);
  25490. }
  25491. }
  25492. if (el.eachPendingDisplayable) {
  25493. el.eachPendingDisplayable(function (displayable) {
  25494. displayable.setStyle('blend', blendMode);
  25495. });
  25496. }
  25497. });
  25498. }
  25499. /**
  25500. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25501. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25502. */
  25503. function updateZ(model, view) {
  25504. var z = model.get('z');
  25505. var zlevel = model.get('zlevel');
  25506. // Set z and zlevel
  25507. view.group.traverse(function (el) {
  25508. if (el.type !== 'group') {
  25509. z != null && (el.z = z);
  25510. zlevel != null && (el.zlevel = zlevel);
  25511. }
  25512. });
  25513. }
  25514. function createExtensionAPI(ecInstance) {
  25515. var coordSysMgr = ecInstance._coordSysMgr;
  25516. return extend(new ExtensionAPI(ecInstance), {
  25517. // Inject methods
  25518. getCoordinateSystems: bind(
  25519. coordSysMgr.getCoordinateSystems, coordSysMgr
  25520. ),
  25521. getComponentByElement: function (el) {
  25522. while (el) {
  25523. var modelInfo = el.__ecComponentInfo;
  25524. if (modelInfo != null) {
  25525. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  25526. }
  25527. el = el.parent;
  25528. }
  25529. }
  25530. });
  25531. }
  25532. /**
  25533. * @class
  25534. * Usage of query:
  25535. * `chart.on('click', query, handler);`
  25536. * The `query` can be:
  25537. * + The component type query string, only `mainType` or `mainType.subType`,
  25538. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25539. * + The component query object, like:
  25540. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25541. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25542. * + The data query object, like:
  25543. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25544. * + The other query object (cmponent customized query), like:
  25545. * `{element: 'some'}` (only available in custom series).
  25546. *
  25547. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25548. * same as there is no such prop in the `query` object.
  25549. */
  25550. function EventProcessor() {
  25551. // These info required: targetEl, packedEvent, model, view
  25552. this.eventInfo;
  25553. }
  25554. EventProcessor.prototype = {
  25555. constructor: EventProcessor,
  25556. normalizeQuery: function (query) {
  25557. var cptQuery = {};
  25558. var dataQuery = {};
  25559. var otherQuery = {};
  25560. // `query` is `mainType` or `mainType.subType` of component.
  25561. if (isString(query)) {
  25562. var condCptType = parseClassType(query);
  25563. // `.main` and `.sub` may be ''.
  25564. cptQuery.mainType = condCptType.main || null;
  25565. cptQuery.subType = condCptType.sub || null;
  25566. }
  25567. // `query` is an object, convert to {mainType, index, name, id}.
  25568. else {
  25569. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25570. // can not be used in `compomentModel.filterForExposedEvent`.
  25571. var suffixes = ['Index', 'Name', 'Id'];
  25572. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25573. each$1(query, function (val, key) {
  25574. var reserved = false;
  25575. for (var i = 0; i < suffixes.length; i++) {
  25576. var propSuffix = suffixes[i];
  25577. var suffixPos = key.lastIndexOf(propSuffix);
  25578. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25579. var mainType = key.slice(0, suffixPos);
  25580. // Consider `dataIndex`.
  25581. if (mainType !== 'data') {
  25582. cptQuery.mainType = mainType;
  25583. cptQuery[propSuffix.toLowerCase()] = val;
  25584. reserved = true;
  25585. }
  25586. }
  25587. }
  25588. if (dataKeys.hasOwnProperty(key)) {
  25589. dataQuery[key] = val;
  25590. reserved = true;
  25591. }
  25592. if (!reserved) {
  25593. otherQuery[key] = val;
  25594. }
  25595. });
  25596. }
  25597. return {
  25598. cptQuery: cptQuery,
  25599. dataQuery: dataQuery,
  25600. otherQuery: otherQuery
  25601. };
  25602. },
  25603. filter: function (eventType, query, args) {
  25604. // They should be assigned before each trigger call.
  25605. var eventInfo = this.eventInfo;
  25606. if (!eventInfo) {
  25607. return true;
  25608. }
  25609. var targetEl = eventInfo.targetEl;
  25610. var packedEvent = eventInfo.packedEvent;
  25611. var model = eventInfo.model;
  25612. var view = eventInfo.view;
  25613. // For event like 'globalout'.
  25614. if (!model || !view) {
  25615. return true;
  25616. }
  25617. var cptQuery = query.cptQuery;
  25618. var dataQuery = query.dataQuery;
  25619. return check(cptQuery, model, 'mainType')
  25620. && check(cptQuery, model, 'subType')
  25621. && check(cptQuery, model, 'index', 'componentIndex')
  25622. && check(cptQuery, model, 'name')
  25623. && check(cptQuery, model, 'id')
  25624. && check(dataQuery, packedEvent, 'name')
  25625. && check(dataQuery, packedEvent, 'dataIndex')
  25626. && check(dataQuery, packedEvent, 'dataType')
  25627. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25628. eventType, query.otherQuery, targetEl, packedEvent
  25629. ));
  25630. function check(query, host, prop, propOnHost) {
  25631. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25632. }
  25633. },
  25634. afterTrigger: function () {
  25635. // Make sure the eventInfo wont be used in next trigger.
  25636. this.eventInfo = null;
  25637. }
  25638. };
  25639. /**
  25640. * @type {Object} key: actionType.
  25641. * @inner
  25642. */
  25643. var actions = {};
  25644. /**
  25645. * Map eventType to actionType
  25646. * @type {Object}
  25647. */
  25648. var eventActionMap = {};
  25649. /**
  25650. * Data processor functions of each stage
  25651. * @type {Array.<Object.<string, Function>>}
  25652. * @inner
  25653. */
  25654. var dataProcessorFuncs = [];
  25655. /**
  25656. * @type {Array.<Function>}
  25657. * @inner
  25658. */
  25659. var optionPreprocessorFuncs = [];
  25660. /**
  25661. * @type {Array.<Function>}
  25662. * @inner
  25663. */
  25664. var postUpdateFuncs = [];
  25665. /**
  25666. * Visual encoding functions of each stage
  25667. * @type {Array.<Object.<string, Function>>}
  25668. */
  25669. var visualFuncs = [];
  25670. /**
  25671. * Theme storage
  25672. * @type {Object.<key, Object>}
  25673. */
  25674. var themeStorage = {};
  25675. /**
  25676. * Loading effects
  25677. */
  25678. var loadingEffects = {};
  25679. var instances = {};
  25680. var connectedGroups = {};
  25681. var idBase = new Date() - 0;
  25682. var groupIdBase = new Date() - 0;
  25683. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25684. function enableConnect(chart) {
  25685. var STATUS_PENDING = 0;
  25686. var STATUS_UPDATING = 1;
  25687. var STATUS_UPDATED = 2;
  25688. var STATUS_KEY = '__connectUpdateStatus';
  25689. function updateConnectedChartsStatus(charts, status) {
  25690. for (var i = 0; i < charts.length; i++) {
  25691. var otherChart = charts[i];
  25692. otherChart[STATUS_KEY] = status;
  25693. }
  25694. }
  25695. each(eventActionMap, function (actionType, eventType) {
  25696. chart._messageCenter.on(eventType, function (event) {
  25697. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25698. if (event && event.escapeConnect) {
  25699. return;
  25700. }
  25701. var action = chart.makeActionFromEvent(event);
  25702. var otherCharts = [];
  25703. each(instances, function (otherChart) {
  25704. if (otherChart !== chart && otherChart.group === chart.group) {
  25705. otherCharts.push(otherChart);
  25706. }
  25707. });
  25708. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25709. each(otherCharts, function (otherChart) {
  25710. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25711. otherChart.dispatchAction(action);
  25712. }
  25713. });
  25714. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25715. }
  25716. });
  25717. });
  25718. }
  25719. /**
  25720. * @param {HTMLElement} dom
  25721. * @param {Object} [theme]
  25722. * @param {Object} opts
  25723. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25724. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  25725. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  25726. * Can be 'auto' (the same as null/undefined)
  25727. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  25728. * Can be 'auto' (the same as null/undefined)
  25729. */
  25730. function init(dom, theme$$1, opts) {
  25731. if (__DEV__) {
  25732. // Check version
  25733. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  25734. throw new Error(
  25735. 'zrender/src ' + version$1
  25736. + ' is too old for ECharts ' + version
  25737. + '. Current version need ZRender '
  25738. + dependencies.zrender + '+'
  25739. );
  25740. }
  25741. if (!dom) {
  25742. throw new Error('Initialize failed: invalid dom.');
  25743. }
  25744. }
  25745. var existInstance = getInstanceByDom(dom);
  25746. if (existInstance) {
  25747. if (__DEV__) {
  25748. console.warn('There is a chart instance already initialized on the dom.');
  25749. }
  25750. return existInstance;
  25751. }
  25752. if (__DEV__) {
  25753. if (isDom(dom)
  25754. && dom.nodeName.toUpperCase() !== 'CANVAS'
  25755. && (
  25756. (!dom.clientWidth && (!opts || opts.width == null))
  25757. || (!dom.clientHeight && (!opts || opts.height == null))
  25758. )
  25759. ) {
  25760. console.warn('Can\'t get DOM width or height. Please check '
  25761. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  25762. + 'For example, you may need to call this in the callback '
  25763. + 'of window.onload.');
  25764. }
  25765. }
  25766. var chart = new ECharts(dom, theme$$1, opts);
  25767. chart.id = 'ec_' + idBase++;
  25768. instances[chart.id] = chart;
  25769. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25770. enableConnect(chart);
  25771. return chart;
  25772. }
  25773. /**
  25774. * @return {string|Array.<module:echarts~ECharts>} groupId
  25775. */
  25776. function connect(groupId) {
  25777. // Is array of charts
  25778. if (isArray(groupId)) {
  25779. var charts = groupId;
  25780. groupId = null;
  25781. // If any chart has group
  25782. each(charts, function (chart) {
  25783. if (chart.group != null) {
  25784. groupId = chart.group;
  25785. }
  25786. });
  25787. groupId = groupId || ('g_' + groupIdBase++);
  25788. each(charts, function (chart) {
  25789. chart.group = groupId;
  25790. });
  25791. }
  25792. connectedGroups[groupId] = true;
  25793. return groupId;
  25794. }
  25795. /**
  25796. * @DEPRECATED
  25797. * @return {string} groupId
  25798. */
  25799. function disConnect(groupId) {
  25800. connectedGroups[groupId] = false;
  25801. }
  25802. /**
  25803. * @return {string} groupId
  25804. */
  25805. var disconnect = disConnect;
  25806. /**
  25807. * Dispose a chart instance
  25808. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25809. */
  25810. function dispose(chart) {
  25811. if (typeof chart === 'string') {
  25812. chart = instances[chart];
  25813. }
  25814. else if (!(chart instanceof ECharts)) {
  25815. // Try to treat as dom
  25816. chart = getInstanceByDom(chart);
  25817. }
  25818. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25819. chart.dispose();
  25820. }
  25821. }
  25822. /**
  25823. * @param {HTMLElement} dom
  25824. * @return {echarts~ECharts}
  25825. */
  25826. function getInstanceByDom(dom) {
  25827. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25828. }
  25829. /**
  25830. * @param {string} key
  25831. * @return {echarts~ECharts}
  25832. */
  25833. function getInstanceById(key) {
  25834. return instances[key];
  25835. }
  25836. /**
  25837. * Register theme
  25838. */
  25839. function registerTheme(name, theme$$1) {
  25840. themeStorage[name] = theme$$1;
  25841. }
  25842. /**
  25843. * Register option preprocessor
  25844. * @param {Function} preprocessorFunc
  25845. */
  25846. function registerPreprocessor(preprocessorFunc) {
  25847. optionPreprocessorFuncs.push(preprocessorFunc);
  25848. }
  25849. /**
  25850. * @param {number} [priority=1000]
  25851. * @param {Object|Function} processor
  25852. */
  25853. function registerProcessor(priority, processor) {
  25854. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25855. }
  25856. /**
  25857. * Register postUpdater
  25858. * @param {Function} postUpdateFunc
  25859. */
  25860. function registerPostUpdate(postUpdateFunc) {
  25861. postUpdateFuncs.push(postUpdateFunc);
  25862. }
  25863. /**
  25864. * Usage:
  25865. * registerAction('someAction', 'someEvent', function () { ... });
  25866. * registerAction('someAction', function () { ... });
  25867. * registerAction(
  25868. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25869. * function () { ... }
  25870. * );
  25871. *
  25872. * @param {(string|Object)} actionInfo
  25873. * @param {string} actionInfo.type
  25874. * @param {string} [actionInfo.event]
  25875. * @param {string} [actionInfo.update]
  25876. * @param {string} [eventName]
  25877. * @param {Function} action
  25878. */
  25879. function registerAction(actionInfo, eventName, action) {
  25880. if (typeof eventName === 'function') {
  25881. action = eventName;
  25882. eventName = '';
  25883. }
  25884. var actionType = isObject(actionInfo)
  25885. ? actionInfo.type
  25886. : ([actionInfo, actionInfo = {
  25887. event: eventName
  25888. }][0]);
  25889. // Event name is all lowercase
  25890. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25891. eventName = actionInfo.event;
  25892. // Validate action type and event name.
  25893. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25894. if (!actions[actionType]) {
  25895. actions[actionType] = {action: action, actionInfo: actionInfo};
  25896. }
  25897. eventActionMap[eventName] = actionType;
  25898. }
  25899. /**
  25900. * @param {string} type
  25901. * @param {*} CoordinateSystem
  25902. */
  25903. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  25904. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  25905. }
  25906. /**
  25907. * Get dimensions of specified coordinate system.
  25908. * @param {string} type
  25909. * @return {Array.<string|Object>}
  25910. */
  25911. function getCoordinateSystemDimensions(type) {
  25912. var coordSysCreator = CoordinateSystemManager.get(type);
  25913. if (coordSysCreator) {
  25914. return coordSysCreator.getDimensionsInfo
  25915. ? coordSysCreator.getDimensionsInfo()
  25916. : coordSysCreator.dimensions.slice();
  25917. }
  25918. }
  25919. /**
  25920. * Layout is a special stage of visual encoding
  25921. * Most visual encoding like color are common for different chart
  25922. * But each chart has it's own layout algorithm
  25923. *
  25924. * @param {number} [priority=1000]
  25925. * @param {Function} layoutTask
  25926. */
  25927. function registerLayout(priority, layoutTask) {
  25928. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  25929. }
  25930. /**
  25931. * @param {number} [priority=3000]
  25932. * @param {module:echarts/stream/Task} visualTask
  25933. */
  25934. function registerVisual(priority, visualTask) {
  25935. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  25936. }
  25937. /**
  25938. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  25939. */
  25940. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  25941. if (isFunction(priority) || isObject(priority)) {
  25942. fn = priority;
  25943. priority = defaultPriority;
  25944. }
  25945. if (__DEV__) {
  25946. if (isNaN(priority) || priority == null) {
  25947. throw new Error('Illegal priority');
  25948. }
  25949. // Check duplicate
  25950. each(targetList, function (wrap) {
  25951. assert(wrap.__raw !== fn);
  25952. });
  25953. }
  25954. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  25955. stageHandler.__prio = priority;
  25956. stageHandler.__raw = fn;
  25957. targetList.push(stageHandler);
  25958. return stageHandler;
  25959. }
  25960. /**
  25961. * @param {string} name
  25962. */
  25963. function registerLoading(name, loadingFx) {
  25964. loadingEffects[name] = loadingFx;
  25965. }
  25966. /**
  25967. * @param {Object} opts
  25968. * @param {string} [superClass]
  25969. */
  25970. function extendComponentModel(opts/*, superClass*/) {
  25971. // var Clazz = ComponentModel;
  25972. // if (superClass) {
  25973. // var classType = parseClassType(superClass);
  25974. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25975. // }
  25976. return ComponentModel.extend(opts);
  25977. }
  25978. /**
  25979. * @param {Object} opts
  25980. * @param {string} [superClass]
  25981. */
  25982. function extendComponentView(opts/*, superClass*/) {
  25983. // var Clazz = ComponentView;
  25984. // if (superClass) {
  25985. // var classType = parseClassType(superClass);
  25986. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  25987. // }
  25988. return Component$1.extend(opts);
  25989. }
  25990. /**
  25991. * @param {Object} opts
  25992. * @param {string} [superClass]
  25993. */
  25994. function extendSeriesModel(opts/*, superClass*/) {
  25995. // var Clazz = SeriesModel;
  25996. // if (superClass) {
  25997. // superClass = 'series.' + superClass.replace('series.', '');
  25998. // var classType = parseClassType(superClass);
  25999. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26000. // }
  26001. return SeriesModel.extend(opts);
  26002. }
  26003. /**
  26004. * @param {Object} opts
  26005. * @param {string} [superClass]
  26006. */
  26007. function extendChartView(opts/*, superClass*/) {
  26008. // var Clazz = ChartView;
  26009. // if (superClass) {
  26010. // superClass = superClass.replace('series.', '');
  26011. // var classType = parseClassType(superClass);
  26012. // Clazz = ChartView.getClass(classType.main, true);
  26013. // }
  26014. return Chart.extend(opts);
  26015. }
  26016. /**
  26017. * ZRender need a canvas context to do measureText.
  26018. * But in node environment canvas may be created by node-canvas.
  26019. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26020. *
  26021. * Be careful of using it in the browser.
  26022. *
  26023. * @param {Function} creator
  26024. * @example
  26025. * var Canvas = require('canvas');
  26026. * var echarts = require('echarts');
  26027. * echarts.setCanvasCreator(function () {
  26028. * // Small size is enough.
  26029. * return new Canvas(32, 32);
  26030. * });
  26031. */
  26032. function setCanvasCreator(creator) {
  26033. $override('createCanvas', creator);
  26034. }
  26035. /**
  26036. * @param {string} mapName
  26037. * @param {Array.<Object>|Object|string} geoJson
  26038. * @param {Object} [specialAreas]
  26039. *
  26040. * @example GeoJSON
  26041. * $.get('USA.json', function (geoJson) {
  26042. * echarts.registerMap('USA', geoJson);
  26043. * // Or
  26044. * echarts.registerMap('USA', {
  26045. * geoJson: geoJson,
  26046. * specialAreas: {}
  26047. * })
  26048. * });
  26049. *
  26050. * $.get('airport.svg', function (svg) {
  26051. * echarts.registerMap('airport', {
  26052. * svg: svg
  26053. * }
  26054. * });
  26055. *
  26056. * echarts.registerMap('eu', [
  26057. * {svg: eu-topographic.svg},
  26058. * {geoJSON: eu.json}
  26059. * ])
  26060. */
  26061. function registerMap(mapName, geoJson, specialAreas) {
  26062. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  26063. }
  26064. /**
  26065. * @param {string} mapName
  26066. * @return {Object}
  26067. */
  26068. function getMap(mapName) {
  26069. // For backward compatibility, only return the first one.
  26070. var records = mapDataStorage.retrieveMap(mapName);
  26071. return records && records[0] && {
  26072. geoJson: records[0].geoJSON,
  26073. specialAreas: records[0].specialAreas
  26074. };
  26075. }
  26076. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  26077. registerPreprocessor(backwardCompat);
  26078. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26079. registerLoading('default', loadingDefault);
  26080. // Default actions
  26081. registerAction({
  26082. type: 'highlight',
  26083. event: 'highlight',
  26084. update: 'highlight'
  26085. }, noop);
  26086. registerAction({
  26087. type: 'downplay',
  26088. event: 'downplay',
  26089. update: 'downplay'
  26090. }, noop);
  26091. // Default theme
  26092. registerTheme('light', lightTheme);
  26093. registerTheme('dark', theme);
  26094. // For backward compatibility, where the namespace `dataTool` will
  26095. // be mounted on `echarts` is the extension `dataTool` is imported.
  26096. var dataTool = {};
  26097. /*
  26098. * Licensed to the Apache Software Foundation (ASF) under one
  26099. * or more contributor license agreements. See the NOTICE file
  26100. * distributed with this work for additional information
  26101. * regarding copyright ownership. The ASF licenses this file
  26102. * to you under the Apache License, Version 2.0 (the
  26103. * "License"); you may not use this file except in compliance
  26104. * with the License. You may obtain a copy of the License at
  26105. *
  26106. * http://www.apache.org/licenses/LICENSE-2.0
  26107. *
  26108. * Unless required by applicable law or agreed to in writing,
  26109. * software distributed under the License is distributed on an
  26110. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26111. * KIND, either express or implied. See the License for the
  26112. * specific language governing permissions and limitations
  26113. * under the License.
  26114. */
  26115. function defaultKeyGetter(item) {
  26116. return item;
  26117. }
  26118. /**
  26119. * @param {Array} oldArr
  26120. * @param {Array} newArr
  26121. * @param {Function} oldKeyGetter
  26122. * @param {Function} newKeyGetter
  26123. * @param {Object} [context] Can be visited by this.context in callback.
  26124. */
  26125. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  26126. this._old = oldArr;
  26127. this._new = newArr;
  26128. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26129. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  26130. this.context = context;
  26131. }
  26132. DataDiffer.prototype = {
  26133. constructor: DataDiffer,
  26134. /**
  26135. * Callback function when add a data
  26136. */
  26137. add: function (func) {
  26138. this._add = func;
  26139. return this;
  26140. },
  26141. /**
  26142. * Callback function when update a data
  26143. */
  26144. update: function (func) {
  26145. this._update = func;
  26146. return this;
  26147. },
  26148. /**
  26149. * Callback function when remove a data
  26150. */
  26151. remove: function (func) {
  26152. this._remove = func;
  26153. return this;
  26154. },
  26155. execute: function () {
  26156. var oldArr = this._old;
  26157. var newArr = this._new;
  26158. var oldDataIndexMap = {};
  26159. var newDataIndexMap = {};
  26160. var oldDataKeyArr = [];
  26161. var newDataKeyArr = [];
  26162. var i;
  26163. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  26164. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  26165. for (i = 0; i < oldArr.length; i++) {
  26166. var key = oldDataKeyArr[i];
  26167. var idx = newDataIndexMap[key];
  26168. // idx can never be empty array here. see 'set null' logic below.
  26169. if (idx != null) {
  26170. // Consider there is duplicate key (for example, use dataItem.name as key).
  26171. // We should make sure every item in newArr and oldArr can be visited.
  26172. var len = idx.length;
  26173. if (len) {
  26174. len === 1 && (newDataIndexMap[key] = null);
  26175. idx = idx.shift();
  26176. }
  26177. else {
  26178. newDataIndexMap[key] = null;
  26179. }
  26180. this._update && this._update(idx, i);
  26181. }
  26182. else {
  26183. this._remove && this._remove(i);
  26184. }
  26185. }
  26186. for (var i = 0; i < newDataKeyArr.length; i++) {
  26187. var key = newDataKeyArr[i];
  26188. if (newDataIndexMap.hasOwnProperty(key)) {
  26189. var idx = newDataIndexMap[key];
  26190. if (idx == null) {
  26191. continue;
  26192. }
  26193. // idx can never be empty array here. see 'set null' logic above.
  26194. if (!idx.length) {
  26195. this._add && this._add(idx);
  26196. }
  26197. else {
  26198. for (var j = 0, len = idx.length; j < len; j++) {
  26199. this._add && this._add(idx[j]);
  26200. }
  26201. }
  26202. }
  26203. }
  26204. }
  26205. };
  26206. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  26207. for (var i = 0; i < arr.length; i++) {
  26208. // Add prefix to avoid conflict with Object.prototype.
  26209. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  26210. var existence = map[key];
  26211. if (existence == null) {
  26212. keyArr.push(key);
  26213. map[key] = i;
  26214. }
  26215. else {
  26216. if (!existence.length) {
  26217. map[key] = existence = [existence];
  26218. }
  26219. existence.push(i);
  26220. }
  26221. }
  26222. }
  26223. /*
  26224. * Licensed to the Apache Software Foundation (ASF) under one
  26225. * or more contributor license agreements. See the NOTICE file
  26226. * distributed with this work for additional information
  26227. * regarding copyright ownership. The ASF licenses this file
  26228. * to you under the Apache License, Version 2.0 (the
  26229. * "License"); you may not use this file except in compliance
  26230. * with the License. You may obtain a copy of the License at
  26231. *
  26232. * http://www.apache.org/licenses/LICENSE-2.0
  26233. *
  26234. * Unless required by applicable law or agreed to in writing,
  26235. * software distributed under the License is distributed on an
  26236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26237. * KIND, either express or implied. See the License for the
  26238. * specific language governing permissions and limitations
  26239. * under the License.
  26240. */
  26241. var OTHER_DIMENSIONS = createHashMap([
  26242. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  26243. ]);
  26244. function summarizeDimensions(data) {
  26245. var summary = {};
  26246. var encode = summary.encode = {};
  26247. var notExtraCoordDimMap = createHashMap();
  26248. var defaultedLabel = [];
  26249. var defaultedTooltip = [];
  26250. // See the comment of `List.js#userOutput`.
  26251. var userOutput = summary.userOutput = {
  26252. dimensionNames: data.dimensions.slice(),
  26253. encode: {}
  26254. };
  26255. each$1(data.dimensions, function (dimName) {
  26256. var dimItem = data.getDimensionInfo(dimName);
  26257. var coordDim = dimItem.coordDim;
  26258. if (coordDim) {
  26259. if (__DEV__) {
  26260. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  26261. }
  26262. var coordDimIndex = dimItem.coordDimIndex;
  26263. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  26264. if (!dimItem.isExtraCoord) {
  26265. notExtraCoordDimMap.set(coordDim, 1);
  26266. // Use the last coord dim (and label friendly) as default label,
  26267. // because when dataset is used, it is hard to guess which dimension
  26268. // can be value dimension. If both show x, y on label is not look good,
  26269. // and conventionally y axis is focused more.
  26270. if (mayLabelDimType(dimItem.type)) {
  26271. defaultedLabel[0] = dimName;
  26272. }
  26273. // User output encode do not contain generated coords.
  26274. // And it only has index. User can use index to retrieve value from the raw item array.
  26275. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  26276. }
  26277. if (dimItem.defaultTooltip) {
  26278. defaultedTooltip.push(dimName);
  26279. }
  26280. }
  26281. OTHER_DIMENSIONS.each(function (v, otherDim) {
  26282. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  26283. var dimIndex = dimItem.otherDims[otherDim];
  26284. if (dimIndex != null && dimIndex !== false) {
  26285. encodeArr[dimIndex] = dimItem.name;
  26286. }
  26287. });
  26288. });
  26289. var dataDimsOnCoord = [];
  26290. var encodeFirstDimNotExtra = {};
  26291. notExtraCoordDimMap.each(function (v, coordDim) {
  26292. var dimArr = encode[coordDim];
  26293. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  26294. // But should fix the case that radar axes: simplify the logic
  26295. // of `completeDimension`, remove `extraPrefix`.
  26296. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  26297. // Not necessary to remove duplicate, because a data
  26298. // dim canot on more than one coordDim.
  26299. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  26300. });
  26301. summary.dataDimsOnCoord = dataDimsOnCoord;
  26302. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  26303. var encodeLabel = encode.label;
  26304. // FIXME `encode.label` is not recommanded, because formatter can not be set
  26305. // in this way. Use label.formatter instead. May be remove this approach someday.
  26306. if (encodeLabel && encodeLabel.length) {
  26307. defaultedLabel = encodeLabel.slice();
  26308. }
  26309. var encodeTooltip = encode.tooltip;
  26310. if (encodeTooltip && encodeTooltip.length) {
  26311. defaultedTooltip = encodeTooltip.slice();
  26312. }
  26313. else if (!defaultedTooltip.length) {
  26314. defaultedTooltip = defaultedLabel.slice();
  26315. }
  26316. encode.defaultedLabel = defaultedLabel;
  26317. encode.defaultedTooltip = defaultedTooltip;
  26318. return summary;
  26319. }
  26320. function getOrCreateEncodeArr(encode, dim) {
  26321. if (!encode.hasOwnProperty(dim)) {
  26322. encode[dim] = [];
  26323. }
  26324. return encode[dim];
  26325. }
  26326. function getDimensionTypeByAxis(axisType) {
  26327. return axisType === 'category'
  26328. ? 'ordinal'
  26329. : axisType === 'time'
  26330. ? 'time'
  26331. : 'float';
  26332. }
  26333. function mayLabelDimType(dimType) {
  26334. // In most cases, ordinal and time do not suitable for label.
  26335. // Ordinal info can be displayed on axis. Time is too long.
  26336. return !(dimType === 'ordinal' || dimType === 'time');
  26337. }
  26338. // function findTheLastDimMayLabel(data) {
  26339. // // Get last value dim
  26340. // var dimensions = data.dimensions.slice();
  26341. // var valueType;
  26342. // var valueDim;
  26343. // while (dimensions.length && (
  26344. // valueDim = dimensions.pop(),
  26345. // valueType = data.getDimensionInfo(valueDim).type,
  26346. // valueType === 'ordinal' || valueType === 'time'
  26347. // )) {} // jshint ignore:line
  26348. // return valueDim;
  26349. // }
  26350. /*
  26351. * Licensed to the Apache Software Foundation (ASF) under one
  26352. * or more contributor license agreements. See the NOTICE file
  26353. * distributed with this work for additional information
  26354. * regarding copyright ownership. The ASF licenses this file
  26355. * to you under the Apache License, Version 2.0 (the
  26356. * "License"); you may not use this file except in compliance
  26357. * with the License. You may obtain a copy of the License at
  26358. *
  26359. * http://www.apache.org/licenses/LICENSE-2.0
  26360. *
  26361. * Unless required by applicable law or agreed to in writing,
  26362. * software distributed under the License is distributed on an
  26363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26364. * KIND, either express or implied. See the License for the
  26365. * specific language governing permissions and limitations
  26366. * under the License.
  26367. */
  26368. /**
  26369. * @class
  26370. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  26371. */
  26372. function DataDimensionInfo(opt) {
  26373. if (opt != null) {
  26374. extend(this, opt);
  26375. }
  26376. /**
  26377. * Dimension name.
  26378. * Mandatory.
  26379. * @type {string}
  26380. */
  26381. // this.name;
  26382. /**
  26383. * The origin name in dimsDef, see source helper.
  26384. * If displayName given, the tooltip will displayed vertically.
  26385. * Optional.
  26386. * @type {string}
  26387. */
  26388. // this.displayName;
  26389. /**
  26390. * Which coordSys dimension this dimension mapped to.
  26391. * A `coordDim` can be a "coordSysDim" that the coordSys required
  26392. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  26393. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  26394. * (That is determined by whether `isExtraCoord` is `true`).
  26395. * Mandatory.
  26396. * @type {string}
  26397. */
  26398. // this.coordDim;
  26399. /**
  26400. * The index of this dimension in `series.encode[coordDim]`.
  26401. * Mandatory.
  26402. * @type {number}
  26403. */
  26404. // this.coordDimIndex;
  26405. /**
  26406. * Dimension type. The enumerable values are the key of
  26407. * `dataCtors` of `data/List`.
  26408. * Optional.
  26409. * @type {string}
  26410. */
  26411. // this.type;
  26412. /**
  26413. * This index of this dimension info in `data/List#_dimensionInfos`.
  26414. * Mandatory after added to `data/List`.
  26415. * @type {number}
  26416. */
  26417. // this.index;
  26418. /**
  26419. * The format of `otherDims` is:
  26420. * ```js
  26421. * {
  26422. * tooltip: number optional,
  26423. * label: number optional,
  26424. * itemName: number optional,
  26425. * seriesName: number optional,
  26426. * }
  26427. * ```
  26428. *
  26429. * A `series.encode` can specified these fields:
  26430. * ```js
  26431. * encode: {
  26432. * // "3, 1, 5" is the index of data dimension.
  26433. * tooltip: [3, 1, 5],
  26434. * label: [0, 3],
  26435. * ...
  26436. * }
  26437. * ```
  26438. * `otherDims` is the parse result of the `series.encode` above, like:
  26439. * ```js
  26440. * // Suppose the index of this data dimension is `3`.
  26441. * this.otherDims = {
  26442. * // `3` is at the index `0` of the `encode.tooltip`
  26443. * tooltip: 0,
  26444. * // `3` is at the index `1` of the `encode.tooltip`
  26445. * label: 1
  26446. * };
  26447. * ```
  26448. *
  26449. * This prop should never be `null`/`undefined` after initialized.
  26450. * @type {Object}
  26451. */
  26452. this.otherDims = {};
  26453. /**
  26454. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  26455. * "coordSys" required.
  26456. * Mandatory.
  26457. * @type {boolean}
  26458. */
  26459. // this.isExtraCoord;
  26460. /**
  26461. * @type {module:data/OrdinalMeta}
  26462. */
  26463. // this.ordinalMeta;
  26464. /**
  26465. * Whether to create inverted indices.
  26466. * @type {boolean}
  26467. */
  26468. // this.createInvertedIndices;
  26469. }
  26470. /*
  26471. * Licensed to the Apache Software Foundation (ASF) under one
  26472. * or more contributor license agreements. See the NOTICE file
  26473. * distributed with this work for additional information
  26474. * regarding copyright ownership. The ASF licenses this file
  26475. * to you under the Apache License, Version 2.0 (the
  26476. * "License"); you may not use this file except in compliance
  26477. * with the License. You may obtain a copy of the License at
  26478. *
  26479. * http://www.apache.org/licenses/LICENSE-2.0
  26480. *
  26481. * Unless required by applicable law or agreed to in writing,
  26482. * software distributed under the License is distributed on an
  26483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26484. * KIND, either express or implied. See the License for the
  26485. * specific language governing permissions and limitations
  26486. * under the License.
  26487. */
  26488. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  26489. /**
  26490. * List for data storage
  26491. * @module echarts/data/List
  26492. */
  26493. var isObject$4 = isObject$1;
  26494. var UNDEFINED = 'undefined';
  26495. var INDEX_NOT_FOUND = -1;
  26496. // Use prefix to avoid index to be the same as otherIdList[idx],
  26497. // which will cause weird udpate animation.
  26498. var ID_PREFIX = 'e\0\0';
  26499. var dataCtors = {
  26500. 'float': typeof Float64Array === UNDEFINED
  26501. ? Array : Float64Array,
  26502. 'int': typeof Int32Array === UNDEFINED
  26503. ? Array : Int32Array,
  26504. // Ordinal data type can be string or int
  26505. 'ordinal': Array,
  26506. 'number': Array,
  26507. 'time': Array
  26508. };
  26509. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  26510. // different from the Ctor of typed array.
  26511. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  26512. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  26513. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  26514. function getIndicesCtor(list) {
  26515. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  26516. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  26517. }
  26518. function cloneChunk(originalChunk) {
  26519. var Ctor = originalChunk.constructor;
  26520. // Only shallow clone is enough when Array.
  26521. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  26522. }
  26523. var TRANSFERABLE_PROPERTIES = [
  26524. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  26525. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  26526. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  26527. ];
  26528. var CLONE_PROPERTIES = [
  26529. '_extent', '_approximateExtent', '_rawExtent'
  26530. ];
  26531. function transferProperties(target, source) {
  26532. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  26533. if (source.hasOwnProperty(propName)) {
  26534. target[propName] = source[propName];
  26535. }
  26536. });
  26537. target.__wrappedMethods = source.__wrappedMethods;
  26538. each$1(CLONE_PROPERTIES, function (propName) {
  26539. target[propName] = clone(source[propName]);
  26540. });
  26541. target._calculationInfo = extend(source._calculationInfo);
  26542. }
  26543. /**
  26544. * @constructor
  26545. * @alias module:echarts/data/List
  26546. *
  26547. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  26548. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26549. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26550. * @param {module:echarts/model/Model} hostModel
  26551. */
  26552. var List = function (dimensions, hostModel) {
  26553. dimensions = dimensions || ['x', 'y'];
  26554. var dimensionInfos = {};
  26555. var dimensionNames = [];
  26556. var invertedIndicesMap = {};
  26557. for (var i = 0; i < dimensions.length; i++) {
  26558. // Use the original dimensions[i], where other flag props may exists.
  26559. var dimensionInfo = dimensions[i];
  26560. if (isString(dimensionInfo)) {
  26561. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26562. }
  26563. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26564. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26565. }
  26566. var dimensionName = dimensionInfo.name;
  26567. dimensionInfo.type = dimensionInfo.type || 'float';
  26568. if (!dimensionInfo.coordDim) {
  26569. dimensionInfo.coordDim = dimensionName;
  26570. dimensionInfo.coordDimIndex = 0;
  26571. }
  26572. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26573. dimensionNames.push(dimensionName);
  26574. dimensionInfos[dimensionName] = dimensionInfo;
  26575. dimensionInfo.index = i;
  26576. if (dimensionInfo.createInvertedIndices) {
  26577. invertedIndicesMap[dimensionName] = [];
  26578. }
  26579. }
  26580. /**
  26581. * @readOnly
  26582. * @type {Array.<string>}
  26583. */
  26584. this.dimensions = dimensionNames;
  26585. /**
  26586. * Infomation of each data dimension, like data type.
  26587. * @type {Object}
  26588. */
  26589. this._dimensionInfos = dimensionInfos;
  26590. /**
  26591. * @type {module:echarts/model/Model}
  26592. */
  26593. this.hostModel = hostModel;
  26594. /**
  26595. * @type {module:echarts/model/Model}
  26596. */
  26597. this.dataType;
  26598. /**
  26599. * Indices stores the indices of data subset after filtered.
  26600. * This data subset will be used in chart.
  26601. * @type {Array.<number>}
  26602. * @readOnly
  26603. */
  26604. this._indices = null;
  26605. this._count = 0;
  26606. this._rawCount = 0;
  26607. /**
  26608. * Data storage
  26609. * @type {Object.<key, Array.<TypedArray|Array>>}
  26610. * @private
  26611. */
  26612. this._storage = {};
  26613. /**
  26614. * @type {Array.<string>}
  26615. */
  26616. this._nameList = [];
  26617. /**
  26618. * @type {Array.<string>}
  26619. */
  26620. this._idList = [];
  26621. /**
  26622. * Models of data option is stored sparse for optimizing memory cost
  26623. * @type {Array.<module:echarts/model/Model>}
  26624. * @private
  26625. */
  26626. this._optionModels = [];
  26627. /**
  26628. * Global visual properties after visual coding
  26629. * @type {Object}
  26630. * @private
  26631. */
  26632. this._visual = {};
  26633. /**
  26634. * Globel layout properties.
  26635. * @type {Object}
  26636. * @private
  26637. */
  26638. this._layout = {};
  26639. /**
  26640. * Item visual properties after visual coding
  26641. * @type {Array.<Object>}
  26642. * @private
  26643. */
  26644. this._itemVisuals = [];
  26645. /**
  26646. * Key: visual type, Value: boolean
  26647. * @type {Object}
  26648. * @readOnly
  26649. */
  26650. this.hasItemVisual = {};
  26651. /**
  26652. * Item layout properties after layout
  26653. * @type {Array.<Object>}
  26654. * @private
  26655. */
  26656. this._itemLayouts = [];
  26657. /**
  26658. * Graphic elemnents
  26659. * @type {Array.<module:zrender/Element>}
  26660. * @private
  26661. */
  26662. this._graphicEls = [];
  26663. /**
  26664. * Max size of each chunk.
  26665. * @type {number}
  26666. * @private
  26667. */
  26668. this._chunkSize = 1e5;
  26669. /**
  26670. * @type {number}
  26671. * @private
  26672. */
  26673. this._chunkCount = 0;
  26674. /**
  26675. * @type {Array.<Array|Object>}
  26676. * @private
  26677. */
  26678. this._rawData;
  26679. /**
  26680. * Raw extent will not be cloned, but only transfered.
  26681. * It will not be calculated util needed.
  26682. * key: dim,
  26683. * value: {end: number, extent: Array.<number>}
  26684. * @type {Object}
  26685. * @private
  26686. */
  26687. this._rawExtent = {};
  26688. /**
  26689. * @type {Object}
  26690. * @private
  26691. */
  26692. this._extent = {};
  26693. /**
  26694. * key: dim
  26695. * value: extent
  26696. * @type {Object}
  26697. * @private
  26698. */
  26699. this._approximateExtent = {};
  26700. /**
  26701. * Cache summary info for fast visit. See "dimensionHelper".
  26702. * @type {Object}
  26703. * @private
  26704. */
  26705. this._dimensionsSummary = summarizeDimensions(this);
  26706. /**
  26707. * @type {Object.<Array|TypedArray>}
  26708. * @private
  26709. */
  26710. this._invertedIndicesMap = invertedIndicesMap;
  26711. /**
  26712. * @type {Object}
  26713. * @private
  26714. */
  26715. this._calculationInfo = {};
  26716. /**
  26717. * User output info of this data.
  26718. * DO NOT use it in other places!
  26719. *
  26720. * When preparing user params for user callbacks, we have
  26721. * to clone these inner data structures to prevent users
  26722. * from modifying them to effect built-in logic. And for
  26723. * performance consideration we make this `userOutput` to
  26724. * avoid clone them too many times.
  26725. *
  26726. * @type {Object}
  26727. * @readOnly
  26728. */
  26729. this.userOutput = this._dimensionsSummary.userOutput;
  26730. };
  26731. var listProto = List.prototype;
  26732. listProto.type = 'list';
  26733. /**
  26734. * If each data item has it's own option
  26735. * @type {boolean}
  26736. */
  26737. listProto.hasItemOption = true;
  26738. /**
  26739. * The meanings of the input parameter `dim`:
  26740. *
  26741. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26742. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26743. * + If dim is a number-like string (e.g., `"1"`):
  26744. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26745. * + If not, it will be converted to a number, which means the index of the dimension.
  26746. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26747. * dimension setting, although now it seems that it is not a good idea.)
  26748. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26749. * if no dimension name is defined as `"1"`.
  26750. * + If dim is a not-number-like string, it means the concrete dim name.
  26751. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26752. * or customized in `dimensions` property of option like `"age"`.
  26753. *
  26754. * Get dimension name
  26755. * @param {string|number} dim See above.
  26756. * @return {string} Concrete dim name.
  26757. */
  26758. listProto.getDimension = function (dim) {
  26759. if (typeof dim === 'number'
  26760. // If being a number-like string but not being defined a dimension name.
  26761. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  26762. ) {
  26763. dim = this.dimensions[dim];
  26764. }
  26765. return dim;
  26766. };
  26767. /**
  26768. * Get type and calculation info of particular dimension
  26769. * @param {string|number} dim
  26770. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26771. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26772. */
  26773. listProto.getDimensionInfo = function (dim) {
  26774. // Do not clone, because there may be categories in dimInfo.
  26775. return this._dimensionInfos[this.getDimension(dim)];
  26776. };
  26777. /**
  26778. * @return {Array.<string>} concrete dimension name list on coord.
  26779. */
  26780. listProto.getDimensionsOnCoord = function () {
  26781. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26782. };
  26783. /**
  26784. * @param {string} coordDim
  26785. * @param {number} [idx] A coordDim may map to more than one data dim.
  26786. * If idx is `true`, return a array of all mapped dims.
  26787. * If idx is not specified, return the first dim not extra.
  26788. * @return {string|Array.<string>} concrete data dim.
  26789. * If idx is number, and not found, return null/undefined.
  26790. * If idx is `true`, and not found, return empty array (always return array).
  26791. */
  26792. listProto.mapDimension = function (coordDim, idx) {
  26793. var dimensionsSummary = this._dimensionsSummary;
  26794. if (idx == null) {
  26795. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26796. }
  26797. var dims = dimensionsSummary.encode[coordDim];
  26798. return idx === true
  26799. // always return array if idx is `true`
  26800. ? (dims || []).slice()
  26801. : (dims && dims[idx]);
  26802. };
  26803. /**
  26804. * Initialize from data
  26805. * @param {Array.<Object|number|Array>} data source or data or data provider.
  26806. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  26807. * defualt label/tooltip.
  26808. * A name can be specified in encode.itemName,
  26809. * or dataItem.name (only for series option data),
  26810. * or provided in nameList from outside.
  26811. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  26812. */
  26813. listProto.initData = function (data, nameList, dimValueGetter) {
  26814. var notProvider = Source.isInstance(data) || isArrayLike(data);
  26815. if (notProvider) {
  26816. data = new DefaultDataProvider(data, this.dimensions.length);
  26817. }
  26818. if (__DEV__) {
  26819. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  26820. throw new Error('Inavlid data provider.');
  26821. }
  26822. }
  26823. this._rawData = data;
  26824. // Clear
  26825. this._storage = {};
  26826. this._indices = null;
  26827. this._nameList = nameList || [];
  26828. this._idList = [];
  26829. this._nameRepeatCount = {};
  26830. if (!dimValueGetter) {
  26831. this.hasItemOption = false;
  26832. }
  26833. /**
  26834. * @readOnly
  26835. */
  26836. this.defaultDimValueGetter = defaultDimValueGetters[
  26837. this._rawData.getSource().sourceFormat
  26838. ];
  26839. // Default dim value getter
  26840. this._dimValueGetter = dimValueGetter = dimValueGetter
  26841. || this.defaultDimValueGetter;
  26842. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  26843. // Reset raw extent.
  26844. this._rawExtent = {};
  26845. this._initDataFromProvider(0, data.count());
  26846. // If data has no item option.
  26847. if (data.pure) {
  26848. this.hasItemOption = false;
  26849. }
  26850. };
  26851. listProto.getProvider = function () {
  26852. return this._rawData;
  26853. };
  26854. /**
  26855. * Caution: Can be only called on raw data (before `this._indices` created).
  26856. */
  26857. listProto.appendData = function (data) {
  26858. if (__DEV__) {
  26859. assert$1(!this._indices, 'appendData can only be called on raw data.');
  26860. }
  26861. var rawData = this._rawData;
  26862. var start = this.count();
  26863. rawData.appendData(data);
  26864. var end = rawData.count();
  26865. if (!rawData.persistent) {
  26866. end += start;
  26867. }
  26868. this._initDataFromProvider(start, end);
  26869. };
  26870. /**
  26871. * Caution: Can be only called on raw data (before `this._indices` created).
  26872. * This method does not modify `rawData` (`dataProvider`), but only
  26873. * add values to storage.
  26874. *
  26875. * The final count will be increased by `Math.max(values.length, names.length)`.
  26876. *
  26877. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  26878. * [
  26879. * [12, 33, 44],
  26880. * [NaN, 43, 1],
  26881. * ['-', 'asdf', 0]
  26882. * ]
  26883. * Each item is exaclty cooresponding to a dimension.
  26884. * @param {Array.<string>} [names]
  26885. */
  26886. listProto.appendValues = function (values, names) {
  26887. var chunkSize = this._chunkSize;
  26888. var storage = this._storage;
  26889. var dimensions = this.dimensions;
  26890. var dimLen = dimensions.length;
  26891. var rawExtent = this._rawExtent;
  26892. var start = this.count();
  26893. var end = start + Math.max(values.length, names ? names.length : 0);
  26894. var originalChunkCount = this._chunkCount;
  26895. for (var i = 0; i < dimLen; i++) {
  26896. var dim = dimensions[i];
  26897. if (!rawExtent[dim]) {
  26898. rawExtent[dim] = getInitialExtent();
  26899. }
  26900. if (!storage[dim]) {
  26901. storage[dim] = [];
  26902. }
  26903. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  26904. this._chunkCount = storage[dim].length;
  26905. }
  26906. var emptyDataItem = new Array(dimLen);
  26907. for (var idx = start; idx < end; idx++) {
  26908. var sourceIdx = idx - start;
  26909. var chunkIndex = Math.floor(idx / chunkSize);
  26910. var chunkOffset = idx % chunkSize;
  26911. // Store the data by dimensions
  26912. for (var k = 0; k < dimLen; k++) {
  26913. var dim = dimensions[k];
  26914. var val = this._dimValueGetterArrayRows(
  26915. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  26916. );
  26917. storage[dim][chunkIndex][chunkOffset] = val;
  26918. var dimRawExtent = rawExtent[dim];
  26919. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26920. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26921. }
  26922. if (names) {
  26923. this._nameList[idx] = names[sourceIdx];
  26924. }
  26925. }
  26926. this._rawCount = this._count = end;
  26927. // Reset data extent
  26928. this._extent = {};
  26929. prepareInvertedIndex(this);
  26930. };
  26931. listProto._initDataFromProvider = function (start, end) {
  26932. // Optimize.
  26933. if (start >= end) {
  26934. return;
  26935. }
  26936. var chunkSize = this._chunkSize;
  26937. var rawData = this._rawData;
  26938. var storage = this._storage;
  26939. var dimensions = this.dimensions;
  26940. var dimLen = dimensions.length;
  26941. var dimensionInfoMap = this._dimensionInfos;
  26942. var nameList = this._nameList;
  26943. var idList = this._idList;
  26944. var rawExtent = this._rawExtent;
  26945. var nameRepeatCount = this._nameRepeatCount = {};
  26946. var nameDimIdx;
  26947. var originalChunkCount = this._chunkCount;
  26948. for (var i = 0; i < dimLen; i++) {
  26949. var dim = dimensions[i];
  26950. if (!rawExtent[dim]) {
  26951. rawExtent[dim] = getInitialExtent();
  26952. }
  26953. var dimInfo = dimensionInfoMap[dim];
  26954. if (dimInfo.otherDims.itemName === 0) {
  26955. nameDimIdx = this._nameDimIdx = i;
  26956. }
  26957. if (dimInfo.otherDims.itemId === 0) {
  26958. this._idDimIdx = i;
  26959. }
  26960. if (!storage[dim]) {
  26961. storage[dim] = [];
  26962. }
  26963. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  26964. this._chunkCount = storage[dim].length;
  26965. }
  26966. var dataItem = new Array(dimLen);
  26967. for (var idx = start; idx < end; idx++) {
  26968. // NOTICE: Try not to write things into dataItem
  26969. dataItem = rawData.getItem(idx, dataItem);
  26970. // Each data item is value
  26971. // [1, 2]
  26972. // 2
  26973. // Bar chart, line chart which uses category axis
  26974. // only gives the 'y' value. 'x' value is the indices of category
  26975. // Use a tempValue to normalize the value to be a (x, y) value
  26976. var chunkIndex = Math.floor(idx / chunkSize);
  26977. var chunkOffset = idx % chunkSize;
  26978. // Store the data by dimensions
  26979. for (var k = 0; k < dimLen; k++) {
  26980. var dim = dimensions[k];
  26981. var dimStorage = storage[dim][chunkIndex];
  26982. // PENDING NULL is empty or zero
  26983. var val = this._dimValueGetter(dataItem, dim, idx, k);
  26984. dimStorage[chunkOffset] = val;
  26985. var dimRawExtent = rawExtent[dim];
  26986. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26987. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26988. }
  26989. // ??? FIXME not check by pure but sourceFormat?
  26990. // TODO refactor these logic.
  26991. if (!rawData.pure) {
  26992. var name = nameList[idx];
  26993. if (dataItem && name == null) {
  26994. // If dataItem is {name: ...}, it has highest priority.
  26995. // That is appropriate for many common cases.
  26996. if (dataItem.name != null) {
  26997. // There is no other place to persistent dataItem.name,
  26998. // so save it to nameList.
  26999. nameList[idx] = name = dataItem.name;
  27000. }
  27001. else if (nameDimIdx != null) {
  27002. var nameDim = dimensions[nameDimIdx];
  27003. var nameDimChunk = storage[nameDim][chunkIndex];
  27004. if (nameDimChunk) {
  27005. name = nameDimChunk[chunkOffset];
  27006. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  27007. if (ordinalMeta && ordinalMeta.categories.length) {
  27008. name = ordinalMeta.categories[name];
  27009. }
  27010. }
  27011. }
  27012. }
  27013. // Try using the id in option
  27014. // id or name is used on dynamical data, mapping old and new items.
  27015. var id = dataItem == null ? null : dataItem.id;
  27016. if (id == null && name != null) {
  27017. // Use name as id and add counter to avoid same name
  27018. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  27019. id = name;
  27020. if (nameRepeatCount[name] > 0) {
  27021. id += '__ec__' + nameRepeatCount[name];
  27022. }
  27023. nameRepeatCount[name]++;
  27024. }
  27025. id != null && (idList[idx] = id);
  27026. }
  27027. }
  27028. if (!rawData.persistent && rawData.clean) {
  27029. // Clean unused data if data source is typed array.
  27030. rawData.clean();
  27031. }
  27032. this._rawCount = this._count = end;
  27033. // Reset data extent
  27034. this._extent = {};
  27035. prepareInvertedIndex(this);
  27036. };
  27037. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  27038. var DataCtor = dataCtors[dimInfo.type];
  27039. var lastChunkIndex = chunkCount - 1;
  27040. var dim = dimInfo.name;
  27041. var resizeChunkArray = storage[dim][lastChunkIndex];
  27042. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  27043. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  27044. // The cost of the copy is probably inconsiderable
  27045. // within the initial chunkSize.
  27046. for (var j = 0; j < resizeChunkArray.length; j++) {
  27047. newStore[j] = resizeChunkArray[j];
  27048. }
  27049. storage[dim][lastChunkIndex] = newStore;
  27050. }
  27051. // Create new chunks.
  27052. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  27053. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  27054. }
  27055. }
  27056. function prepareInvertedIndex(list) {
  27057. var invertedIndicesMap = list._invertedIndicesMap;
  27058. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  27059. var dimInfo = list._dimensionInfos[dim];
  27060. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  27061. var ordinalMeta = dimInfo.ordinalMeta;
  27062. if (ordinalMeta) {
  27063. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  27064. ordinalMeta.categories.length
  27065. );
  27066. // The default value of TypedArray is 0. To avoid miss
  27067. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  27068. for (var i = 0; i < invertedIndices.length; i++) {
  27069. invertedIndices[i] = INDEX_NOT_FOUND;
  27070. }
  27071. for (var i = 0; i < list._count; i++) {
  27072. // Only support the case that all values are distinct.
  27073. invertedIndices[list.get(dim, i)] = i;
  27074. }
  27075. }
  27076. });
  27077. }
  27078. function getRawValueFromStore(list, dimIndex, rawIndex) {
  27079. var val;
  27080. if (dimIndex != null) {
  27081. var chunkSize = list._chunkSize;
  27082. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27083. var chunkOffset = rawIndex % chunkSize;
  27084. var dim = list.dimensions[dimIndex];
  27085. var chunk = list._storage[dim][chunkIndex];
  27086. if (chunk) {
  27087. val = chunk[chunkOffset];
  27088. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  27089. if (ordinalMeta && ordinalMeta.categories.length) {
  27090. val = ordinalMeta.categories[val];
  27091. }
  27092. }
  27093. }
  27094. return val;
  27095. }
  27096. /**
  27097. * @return {number}
  27098. */
  27099. listProto.count = function () {
  27100. return this._count;
  27101. };
  27102. listProto.getIndices = function () {
  27103. var newIndices;
  27104. var indices = this._indices;
  27105. if (indices) {
  27106. var Ctor = indices.constructor;
  27107. var thisCount = this._count;
  27108. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  27109. if (Ctor === Array) {
  27110. newIndices = new Ctor(thisCount);
  27111. for (var i = 0; i < thisCount; i++) {
  27112. newIndices[i] = indices[i];
  27113. }
  27114. }
  27115. else {
  27116. newIndices = new Ctor(indices.buffer, 0, thisCount);
  27117. }
  27118. }
  27119. else {
  27120. var Ctor = getIndicesCtor(this);
  27121. var newIndices = new Ctor(this.count());
  27122. for (var i = 0; i < newIndices.length; i++) {
  27123. newIndices[i] = i;
  27124. }
  27125. }
  27126. return newIndices;
  27127. };
  27128. /**
  27129. * Get value. Return NaN if idx is out of range.
  27130. * @param {string} dim Dim must be concrete name.
  27131. * @param {number} idx
  27132. * @param {boolean} stack
  27133. * @return {number}
  27134. */
  27135. listProto.get = function (dim, idx /*, stack */) {
  27136. if (!(idx >= 0 && idx < this._count)) {
  27137. return NaN;
  27138. }
  27139. var storage = this._storage;
  27140. if (!storage[dim]) {
  27141. // TODO Warn ?
  27142. return NaN;
  27143. }
  27144. idx = this.getRawIndex(idx);
  27145. var chunkIndex = Math.floor(idx / this._chunkSize);
  27146. var chunkOffset = idx % this._chunkSize;
  27147. var chunkStore = storage[dim][chunkIndex];
  27148. var value = chunkStore[chunkOffset];
  27149. // FIXME ordinal data type is not stackable
  27150. // if (stack) {
  27151. // var dimensionInfo = this._dimensionInfos[dim];
  27152. // if (dimensionInfo && dimensionInfo.stackable) {
  27153. // var stackedOn = this.stackedOn;
  27154. // while (stackedOn) {
  27155. // // Get no stacked data of stacked on
  27156. // var stackedValue = stackedOn.get(dim, idx);
  27157. // // Considering positive stack, negative stack and empty data
  27158. // if ((value >= 0 && stackedValue > 0) // Positive stack
  27159. // || (value <= 0 && stackedValue < 0) // Negative stack
  27160. // ) {
  27161. // value += stackedValue;
  27162. // }
  27163. // stackedOn = stackedOn.stackedOn;
  27164. // }
  27165. // }
  27166. // }
  27167. return value;
  27168. };
  27169. /**
  27170. * @param {string} dim concrete dim
  27171. * @param {number} rawIndex
  27172. * @return {number|string}
  27173. */
  27174. listProto.getByRawIndex = function (dim, rawIdx) {
  27175. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  27176. return NaN;
  27177. }
  27178. var dimStore = this._storage[dim];
  27179. if (!dimStore) {
  27180. // TODO Warn ?
  27181. return NaN;
  27182. }
  27183. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27184. var chunkOffset = rawIdx % this._chunkSize;
  27185. var chunkStore = dimStore[chunkIndex];
  27186. return chunkStore[chunkOffset];
  27187. };
  27188. /**
  27189. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  27190. * Hack a much simpler _getFast
  27191. * @private
  27192. */
  27193. listProto._getFast = function (dim, rawIdx) {
  27194. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27195. var chunkOffset = rawIdx % this._chunkSize;
  27196. var chunkStore = this._storage[dim][chunkIndex];
  27197. return chunkStore[chunkOffset];
  27198. };
  27199. /**
  27200. * Get value for multi dimensions.
  27201. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  27202. * @param {number} idx
  27203. * @return {number}
  27204. */
  27205. listProto.getValues = function (dimensions, idx /*, stack */) {
  27206. var values = [];
  27207. if (!isArray(dimensions)) {
  27208. // stack = idx;
  27209. idx = dimensions;
  27210. dimensions = this.dimensions;
  27211. }
  27212. for (var i = 0, len = dimensions.length; i < len; i++) {
  27213. values.push(this.get(dimensions[i], idx /*, stack */));
  27214. }
  27215. return values;
  27216. };
  27217. /**
  27218. * If value is NaN. Inlcuding '-'
  27219. * Only check the coord dimensions.
  27220. * @param {string} dim
  27221. * @param {number} idx
  27222. * @return {number}
  27223. */
  27224. listProto.hasValue = function (idx) {
  27225. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  27226. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  27227. // Ordinal type originally can be string or number.
  27228. // But when an ordinal type is used on coord, it can
  27229. // not be string but only number. So we can also use isNaN.
  27230. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  27231. return false;
  27232. }
  27233. }
  27234. return true;
  27235. };
  27236. /**
  27237. * Get extent of data in one dimension
  27238. * @param {string} dim
  27239. * @param {boolean} stack
  27240. */
  27241. listProto.getDataExtent = function (dim /*, stack */) {
  27242. // Make sure use concrete dim as cache name.
  27243. dim = this.getDimension(dim);
  27244. var dimData = this._storage[dim];
  27245. var initialExtent = getInitialExtent();
  27246. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  27247. if (!dimData) {
  27248. return initialExtent;
  27249. }
  27250. // Make more strict checkings to ensure hitting cache.
  27251. var currEnd = this.count();
  27252. // var cacheName = [dim, !!stack].join('_');
  27253. // var cacheName = dim;
  27254. // Consider the most cases when using data zoom, `getDataExtent`
  27255. // happened before filtering. We cache raw extent, which is not
  27256. // necessary to be cleared and recalculated when restore data.
  27257. var useRaw = !this._indices; // && !stack;
  27258. var dimExtent;
  27259. if (useRaw) {
  27260. return this._rawExtent[dim].slice();
  27261. }
  27262. dimExtent = this._extent[dim];
  27263. if (dimExtent) {
  27264. return dimExtent.slice();
  27265. }
  27266. dimExtent = initialExtent;
  27267. var min = dimExtent[0];
  27268. var max = dimExtent[1];
  27269. for (var i = 0; i < currEnd; i++) {
  27270. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  27271. var value = this._getFast(dim, this.getRawIndex(i));
  27272. value < min && (min = value);
  27273. value > max && (max = value);
  27274. }
  27275. dimExtent = [min, max];
  27276. this._extent[dim] = dimExtent;
  27277. return dimExtent;
  27278. };
  27279. /**
  27280. * Optimize for the scenario that data is filtered by a given extent.
  27281. * Consider that if data amount is more than hundreds of thousand,
  27282. * extent calculation will cost more than 10ms and the cache will
  27283. * be erased because of the filtering.
  27284. */
  27285. listProto.getApproximateExtent = function (dim /*, stack */) {
  27286. dim = this.getDimension(dim);
  27287. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  27288. };
  27289. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  27290. dim = this.getDimension(dim);
  27291. this._approximateExtent[dim] = extent.slice();
  27292. };
  27293. /**
  27294. * @param {string} key
  27295. * @return {*}
  27296. */
  27297. listProto.getCalculationInfo = function (key) {
  27298. return this._calculationInfo[key];
  27299. };
  27300. /**
  27301. * @param {string|Object} key or k-v object
  27302. * @param {*} [value]
  27303. */
  27304. listProto.setCalculationInfo = function (key, value) {
  27305. isObject$4(key)
  27306. ? extend(this._calculationInfo, key)
  27307. : (this._calculationInfo[key] = value);
  27308. };
  27309. /**
  27310. * Get sum of data in one dimension
  27311. * @param {string} dim
  27312. */
  27313. listProto.getSum = function (dim /*, stack */) {
  27314. var dimData = this._storage[dim];
  27315. var sum = 0;
  27316. if (dimData) {
  27317. for (var i = 0, len = this.count(); i < len; i++) {
  27318. var value = this.get(dim, i /*, stack */);
  27319. if (!isNaN(value)) {
  27320. sum += value;
  27321. }
  27322. }
  27323. }
  27324. return sum;
  27325. };
  27326. /**
  27327. * Get median of data in one dimension
  27328. * @param {string} dim
  27329. */
  27330. listProto.getMedian = function (dim /*, stack */) {
  27331. var dimDataArray = [];
  27332. // map all data of one dimension
  27333. this.each(dim, function (val, idx) {
  27334. if (!isNaN(val)) {
  27335. dimDataArray.push(val);
  27336. }
  27337. });
  27338. // TODO
  27339. // Use quick select?
  27340. // immutability & sort
  27341. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  27342. return a - b;
  27343. });
  27344. var len = this.count();
  27345. // calculate median
  27346. return len === 0
  27347. ? 0
  27348. : len % 2 === 1
  27349. ? sortedDimDataArray[(len - 1) / 2]
  27350. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  27351. };
  27352. // /**
  27353. // * Retreive the index with given value
  27354. // * @param {string} dim Concrete dimension.
  27355. // * @param {number} value
  27356. // * @return {number}
  27357. // */
  27358. // Currently incorrect: should return dataIndex but not rawIndex.
  27359. // Do not fix it until this method is to be used somewhere.
  27360. // FIXME Precision of float value
  27361. // listProto.indexOf = function (dim, value) {
  27362. // var storage = this._storage;
  27363. // var dimData = storage[dim];
  27364. // var chunkSize = this._chunkSize;
  27365. // if (dimData) {
  27366. // for (var i = 0, len = this.count(); i < len; i++) {
  27367. // var chunkIndex = Math.floor(i / chunkSize);
  27368. // var chunkOffset = i % chunkSize;
  27369. // if (dimData[chunkIndex][chunkOffset] === value) {
  27370. // return i;
  27371. // }
  27372. // }
  27373. // }
  27374. // return -1;
  27375. // };
  27376. /**
  27377. * Only support the dimension which inverted index created.
  27378. * Do not support other cases until required.
  27379. * @param {string} concrete dim
  27380. * @param {number|string} value
  27381. * @return {number} rawIndex
  27382. */
  27383. listProto.rawIndexOf = function (dim, value) {
  27384. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27385. if (__DEV__) {
  27386. if (!invertedIndices) {
  27387. throw new Error('Do not supported yet');
  27388. }
  27389. }
  27390. var rawIndex = invertedIndices[value];
  27391. if (rawIndex == null || isNaN(rawIndex)) {
  27392. return INDEX_NOT_FOUND;
  27393. }
  27394. return rawIndex;
  27395. };
  27396. /**
  27397. * Retreive the index with given name
  27398. * @param {number} idx
  27399. * @param {number} name
  27400. * @return {number}
  27401. */
  27402. listProto.indexOfName = function (name) {
  27403. for (var i = 0, len = this.count(); i < len; i++) {
  27404. if (this.getName(i) === name) {
  27405. return i;
  27406. }
  27407. }
  27408. return -1;
  27409. };
  27410. /**
  27411. * Retreive the index with given raw data index
  27412. * @param {number} idx
  27413. * @param {number} name
  27414. * @return {number}
  27415. */
  27416. listProto.indexOfRawIndex = function (rawIndex) {
  27417. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27418. return -1;
  27419. }
  27420. if (!this._indices) {
  27421. return rawIndex;
  27422. }
  27423. // Indices are ascending
  27424. var indices = this._indices;
  27425. // If rawIndex === dataIndex
  27426. var rawDataIndex = indices[rawIndex];
  27427. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  27428. return rawIndex;
  27429. }
  27430. var left = 0;
  27431. var right = this._count - 1;
  27432. while (left <= right) {
  27433. var mid = (left + right) / 2 | 0;
  27434. if (indices[mid] < rawIndex) {
  27435. left = mid + 1;
  27436. }
  27437. else if (indices[mid] > rawIndex) {
  27438. right = mid - 1;
  27439. }
  27440. else {
  27441. return mid;
  27442. }
  27443. }
  27444. return -1;
  27445. };
  27446. /**
  27447. * Retreive the index of nearest value
  27448. * @param {string} dim
  27449. * @param {number} value
  27450. * @param {number} [maxDistance=Infinity]
  27451. * @return {Array.<number>} If and only if multiple indices has
  27452. * the same value, they are put to the result.
  27453. */
  27454. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  27455. var storage = this._storage;
  27456. var dimData = storage[dim];
  27457. var nearestIndices = [];
  27458. if (!dimData) {
  27459. return nearestIndices;
  27460. }
  27461. if (maxDistance == null) {
  27462. maxDistance = Infinity;
  27463. }
  27464. var minDist = Infinity;
  27465. var minDiff = -1;
  27466. var nearestIndicesLen = 0;
  27467. // Check the test case of `test/ut/spec/data/List.js`.
  27468. for (var i = 0, len = this.count(); i < len; i++) {
  27469. var diff = value - this.get(dim, i);
  27470. var dist = Math.abs(diff);
  27471. if (dist <= maxDistance) {
  27472. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27473. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27474. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27475. // So we chose the one that `diff >= 0` in this csae.
  27476. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27477. // should be push to `nearestIndices`.
  27478. if (dist < minDist
  27479. || (dist === minDist && diff >= 0 && minDiff < 0)
  27480. ) {
  27481. minDist = dist;
  27482. minDiff = diff;
  27483. nearestIndicesLen = 0;
  27484. }
  27485. if (diff === minDiff) {
  27486. nearestIndices[nearestIndicesLen++] = i;
  27487. }
  27488. }
  27489. }
  27490. nearestIndices.length = nearestIndicesLen;
  27491. return nearestIndices;
  27492. };
  27493. /**
  27494. * Get raw data index
  27495. * @param {number} idx
  27496. * @return {number}
  27497. */
  27498. listProto.getRawIndex = getRawIndexWithoutIndices;
  27499. function getRawIndexWithoutIndices(idx) {
  27500. return idx;
  27501. }
  27502. function getRawIndexWithIndices(idx) {
  27503. if (idx < this._count && idx >= 0) {
  27504. return this._indices[idx];
  27505. }
  27506. return -1;
  27507. }
  27508. /**
  27509. * Get raw data item
  27510. * @param {number} idx
  27511. * @return {number}
  27512. */
  27513. listProto.getRawDataItem = function (idx) {
  27514. if (!this._rawData.persistent) {
  27515. var val = [];
  27516. for (var i = 0; i < this.dimensions.length; i++) {
  27517. var dim = this.dimensions[i];
  27518. val.push(this.get(dim, idx));
  27519. }
  27520. return val;
  27521. }
  27522. else {
  27523. return this._rawData.getItem(this.getRawIndex(idx));
  27524. }
  27525. };
  27526. /**
  27527. * @param {number} idx
  27528. * @param {boolean} [notDefaultIdx=false]
  27529. * @return {string}
  27530. */
  27531. listProto.getName = function (idx) {
  27532. var rawIndex = this.getRawIndex(idx);
  27533. return this._nameList[rawIndex]
  27534. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  27535. || '';
  27536. };
  27537. /**
  27538. * @param {number} idx
  27539. * @param {boolean} [notDefaultIdx=false]
  27540. * @return {string}
  27541. */
  27542. listProto.getId = function (idx) {
  27543. return getId(this, this.getRawIndex(idx));
  27544. };
  27545. function getId(list, rawIndex) {
  27546. var id = list._idList[rawIndex];
  27547. if (id == null) {
  27548. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  27549. }
  27550. if (id == null) {
  27551. // FIXME Check the usage in graph, should not use prefix.
  27552. id = ID_PREFIX + rawIndex;
  27553. }
  27554. return id;
  27555. }
  27556. function normalizeDimensions(dimensions) {
  27557. if (!isArray(dimensions)) {
  27558. dimensions = [dimensions];
  27559. }
  27560. return dimensions;
  27561. }
  27562. function validateDimensions(list, dims) {
  27563. for (var i = 0; i < dims.length; i++) {
  27564. // stroage may be empty when no data, so use
  27565. // dimensionInfos to check.
  27566. if (!list._dimensionInfos[dims[i]]) {
  27567. console.error('Unkown dimension ' + dims[i]);
  27568. }
  27569. }
  27570. }
  27571. /**
  27572. * Data iteration
  27573. * @param {string|Array.<string>}
  27574. * @param {Function} cb
  27575. * @param {*} [context=this]
  27576. *
  27577. * @example
  27578. * list.each('x', function (x, idx) {});
  27579. * list.each(['x', 'y'], function (x, y, idx) {});
  27580. * list.each(function (idx) {})
  27581. */
  27582. listProto.each = function (dims, cb, context, contextCompat) {
  27583. 'use strict';
  27584. if (!this._count) {
  27585. return;
  27586. }
  27587. if (typeof dims === 'function') {
  27588. contextCompat = context;
  27589. context = cb;
  27590. cb = dims;
  27591. dims = [];
  27592. }
  27593. // contextCompat just for compat echarts3
  27594. context = context || contextCompat || this;
  27595. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27596. if (__DEV__) {
  27597. validateDimensions(this, dims);
  27598. }
  27599. var dimSize = dims.length;
  27600. for (var i = 0; i < this.count(); i++) {
  27601. // Simple optimization
  27602. switch (dimSize) {
  27603. case 0:
  27604. cb.call(context, i);
  27605. break;
  27606. case 1:
  27607. cb.call(context, this.get(dims[0], i), i);
  27608. break;
  27609. case 2:
  27610. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27611. break;
  27612. default:
  27613. var k = 0;
  27614. var value = [];
  27615. for (; k < dimSize; k++) {
  27616. value[k] = this.get(dims[k], i);
  27617. }
  27618. // Index
  27619. value[k] = i;
  27620. cb.apply(context, value);
  27621. }
  27622. }
  27623. };
  27624. /**
  27625. * Data filter
  27626. * @param {string|Array.<string>}
  27627. * @param {Function} cb
  27628. * @param {*} [context=this]
  27629. */
  27630. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27631. 'use strict';
  27632. if (!this._count) {
  27633. return;
  27634. }
  27635. if (typeof dimensions === 'function') {
  27636. contextCompat = context;
  27637. context = cb;
  27638. cb = dimensions;
  27639. dimensions = [];
  27640. }
  27641. // contextCompat just for compat echarts3
  27642. context = context || contextCompat || this;
  27643. dimensions = map(
  27644. normalizeDimensions(dimensions), this.getDimension, this
  27645. );
  27646. if (__DEV__) {
  27647. validateDimensions(this, dimensions);
  27648. }
  27649. var count = this.count();
  27650. var Ctor = getIndicesCtor(this);
  27651. var newIndices = new Ctor(count);
  27652. var value = [];
  27653. var dimSize = dimensions.length;
  27654. var offset = 0;
  27655. var dim0 = dimensions[0];
  27656. for (var i = 0; i < count; i++) {
  27657. var keep;
  27658. var rawIdx = this.getRawIndex(i);
  27659. // Simple optimization
  27660. if (dimSize === 0) {
  27661. keep = cb.call(context, i);
  27662. }
  27663. else if (dimSize === 1) {
  27664. var val = this._getFast(dim0, rawIdx);
  27665. keep = cb.call(context, val, i);
  27666. }
  27667. else {
  27668. for (var k = 0; k < dimSize; k++) {
  27669. value[k] = this._getFast(dim0, rawIdx);
  27670. }
  27671. value[k] = i;
  27672. keep = cb.apply(context, value);
  27673. }
  27674. if (keep) {
  27675. newIndices[offset++] = rawIdx;
  27676. }
  27677. }
  27678. // Set indices after filtered.
  27679. if (offset < count) {
  27680. this._indices = newIndices;
  27681. }
  27682. this._count = offset;
  27683. // Reset data extent
  27684. this._extent = {};
  27685. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27686. return this;
  27687. };
  27688. /**
  27689. * Select data in range. (For optimization of filter)
  27690. * (Manually inline code, support 5 million data filtering in data zoom.)
  27691. */
  27692. listProto.selectRange = function (range) {
  27693. 'use strict';
  27694. if (!this._count) {
  27695. return;
  27696. }
  27697. var dimensions = [];
  27698. for (var dim in range) {
  27699. if (range.hasOwnProperty(dim)) {
  27700. dimensions.push(dim);
  27701. }
  27702. }
  27703. if (__DEV__) {
  27704. validateDimensions(this, dimensions);
  27705. }
  27706. var dimSize = dimensions.length;
  27707. if (!dimSize) {
  27708. return;
  27709. }
  27710. var originalCount = this.count();
  27711. var Ctor = getIndicesCtor(this);
  27712. var newIndices = new Ctor(originalCount);
  27713. var offset = 0;
  27714. var dim0 = dimensions[0];
  27715. var min = range[dim0][0];
  27716. var max = range[dim0][1];
  27717. var quickFinished = false;
  27718. if (!this._indices) {
  27719. // Extreme optimization for common case. About 2x faster in chrome.
  27720. var idx = 0;
  27721. if (dimSize === 1) {
  27722. var dimStorage = this._storage[dimensions[0]];
  27723. for (var k = 0; k < this._chunkCount; k++) {
  27724. var chunkStorage = dimStorage[k];
  27725. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27726. for (var i = 0; i < len; i++) {
  27727. var val = chunkStorage[i];
  27728. // NaN will not be filtered. Consider the case, in line chart, empty
  27729. // value indicates the line should be broken. But for the case like
  27730. // scatter plot, a data item with empty value will not be rendered,
  27731. // but the axis extent may be effected if some other dim of the data
  27732. // item has value. Fortunately it is not a significant negative effect.
  27733. if (
  27734. (val >= min && val <= max) || isNaN(val)
  27735. ) {
  27736. newIndices[offset++] = idx;
  27737. }
  27738. idx++;
  27739. }
  27740. }
  27741. quickFinished = true;
  27742. }
  27743. else if (dimSize === 2) {
  27744. var dimStorage = this._storage[dim0];
  27745. var dimStorage2 = this._storage[dimensions[1]];
  27746. var min2 = range[dimensions[1]][0];
  27747. var max2 = range[dimensions[1]][1];
  27748. for (var k = 0; k < this._chunkCount; k++) {
  27749. var chunkStorage = dimStorage[k];
  27750. var chunkStorage2 = dimStorage2[k];
  27751. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27752. for (var i = 0; i < len; i++) {
  27753. var val = chunkStorage[i];
  27754. var val2 = chunkStorage2[i];
  27755. // Do not filter NaN, see comment above.
  27756. if ((
  27757. (val >= min && val <= max) || isNaN(val)
  27758. )
  27759. && (
  27760. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  27761. )
  27762. ) {
  27763. newIndices[offset++] = idx;
  27764. }
  27765. idx++;
  27766. }
  27767. }
  27768. quickFinished = true;
  27769. }
  27770. }
  27771. if (!quickFinished) {
  27772. if (dimSize === 1) {
  27773. for (var i = 0; i < originalCount; i++) {
  27774. var rawIndex = this.getRawIndex(i);
  27775. var val = this._getFast(dim0, rawIndex);
  27776. // Do not filter NaN, see comment above.
  27777. if (
  27778. (val >= min && val <= max) || isNaN(val)
  27779. ) {
  27780. newIndices[offset++] = rawIndex;
  27781. }
  27782. }
  27783. }
  27784. else {
  27785. for (var i = 0; i < originalCount; i++) {
  27786. var keep = true;
  27787. var rawIndex = this.getRawIndex(i);
  27788. for (var k = 0; k < dimSize; k++) {
  27789. var dimk = dimensions[k];
  27790. var val = this._getFast(dim, rawIndex);
  27791. // Do not filter NaN, see comment above.
  27792. if (val < range[dimk][0] || val > range[dimk][1]) {
  27793. keep = false;
  27794. }
  27795. }
  27796. if (keep) {
  27797. newIndices[offset++] = this.getRawIndex(i);
  27798. }
  27799. }
  27800. }
  27801. }
  27802. // Set indices after filtered.
  27803. if (offset < originalCount) {
  27804. this._indices = newIndices;
  27805. }
  27806. this._count = offset;
  27807. // Reset data extent
  27808. this._extent = {};
  27809. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27810. return this;
  27811. };
  27812. /**
  27813. * Data mapping to a plain array
  27814. * @param {string|Array.<string>} [dimensions]
  27815. * @param {Function} cb
  27816. * @param {*} [context=this]
  27817. * @return {Array}
  27818. */
  27819. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  27820. 'use strict';
  27821. if (typeof dimensions === 'function') {
  27822. contextCompat = context;
  27823. context = cb;
  27824. cb = dimensions;
  27825. dimensions = [];
  27826. }
  27827. // contextCompat just for compat echarts3
  27828. context = context || contextCompat || this;
  27829. var result = [];
  27830. this.each(dimensions, function () {
  27831. result.push(cb && cb.apply(this, arguments));
  27832. }, context);
  27833. return result;
  27834. };
  27835. // Data in excludeDimensions is copied, otherwise transfered.
  27836. function cloneListForMapAndSample(original, excludeDimensions) {
  27837. var allDimensions = original.dimensions;
  27838. var list = new List(
  27839. map(allDimensions, original.getDimensionInfo, original),
  27840. original.hostModel
  27841. );
  27842. // FIXME If needs stackedOn, value may already been stacked
  27843. transferProperties(list, original);
  27844. var storage = list._storage = {};
  27845. var originalStorage = original._storage;
  27846. // Init storage
  27847. for (var i = 0; i < allDimensions.length; i++) {
  27848. var dim = allDimensions[i];
  27849. if (originalStorage[dim]) {
  27850. // Notice that we do not reset invertedIndicesMap here, becuase
  27851. // there is no scenario of mapping or sampling ordinal dimension.
  27852. if (indexOf(excludeDimensions, dim) >= 0) {
  27853. storage[dim] = cloneDimStore(originalStorage[dim]);
  27854. list._rawExtent[dim] = getInitialExtent();
  27855. list._extent[dim] = null;
  27856. }
  27857. else {
  27858. // Direct reference for other dimensions
  27859. storage[dim] = originalStorage[dim];
  27860. }
  27861. }
  27862. }
  27863. return list;
  27864. }
  27865. function cloneDimStore(originalDimStore) {
  27866. var newDimStore = new Array(originalDimStore.length);
  27867. for (var j = 0; j < originalDimStore.length; j++) {
  27868. newDimStore[j] = cloneChunk(originalDimStore[j]);
  27869. }
  27870. return newDimStore;
  27871. }
  27872. function getInitialExtent() {
  27873. return [Infinity, -Infinity];
  27874. }
  27875. /**
  27876. * Data mapping to a new List with given dimensions
  27877. * @param {string|Array.<string>} dimensions
  27878. * @param {Function} cb
  27879. * @param {*} [context=this]
  27880. * @return {Array}
  27881. */
  27882. listProto.map = function (dimensions, cb, context, contextCompat) {
  27883. 'use strict';
  27884. // contextCompat just for compat echarts3
  27885. context = context || contextCompat || this;
  27886. dimensions = map(
  27887. normalizeDimensions(dimensions), this.getDimension, this
  27888. );
  27889. if (__DEV__) {
  27890. validateDimensions(this, dimensions);
  27891. }
  27892. var list = cloneListForMapAndSample(this, dimensions);
  27893. // Following properties are all immutable.
  27894. // So we can reference to the same value
  27895. list._indices = this._indices;
  27896. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27897. var storage = list._storage;
  27898. var tmpRetValue = [];
  27899. var chunkSize = this._chunkSize;
  27900. var dimSize = dimensions.length;
  27901. var dataCount = this.count();
  27902. var values = [];
  27903. var rawExtent = list._rawExtent;
  27904. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  27905. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  27906. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  27907. }
  27908. values[dimSize] = dataIndex;
  27909. var retValue = cb && cb.apply(context, values);
  27910. if (retValue != null) {
  27911. // a number or string (in oridinal dimension)?
  27912. if (typeof retValue !== 'object') {
  27913. tmpRetValue[0] = retValue;
  27914. retValue = tmpRetValue;
  27915. }
  27916. var rawIndex = this.getRawIndex(dataIndex);
  27917. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27918. var chunkOffset = rawIndex % chunkSize;
  27919. for (var i = 0; i < retValue.length; i++) {
  27920. var dim = dimensions[i];
  27921. var val = retValue[i];
  27922. var rawExtentOnDim = rawExtent[dim];
  27923. var dimStore = storage[dim];
  27924. if (dimStore) {
  27925. dimStore[chunkIndex][chunkOffset] = val;
  27926. }
  27927. if (val < rawExtentOnDim[0]) {
  27928. rawExtentOnDim[0] = val;
  27929. }
  27930. if (val > rawExtentOnDim[1]) {
  27931. rawExtentOnDim[1] = val;
  27932. }
  27933. }
  27934. }
  27935. }
  27936. return list;
  27937. };
  27938. /**
  27939. * Large data down sampling on given dimension
  27940. * @param {string} dimension
  27941. * @param {number} rate
  27942. * @param {Function} sampleValue
  27943. * @param {Function} sampleIndex Sample index for name and id
  27944. */
  27945. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  27946. var list = cloneListForMapAndSample(this, [dimension]);
  27947. var targetStorage = list._storage;
  27948. var frameValues = [];
  27949. var frameSize = Math.floor(1 / rate);
  27950. var dimStore = targetStorage[dimension];
  27951. var len = this.count();
  27952. var chunkSize = this._chunkSize;
  27953. var rawExtentOnDim = list._rawExtent[dimension];
  27954. var newIndices = new (getIndicesCtor(this))(len);
  27955. var offset = 0;
  27956. for (var i = 0; i < len; i += frameSize) {
  27957. // Last frame
  27958. if (frameSize > len - i) {
  27959. frameSize = len - i;
  27960. frameValues.length = frameSize;
  27961. }
  27962. for (var k = 0; k < frameSize; k++) {
  27963. var dataIdx = this.getRawIndex(i + k);
  27964. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  27965. var originalChunkOffset = dataIdx % chunkSize;
  27966. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  27967. }
  27968. var value = sampleValue(frameValues);
  27969. var sampleFrameIdx = this.getRawIndex(
  27970. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  27971. );
  27972. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  27973. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  27974. // Only write value on the filtered data
  27975. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  27976. if (value < rawExtentOnDim[0]) {
  27977. rawExtentOnDim[0] = value;
  27978. }
  27979. if (value > rawExtentOnDim[1]) {
  27980. rawExtentOnDim[1] = value;
  27981. }
  27982. newIndices[offset++] = sampleFrameIdx;
  27983. }
  27984. list._count = offset;
  27985. list._indices = newIndices;
  27986. list.getRawIndex = getRawIndexWithIndices;
  27987. return list;
  27988. };
  27989. /**
  27990. * Get model of one data item.
  27991. *
  27992. * @param {number} idx
  27993. */
  27994. // FIXME Model proxy ?
  27995. listProto.getItemModel = function (idx) {
  27996. var hostModel = this.hostModel;
  27997. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  27998. };
  27999. /**
  28000. * Create a data differ
  28001. * @param {module:echarts/data/List} otherList
  28002. * @return {module:echarts/data/DataDiffer}
  28003. */
  28004. listProto.diff = function (otherList) {
  28005. var thisList = this;
  28006. return new DataDiffer(
  28007. otherList ? otherList.getIndices() : [],
  28008. this.getIndices(),
  28009. function (idx) {
  28010. return getId(otherList, idx);
  28011. },
  28012. function (idx) {
  28013. return getId(thisList, idx);
  28014. }
  28015. );
  28016. };
  28017. /**
  28018. * Get visual property.
  28019. * @param {string} key
  28020. */
  28021. listProto.getVisual = function (key) {
  28022. var visual = this._visual;
  28023. return visual && visual[key];
  28024. };
  28025. /**
  28026. * Set visual property
  28027. * @param {string|Object} key
  28028. * @param {*} [value]
  28029. *
  28030. * @example
  28031. * setVisual('color', color);
  28032. * setVisual({
  28033. * 'color': color
  28034. * });
  28035. */
  28036. listProto.setVisual = function (key, val) {
  28037. if (isObject$4(key)) {
  28038. for (var name in key) {
  28039. if (key.hasOwnProperty(name)) {
  28040. this.setVisual(name, key[name]);
  28041. }
  28042. }
  28043. return;
  28044. }
  28045. this._visual = this._visual || {};
  28046. this._visual[key] = val;
  28047. };
  28048. /**
  28049. * Set layout property.
  28050. * @param {string|Object} key
  28051. * @param {*} [val]
  28052. */
  28053. listProto.setLayout = function (key, val) {
  28054. if (isObject$4(key)) {
  28055. for (var name in key) {
  28056. if (key.hasOwnProperty(name)) {
  28057. this.setLayout(name, key[name]);
  28058. }
  28059. }
  28060. return;
  28061. }
  28062. this._layout[key] = val;
  28063. };
  28064. /**
  28065. * Get layout property.
  28066. * @param {string} key.
  28067. * @return {*}
  28068. */
  28069. listProto.getLayout = function (key) {
  28070. return this._layout[key];
  28071. };
  28072. /**
  28073. * Get layout of single data item
  28074. * @param {number} idx
  28075. */
  28076. listProto.getItemLayout = function (idx) {
  28077. return this._itemLayouts[idx];
  28078. };
  28079. /**
  28080. * Set layout of single data item
  28081. * @param {number} idx
  28082. * @param {Object} layout
  28083. * @param {boolean=} [merge=false]
  28084. */
  28085. listProto.setItemLayout = function (idx, layout, merge$$1) {
  28086. this._itemLayouts[idx] = merge$$1
  28087. ? extend(this._itemLayouts[idx] || {}, layout)
  28088. : layout;
  28089. };
  28090. /**
  28091. * Clear all layout of single data item
  28092. */
  28093. listProto.clearItemLayouts = function () {
  28094. this._itemLayouts.length = 0;
  28095. };
  28096. /**
  28097. * Get visual property of single data item
  28098. * @param {number} idx
  28099. * @param {string} key
  28100. * @param {boolean} [ignoreParent=false]
  28101. */
  28102. listProto.getItemVisual = function (idx, key, ignoreParent) {
  28103. var itemVisual = this._itemVisuals[idx];
  28104. var val = itemVisual && itemVisual[key];
  28105. if (val == null && !ignoreParent) {
  28106. // Use global visual property
  28107. return this.getVisual(key);
  28108. }
  28109. return val;
  28110. };
  28111. /**
  28112. * Set visual property of single data item
  28113. *
  28114. * @param {number} idx
  28115. * @param {string|Object} key
  28116. * @param {*} [value]
  28117. *
  28118. * @example
  28119. * setItemVisual(0, 'color', color);
  28120. * setItemVisual(0, {
  28121. * 'color': color
  28122. * });
  28123. */
  28124. listProto.setItemVisual = function (idx, key, value) {
  28125. var itemVisual = this._itemVisuals[idx] || {};
  28126. var hasItemVisual = this.hasItemVisual;
  28127. this._itemVisuals[idx] = itemVisual;
  28128. if (isObject$4(key)) {
  28129. for (var name in key) {
  28130. if (key.hasOwnProperty(name)) {
  28131. itemVisual[name] = key[name];
  28132. hasItemVisual[name] = true;
  28133. }
  28134. }
  28135. return;
  28136. }
  28137. itemVisual[key] = value;
  28138. hasItemVisual[key] = true;
  28139. };
  28140. /**
  28141. * Clear itemVisuals and list visual.
  28142. */
  28143. listProto.clearAllVisual = function () {
  28144. this._visual = {};
  28145. this._itemVisuals = [];
  28146. this.hasItemVisual = {};
  28147. };
  28148. var setItemDataAndSeriesIndex = function (child) {
  28149. child.seriesIndex = this.seriesIndex;
  28150. child.dataIndex = this.dataIndex;
  28151. child.dataType = this.dataType;
  28152. };
  28153. /**
  28154. * Set graphic element relative to data. It can be set as null
  28155. * @param {number} idx
  28156. * @param {module:zrender/Element} [el]
  28157. */
  28158. listProto.setItemGraphicEl = function (idx, el) {
  28159. var hostModel = this.hostModel;
  28160. if (el) {
  28161. // Add data index and series index for indexing the data by element
  28162. // Useful in tooltip
  28163. el.dataIndex = idx;
  28164. el.dataType = this.dataType;
  28165. el.seriesIndex = hostModel && hostModel.seriesIndex;
  28166. if (el.type === 'group') {
  28167. el.traverse(setItemDataAndSeriesIndex, el);
  28168. }
  28169. }
  28170. this._graphicEls[idx] = el;
  28171. };
  28172. /**
  28173. * @param {number} idx
  28174. * @return {module:zrender/Element}
  28175. */
  28176. listProto.getItemGraphicEl = function (idx) {
  28177. return this._graphicEls[idx];
  28178. };
  28179. /**
  28180. * @param {Function} cb
  28181. * @param {*} context
  28182. */
  28183. listProto.eachItemGraphicEl = function (cb, context) {
  28184. each$1(this._graphicEls, function (el, idx) {
  28185. if (el) {
  28186. cb && cb.call(context, el, idx);
  28187. }
  28188. });
  28189. };
  28190. /**
  28191. * Shallow clone a new list except visual and layout properties, and graph elements.
  28192. * New list only change the indices.
  28193. */
  28194. listProto.cloneShallow = function (list) {
  28195. if (!list) {
  28196. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  28197. list = new List(dimensionInfoList, this.hostModel);
  28198. }
  28199. // FIXME
  28200. list._storage = this._storage;
  28201. transferProperties(list, this);
  28202. // Clone will not change the data extent and indices
  28203. if (this._indices) {
  28204. var Ctor = this._indices.constructor;
  28205. list._indices = new Ctor(this._indices);
  28206. }
  28207. else {
  28208. list._indices = null;
  28209. }
  28210. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28211. return list;
  28212. };
  28213. /**
  28214. * Wrap some method to add more feature
  28215. * @param {string} methodName
  28216. * @param {Function} injectFunction
  28217. */
  28218. listProto.wrapMethod = function (methodName, injectFunction) {
  28219. var originalMethod = this[methodName];
  28220. if (typeof originalMethod !== 'function') {
  28221. return;
  28222. }
  28223. this.__wrappedMethods = this.__wrappedMethods || [];
  28224. this.__wrappedMethods.push(methodName);
  28225. this[methodName] = function () {
  28226. var res = originalMethod.apply(this, arguments);
  28227. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28228. };
  28229. };
  28230. // Methods that create a new list based on this list should be listed here.
  28231. // Notice that those method should `RETURN` the new list.
  28232. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  28233. // Methods that change indices of this list should be listed here.
  28234. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28235. /*
  28236. * Licensed to the Apache Software Foundation (ASF) under one
  28237. * or more contributor license agreements. See the NOTICE file
  28238. * distributed with this work for additional information
  28239. * regarding copyright ownership. The ASF licenses this file
  28240. * to you under the Apache License, Version 2.0 (the
  28241. * "License"); you may not use this file except in compliance
  28242. * with the License. You may obtain a copy of the License at
  28243. *
  28244. * http://www.apache.org/licenses/LICENSE-2.0
  28245. *
  28246. * Unless required by applicable law or agreed to in writing,
  28247. * software distributed under the License is distributed on an
  28248. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28249. * KIND, either express or implied. See the License for the
  28250. * specific language governing permissions and limitations
  28251. * under the License.
  28252. */
  28253. /**
  28254. * @deprecated
  28255. * Use `echarts/data/helper/createDimensions` instead.
  28256. */
  28257. /**
  28258. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  28259. *
  28260. * This method builds the relationship between:
  28261. * + "what the coord sys or series requires (see `sysDims`)",
  28262. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  28263. * + "what the data source provids (see `source`)".
  28264. *
  28265. * Some guess strategy will be adapted if user does not define something.
  28266. * If no 'value' dimension specified, the first no-named dimension will be
  28267. * named as 'value'.
  28268. *
  28269. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  28270. * provides not only dim template, but also default order.
  28271. * properties: 'name', 'type', 'displayName'.
  28272. * `name` of each item provides default coord name.
  28273. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  28274. * provide dims count that the sysDim required.
  28275. * [{ordinalMeta}] can be specified.
  28276. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  28277. * @param {Object} [opt]
  28278. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  28279. * For example: ['asdf', {name, type}, ...].
  28280. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  28281. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  28282. * If not specified, auto find the next available data dim.
  28283. * param source {module:data/Source}
  28284. * param dimCount {number}
  28285. * return {Object} encode Never be `null/undefined`.
  28286. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  28287. * If not specified, extra dim names will be:
  28288. * 'value', 'value0', 'value1', ...
  28289. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  28290. * If `generateCoordCount` specified, the generated dim names will be:
  28291. * `generateCoord` + 0, `generateCoord` + 1, ...
  28292. * can be Infinity, indicate that use all of the remain columns.
  28293. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  28294. * @return {Array.<module:data/DataDimensionInfo>}
  28295. */
  28296. function completeDimensions(sysDims, source, opt) {
  28297. if (!Source.isInstance(source)) {
  28298. source = Source.seriesDataToSource(source);
  28299. }
  28300. opt = opt || {};
  28301. sysDims = (sysDims || []).slice();
  28302. var dimsDef = (opt.dimsDef || []).slice();
  28303. var dataDimNameMap = createHashMap();
  28304. var coordDimNameMap = createHashMap();
  28305. // var valueCandidate;
  28306. var result = [];
  28307. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  28308. // Apply user defined dims (`name` and `type`) and init result.
  28309. for (var i = 0; i < dimCount; i++) {
  28310. var dimDefItem = dimsDef[i] = extend(
  28311. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  28312. );
  28313. var userDimName = dimDefItem.name;
  28314. var resultItem = result[i] = new DataDimensionInfo();
  28315. // Name will be applied later for avoiding duplication.
  28316. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28317. // Only if `series.dimensions` is defined in option
  28318. // displayName, will be set, and dimension will be diplayed vertically in
  28319. // tooltip by default.
  28320. resultItem.name = resultItem.displayName = userDimName;
  28321. dataDimNameMap.set(userDimName, i);
  28322. }
  28323. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28324. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28325. }
  28326. var encodeDef = opt.encodeDef;
  28327. if (!encodeDef && opt.encodeDefaulter) {
  28328. encodeDef = opt.encodeDefaulter(source, dimCount);
  28329. }
  28330. encodeDef = createHashMap(encodeDef);
  28331. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  28332. encodeDef.each(function (dataDims, coordDim) {
  28333. dataDims = normalizeToArray(dataDims).slice();
  28334. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28335. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28336. // this case.
  28337. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28338. encodeDef.set(coordDim, false);
  28339. return;
  28340. }
  28341. var validDataDims = encodeDef.set(coordDim, []);
  28342. each$1(dataDims, function (resultDimIdx, idx) {
  28343. // The input resultDimIdx can be dim name or index.
  28344. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  28345. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28346. validDataDims[idx] = resultDimIdx;
  28347. applyDim(result[resultDimIdx], coordDim, idx);
  28348. }
  28349. });
  28350. });
  28351. // Apply templetes and default order from `sysDims`.
  28352. var availDimIdx = 0;
  28353. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  28354. var coordDim;
  28355. var sysDimItem;
  28356. var sysDimItemDimsDef;
  28357. var sysDimItemOtherDims;
  28358. if (isString(sysDimItem)) {
  28359. coordDim = sysDimItem;
  28360. sysDimItem = {};
  28361. }
  28362. else {
  28363. coordDim = sysDimItem.name;
  28364. var ordinalMeta = sysDimItem.ordinalMeta;
  28365. sysDimItem.ordinalMeta = null;
  28366. sysDimItem = clone(sysDimItem);
  28367. sysDimItem.ordinalMeta = ordinalMeta;
  28368. // `coordDimIndex` should not be set directly.
  28369. sysDimItemDimsDef = sysDimItem.dimsDef;
  28370. sysDimItemOtherDims = sysDimItem.otherDims;
  28371. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  28372. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28373. }
  28374. var dataDims = encodeDef.get(coordDim);
  28375. // negative resultDimIdx means no need to mapping.
  28376. if (dataDims === false) {
  28377. return;
  28378. }
  28379. var dataDims = normalizeToArray(dataDims);
  28380. // dimensions provides default dim sequences.
  28381. if (!dataDims.length) {
  28382. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28383. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  28384. availDimIdx++;
  28385. }
  28386. availDimIdx < result.length && dataDims.push(availDimIdx++);
  28387. }
  28388. }
  28389. // Apply templates.
  28390. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  28391. var resultItem = result[resultDimIdx];
  28392. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28393. if (resultItem.name == null && sysDimItemDimsDef) {
  28394. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28395. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  28396. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28397. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28398. }
  28399. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28400. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28401. });
  28402. });
  28403. function applyDim(resultItem, coordDim, coordDimIndex) {
  28404. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  28405. resultItem.otherDims[coordDim] = coordDimIndex;
  28406. }
  28407. else {
  28408. resultItem.coordDim = coordDim;
  28409. resultItem.coordDimIndex = coordDimIndex;
  28410. coordDimNameMap.set(coordDim, true);
  28411. }
  28412. }
  28413. // Make sure the first extra dim is 'value'.
  28414. var generateCoord = opt.generateCoord;
  28415. var generateCoordCount = opt.generateCoordCount;
  28416. var fromZero = generateCoordCount != null;
  28417. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  28418. var extra = generateCoord || 'value';
  28419. // Set dim `name` and other `coordDim` and other props.
  28420. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28421. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  28422. var coordDim = resultItem.coordDim;
  28423. if (coordDim == null) {
  28424. resultItem.coordDim = genName(
  28425. extra, coordDimNameMap, fromZero
  28426. );
  28427. resultItem.coordDimIndex = 0;
  28428. if (!generateCoord || generateCoordCount <= 0) {
  28429. resultItem.isExtraCoord = true;
  28430. }
  28431. generateCoordCount--;
  28432. }
  28433. resultItem.name == null && (resultItem.name = genName(
  28434. resultItem.coordDim,
  28435. dataDimNameMap
  28436. ));
  28437. if (resultItem.type == null
  28438. && (
  28439. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  28440. // Consider the case:
  28441. // {
  28442. // dataset: {source: [
  28443. // ['2001', 123],
  28444. // ['2002', 456],
  28445. // ...
  28446. // ['The others', 987],
  28447. // ]},
  28448. // series: {type: 'pie'}
  28449. // }
  28450. // The first colum should better be treated as a "ordinal" although it
  28451. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28452. || (resultItem.isExtraCoord
  28453. && (resultItem.otherDims.itemName != null
  28454. || resultItem.otherDims.seriesName != null
  28455. )
  28456. )
  28457. )
  28458. ) {
  28459. resultItem.type = 'ordinal';
  28460. }
  28461. }
  28462. return result;
  28463. }
  28464. // ??? TODO
  28465. // Originally detect dimCount by data[0]. Should we
  28466. // optimize it to only by sysDims and dimensions and encode.
  28467. // So only necessary dims will be initialized.
  28468. // But
  28469. // (1) custom series should be considered. where other dims
  28470. // may be visited.
  28471. // (2) sometimes user need to calcualte bubble size or use visualMap
  28472. // on other dimensions besides coordSys needed.
  28473. // So, dims that is not used by system, should be shared in storage?
  28474. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28475. // Note that the result dimCount should not small than columns count
  28476. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28477. var dimCount = Math.max(
  28478. source.dimensionsDetectCount || 1,
  28479. sysDims.length,
  28480. dimsDef.length,
  28481. optDimCount || 0
  28482. );
  28483. each$1(sysDims, function (sysDimItem) {
  28484. var sysDimItemDimsDef = sysDimItem.dimsDef;
  28485. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  28486. });
  28487. return dimCount;
  28488. }
  28489. function genName(name, map$$1, fromZero) {
  28490. if (fromZero || map$$1.get(name) != null) {
  28491. var i = 0;
  28492. while (map$$1.get(name + i) != null) {
  28493. i++;
  28494. }
  28495. name += i;
  28496. }
  28497. map$$1.set(name, true);
  28498. return name;
  28499. }
  28500. /*
  28501. * Licensed to the Apache Software Foundation (ASF) under one
  28502. * or more contributor license agreements. See the NOTICE file
  28503. * distributed with this work for additional information
  28504. * regarding copyright ownership. The ASF licenses this file
  28505. * to you under the Apache License, Version 2.0 (the
  28506. * "License"); you may not use this file except in compliance
  28507. * with the License. You may obtain a copy of the License at
  28508. *
  28509. * http://www.apache.org/licenses/LICENSE-2.0
  28510. *
  28511. * Unless required by applicable law or agreed to in writing,
  28512. * software distributed under the License is distributed on an
  28513. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28514. * KIND, either express or implied. See the License for the
  28515. * specific language governing permissions and limitations
  28516. * under the License.
  28517. */
  28518. /**
  28519. * Substitute `completeDimensions`.
  28520. * `completeDimensions` is to be deprecated.
  28521. */
  28522. /**
  28523. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  28524. * @param {Object|Array} [opt]
  28525. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  28526. * @param {number} [opt.dimensionsCount]
  28527. * @param {string} [opt.generateCoord]
  28528. * @param {string} [opt.generateCoordCount]
  28529. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  28530. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  28531. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  28532. * @return {Array.<Object>} dimensionsInfo
  28533. */
  28534. var createDimensions = function (source, opt) {
  28535. opt = opt || {};
  28536. return completeDimensions(opt.coordDimensions || [], source, {
  28537. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28538. encodeDef: opt.encodeDefine || source.encodeDefine,
  28539. dimCount: opt.dimensionsCount,
  28540. encodeDefaulter: opt.encodeDefaulter,
  28541. generateCoord: opt.generateCoord,
  28542. generateCoordCount: opt.generateCoordCount
  28543. });
  28544. };
  28545. /*
  28546. * Licensed to the Apache Software Foundation (ASF) under one
  28547. * or more contributor license agreements. See the NOTICE file
  28548. * distributed with this work for additional information
  28549. * regarding copyright ownership. The ASF licenses this file
  28550. * to you under the Apache License, Version 2.0 (the
  28551. * "License"); you may not use this file except in compliance
  28552. * with the License. You may obtain a copy of the License at
  28553. *
  28554. * http://www.apache.org/licenses/LICENSE-2.0
  28555. *
  28556. * Unless required by applicable law or agreed to in writing,
  28557. * software distributed under the License is distributed on an
  28558. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28559. * KIND, either express or implied. See the License for the
  28560. * specific language governing permissions and limitations
  28561. * under the License.
  28562. */
  28563. /**
  28564. * Helper for model references.
  28565. * There are many manners to refer axis/coordSys.
  28566. */
  28567. // TODO
  28568. // merge relevant logic to this file?
  28569. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28570. /**
  28571. * @class
  28572. * For example:
  28573. * {
  28574. * coordSysName: 'cartesian2d',
  28575. * coordSysDims: ['x', 'y', ...],
  28576. * axisMap: HashMap({
  28577. * x: xAxisModel,
  28578. * y: yAxisModel
  28579. * }),
  28580. * categoryAxisMap: HashMap({
  28581. * x: xAxisModel,
  28582. * y: undefined
  28583. * }),
  28584. * // The index of the first category axis in `coordSysDims`.
  28585. * // `null/undefined` means no category axis exists.
  28586. * firstCategoryDimIndex: 1,
  28587. * // To replace user specified encode.
  28588. * }
  28589. */
  28590. function CoordSysInfo(coordSysName) {
  28591. /**
  28592. * @type {string}
  28593. */
  28594. this.coordSysName = coordSysName;
  28595. /**
  28596. * @type {Array.<string>}
  28597. */
  28598. this.coordSysDims = [];
  28599. /**
  28600. * @type {module:zrender/core/util#HashMap}
  28601. */
  28602. this.axisMap = createHashMap();
  28603. /**
  28604. * @type {module:zrender/core/util#HashMap}
  28605. */
  28606. this.categoryAxisMap = createHashMap();
  28607. /**
  28608. * @type {number}
  28609. */
  28610. this.firstCategoryDimIndex = null;
  28611. }
  28612. /**
  28613. * @return {module:model/referHelper#CoordSysInfo}
  28614. */
  28615. function getCoordSysInfoBySeries(seriesModel) {
  28616. var coordSysName = seriesModel.get('coordinateSystem');
  28617. var result = new CoordSysInfo(coordSysName);
  28618. var fetch = fetchers[coordSysName];
  28619. if (fetch) {
  28620. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28621. return result;
  28622. }
  28623. }
  28624. var fetchers = {
  28625. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28626. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28627. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28628. if (__DEV__) {
  28629. if (!xAxisModel) {
  28630. throw new Error('xAxis "' + retrieve(
  28631. seriesModel.get('xAxisIndex'),
  28632. seriesModel.get('xAxisId'),
  28633. 0
  28634. ) + '" not found');
  28635. }
  28636. if (!yAxisModel) {
  28637. throw new Error('yAxis "' + retrieve(
  28638. seriesModel.get('xAxisIndex'),
  28639. seriesModel.get('yAxisId'),
  28640. 0
  28641. ) + '" not found');
  28642. }
  28643. }
  28644. result.coordSysDims = ['x', 'y'];
  28645. axisMap.set('x', xAxisModel);
  28646. axisMap.set('y', yAxisModel);
  28647. if (isCategory(xAxisModel)) {
  28648. categoryAxisMap.set('x', xAxisModel);
  28649. result.firstCategoryDimIndex = 0;
  28650. }
  28651. if (isCategory(yAxisModel)) {
  28652. categoryAxisMap.set('y', yAxisModel);
  28653. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28654. }
  28655. },
  28656. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28657. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28658. if (__DEV__) {
  28659. if (!singleAxisModel) {
  28660. throw new Error('singleAxis should be specified.');
  28661. }
  28662. }
  28663. result.coordSysDims = ['single'];
  28664. axisMap.set('single', singleAxisModel);
  28665. if (isCategory(singleAxisModel)) {
  28666. categoryAxisMap.set('single', singleAxisModel);
  28667. result.firstCategoryDimIndex = 0;
  28668. }
  28669. },
  28670. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28671. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28672. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28673. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28674. if (__DEV__) {
  28675. if (!angleAxisModel) {
  28676. throw new Error('angleAxis option not found');
  28677. }
  28678. if (!radiusAxisModel) {
  28679. throw new Error('radiusAxis option not found');
  28680. }
  28681. }
  28682. result.coordSysDims = ['radius', 'angle'];
  28683. axisMap.set('radius', radiusAxisModel);
  28684. axisMap.set('angle', angleAxisModel);
  28685. if (isCategory(radiusAxisModel)) {
  28686. categoryAxisMap.set('radius', radiusAxisModel);
  28687. result.firstCategoryDimIndex = 0;
  28688. }
  28689. if (isCategory(angleAxisModel)) {
  28690. categoryAxisMap.set('angle', angleAxisModel);
  28691. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28692. }
  28693. },
  28694. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28695. result.coordSysDims = ['lng', 'lat'];
  28696. },
  28697. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28698. var ecModel = seriesModel.ecModel;
  28699. var parallelModel = ecModel.getComponent(
  28700. 'parallel', seriesModel.get('parallelIndex')
  28701. );
  28702. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28703. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28704. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28705. var axisDim = coordSysDims[index];
  28706. axisMap.set(axisDim, axisModel);
  28707. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28708. categoryAxisMap.set(axisDim, axisModel);
  28709. result.firstCategoryDimIndex = index;
  28710. }
  28711. });
  28712. }
  28713. };
  28714. function isCategory(axisModel) {
  28715. return axisModel.get('type') === 'category';
  28716. }
  28717. /*
  28718. * Licensed to the Apache Software Foundation (ASF) under one
  28719. * or more contributor license agreements. See the NOTICE file
  28720. * distributed with this work for additional information
  28721. * regarding copyright ownership. The ASF licenses this file
  28722. * to you under the Apache License, Version 2.0 (the
  28723. * "License"); you may not use this file except in compliance
  28724. * with the License. You may obtain a copy of the License at
  28725. *
  28726. * http://www.apache.org/licenses/LICENSE-2.0
  28727. *
  28728. * Unless required by applicable law or agreed to in writing,
  28729. * software distributed under the License is distributed on an
  28730. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28731. * KIND, either express or implied. See the License for the
  28732. * specific language governing permissions and limitations
  28733. * under the License.
  28734. */
  28735. /**
  28736. * Note that it is too complicated to support 3d stack by value
  28737. * (have to create two-dimension inverted index), so in 3d case
  28738. * we just support that stacked by index.
  28739. *
  28740. * @param {module:echarts/model/Series} seriesModel
  28741. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  28742. * The input dimensionInfoList will be modified.
  28743. * @param {Object} [opt]
  28744. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  28745. * @param {boolean} [opt.byIndex=false]
  28746. * @return {Object} calculationInfo
  28747. * {
  28748. * stackedDimension: string
  28749. * stackedByDimension: string
  28750. * isStackedByIndex: boolean
  28751. * stackedOverDimension: string
  28752. * stackResultDimension: string
  28753. * }
  28754. */
  28755. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28756. opt = opt || {};
  28757. var byIndex = opt.byIndex;
  28758. var stackedCoordDimension = opt.stackedCoordDimension;
  28759. // Compatibal: when `stack` is set as '', do not stack.
  28760. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28761. var stackedByDimInfo;
  28762. var stackedDimInfo;
  28763. var stackResultDimension;
  28764. var stackedOverDimension;
  28765. each$1(dimensionInfoList, function (dimensionInfo, index) {
  28766. if (isString(dimensionInfo)) {
  28767. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  28768. }
  28769. if (mayStack && !dimensionInfo.isExtraCoord) {
  28770. // Find the first ordinal dimension as the stackedByDimInfo.
  28771. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28772. stackedByDimInfo = dimensionInfo;
  28773. }
  28774. // Find the first stackable dimension as the stackedDimInfo.
  28775. if (!stackedDimInfo
  28776. && dimensionInfo.type !== 'ordinal'
  28777. && dimensionInfo.type !== 'time'
  28778. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  28779. ) {
  28780. stackedDimInfo = dimensionInfo;
  28781. }
  28782. }
  28783. });
  28784. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28785. // Compatible with previous design, value axis (time axis) only stack by index.
  28786. // It may make sense if the user provides elaborately constructed data.
  28787. byIndex = true;
  28788. }
  28789. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28790. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28791. // might not be a good way.
  28792. if (stackedDimInfo) {
  28793. // Use a weird name that not duplicated with other names.
  28794. stackResultDimension = '__\0ecstackresult';
  28795. stackedOverDimension = '__\0ecstackedover';
  28796. // Create inverted index to fast query index by value.
  28797. if (stackedByDimInfo) {
  28798. stackedByDimInfo.createInvertedIndices = true;
  28799. }
  28800. var stackedDimCoordDim = stackedDimInfo.coordDim;
  28801. var stackedDimType = stackedDimInfo.type;
  28802. var stackedDimCoordIndex = 0;
  28803. each$1(dimensionInfoList, function (dimensionInfo) {
  28804. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  28805. stackedDimCoordIndex++;
  28806. }
  28807. });
  28808. dimensionInfoList.push({
  28809. name: stackResultDimension,
  28810. coordDim: stackedDimCoordDim,
  28811. coordDimIndex: stackedDimCoordIndex,
  28812. type: stackedDimType,
  28813. isExtraCoord: true,
  28814. isCalculationCoord: true
  28815. });
  28816. stackedDimCoordIndex++;
  28817. dimensionInfoList.push({
  28818. name: stackedOverDimension,
  28819. // This dimension contains stack base (generally, 0), so do not set it as
  28820. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  28821. coordDim: stackedOverDimension,
  28822. coordDimIndex: stackedDimCoordIndex,
  28823. type: stackedDimType,
  28824. isExtraCoord: true,
  28825. isCalculationCoord: true
  28826. });
  28827. }
  28828. return {
  28829. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  28830. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  28831. isStackedByIndex: byIndex,
  28832. stackedOverDimension: stackedOverDimension,
  28833. stackResultDimension: stackResultDimension
  28834. };
  28835. }
  28836. /**
  28837. * @param {module:echarts/data/List} data
  28838. * @param {string} stackedDim
  28839. */
  28840. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  28841. // Each single series only maps to one pair of axis. So we do not need to
  28842. // check stackByDim, whatever stacked by a dimension or stacked by index.
  28843. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  28844. // && (
  28845. // stackedByDim != null
  28846. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  28847. // : data.getCalculationInfo('isStackedByIndex')
  28848. // );
  28849. }
  28850. /**
  28851. * @param {module:echarts/data/List} data
  28852. * @param {string} targetDim
  28853. * @param {string} [stackedByDim] If not input this parameter, check whether
  28854. * stacked by index.
  28855. * @return {string} dimension
  28856. */
  28857. function getStackedDimension(data, targetDim) {
  28858. return isDimensionStacked(data, targetDim)
  28859. ? data.getCalculationInfo('stackResultDimension')
  28860. : targetDim;
  28861. }
  28862. /*
  28863. * Licensed to the Apache Software Foundation (ASF) under one
  28864. * or more contributor license agreements. See the NOTICE file
  28865. * distributed with this work for additional information
  28866. * regarding copyright ownership. The ASF licenses this file
  28867. * to you under the Apache License, Version 2.0 (the
  28868. * "License"); you may not use this file except in compliance
  28869. * with the License. You may obtain a copy of the License at
  28870. *
  28871. * http://www.apache.org/licenses/LICENSE-2.0
  28872. *
  28873. * Unless required by applicable law or agreed to in writing,
  28874. * software distributed under the License is distributed on an
  28875. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28876. * KIND, either express or implied. See the License for the
  28877. * specific language governing permissions and limitations
  28878. * under the License.
  28879. */
  28880. /**
  28881. * @param {module:echarts/data/Source|Array} source Or raw data.
  28882. * @param {module:echarts/model/Series} seriesModel
  28883. * @param {Object} [opt]
  28884. * @param {string} [opt.generateCoord]
  28885. * @param {boolean} [opt.useEncodeDefaulter]
  28886. */
  28887. function createListFromArray(source, seriesModel, opt) {
  28888. opt = opt || {};
  28889. if (!Source.isInstance(source)) {
  28890. source = Source.seriesDataToSource(source);
  28891. }
  28892. var coordSysName = seriesModel.get('coordinateSystem');
  28893. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  28894. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  28895. var coordSysDimDefs;
  28896. if (coordSysInfo) {
  28897. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  28898. var dimInfo = {name: dim};
  28899. var axisModel = coordSysInfo.axisMap.get(dim);
  28900. if (axisModel) {
  28901. var axisType = axisModel.get('type');
  28902. dimInfo.type = getDimensionTypeByAxis(axisType);
  28903. // dimInfo.stackable = isStackable(axisType);
  28904. }
  28905. return dimInfo;
  28906. });
  28907. }
  28908. if (!coordSysDimDefs) {
  28909. // Get dimensions from registered coordinate system
  28910. coordSysDimDefs = (registeredCoordSys && (
  28911. registeredCoordSys.getDimensionsInfo
  28912. ? registeredCoordSys.getDimensionsInfo()
  28913. : registeredCoordSys.dimensions.slice()
  28914. )) || ['x', 'y'];
  28915. }
  28916. var dimInfoList = createDimensions(source, {
  28917. coordDimensions: coordSysDimDefs,
  28918. generateCoord: opt.generateCoord,
  28919. encodeDefaulter: opt.useEncodeDefaulter
  28920. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  28921. : null
  28922. });
  28923. var firstCategoryDimIndex;
  28924. var hasNameEncode;
  28925. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  28926. var coordDim = dimInfo.coordDim;
  28927. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  28928. if (categoryAxisModel) {
  28929. if (firstCategoryDimIndex == null) {
  28930. firstCategoryDimIndex = dimIndex;
  28931. }
  28932. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  28933. }
  28934. if (dimInfo.otherDims.itemName != null) {
  28935. hasNameEncode = true;
  28936. }
  28937. });
  28938. if (!hasNameEncode && firstCategoryDimIndex != null) {
  28939. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  28940. }
  28941. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  28942. var list = new List(dimInfoList, seriesModel);
  28943. list.setCalculationInfo(stackCalculationInfo);
  28944. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  28945. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  28946. // Use dataIndex as ordinal value in categoryAxis
  28947. return dimIndex === firstCategoryDimIndex
  28948. ? dataIndex
  28949. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  28950. }
  28951. : null;
  28952. list.hasItemOption = false;
  28953. list.initData(source, null, dimValueGetter);
  28954. return list;
  28955. }
  28956. function isNeedCompleteOrdinalData(source) {
  28957. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  28958. var sampleItem = firstDataNotNull(source.data || []);
  28959. return sampleItem != null
  28960. && !isArray(getDataItemValue(sampleItem));
  28961. }
  28962. }
  28963. function firstDataNotNull(data) {
  28964. var i = 0;
  28965. while (i < data.length && data[i] == null) {
  28966. i++;
  28967. }
  28968. return data[i];
  28969. }
  28970. /*
  28971. * Licensed to the Apache Software Foundation (ASF) under one
  28972. * or more contributor license agreements. See the NOTICE file
  28973. * distributed with this work for additional information
  28974. * regarding copyright ownership. The ASF licenses this file
  28975. * to you under the Apache License, Version 2.0 (the
  28976. * "License"); you may not use this file except in compliance
  28977. * with the License. You may obtain a copy of the License at
  28978. *
  28979. * http://www.apache.org/licenses/LICENSE-2.0
  28980. *
  28981. * Unless required by applicable law or agreed to in writing,
  28982. * software distributed under the License is distributed on an
  28983. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28984. * KIND, either express or implied. See the License for the
  28985. * specific language governing permissions and limitations
  28986. * under the License.
  28987. */
  28988. /**
  28989. * // Scale class management
  28990. * @module echarts/scale/Scale
  28991. */
  28992. /**
  28993. * @param {Object} [setting]
  28994. */
  28995. function Scale(setting) {
  28996. this._setting = setting || {};
  28997. /**
  28998. * Extent
  28999. * @type {Array.<number>}
  29000. * @protected
  29001. */
  29002. this._extent = [Infinity, -Infinity];
  29003. /**
  29004. * Step is calculated in adjustExtent
  29005. * @type {Array.<number>}
  29006. * @protected
  29007. */
  29008. this._interval = 0;
  29009. this.init && this.init.apply(this, arguments);
  29010. }
  29011. /**
  29012. * Parse input val to valid inner number.
  29013. * @param {*} val
  29014. * @return {number}
  29015. */
  29016. Scale.prototype.parse = function (val) {
  29017. // Notice: This would be a trap here, If the implementation
  29018. // of this method depends on extent, and this method is used
  29019. // before extent set (like in dataZoom), it would be wrong.
  29020. // Nevertheless, parse does not depend on extent generally.
  29021. return val;
  29022. };
  29023. Scale.prototype.getSetting = function (name) {
  29024. return this._setting[name];
  29025. };
  29026. Scale.prototype.contain = function (val) {
  29027. var extent = this._extent;
  29028. return val >= extent[0] && val <= extent[1];
  29029. };
  29030. /**
  29031. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  29032. * @param {number} val
  29033. * @return {number}
  29034. */
  29035. Scale.prototype.normalize = function (val) {
  29036. var extent = this._extent;
  29037. if (extent[1] === extent[0]) {
  29038. return 0.5;
  29039. }
  29040. return (val - extent[0]) / (extent[1] - extent[0]);
  29041. };
  29042. /**
  29043. * Scale normalized value
  29044. * @param {number} val
  29045. * @return {number}
  29046. */
  29047. Scale.prototype.scale = function (val) {
  29048. var extent = this._extent;
  29049. return val * (extent[1] - extent[0]) + extent[0];
  29050. };
  29051. /**
  29052. * Set extent from data
  29053. * @param {Array.<number>} other
  29054. */
  29055. Scale.prototype.unionExtent = function (other) {
  29056. var extent = this._extent;
  29057. other[0] < extent[0] && (extent[0] = other[0]);
  29058. other[1] > extent[1] && (extent[1] = other[1]);
  29059. // not setExtent because in log axis it may transformed to power
  29060. // this.setExtent(extent[0], extent[1]);
  29061. };
  29062. /**
  29063. * Set extent from data
  29064. * @param {module:echarts/data/List} data
  29065. * @param {string} dim
  29066. */
  29067. Scale.prototype.unionExtentFromData = function (data, dim) {
  29068. this.unionExtent(data.getApproximateExtent(dim));
  29069. };
  29070. /**
  29071. * Get extent
  29072. * @return {Array.<number>}
  29073. */
  29074. Scale.prototype.getExtent = function () {
  29075. return this._extent.slice();
  29076. };
  29077. /**
  29078. * Set extent
  29079. * @param {number} start
  29080. * @param {number} end
  29081. */
  29082. Scale.prototype.setExtent = function (start, end) {
  29083. var thisExtent = this._extent;
  29084. if (!isNaN(start)) {
  29085. thisExtent[0] = start;
  29086. }
  29087. if (!isNaN(end)) {
  29088. thisExtent[1] = end;
  29089. }
  29090. };
  29091. /**
  29092. * When axis extent depends on data and no data exists,
  29093. * axis ticks should not be drawn, which is named 'blank'.
  29094. */
  29095. Scale.prototype.isBlank = function () {
  29096. return this._isBlank;
  29097. },
  29098. /**
  29099. * When axis extent depends on data and no data exists,
  29100. * axis ticks should not be drawn, which is named 'blank'.
  29101. */
  29102. Scale.prototype.setBlank = function (isBlank) {
  29103. this._isBlank = isBlank;
  29104. };
  29105. /**
  29106. * @abstract
  29107. * @param {*} tick
  29108. * @return {string} label of the tick.
  29109. */
  29110. Scale.prototype.getLabel = null;
  29111. enableClassExtend(Scale);
  29112. enableClassManagement(Scale, {
  29113. registerWhenExtend: true
  29114. });
  29115. /*
  29116. * Licensed to the Apache Software Foundation (ASF) under one
  29117. * or more contributor license agreements. See the NOTICE file
  29118. * distributed with this work for additional information
  29119. * regarding copyright ownership. The ASF licenses this file
  29120. * to you under the Apache License, Version 2.0 (the
  29121. * "License"); you may not use this file except in compliance
  29122. * with the License. You may obtain a copy of the License at
  29123. *
  29124. * http://www.apache.org/licenses/LICENSE-2.0
  29125. *
  29126. * Unless required by applicable law or agreed to in writing,
  29127. * software distributed under the License is distributed on an
  29128. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29129. * KIND, either express or implied. See the License for the
  29130. * specific language governing permissions and limitations
  29131. * under the License.
  29132. */
  29133. /**
  29134. * @constructor
  29135. * @param {Object} [opt]
  29136. * @param {Object} [opt.categories=[]]
  29137. * @param {Object} [opt.needCollect=false]
  29138. * @param {Object} [opt.deduplication=false]
  29139. */
  29140. function OrdinalMeta(opt) {
  29141. /**
  29142. * @readOnly
  29143. * @type {Array.<string>}
  29144. */
  29145. this.categories = opt.categories || [];
  29146. /**
  29147. * @private
  29148. * @type {boolean}
  29149. */
  29150. this._needCollect = opt.needCollect;
  29151. /**
  29152. * @private
  29153. * @type {boolean}
  29154. */
  29155. this._deduplication = opt.deduplication;
  29156. /**
  29157. * @private
  29158. * @type {boolean}
  29159. */
  29160. this._map;
  29161. }
  29162. /**
  29163. * @param {module:echarts/model/Model} axisModel
  29164. * @return {module:echarts/data/OrdinalMeta}
  29165. */
  29166. OrdinalMeta.createByAxisModel = function (axisModel) {
  29167. var option = axisModel.option;
  29168. var data = option.data;
  29169. var categories = data && map(data, getName);
  29170. return new OrdinalMeta({
  29171. categories: categories,
  29172. needCollect: !categories,
  29173. // deduplication is default in axis.
  29174. deduplication: option.dedplication !== false
  29175. });
  29176. };
  29177. var proto$1 = OrdinalMeta.prototype;
  29178. /**
  29179. * @param {string} category
  29180. * @return {number} ordinal
  29181. */
  29182. proto$1.getOrdinal = function (category) {
  29183. return getOrCreateMap(this).get(category);
  29184. };
  29185. /**
  29186. * @param {*} category
  29187. * @return {number} The ordinal. If not found, return NaN.
  29188. */
  29189. proto$1.parseAndCollect = function (category) {
  29190. var index;
  29191. var needCollect = this._needCollect;
  29192. // The value of category dim can be the index of the given category set.
  29193. // This feature is only supported when !needCollect, because we should
  29194. // consider a common case: a value is 2017, which is a number but is
  29195. // expected to be tread as a category. This case usually happen in dataset,
  29196. // where it happent to be no need of the index feature.
  29197. if (typeof category !== 'string' && !needCollect) {
  29198. return category;
  29199. }
  29200. // Optimize for the scenario:
  29201. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29202. // data has been ensured not duplicate and is large data.
  29203. // Notice, if a dataset dimension provide categroies, usually echarts
  29204. // should remove duplication except user tell echarts dont do that
  29205. // (set axis.deduplication = false), because echarts do not know whether
  29206. // the values in the category dimension has duplication (consider the
  29207. // parallel-aqi example)
  29208. if (needCollect && !this._deduplication) {
  29209. index = this.categories.length;
  29210. this.categories[index] = category;
  29211. return index;
  29212. }
  29213. var map$$1 = getOrCreateMap(this);
  29214. index = map$$1.get(category);
  29215. if (index == null) {
  29216. if (needCollect) {
  29217. index = this.categories.length;
  29218. this.categories[index] = category;
  29219. map$$1.set(category, index);
  29220. }
  29221. else {
  29222. index = NaN;
  29223. }
  29224. }
  29225. return index;
  29226. };
  29227. // Consider big data, do not create map until needed.
  29228. function getOrCreateMap(ordinalMeta) {
  29229. return ordinalMeta._map || (
  29230. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  29231. );
  29232. }
  29233. function getName(obj) {
  29234. if (isObject$1(obj) && obj.value != null) {
  29235. return obj.value;
  29236. }
  29237. else {
  29238. return obj + '';
  29239. }
  29240. }
  29241. /*
  29242. * Licensed to the Apache Software Foundation (ASF) under one
  29243. * or more contributor license agreements. See the NOTICE file
  29244. * distributed with this work for additional information
  29245. * regarding copyright ownership. The ASF licenses this file
  29246. * to you under the Apache License, Version 2.0 (the
  29247. * "License"); you may not use this file except in compliance
  29248. * with the License. You may obtain a copy of the License at
  29249. *
  29250. * http://www.apache.org/licenses/LICENSE-2.0
  29251. *
  29252. * Unless required by applicable law or agreed to in writing,
  29253. * software distributed under the License is distributed on an
  29254. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29255. * KIND, either express or implied. See the License for the
  29256. * specific language governing permissions and limitations
  29257. * under the License.
  29258. */
  29259. /**
  29260. * Linear continuous scale
  29261. * @module echarts/coord/scale/Ordinal
  29262. *
  29263. * http://en.wikipedia.org/wiki/Level_of_measurement
  29264. */
  29265. // FIXME only one data
  29266. var scaleProto = Scale.prototype;
  29267. var OrdinalScale = Scale.extend({
  29268. type: 'ordinal',
  29269. /**
  29270. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  29271. */
  29272. init: function (ordinalMeta, extent) {
  29273. // Caution: Should not use instanceof, consider ec-extensions using
  29274. // import approach to get OrdinalMeta class.
  29275. if (!ordinalMeta || isArray(ordinalMeta)) {
  29276. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  29277. }
  29278. this._ordinalMeta = ordinalMeta;
  29279. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  29280. },
  29281. parse: function (val) {
  29282. return typeof val === 'string'
  29283. ? this._ordinalMeta.getOrdinal(val)
  29284. // val might be float.
  29285. : Math.round(val);
  29286. },
  29287. contain: function (rank) {
  29288. rank = this.parse(rank);
  29289. return scaleProto.contain.call(this, rank)
  29290. && this._ordinalMeta.categories[rank] != null;
  29291. },
  29292. /**
  29293. * Normalize given rank or name to linear [0, 1]
  29294. * @param {number|string} [val]
  29295. * @return {number}
  29296. */
  29297. normalize: function (val) {
  29298. return scaleProto.normalize.call(this, this.parse(val));
  29299. },
  29300. scale: function (val) {
  29301. return Math.round(scaleProto.scale.call(this, val));
  29302. },
  29303. /**
  29304. * @return {Array}
  29305. */
  29306. getTicks: function () {
  29307. var ticks = [];
  29308. var extent = this._extent;
  29309. var rank = extent[0];
  29310. while (rank <= extent[1]) {
  29311. ticks.push(rank);
  29312. rank++;
  29313. }
  29314. return ticks;
  29315. },
  29316. /**
  29317. * Get item on rank n
  29318. * @param {number} n
  29319. * @return {string}
  29320. */
  29321. getLabel: function (n) {
  29322. if (!this.isBlank()) {
  29323. // Note that if no data, ordinalMeta.categories is an empty array.
  29324. return this._ordinalMeta.categories[n];
  29325. }
  29326. },
  29327. /**
  29328. * @return {number}
  29329. */
  29330. count: function () {
  29331. return this._extent[1] - this._extent[0] + 1;
  29332. },
  29333. /**
  29334. * @override
  29335. */
  29336. unionExtentFromData: function (data, dim) {
  29337. this.unionExtent(data.getApproximateExtent(dim));
  29338. },
  29339. getOrdinalMeta: function () {
  29340. return this._ordinalMeta;
  29341. },
  29342. niceTicks: noop,
  29343. niceExtent: noop
  29344. });
  29345. /**
  29346. * @return {module:echarts/scale/Time}
  29347. */
  29348. OrdinalScale.create = function () {
  29349. return new OrdinalScale();
  29350. };
  29351. /*
  29352. * Licensed to the Apache Software Foundation (ASF) under one
  29353. * or more contributor license agreements. See the NOTICE file
  29354. * distributed with this work for additional information
  29355. * regarding copyright ownership. The ASF licenses this file
  29356. * to you under the Apache License, Version 2.0 (the
  29357. * "License"); you may not use this file except in compliance
  29358. * with the License. You may obtain a copy of the License at
  29359. *
  29360. * http://www.apache.org/licenses/LICENSE-2.0
  29361. *
  29362. * Unless required by applicable law or agreed to in writing,
  29363. * software distributed under the License is distributed on an
  29364. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29365. * KIND, either express or implied. See the License for the
  29366. * specific language governing permissions and limitations
  29367. * under the License.
  29368. */
  29369. /**
  29370. * For testable.
  29371. */
  29372. var roundNumber$1 = round$1;
  29373. /**
  29374. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  29375. * Should be extent[0] < extent[1].
  29376. * @param {number} splitNumber splitNumber should be >= 1.
  29377. * @param {number} [minInterval]
  29378. * @param {number} [maxInterval]
  29379. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  29380. */
  29381. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29382. var result = {};
  29383. var span = extent[1] - extent[0];
  29384. var interval = result.interval = nice(span / splitNumber, true);
  29385. if (minInterval != null && interval < minInterval) {
  29386. interval = result.interval = minInterval;
  29387. }
  29388. if (maxInterval != null && interval > maxInterval) {
  29389. interval = result.interval = maxInterval;
  29390. }
  29391. // Tow more digital for tick.
  29392. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  29393. // Niced extent inside original extent
  29394. var niceTickExtent = result.niceTickExtent = [
  29395. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  29396. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  29397. ];
  29398. fixExtent(niceTickExtent, extent);
  29399. return result;
  29400. }
  29401. /**
  29402. * @param {number} interval
  29403. * @return {number} interval precision
  29404. */
  29405. function getIntervalPrecision(interval) {
  29406. // Tow more digital for tick.
  29407. return getPrecisionSafe(interval) + 2;
  29408. }
  29409. function clamp(niceTickExtent, idx, extent) {
  29410. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29411. }
  29412. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29413. function fixExtent(niceTickExtent, extent) {
  29414. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29415. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29416. clamp(niceTickExtent, 0, extent);
  29417. clamp(niceTickExtent, 1, extent);
  29418. if (niceTickExtent[0] > niceTickExtent[1]) {
  29419. niceTickExtent[0] = niceTickExtent[1];
  29420. }
  29421. }
  29422. /*
  29423. * Licensed to the Apache Software Foundation (ASF) under one
  29424. * or more contributor license agreements. See the NOTICE file
  29425. * distributed with this work for additional information
  29426. * regarding copyright ownership. The ASF licenses this file
  29427. * to you under the Apache License, Version 2.0 (the
  29428. * "License"); you may not use this file except in compliance
  29429. * with the License. You may obtain a copy of the License at
  29430. *
  29431. * http://www.apache.org/licenses/LICENSE-2.0
  29432. *
  29433. * Unless required by applicable law or agreed to in writing,
  29434. * software distributed under the License is distributed on an
  29435. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29436. * KIND, either express or implied. See the License for the
  29437. * specific language governing permissions and limitations
  29438. * under the License.
  29439. */
  29440. /**
  29441. * Interval scale
  29442. * @module echarts/scale/Interval
  29443. */
  29444. var roundNumber = round$1;
  29445. /**
  29446. * @alias module:echarts/coord/scale/Interval
  29447. * @constructor
  29448. */
  29449. var IntervalScale = Scale.extend({
  29450. type: 'interval',
  29451. _interval: 0,
  29452. _intervalPrecision: 2,
  29453. setExtent: function (start, end) {
  29454. var thisExtent = this._extent;
  29455. //start,end may be a Number like '25',so...
  29456. if (!isNaN(start)) {
  29457. thisExtent[0] = parseFloat(start);
  29458. }
  29459. if (!isNaN(end)) {
  29460. thisExtent[1] = parseFloat(end);
  29461. }
  29462. },
  29463. unionExtent: function (other) {
  29464. var extent = this._extent;
  29465. other[0] < extent[0] && (extent[0] = other[0]);
  29466. other[1] > extent[1] && (extent[1] = other[1]);
  29467. // unionExtent may called by it's sub classes
  29468. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  29469. },
  29470. /**
  29471. * Get interval
  29472. */
  29473. getInterval: function () {
  29474. return this._interval;
  29475. },
  29476. /**
  29477. * Set interval
  29478. */
  29479. setInterval: function (interval) {
  29480. this._interval = interval;
  29481. // Dropped auto calculated niceExtent and use user setted extent
  29482. // We assume user wan't to set both interval, min, max to get a better result
  29483. this._niceExtent = this._extent.slice();
  29484. this._intervalPrecision = getIntervalPrecision(interval);
  29485. },
  29486. /**
  29487. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  29488. * @return {Array.<number>}
  29489. */
  29490. getTicks: function (expandToNicedExtent) {
  29491. var interval = this._interval;
  29492. var extent = this._extent;
  29493. var niceTickExtent = this._niceExtent;
  29494. var intervalPrecision = this._intervalPrecision;
  29495. var ticks = [];
  29496. // If interval is 0, return [];
  29497. if (!interval) {
  29498. return ticks;
  29499. }
  29500. // Consider this case: using dataZoom toolbox, zoom and zoom.
  29501. var safeLimit = 10000;
  29502. if (extent[0] < niceTickExtent[0]) {
  29503. if (expandToNicedExtent) {
  29504. ticks.push(roundNumber(niceTickExtent[0] - interval));
  29505. }
  29506. else {
  29507. ticks.push(extent[0]);
  29508. }
  29509. }
  29510. var tick = niceTickExtent[0];
  29511. while (tick <= niceTickExtent[1]) {
  29512. ticks.push(tick);
  29513. // Avoid rounding error
  29514. tick = roundNumber(tick + interval, intervalPrecision);
  29515. if (tick === ticks[ticks.length - 1]) {
  29516. // Consider out of safe float point, e.g.,
  29517. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29518. break;
  29519. }
  29520. if (ticks.length > safeLimit) {
  29521. return [];
  29522. }
  29523. }
  29524. // Consider this case: the last item of ticks is smaller
  29525. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29526. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  29527. if (extent[1] > lastNiceTick) {
  29528. if (expandToNicedExtent) {
  29529. ticks.push(lastNiceTick + interval);
  29530. }
  29531. else {
  29532. ticks.push(extent[1]);
  29533. }
  29534. }
  29535. return ticks;
  29536. },
  29537. /**
  29538. * @param {number} [splitNumber=5]
  29539. * @return {Array.<Array.<number>>}
  29540. */
  29541. getMinorTicks: function (splitNumber) {
  29542. var ticks = this.getTicks(true);
  29543. var minorTicks = [];
  29544. var extent = this.getExtent();
  29545. for (var i = 1; i < ticks.length; i++) {
  29546. var nextTick = ticks[i];
  29547. var prevTick = ticks[i - 1];
  29548. var count = 0;
  29549. var minorTicksGroup = [];
  29550. var interval = nextTick - prevTick;
  29551. var minorInterval = interval / splitNumber;
  29552. while (count < splitNumber - 1) {
  29553. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  29554. // For the first and last interval. The count may be less than splitNumber.
  29555. if (minorTick > extent[0] && minorTick < extent[1]) {
  29556. minorTicksGroup.push(minorTick);
  29557. }
  29558. count++;
  29559. }
  29560. minorTicks.push(minorTicksGroup);
  29561. }
  29562. return minorTicks;
  29563. },
  29564. /**
  29565. * @param {number} data
  29566. * @param {Object} [opt]
  29567. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  29568. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  29569. * @return {string}
  29570. */
  29571. getLabel: function (data, opt) {
  29572. if (data == null) {
  29573. return '';
  29574. }
  29575. var precision = opt && opt.precision;
  29576. if (precision == null) {
  29577. precision = getPrecisionSafe(data) || 0;
  29578. }
  29579. else if (precision === 'auto') {
  29580. // Should be more precise then tick.
  29581. precision = this._intervalPrecision;
  29582. }
  29583. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29584. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29585. data = roundNumber(data, precision, true);
  29586. return addCommas(data);
  29587. },
  29588. /**
  29589. * Update interval and extent of intervals for nice ticks
  29590. *
  29591. * @param {number} [splitNumber = 5] Desired number of ticks
  29592. * @param {number} [minInterval]
  29593. * @param {number} [maxInterval]
  29594. */
  29595. niceTicks: function (splitNumber, minInterval, maxInterval) {
  29596. splitNumber = splitNumber || 5;
  29597. var extent = this._extent;
  29598. var span = extent[1] - extent[0];
  29599. if (!isFinite(span)) {
  29600. return;
  29601. }
  29602. // User may set axis min 0 and data are all negative
  29603. // FIXME If it needs to reverse ?
  29604. if (span < 0) {
  29605. span = -span;
  29606. extent.reverse();
  29607. }
  29608. var result = intervalScaleNiceTicks(
  29609. extent, splitNumber, minInterval, maxInterval
  29610. );
  29611. this._intervalPrecision = result.intervalPrecision;
  29612. this._interval = result.interval;
  29613. this._niceExtent = result.niceTickExtent;
  29614. },
  29615. /**
  29616. * Nice extent.
  29617. * @param {Object} opt
  29618. * @param {number} [opt.splitNumber = 5] Given approx tick number
  29619. * @param {boolean} [opt.fixMin=false]
  29620. * @param {boolean} [opt.fixMax=false]
  29621. * @param {boolean} [opt.minInterval]
  29622. * @param {boolean} [opt.maxInterval]
  29623. */
  29624. niceExtent: function (opt) {
  29625. var extent = this._extent;
  29626. // If extent start and end are same, expand them
  29627. if (extent[0] === extent[1]) {
  29628. if (extent[0] !== 0) {
  29629. // Expand extent
  29630. var expandSize = extent[0];
  29631. // In the fowllowing case
  29632. // Axis has been fixed max 100
  29633. // Plus data are all 100 and axis extent are [100, 100].
  29634. // Extend to the both side will cause expanded max is larger than fixed max.
  29635. // So only expand to the smaller side.
  29636. if (!opt.fixMax) {
  29637. extent[1] += expandSize / 2;
  29638. extent[0] -= expandSize / 2;
  29639. }
  29640. else {
  29641. extent[0] -= expandSize / 2;
  29642. }
  29643. }
  29644. else {
  29645. extent[1] = 1;
  29646. }
  29647. }
  29648. var span = extent[1] - extent[0];
  29649. // If there are no data and extent are [Infinity, -Infinity]
  29650. if (!isFinite(span)) {
  29651. extent[0] = 0;
  29652. extent[1] = 1;
  29653. }
  29654. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29655. // var extent = this._extent;
  29656. var interval = this._interval;
  29657. if (!opt.fixMin) {
  29658. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29659. }
  29660. if (!opt.fixMax) {
  29661. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29662. }
  29663. }
  29664. });
  29665. /**
  29666. * @return {module:echarts/scale/Time}
  29667. */
  29668. IntervalScale.create = function () {
  29669. return new IntervalScale();
  29670. };
  29671. /*
  29672. * Licensed to the Apache Software Foundation (ASF) under one
  29673. * or more contributor license agreements. See the NOTICE file
  29674. * distributed with this work for additional information
  29675. * regarding copyright ownership. The ASF licenses this file
  29676. * to you under the Apache License, Version 2.0 (the
  29677. * "License"); you may not use this file except in compliance
  29678. * with the License. You may obtain a copy of the License at
  29679. *
  29680. * http://www.apache.org/licenses/LICENSE-2.0
  29681. *
  29682. * Unless required by applicable law or agreed to in writing,
  29683. * software distributed under the License is distributed on an
  29684. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29685. * KIND, either express or implied. See the License for the
  29686. * specific language governing permissions and limitations
  29687. * under the License.
  29688. */
  29689. /* global Float32Array */
  29690. var STACK_PREFIX = '__ec_stack_';
  29691. var LARGE_BAR_MIN_WIDTH = 0.5;
  29692. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  29693. function getSeriesStackId(seriesModel) {
  29694. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29695. }
  29696. function getAxisKey(axis) {
  29697. return axis.dim + axis.index;
  29698. }
  29699. /**
  29700. * @param {Object} opt
  29701. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  29702. * @param {number} opt.count Positive interger.
  29703. * @param {number} [opt.barWidth]
  29704. * @param {number} [opt.barMaxWidth]
  29705. * @param {number} [opt.barMinWidth]
  29706. * @param {number} [opt.barGap]
  29707. * @param {number} [opt.barCategoryGap]
  29708. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  29709. */
  29710. function prepareLayoutBarSeries(seriesType, ecModel) {
  29711. var seriesModels = [];
  29712. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29713. // Check series coordinate, do layout for cartesian2d only
  29714. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  29715. seriesModels.push(seriesModel);
  29716. }
  29717. });
  29718. return seriesModels;
  29719. }
  29720. /**
  29721. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29722. * values.
  29723. * This works for time axes, value axes, and log axes.
  29724. * For a single time axis, return value is in the form like
  29725. * {'x_0': [1000000]}.
  29726. * The value of 1000000 is in milliseconds.
  29727. */
  29728. function getValueAxesMinGaps(barSeries) {
  29729. /**
  29730. * Map from axis.index to values.
  29731. * For a single time axis, axisValues is in the form like
  29732. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29733. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29734. * series.
  29735. */
  29736. var axisValues = {};
  29737. each$1(barSeries, function (seriesModel) {
  29738. var cartesian = seriesModel.coordinateSystem;
  29739. var baseAxis = cartesian.getBaseAxis();
  29740. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29741. return;
  29742. }
  29743. var data = seriesModel.getData();
  29744. var key = baseAxis.dim + '_' + baseAxis.index;
  29745. var dim = data.mapDimension(baseAxis.dim);
  29746. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  29747. var value = data.get(dim, i);
  29748. if (!axisValues[key]) {
  29749. // No previous data for the axis
  29750. axisValues[key] = [value];
  29751. }
  29752. else {
  29753. // No value in previous series
  29754. axisValues[key].push(value);
  29755. }
  29756. // Ignore duplicated time values in the same axis
  29757. }
  29758. });
  29759. var axisMinGaps = [];
  29760. for (var key in axisValues) {
  29761. if (axisValues.hasOwnProperty(key)) {
  29762. var valuesInAxis = axisValues[key];
  29763. if (valuesInAxis) {
  29764. // Sort axis values into ascending order to calculate gaps
  29765. valuesInAxis.sort(function (a, b) {
  29766. return a - b;
  29767. });
  29768. var min = null;
  29769. for (var j = 1; j < valuesInAxis.length; ++j) {
  29770. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29771. if (delta > 0) {
  29772. // Ignore 0 delta because they are of the same axis value
  29773. min = min === null ? delta : Math.min(min, delta);
  29774. }
  29775. }
  29776. // Set to null if only have one data
  29777. axisMinGaps[key] = min;
  29778. }
  29779. }
  29780. }
  29781. return axisMinGaps;
  29782. }
  29783. function makeColumnLayout(barSeries) {
  29784. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29785. var seriesInfoList = [];
  29786. each$1(barSeries, function (seriesModel) {
  29787. var cartesian = seriesModel.coordinateSystem;
  29788. var baseAxis = cartesian.getBaseAxis();
  29789. var axisExtent = baseAxis.getExtent();
  29790. var bandWidth;
  29791. if (baseAxis.type === 'category') {
  29792. bandWidth = baseAxis.getBandWidth();
  29793. }
  29794. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29795. var key = baseAxis.dim + '_' + baseAxis.index;
  29796. var minGap = axisMinGaps[key];
  29797. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29798. var scale = baseAxis.scale.getExtent();
  29799. var scaleSpan = Math.abs(scale[1] - scale[0]);
  29800. bandWidth = minGap
  29801. ? extentSpan / scaleSpan * minGap
  29802. : extentSpan; // When there is only one data value
  29803. }
  29804. else {
  29805. var data = seriesModel.getData();
  29806. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  29807. }
  29808. var barWidth = parsePercent$1(
  29809. seriesModel.get('barWidth'), bandWidth
  29810. );
  29811. var barMaxWidth = parsePercent$1(
  29812. seriesModel.get('barMaxWidth'), bandWidth
  29813. );
  29814. var barMinWidth = parsePercent$1(
  29815. // barMinWidth by default is 1 in cartesian. Because in value axis,
  29816. // the auto-calculated bar width might be less than 1.
  29817. seriesModel.get('barMinWidth') || 1, bandWidth
  29818. );
  29819. var barGap = seriesModel.get('barGap');
  29820. var barCategoryGap = seriesModel.get('barCategoryGap');
  29821. seriesInfoList.push({
  29822. bandWidth: bandWidth,
  29823. barWidth: barWidth,
  29824. barMaxWidth: barMaxWidth,
  29825. barMinWidth: barMinWidth,
  29826. barGap: barGap,
  29827. barCategoryGap: barCategoryGap,
  29828. axisKey: getAxisKey(baseAxis),
  29829. stackId: getSeriesStackId(seriesModel)
  29830. });
  29831. });
  29832. return doCalBarWidthAndOffset(seriesInfoList);
  29833. }
  29834. function doCalBarWidthAndOffset(seriesInfoList) {
  29835. // Columns info on each category axis. Key is cartesian name
  29836. var columnsMap = {};
  29837. each$1(seriesInfoList, function (seriesInfo, idx) {
  29838. var axisKey = seriesInfo.axisKey;
  29839. var bandWidth = seriesInfo.bandWidth;
  29840. var columnsOnAxis = columnsMap[axisKey] || {
  29841. bandWidth: bandWidth,
  29842. remainedWidth: bandWidth,
  29843. autoWidthCount: 0,
  29844. categoryGap: '20%',
  29845. gap: '30%',
  29846. stacks: {}
  29847. };
  29848. var stacks = columnsOnAxis.stacks;
  29849. columnsMap[axisKey] = columnsOnAxis;
  29850. var stackId = seriesInfo.stackId;
  29851. if (!stacks[stackId]) {
  29852. columnsOnAxis.autoWidthCount++;
  29853. }
  29854. stacks[stackId] = stacks[stackId] || {
  29855. width: 0,
  29856. maxWidth: 0
  29857. };
  29858. // Caution: In a single coordinate system, these barGrid attributes
  29859. // will be shared by series. Consider that they have default values,
  29860. // only the attributes set on the last series will work.
  29861. // Do not change this fact unless there will be a break change.
  29862. var barWidth = seriesInfo.barWidth;
  29863. if (barWidth && !stacks[stackId].width) {
  29864. // See #6312, do not restrict width.
  29865. stacks[stackId].width = barWidth;
  29866. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  29867. columnsOnAxis.remainedWidth -= barWidth;
  29868. }
  29869. var barMaxWidth = seriesInfo.barMaxWidth;
  29870. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  29871. var barMinWidth = seriesInfo.barMinWidth;
  29872. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  29873. var barGap = seriesInfo.barGap;
  29874. (barGap != null) && (columnsOnAxis.gap = barGap);
  29875. var barCategoryGap = seriesInfo.barCategoryGap;
  29876. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  29877. });
  29878. var result = {};
  29879. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  29880. result[coordSysName] = {};
  29881. var stacks = columnsOnAxis.stacks;
  29882. var bandWidth = columnsOnAxis.bandWidth;
  29883. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  29884. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  29885. var remainedWidth = columnsOnAxis.remainedWidth;
  29886. var autoWidthCount = columnsOnAxis.autoWidthCount;
  29887. var autoWidth = (remainedWidth - categoryGap)
  29888. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29889. autoWidth = Math.max(autoWidth, 0);
  29890. // Find if any auto calculated bar exceeded maxBarWidth
  29891. each$1(stacks, function (column) {
  29892. var maxWidth = column.maxWidth;
  29893. var minWidth = column.minWidth;
  29894. if (!column.width) {
  29895. var finalWidth = autoWidth;
  29896. if (maxWidth && maxWidth < finalWidth) {
  29897. finalWidth = Math.min(maxWidth, remainedWidth);
  29898. }
  29899. // `minWidth` has higher priority. `minWidth` decide that wheter the
  29900. // bar is able to be visible. So `minWidth` should not be restricted
  29901. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  29902. // the extreme cases for `value` axis, bars are allowed to overlap
  29903. // with each other if `minWidth` specified.
  29904. if (minWidth && minWidth > finalWidth) {
  29905. finalWidth = minWidth;
  29906. }
  29907. if (finalWidth !== autoWidth) {
  29908. column.width = finalWidth;
  29909. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29910. autoWidthCount--;
  29911. }
  29912. }
  29913. else {
  29914. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  29915. // CSS does. Becuase barWidth can be a percent value, where
  29916. // `barMaxWidth` can be used to restrict the final width.
  29917. var finalWidth = column.width;
  29918. if (maxWidth) {
  29919. finalWidth = Math.min(finalWidth, maxWidth);
  29920. }
  29921. // `minWidth` has higher priority, as described above
  29922. if (minWidth) {
  29923. finalWidth = Math.max(finalWidth, minWidth);
  29924. }
  29925. column.width = finalWidth;
  29926. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29927. autoWidthCount--;
  29928. }
  29929. });
  29930. // Recalculate width again
  29931. autoWidth = (remainedWidth - categoryGap)
  29932. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29933. autoWidth = Math.max(autoWidth, 0);
  29934. var widthSum = 0;
  29935. var lastColumn;
  29936. each$1(stacks, function (column, idx) {
  29937. if (!column.width) {
  29938. column.width = autoWidth;
  29939. }
  29940. lastColumn = column;
  29941. widthSum += column.width * (1 + barGapPercent);
  29942. });
  29943. if (lastColumn) {
  29944. widthSum -= lastColumn.width * barGapPercent;
  29945. }
  29946. var offset = -widthSum / 2;
  29947. each$1(stacks, function (column, stackId) {
  29948. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  29949. bandWidth: bandWidth,
  29950. offset: offset,
  29951. width: column.width
  29952. };
  29953. offset += column.width * (1 + barGapPercent);
  29954. });
  29955. });
  29956. return result;
  29957. }
  29958. /**
  29959. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  29960. * @param {module:echarts/coord/Axis} axis
  29961. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  29962. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  29963. */
  29964. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  29965. if (barWidthAndOffset && axis) {
  29966. var result = barWidthAndOffset[getAxisKey(axis)];
  29967. if (result != null && seriesModel != null) {
  29968. result = result[getSeriesStackId(seriesModel)];
  29969. }
  29970. return result;
  29971. }
  29972. }
  29973. /**
  29974. * @param {string} seriesType
  29975. * @param {module:echarts/model/Global} ecModel
  29976. */
  29977. function layout(seriesType, ecModel) {
  29978. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  29979. var barWidthAndOffset = makeColumnLayout(seriesModels);
  29980. var lastStackCoords = {};
  29981. each$1(seriesModels, function (seriesModel) {
  29982. var data = seriesModel.getData();
  29983. var cartesian = seriesModel.coordinateSystem;
  29984. var baseAxis = cartesian.getBaseAxis();
  29985. var stackId = getSeriesStackId(seriesModel);
  29986. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  29987. var columnOffset = columnLayoutInfo.offset;
  29988. var columnWidth = columnLayoutInfo.width;
  29989. var valueAxis = cartesian.getOtherAxis(baseAxis);
  29990. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  29991. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  29992. data.setLayout({
  29993. bandWidth: columnLayoutInfo.bandWidth,
  29994. offset: columnOffset,
  29995. size: columnWidth
  29996. });
  29997. var valueDim = data.mapDimension(valueAxis.dim);
  29998. var baseDim = data.mapDimension(baseAxis.dim);
  29999. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  30000. var isValueAxisH = valueAxis.isHorizontal();
  30001. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  30002. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30003. var value = data.get(valueDim, idx);
  30004. var baseValue = data.get(baseDim, idx);
  30005. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  30006. if (isNaN(value) || isNaN(baseValue)) {
  30007. continue;
  30008. }
  30009. var sign = value >= 0 ? 'p' : 'n';
  30010. var baseCoord = valueAxisStart;
  30011. // Because of the barMinHeight, we can not use the value in
  30012. // stackResultDimension directly.
  30013. if (stacked) {
  30014. // Only ordinal axis can be stacked.
  30015. if (!lastStackCoords[stackId][baseValue]) {
  30016. lastStackCoords[stackId][baseValue] = {
  30017. p: valueAxisStart, // Positive stack
  30018. n: valueAxisStart // Negative stack
  30019. };
  30020. }
  30021. // Should also consider #4243
  30022. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30023. }
  30024. var x;
  30025. var y;
  30026. var width;
  30027. var height;
  30028. if (isValueAxisH) {
  30029. var coord = cartesian.dataToPoint([value, baseValue]);
  30030. x = baseCoord;
  30031. y = coord[1] + columnOffset;
  30032. width = coord[0] - valueAxisStart;
  30033. height = columnWidth;
  30034. if (Math.abs(width) < barMinHeight) {
  30035. width = (width < 0 ? -1 : 1) * barMinHeight;
  30036. }
  30037. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30038. }
  30039. else {
  30040. var coord = cartesian.dataToPoint([baseValue, value]);
  30041. x = coord[0] + columnOffset;
  30042. y = baseCoord;
  30043. width = columnWidth;
  30044. height = coord[1] - valueAxisStart;
  30045. if (Math.abs(height) < barMinHeight) {
  30046. // Include zero to has a positive bar
  30047. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30048. }
  30049. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30050. }
  30051. data.setItemLayout(idx, {
  30052. x: x,
  30053. y: y,
  30054. width: width,
  30055. height: height
  30056. });
  30057. }
  30058. }, this);
  30059. }
  30060. // TODO: Do not support stack in large mode yet.
  30061. var largeLayout = {
  30062. seriesType: 'bar',
  30063. plan: createRenderPlanner(),
  30064. reset: function (seriesModel) {
  30065. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30066. return;
  30067. }
  30068. var data = seriesModel.getData();
  30069. var cartesian = seriesModel.coordinateSystem;
  30070. var baseAxis = cartesian.getBaseAxis();
  30071. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30072. var valueDim = data.mapDimension(valueAxis.dim);
  30073. var baseDim = data.mapDimension(baseAxis.dim);
  30074. var valueAxisHorizontal = valueAxis.isHorizontal();
  30075. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30076. var barWidth = retrieveColumnLayout(
  30077. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  30078. ).width;
  30079. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  30080. barWidth = LARGE_BAR_MIN_WIDTH;
  30081. }
  30082. return {progress: progress};
  30083. function progress(params, data) {
  30084. var count = params.count;
  30085. var largePoints = new LargeArr(count * 2);
  30086. var largeDataIndices = new LargeArr(count);
  30087. var dataIndex;
  30088. var coord = [];
  30089. var valuePair = [];
  30090. var pointsOffset = 0;
  30091. var idxOffset = 0;
  30092. while ((dataIndex = params.next()) != null) {
  30093. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30094. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30095. coord = cartesian.dataToPoint(valuePair, null, coord);
  30096. // Data index might not be in order, depends on `progressiveChunkMode`.
  30097. largePoints[pointsOffset++] = coord[0];
  30098. largePoints[pointsOffset++] = coord[1];
  30099. largeDataIndices[idxOffset++] = dataIndex;
  30100. }
  30101. data.setLayout({
  30102. largePoints: largePoints,
  30103. largeDataIndices: largeDataIndices,
  30104. barWidth: barWidth,
  30105. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  30106. valueAxisHorizontal: valueAxisHorizontal
  30107. });
  30108. }
  30109. }
  30110. };
  30111. function isOnCartesian(seriesModel) {
  30112. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30113. }
  30114. function isInLargeMode(seriesModel) {
  30115. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30116. }
  30117. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30118. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30119. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30120. }
  30121. /*
  30122. * Licensed to the Apache Software Foundation (ASF) under one
  30123. * or more contributor license agreements. See the NOTICE file
  30124. * distributed with this work for additional information
  30125. * regarding copyright ownership. The ASF licenses this file
  30126. * to you under the Apache License, Version 2.0 (the
  30127. * "License"); you may not use this file except in compliance
  30128. * with the License. You may obtain a copy of the License at
  30129. *
  30130. * http://www.apache.org/licenses/LICENSE-2.0
  30131. *
  30132. * Unless required by applicable law or agreed to in writing,
  30133. * software distributed under the License is distributed on an
  30134. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30135. * KIND, either express or implied. See the License for the
  30136. * specific language governing permissions and limitations
  30137. * under the License.
  30138. */
  30139. /*
  30140. * A third-party license is embeded for some of the code in this file:
  30141. * The "scaleLevels" was originally copied from "d3.js" with some
  30142. * modifications made for this project.
  30143. * (See more details in the comment on the definition of "scaleLevels" below.)
  30144. * The use of the source code of this file is also subject to the terms
  30145. * and consitions of the license of "d3.js" (BSD-3Clause, see
  30146. * </licenses/LICENSE-d3>).
  30147. */
  30148. // [About UTC and local time zone]:
  30149. // In most cases, `number.parseDate` will treat input data string as local time
  30150. // (except time zone is specified in time string). And `format.formateTime` returns
  30151. // local time by default. option.useUTC is false by default. This design have
  30152. // concidered these common case:
  30153. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  30154. // in local time by default.
  30155. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  30156. // as its original time, without any time difference.
  30157. var intervalScaleProto = IntervalScale.prototype;
  30158. var mathCeil = Math.ceil;
  30159. var mathFloor = Math.floor;
  30160. var ONE_SECOND = 1000;
  30161. var ONE_MINUTE = ONE_SECOND * 60;
  30162. var ONE_HOUR = ONE_MINUTE * 60;
  30163. var ONE_DAY = ONE_HOUR * 24;
  30164. // FIXME 公用?
  30165. var bisect = function (a, x, lo, hi) {
  30166. while (lo < hi) {
  30167. var mid = lo + hi >>> 1;
  30168. if (a[mid][1] < x) {
  30169. lo = mid + 1;
  30170. }
  30171. else {
  30172. hi = mid;
  30173. }
  30174. }
  30175. return lo;
  30176. };
  30177. /**
  30178. * @alias module:echarts/coord/scale/Time
  30179. * @constructor
  30180. */
  30181. var TimeScale = IntervalScale.extend({
  30182. type: 'time',
  30183. /**
  30184. * @override
  30185. */
  30186. getLabel: function (val) {
  30187. var stepLvl = this._stepLvl;
  30188. var date = new Date(val);
  30189. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  30190. },
  30191. /**
  30192. * @override
  30193. */
  30194. niceExtent: function (opt) {
  30195. var extent = this._extent;
  30196. // If extent start and end are same, expand them
  30197. if (extent[0] === extent[1]) {
  30198. // Expand extent
  30199. extent[0] -= ONE_DAY;
  30200. extent[1] += ONE_DAY;
  30201. }
  30202. // If there are no data and extent are [Infinity, -Infinity]
  30203. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30204. var d = new Date();
  30205. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30206. extent[0] = extent[1] - ONE_DAY;
  30207. }
  30208. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30209. // var extent = this._extent;
  30210. var interval = this._interval;
  30211. if (!opt.fixMin) {
  30212. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  30213. }
  30214. if (!opt.fixMax) {
  30215. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  30216. }
  30217. },
  30218. /**
  30219. * @override
  30220. */
  30221. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  30222. approxTickNum = approxTickNum || 10;
  30223. var extent = this._extent;
  30224. var span = extent[1] - extent[0];
  30225. var approxInterval = span / approxTickNum;
  30226. if (minInterval != null && approxInterval < minInterval) {
  30227. approxInterval = minInterval;
  30228. }
  30229. if (maxInterval != null && approxInterval > maxInterval) {
  30230. approxInterval = maxInterval;
  30231. }
  30232. var scaleLevelsLen = scaleLevels.length;
  30233. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  30234. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  30235. var interval = level[1];
  30236. // Same with interval scale if span is much larger than 1 year
  30237. if (level[0] === 'year') {
  30238. var yearSpan = span / interval;
  30239. // From "Nice Numbers for Graph Labels" of Graphic Gems
  30240. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  30241. var yearStep = nice(yearSpan / approxTickNum, true);
  30242. interval *= yearStep;
  30243. }
  30244. var timezoneOffset = this.getSetting('useUTC')
  30245. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  30246. var niceExtent = [
  30247. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  30248. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  30249. ];
  30250. fixExtent(niceExtent, extent);
  30251. this._stepLvl = level;
  30252. // Interval will be used in getTicks
  30253. this._interval = interval;
  30254. this._niceExtent = niceExtent;
  30255. },
  30256. parse: function (val) {
  30257. // val might be float.
  30258. return +parseDate(val);
  30259. }
  30260. });
  30261. each$1(['contain', 'normalize'], function (methodName) {
  30262. TimeScale.prototype[methodName] = function (val) {
  30263. return intervalScaleProto[methodName].call(this, this.parse(val));
  30264. };
  30265. });
  30266. /**
  30267. * This implementation was originally copied from "d3.js"
  30268. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30269. * with some modifications made for this program.
  30270. * See the license statement at the head of this file.
  30271. */
  30272. var scaleLevels = [
  30273. // Format interval
  30274. ['hh:mm:ss', ONE_SECOND], // 1s
  30275. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  30276. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  30277. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  30278. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  30279. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  30280. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  30281. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  30282. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  30283. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  30284. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  30285. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  30286. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  30287. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  30288. ['MM-dd\nyyyy', ONE_DAY], // 1d
  30289. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  30290. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  30291. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  30292. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  30293. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  30294. ['week', ONE_DAY * 7], // 7d
  30295. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  30296. ['week', ONE_DAY * 14], // 2w
  30297. ['week', ONE_DAY * 21], // 3w
  30298. ['month', ONE_DAY * 31], // 1M
  30299. ['week', ONE_DAY * 42], // 6w
  30300. ['month', ONE_DAY * 62], // 2M
  30301. ['week', ONE_DAY * 70], // 10w
  30302. ['quarter', ONE_DAY * 95], // 3M
  30303. ['month', ONE_DAY * 31 * 4], // 4M
  30304. ['month', ONE_DAY * 31 * 5], // 5M
  30305. ['half-year', ONE_DAY * 380 / 2], // 6M
  30306. ['month', ONE_DAY * 31 * 8], // 8M
  30307. ['month', ONE_DAY * 31 * 10], // 10M
  30308. ['year', ONE_DAY * 380] // 1Y
  30309. ];
  30310. /**
  30311. * @param {module:echarts/model/Model}
  30312. * @return {module:echarts/scale/Time}
  30313. */
  30314. TimeScale.create = function (model) {
  30315. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  30316. };
  30317. /*
  30318. * Licensed to the Apache Software Foundation (ASF) under one
  30319. * or more contributor license agreements. See the NOTICE file
  30320. * distributed with this work for additional information
  30321. * regarding copyright ownership. The ASF licenses this file
  30322. * to you under the Apache License, Version 2.0 (the
  30323. * "License"); you may not use this file except in compliance
  30324. * with the License. You may obtain a copy of the License at
  30325. *
  30326. * http://www.apache.org/licenses/LICENSE-2.0
  30327. *
  30328. * Unless required by applicable law or agreed to in writing,
  30329. * software distributed under the License is distributed on an
  30330. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30331. * KIND, either express or implied. See the License for the
  30332. * specific language governing permissions and limitations
  30333. * under the License.
  30334. */
  30335. /**
  30336. * Log scale
  30337. * @module echarts/scale/Log
  30338. */
  30339. // Use some method of IntervalScale
  30340. var scaleProto$1 = Scale.prototype;
  30341. var intervalScaleProto$1 = IntervalScale.prototype;
  30342. var getPrecisionSafe$1 = getPrecisionSafe;
  30343. var roundingErrorFix = round$1;
  30344. var mathFloor$1 = Math.floor;
  30345. var mathCeil$1 = Math.ceil;
  30346. var mathPow$1 = Math.pow;
  30347. var mathLog = Math.log;
  30348. var LogScale = Scale.extend({
  30349. type: 'log',
  30350. base: 10,
  30351. $constructor: function () {
  30352. Scale.apply(this, arguments);
  30353. this._originalScale = new IntervalScale();
  30354. },
  30355. /**
  30356. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  30357. * @return {Array.<number>}
  30358. */
  30359. getTicks: function (expandToNicedExtent) {
  30360. var originalScale = this._originalScale;
  30361. var extent = this._extent;
  30362. var originalExtent = originalScale.getExtent();
  30363. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  30364. var powVal = round$1(mathPow$1(this.base, val));
  30365. // Fix #4158
  30366. powVal = (val === extent[0] && originalScale.__fixMin)
  30367. ? fixRoundingError(powVal, originalExtent[0])
  30368. : powVal;
  30369. powVal = (val === extent[1] && originalScale.__fixMax)
  30370. ? fixRoundingError(powVal, originalExtent[1])
  30371. : powVal;
  30372. return powVal;
  30373. }, this);
  30374. },
  30375. /**
  30376. * @param {number} splitNumber
  30377. * @return {Array.<Array.<number>>}
  30378. */
  30379. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  30380. /**
  30381. * @param {number} val
  30382. * @return {string}
  30383. */
  30384. getLabel: intervalScaleProto$1.getLabel,
  30385. /**
  30386. * @param {number} val
  30387. * @return {number}
  30388. */
  30389. scale: function (val) {
  30390. val = scaleProto$1.scale.call(this, val);
  30391. return mathPow$1(this.base, val);
  30392. },
  30393. /**
  30394. * @param {number} start
  30395. * @param {number} end
  30396. */
  30397. setExtent: function (start, end) {
  30398. var base = this.base;
  30399. start = mathLog(start) / mathLog(base);
  30400. end = mathLog(end) / mathLog(base);
  30401. intervalScaleProto$1.setExtent.call(this, start, end);
  30402. },
  30403. /**
  30404. * @return {number} end
  30405. */
  30406. getExtent: function () {
  30407. var base = this.base;
  30408. var extent = scaleProto$1.getExtent.call(this);
  30409. extent[0] = mathPow$1(base, extent[0]);
  30410. extent[1] = mathPow$1(base, extent[1]);
  30411. // Fix #4158
  30412. var originalScale = this._originalScale;
  30413. var originalExtent = originalScale.getExtent();
  30414. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30415. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30416. return extent;
  30417. },
  30418. /**
  30419. * @param {Array.<number>} extent
  30420. */
  30421. unionExtent: function (extent) {
  30422. this._originalScale.unionExtent(extent);
  30423. var base = this.base;
  30424. extent[0] = mathLog(extent[0]) / mathLog(base);
  30425. extent[1] = mathLog(extent[1]) / mathLog(base);
  30426. scaleProto$1.unionExtent.call(this, extent);
  30427. },
  30428. /**
  30429. * @override
  30430. */
  30431. unionExtentFromData: function (data, dim) {
  30432. // TODO
  30433. // filter value that <= 0
  30434. this.unionExtent(data.getApproximateExtent(dim));
  30435. },
  30436. /**
  30437. * Update interval and extent of intervals for nice ticks
  30438. * @param {number} [approxTickNum = 10] Given approx tick number
  30439. */
  30440. niceTicks: function (approxTickNum) {
  30441. approxTickNum = approxTickNum || 10;
  30442. var extent = this._extent;
  30443. var span = extent[1] - extent[0];
  30444. if (span === Infinity || span <= 0) {
  30445. return;
  30446. }
  30447. var interval = quantity(span);
  30448. var err = approxTickNum / span * interval;
  30449. // Filter ticks to get closer to the desired count.
  30450. if (err <= 0.5) {
  30451. interval *= 10;
  30452. }
  30453. // Interval should be integer
  30454. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30455. interval *= 10;
  30456. }
  30457. var niceExtent = [
  30458. round$1(mathCeil$1(extent[0] / interval) * interval),
  30459. round$1(mathFloor$1(extent[1] / interval) * interval)
  30460. ];
  30461. this._interval = interval;
  30462. this._niceExtent = niceExtent;
  30463. },
  30464. /**
  30465. * Nice extent.
  30466. * @override
  30467. */
  30468. niceExtent: function (opt) {
  30469. intervalScaleProto$1.niceExtent.call(this, opt);
  30470. var originalScale = this._originalScale;
  30471. originalScale.__fixMin = opt.fixMin;
  30472. originalScale.__fixMax = opt.fixMax;
  30473. }
  30474. });
  30475. each$1(['contain', 'normalize'], function (methodName) {
  30476. LogScale.prototype[methodName] = function (val) {
  30477. val = mathLog(val) / mathLog(this.base);
  30478. return scaleProto$1[methodName].call(this, val);
  30479. };
  30480. });
  30481. LogScale.create = function () {
  30482. return new LogScale();
  30483. };
  30484. function fixRoundingError(val, originalVal) {
  30485. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  30486. }
  30487. /*
  30488. * Licensed to the Apache Software Foundation (ASF) under one
  30489. * or more contributor license agreements. See the NOTICE file
  30490. * distributed with this work for additional information
  30491. * regarding copyright ownership. The ASF licenses this file
  30492. * to you under the Apache License, Version 2.0 (the
  30493. * "License"); you may not use this file except in compliance
  30494. * with the License. You may obtain a copy of the License at
  30495. *
  30496. * http://www.apache.org/licenses/LICENSE-2.0
  30497. *
  30498. * Unless required by applicable law or agreed to in writing,
  30499. * software distributed under the License is distributed on an
  30500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30501. * KIND, either express or implied. See the License for the
  30502. * specific language governing permissions and limitations
  30503. * under the License.
  30504. */
  30505. /**
  30506. * Get axis scale extent before niced.
  30507. * Item of returned array can only be number (including Infinity and NaN).
  30508. */
  30509. function getScaleExtent(scale, model) {
  30510. var scaleType = scale.type;
  30511. var min = model.getMin();
  30512. var max = model.getMax();
  30513. var fixMin = min != null;
  30514. var fixMax = max != null;
  30515. var originalExtent = scale.getExtent();
  30516. var axisDataLen;
  30517. var boundaryGap;
  30518. var span;
  30519. if (scaleType === 'ordinal') {
  30520. axisDataLen = model.getCategories().length;
  30521. }
  30522. else {
  30523. boundaryGap = model.get('boundaryGap');
  30524. if (!isArray(boundaryGap)) {
  30525. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  30526. }
  30527. if (typeof boundaryGap[0] === 'boolean') {
  30528. if (__DEV__) {
  30529. console.warn('Boolean type for boundaryGap is only '
  30530. + 'allowed for ordinal axis. Please use string in '
  30531. + 'percentage instead, e.g., "20%". Currently, '
  30532. + 'boundaryGap is set to be 0.');
  30533. }
  30534. boundaryGap = [0, 0];
  30535. }
  30536. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  30537. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  30538. span = (originalExtent[1] - originalExtent[0])
  30539. || Math.abs(originalExtent[0]);
  30540. }
  30541. // Notice: When min/max is not set (that is, when there are null/undefined,
  30542. // which is the most common case), these cases should be ensured:
  30543. // (1) For 'ordinal', show all axis.data.
  30544. // (2) For others:
  30545. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30546. // disabled).
  30547. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30548. // be the result that originalExtent enlarged by boundaryGap.
  30549. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30550. // FIXME
  30551. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  30552. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  30553. // that the results processed by boundaryGap are positive/negative?
  30554. if (min == null) {
  30555. min = scaleType === 'ordinal'
  30556. ? (axisDataLen ? 0 : NaN)
  30557. : originalExtent[0] - boundaryGap[0] * span;
  30558. }
  30559. if (max == null) {
  30560. max = scaleType === 'ordinal'
  30561. ? (axisDataLen ? axisDataLen - 1 : NaN)
  30562. : originalExtent[1] + boundaryGap[1] * span;
  30563. }
  30564. if (min === 'dataMin') {
  30565. min = originalExtent[0];
  30566. }
  30567. else if (typeof min === 'function') {
  30568. min = min({
  30569. min: originalExtent[0],
  30570. max: originalExtent[1]
  30571. });
  30572. }
  30573. if (max === 'dataMax') {
  30574. max = originalExtent[1];
  30575. }
  30576. else if (typeof max === 'function') {
  30577. max = max({
  30578. min: originalExtent[0],
  30579. max: originalExtent[1]
  30580. });
  30581. }
  30582. (min == null || !isFinite(min)) && (min = NaN);
  30583. (max == null || !isFinite(max)) && (max = NaN);
  30584. scale.setBlank(
  30585. eqNaN(min)
  30586. || eqNaN(max)
  30587. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  30588. );
  30589. // Evaluate if axis needs cross zero
  30590. if (model.getNeedCrossZero()) {
  30591. // Axis is over zero and min is not set
  30592. if (min > 0 && max > 0 && !fixMin) {
  30593. min = 0;
  30594. }
  30595. // Axis is under zero and max is not set
  30596. if (min < 0 && max < 0 && !fixMax) {
  30597. max = 0;
  30598. }
  30599. }
  30600. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  30601. // is base axis
  30602. // FIXME
  30603. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30604. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30605. // Should not depend on series type `bar`?
  30606. // (3) Fix that might overlap when using dataZoom.
  30607. // (4) Consider other chart types using `barGrid`?
  30608. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30609. var ecModel = model.ecModel;
  30610. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  30611. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30612. var isBaseAxisAndHasBarSeries;
  30613. each$1(barSeriesModels, function (seriesModel) {
  30614. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  30615. });
  30616. if (isBaseAxisAndHasBarSeries) {
  30617. // Calculate placement of bars on axis
  30618. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  30619. // Adjust axis min and max to account for overflow
  30620. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30621. min = adjustedScale.min;
  30622. max = adjustedScale.max;
  30623. }
  30624. }
  30625. return [min, max];
  30626. }
  30627. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  30628. // Get Axis Length
  30629. var axisExtent = model.axis.getExtent();
  30630. var axisLength = axisExtent[1] - axisExtent[0];
  30631. // Get bars on current base axis and calculate min and max overflow
  30632. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30633. if (barsOnCurrentAxis === undefined) {
  30634. return {min: min, max: max};
  30635. }
  30636. var minOverflow = Infinity;
  30637. each$1(barsOnCurrentAxis, function (item) {
  30638. minOverflow = Math.min(item.offset, minOverflow);
  30639. });
  30640. var maxOverflow = -Infinity;
  30641. each$1(barsOnCurrentAxis, function (item) {
  30642. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30643. });
  30644. minOverflow = Math.abs(minOverflow);
  30645. maxOverflow = Math.abs(maxOverflow);
  30646. var totalOverFlow = minOverflow + maxOverflow;
  30647. // Calulate required buffer based on old range and overflow
  30648. var oldRange = max - min;
  30649. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  30650. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  30651. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30652. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30653. return {min: min, max: max};
  30654. }
  30655. function niceScaleExtent(scale, model) {
  30656. var extent = getScaleExtent(scale, model);
  30657. var fixMin = model.getMin() != null;
  30658. var fixMax = model.getMax() != null;
  30659. var splitNumber = model.get('splitNumber');
  30660. if (scale.type === 'log') {
  30661. scale.base = model.get('logBase');
  30662. }
  30663. var scaleType = scale.type;
  30664. scale.setExtent(extent[0], extent[1]);
  30665. scale.niceExtent({
  30666. splitNumber: splitNumber,
  30667. fixMin: fixMin,
  30668. fixMax: fixMax,
  30669. minInterval: (scaleType === 'interval' || scaleType === 'time')
  30670. ? model.get('minInterval') : null,
  30671. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  30672. ? model.get('maxInterval') : null
  30673. });
  30674. // If some one specified the min, max. And the default calculated interval
  30675. // is not good enough. He can specify the interval. It is often appeared
  30676. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30677. // to be 60.
  30678. // FIXME
  30679. var interval = model.get('interval');
  30680. if (interval != null) {
  30681. scale.setInterval && scale.setInterval(interval);
  30682. }
  30683. }
  30684. /**
  30685. * @param {module:echarts/model/Model} model
  30686. * @param {string} [axisType] Default retrieve from model.type
  30687. * @return {module:echarts/scale/*}
  30688. */
  30689. function createScaleByModel(model, axisType) {
  30690. axisType = axisType || model.get('type');
  30691. if (axisType) {
  30692. switch (axisType) {
  30693. // Buildin scale
  30694. case 'category':
  30695. return new OrdinalScale(
  30696. model.getOrdinalMeta
  30697. ? model.getOrdinalMeta()
  30698. : model.getCategories(),
  30699. [Infinity, -Infinity]
  30700. );
  30701. case 'value':
  30702. return new IntervalScale();
  30703. // Extended scale, like time and log
  30704. default:
  30705. return (Scale.getClass(axisType) || IntervalScale).create(model);
  30706. }
  30707. }
  30708. }
  30709. /**
  30710. * Check if the axis corss 0
  30711. */
  30712. function ifAxisCrossZero(axis) {
  30713. var dataExtent = axis.scale.getExtent();
  30714. var min = dataExtent[0];
  30715. var max = dataExtent[1];
  30716. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  30717. }
  30718. /**
  30719. * @param {module:echarts/coord/Axis} axis
  30720. * @return {Function} Label formatter function.
  30721. * param: {number} tickValue,
  30722. * param: {number} idx, the index in all ticks.
  30723. * If category axis, this param is not requied.
  30724. * return: {string} label string.
  30725. */
  30726. function makeLabelFormatter(axis) {
  30727. var labelFormatter = axis.getLabelModel().get('formatter');
  30728. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  30729. if (typeof labelFormatter === 'string') {
  30730. labelFormatter = (function (tpl) {
  30731. return function (val) {
  30732. // For category axis, get raw value; for numeric axis,
  30733. // get foramtted label like '1,333,444'.
  30734. val = axis.scale.getLabel(val);
  30735. return tpl.replace('{value}', val != null ? val : '');
  30736. };
  30737. })(labelFormatter);
  30738. // Consider empty array
  30739. return labelFormatter;
  30740. }
  30741. else if (typeof labelFormatter === 'function') {
  30742. return function (tickValue, idx) {
  30743. // The original intention of `idx` is "the index of the tick in all ticks".
  30744. // But the previous implementation of category axis do not consider the
  30745. // `axisLabel.interval`, which cause that, for example, the `interval` is
  30746. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  30747. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  30748. // the definition here for back compatibility.
  30749. if (categoryTickStart != null) {
  30750. idx = tickValue - categoryTickStart;
  30751. }
  30752. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  30753. };
  30754. }
  30755. else {
  30756. return function (tick) {
  30757. return axis.scale.getLabel(tick);
  30758. };
  30759. }
  30760. }
  30761. function getAxisRawValue(axis, value) {
  30762. // In category axis with data zoom, tick is not the original
  30763. // index of axis.data. So tick should not be exposed to user
  30764. // in category axis.
  30765. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  30766. }
  30767. /**
  30768. * @param {module:echarts/coord/Axis} axis
  30769. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  30770. */
  30771. function estimateLabelUnionRect(axis) {
  30772. var axisModel = axis.model;
  30773. var scale = axis.scale;
  30774. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  30775. return;
  30776. }
  30777. var isCategory = axis.type === 'category';
  30778. var realNumberScaleTicks;
  30779. var tickCount;
  30780. var categoryScaleExtent = scale.getExtent();
  30781. // Optimize for large category data, avoid call `getTicks()`.
  30782. if (isCategory) {
  30783. tickCount = scale.count();
  30784. }
  30785. else {
  30786. realNumberScaleTicks = scale.getTicks();
  30787. tickCount = realNumberScaleTicks.length;
  30788. }
  30789. var axisLabelModel = axis.getLabelModel();
  30790. var labelFormatter = makeLabelFormatter(axis);
  30791. var rect;
  30792. var step = 1;
  30793. // Simple optimization for large amount of labels
  30794. if (tickCount > 40) {
  30795. step = Math.ceil(tickCount / 40);
  30796. }
  30797. for (var i = 0; i < tickCount; i += step) {
  30798. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  30799. var label = labelFormatter(tickValue);
  30800. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  30801. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  30802. rect ? rect.union(singleRect) : (rect = singleRect);
  30803. }
  30804. return rect;
  30805. }
  30806. function rotateTextRect(textRect, rotate) {
  30807. var rotateRadians = rotate * Math.PI / 180;
  30808. var boundingBox = textRect.plain();
  30809. var beforeWidth = boundingBox.width;
  30810. var beforeHeight = boundingBox.height;
  30811. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  30812. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  30813. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  30814. return rotatedRect;
  30815. }
  30816. /**
  30817. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  30818. * @return {number|String} Can be null|'auto'|number|function
  30819. */
  30820. function getOptionCategoryInterval(model) {
  30821. var interval = model.get('interval');
  30822. return interval == null ? 'auto' : interval;
  30823. }
  30824. /**
  30825. * Set `categoryInterval` as 0 implicitly indicates that
  30826. * show all labels reguardless of overlap.
  30827. * @param {Object} axis axisModel.axis
  30828. * @return {boolean}
  30829. */
  30830. function shouldShowAllLabels(axis) {
  30831. return axis.type === 'category'
  30832. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  30833. }
  30834. /*
  30835. * Licensed to the Apache Software Foundation (ASF) under one
  30836. * or more contributor license agreements. See the NOTICE file
  30837. * distributed with this work for additional information
  30838. * regarding copyright ownership. The ASF licenses this file
  30839. * to you under the Apache License, Version 2.0 (the
  30840. * "License"); you may not use this file except in compliance
  30841. * with the License. You may obtain a copy of the License at
  30842. *
  30843. * http://www.apache.org/licenses/LICENSE-2.0
  30844. *
  30845. * Unless required by applicable law or agreed to in writing,
  30846. * software distributed under the License is distributed on an
  30847. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30848. * KIND, either express or implied. See the License for the
  30849. * specific language governing permissions and limitations
  30850. * under the License.
  30851. */
  30852. // import * as axisHelper from './axisHelper';
  30853. var axisModelCommonMixin = {
  30854. /**
  30855. * @param {boolean} origin
  30856. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  30857. */
  30858. getMin: function (origin) {
  30859. var option = this.option;
  30860. var min = (!origin && option.rangeStart != null)
  30861. ? option.rangeStart : option.min;
  30862. if (this.axis
  30863. && min != null
  30864. && min !== 'dataMin'
  30865. && typeof min !== 'function'
  30866. && !eqNaN(min)
  30867. ) {
  30868. min = this.axis.scale.parse(min);
  30869. }
  30870. return min;
  30871. },
  30872. /**
  30873. * @param {boolean} origin
  30874. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  30875. */
  30876. getMax: function (origin) {
  30877. var option = this.option;
  30878. var max = (!origin && option.rangeEnd != null)
  30879. ? option.rangeEnd : option.max;
  30880. if (this.axis
  30881. && max != null
  30882. && max !== 'dataMax'
  30883. && typeof max !== 'function'
  30884. && !eqNaN(max)
  30885. ) {
  30886. max = this.axis.scale.parse(max);
  30887. }
  30888. return max;
  30889. },
  30890. /**
  30891. * @return {boolean}
  30892. */
  30893. getNeedCrossZero: function () {
  30894. var option = this.option;
  30895. return (option.rangeStart != null || option.rangeEnd != null)
  30896. ? false : !option.scale;
  30897. },
  30898. /**
  30899. * Should be implemented by each axis model if necessary.
  30900. * @return {module:echarts/model/Component} coordinate system model
  30901. */
  30902. getCoordSysModel: noop,
  30903. /**
  30904. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  30905. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  30906. */
  30907. setRange: function (rangeStart, rangeEnd) {
  30908. this.option.rangeStart = rangeStart;
  30909. this.option.rangeEnd = rangeEnd;
  30910. },
  30911. /**
  30912. * Reset range
  30913. */
  30914. resetRange: function () {
  30915. // rangeStart and rangeEnd is readonly.
  30916. this.option.rangeStart = this.option.rangeEnd = null;
  30917. }
  30918. };
  30919. /*
  30920. * Licensed to the Apache Software Foundation (ASF) under one
  30921. * or more contributor license agreements. See the NOTICE file
  30922. * distributed with this work for additional information
  30923. * regarding copyright ownership. The ASF licenses this file
  30924. * to you under the Apache License, Version 2.0 (the
  30925. * "License"); you may not use this file except in compliance
  30926. * with the License. You may obtain a copy of the License at
  30927. *
  30928. * http://www.apache.org/licenses/LICENSE-2.0
  30929. *
  30930. * Unless required by applicable law or agreed to in writing,
  30931. * software distributed under the License is distributed on an
  30932. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30933. * KIND, either express or implied. See the License for the
  30934. * specific language governing permissions and limitations
  30935. * under the License.
  30936. */
  30937. // Symbol factory
  30938. /**
  30939. * Triangle shape
  30940. * @inner
  30941. */
  30942. var Triangle = extendShape({
  30943. type: 'triangle',
  30944. shape: {
  30945. cx: 0,
  30946. cy: 0,
  30947. width: 0,
  30948. height: 0
  30949. },
  30950. buildPath: function (path, shape) {
  30951. var cx = shape.cx;
  30952. var cy = shape.cy;
  30953. var width = shape.width / 2;
  30954. var height = shape.height / 2;
  30955. path.moveTo(cx, cy - height);
  30956. path.lineTo(cx + width, cy + height);
  30957. path.lineTo(cx - width, cy + height);
  30958. path.closePath();
  30959. }
  30960. });
  30961. /**
  30962. * Diamond shape
  30963. * @inner
  30964. */
  30965. var Diamond = extendShape({
  30966. type: 'diamond',
  30967. shape: {
  30968. cx: 0,
  30969. cy: 0,
  30970. width: 0,
  30971. height: 0
  30972. },
  30973. buildPath: function (path, shape) {
  30974. var cx = shape.cx;
  30975. var cy = shape.cy;
  30976. var width = shape.width / 2;
  30977. var height = shape.height / 2;
  30978. path.moveTo(cx, cy - height);
  30979. path.lineTo(cx + width, cy);
  30980. path.lineTo(cx, cy + height);
  30981. path.lineTo(cx - width, cy);
  30982. path.closePath();
  30983. }
  30984. });
  30985. /**
  30986. * Pin shape
  30987. * @inner
  30988. */
  30989. var Pin = extendShape({
  30990. type: 'pin',
  30991. shape: {
  30992. // x, y on the cusp
  30993. x: 0,
  30994. y: 0,
  30995. width: 0,
  30996. height: 0
  30997. },
  30998. buildPath: function (path, shape) {
  30999. var x = shape.x;
  31000. var y = shape.y;
  31001. var w = shape.width / 5 * 3;
  31002. // Height must be larger than width
  31003. var h = Math.max(w, shape.height);
  31004. var r = w / 2;
  31005. // Dist on y with tangent point and circle center
  31006. var dy = r * r / (h - r);
  31007. var cy = y - h + r + dy;
  31008. var angle = Math.asin(dy / r);
  31009. // Dist on x with tangent point and circle center
  31010. var dx = Math.cos(angle) * r;
  31011. var tanX = Math.sin(angle);
  31012. var tanY = Math.cos(angle);
  31013. var cpLen = r * 0.6;
  31014. var cpLen2 = r * 0.7;
  31015. path.moveTo(x - dx, cy + dy);
  31016. path.arc(
  31017. x, cy, r,
  31018. Math.PI - angle,
  31019. Math.PI * 2 + angle
  31020. );
  31021. path.bezierCurveTo(
  31022. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  31023. x, y - cpLen2,
  31024. x, y
  31025. );
  31026. path.bezierCurveTo(
  31027. x, y - cpLen2,
  31028. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  31029. x - dx, cy + dy
  31030. );
  31031. path.closePath();
  31032. }
  31033. });
  31034. /**
  31035. * Arrow shape
  31036. * @inner
  31037. */
  31038. var Arrow = extendShape({
  31039. type: 'arrow',
  31040. shape: {
  31041. x: 0,
  31042. y: 0,
  31043. width: 0,
  31044. height: 0
  31045. },
  31046. buildPath: function (ctx, shape) {
  31047. var height = shape.height;
  31048. var width = shape.width;
  31049. var x = shape.x;
  31050. var y = shape.y;
  31051. var dx = width / 3 * 2;
  31052. ctx.moveTo(x, y);
  31053. ctx.lineTo(x + dx, y + height);
  31054. ctx.lineTo(x, y + height / 4 * 3);
  31055. ctx.lineTo(x - dx, y + height);
  31056. ctx.lineTo(x, y);
  31057. ctx.closePath();
  31058. }
  31059. });
  31060. /**
  31061. * Map of path contructors
  31062. * @type {Object.<string, module:zrender/graphic/Path>}
  31063. */
  31064. var symbolCtors = {
  31065. line: Line,
  31066. rect: Rect,
  31067. roundRect: Rect,
  31068. square: Rect,
  31069. circle: Circle,
  31070. diamond: Diamond,
  31071. pin: Pin,
  31072. arrow: Arrow,
  31073. triangle: Triangle
  31074. };
  31075. var symbolShapeMakers = {
  31076. line: function (x, y, w, h, shape) {
  31077. // FIXME
  31078. shape.x1 = x;
  31079. shape.y1 = y + h / 2;
  31080. shape.x2 = x + w;
  31081. shape.y2 = y + h / 2;
  31082. },
  31083. rect: function (x, y, w, h, shape) {
  31084. shape.x = x;
  31085. shape.y = y;
  31086. shape.width = w;
  31087. shape.height = h;
  31088. },
  31089. roundRect: function (x, y, w, h, shape) {
  31090. shape.x = x;
  31091. shape.y = y;
  31092. shape.width = w;
  31093. shape.height = h;
  31094. shape.r = Math.min(w, h) / 4;
  31095. },
  31096. square: function (x, y, w, h, shape) {
  31097. var size = Math.min(w, h);
  31098. shape.x = x;
  31099. shape.y = y;
  31100. shape.width = size;
  31101. shape.height = size;
  31102. },
  31103. circle: function (x, y, w, h, shape) {
  31104. // Put circle in the center of square
  31105. shape.cx = x + w / 2;
  31106. shape.cy = y + h / 2;
  31107. shape.r = Math.min(w, h) / 2;
  31108. },
  31109. diamond: function (x, y, w, h, shape) {
  31110. shape.cx = x + w / 2;
  31111. shape.cy = y + h / 2;
  31112. shape.width = w;
  31113. shape.height = h;
  31114. },
  31115. pin: function (x, y, w, h, shape) {
  31116. shape.x = x + w / 2;
  31117. shape.y = y + h / 2;
  31118. shape.width = w;
  31119. shape.height = h;
  31120. },
  31121. arrow: function (x, y, w, h, shape) {
  31122. shape.x = x + w / 2;
  31123. shape.y = y + h / 2;
  31124. shape.width = w;
  31125. shape.height = h;
  31126. },
  31127. triangle: function (x, y, w, h, shape) {
  31128. shape.cx = x + w / 2;
  31129. shape.cy = y + h / 2;
  31130. shape.width = w;
  31131. shape.height = h;
  31132. }
  31133. };
  31134. var symbolBuildProxies = {};
  31135. each$1(symbolCtors, function (Ctor, name) {
  31136. symbolBuildProxies[name] = new Ctor();
  31137. });
  31138. var SymbolClz = extendShape({
  31139. type: 'symbol',
  31140. shape: {
  31141. symbolType: '',
  31142. x: 0,
  31143. y: 0,
  31144. width: 0,
  31145. height: 0
  31146. },
  31147. calculateTextPosition: function (out, style, rect) {
  31148. var res = calculateTextPosition(out, style, rect);
  31149. var shape = this.shape;
  31150. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  31151. res.y = rect.y + rect.height * 0.4;
  31152. }
  31153. return res;
  31154. },
  31155. buildPath: function (ctx, shape, inBundle) {
  31156. var symbolType = shape.symbolType;
  31157. if (symbolType !== 'none') {
  31158. var proxySymbol = symbolBuildProxies[symbolType];
  31159. if (!proxySymbol) {
  31160. // Default rect
  31161. symbolType = 'rect';
  31162. proxySymbol = symbolBuildProxies[symbolType];
  31163. }
  31164. symbolShapeMakers[symbolType](
  31165. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  31166. );
  31167. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  31168. }
  31169. }
  31170. });
  31171. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  31172. function symbolPathSetColor(color, innerColor) {
  31173. if (this.type !== 'image') {
  31174. var symbolStyle = this.style;
  31175. var symbolShape = this.shape;
  31176. if (symbolShape && symbolShape.symbolType === 'line') {
  31177. symbolStyle.stroke = color;
  31178. }
  31179. else if (this.__isEmptyBrush) {
  31180. symbolStyle.stroke = color;
  31181. symbolStyle.fill = innerColor || '#fff';
  31182. }
  31183. else {
  31184. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  31185. symbolStyle.fill && (symbolStyle.fill = color);
  31186. symbolStyle.stroke && (symbolStyle.stroke = color);
  31187. }
  31188. this.dirty(false);
  31189. }
  31190. }
  31191. /**
  31192. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  31193. * @param {string} symbolType
  31194. * @param {number} x
  31195. * @param {number} y
  31196. * @param {number} w
  31197. * @param {number} h
  31198. * @param {string} color
  31199. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  31200. * for path and image only.
  31201. */
  31202. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  31203. // TODO Support image object, DynamicImage.
  31204. var isEmpty = symbolType.indexOf('empty') === 0;
  31205. if (isEmpty) {
  31206. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  31207. }
  31208. var symbolPath;
  31209. if (symbolType.indexOf('image://') === 0) {
  31210. symbolPath = makeImage(
  31211. symbolType.slice(8),
  31212. new BoundingRect(x, y, w, h),
  31213. keepAspect ? 'center' : 'cover'
  31214. );
  31215. }
  31216. else if (symbolType.indexOf('path://') === 0) {
  31217. symbolPath = makePath(
  31218. symbolType.slice(7),
  31219. {},
  31220. new BoundingRect(x, y, w, h),
  31221. keepAspect ? 'center' : 'cover'
  31222. );
  31223. }
  31224. else {
  31225. symbolPath = new SymbolClz({
  31226. shape: {
  31227. symbolType: symbolType,
  31228. x: x,
  31229. y: y,
  31230. width: w,
  31231. height: h
  31232. }
  31233. });
  31234. }
  31235. symbolPath.__isEmptyBrush = isEmpty;
  31236. symbolPath.setColor = symbolPathSetColor;
  31237. symbolPath.setColor(color);
  31238. return symbolPath;
  31239. }
  31240. /*
  31241. * Licensed to the Apache Software Foundation (ASF) under one
  31242. * or more contributor license agreements. See the NOTICE file
  31243. * distributed with this work for additional information
  31244. * regarding copyright ownership. The ASF licenses this file
  31245. * to you under the Apache License, Version 2.0 (the
  31246. * "License"); you may not use this file except in compliance
  31247. * with the License. You may obtain a copy of the License at
  31248. *
  31249. * http://www.apache.org/licenses/LICENSE-2.0
  31250. *
  31251. * Unless required by applicable law or agreed to in writing,
  31252. * software distributed under the License is distributed on an
  31253. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31254. * KIND, either express or implied. See the License for the
  31255. * specific language governing permissions and limitations
  31256. * under the License.
  31257. */
  31258. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  31259. /**
  31260. * Create a muti dimension List structure from seriesModel.
  31261. * @param {module:echarts/model/Model} seriesModel
  31262. * @return {module:echarts/data/List} list
  31263. */
  31264. function createList(seriesModel) {
  31265. return createListFromArray(seriesModel.getSource(), seriesModel);
  31266. }
  31267. var dataStack$1 = {
  31268. isDimensionStacked: isDimensionStacked,
  31269. enableDataStack: enableDataStack,
  31270. getStackedDimension: getStackedDimension
  31271. };
  31272. /**
  31273. * Create scale
  31274. * @param {Array.<number>} dataExtent
  31275. * @param {Object|module:echarts/Model} option
  31276. */
  31277. function createScale(dataExtent, option) {
  31278. var axisModel = option;
  31279. if (!Model.isInstance(option)) {
  31280. axisModel = new Model(option);
  31281. mixin(axisModel, axisModelCommonMixin);
  31282. }
  31283. var scale = createScaleByModel(axisModel);
  31284. scale.setExtent(dataExtent[0], dataExtent[1]);
  31285. niceScaleExtent(scale, axisModel);
  31286. return scale;
  31287. }
  31288. /**
  31289. * Mixin common methods to axis model,
  31290. *
  31291. * Inlcude methods
  31292. * `getFormattedLabels() => Array.<string>`
  31293. * `getCategories() => Array.<string>`
  31294. * `getMin(origin: boolean) => number`
  31295. * `getMax(origin: boolean) => number`
  31296. * `getNeedCrossZero() => boolean`
  31297. * `setRange(start: number, end: number)`
  31298. * `resetRange()`
  31299. */
  31300. function mixinAxisModelCommonMethods(Model$$1) {
  31301. mixin(Model$$1, axisModelCommonMixin);
  31302. }
  31303. var helper = (Object.freeze || Object)({
  31304. createList: createList,
  31305. getLayoutRect: getLayoutRect,
  31306. dataStack: dataStack$1,
  31307. createScale: createScale,
  31308. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31309. completeDimensions: completeDimensions,
  31310. createDimensions: createDimensions,
  31311. createSymbol: createSymbol
  31312. });
  31313. var EPSILON$3 = 1e-8;
  31314. function isAroundEqual$1(a, b) {
  31315. return Math.abs(a - b) < EPSILON$3;
  31316. }
  31317. function contain$1(points, x, y) {
  31318. var w = 0;
  31319. var p = points[0];
  31320. if (!p) {
  31321. return false;
  31322. }
  31323. for (var i = 1; i < points.length; i++) {
  31324. var p2 = points[i];
  31325. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31326. p = p2;
  31327. }
  31328. // Close polygon
  31329. var p0 = points[0];
  31330. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31331. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31332. }
  31333. return w !== 0;
  31334. }
  31335. /*
  31336. * Licensed to the Apache Software Foundation (ASF) under one
  31337. * or more contributor license agreements. See the NOTICE file
  31338. * distributed with this work for additional information
  31339. * regarding copyright ownership. The ASF licenses this file
  31340. * to you under the Apache License, Version 2.0 (the
  31341. * "License"); you may not use this file except in compliance
  31342. * with the License. You may obtain a copy of the License at
  31343. *
  31344. * http://www.apache.org/licenses/LICENSE-2.0
  31345. *
  31346. * Unless required by applicable law or agreed to in writing,
  31347. * software distributed under the License is distributed on an
  31348. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31349. * KIND, either express or implied. See the License for the
  31350. * specific language governing permissions and limitations
  31351. * under the License.
  31352. */
  31353. /**
  31354. * @module echarts/coord/geo/Region
  31355. */
  31356. /**
  31357. * @param {string|Region} name
  31358. * @param {Array} geometries
  31359. * @param {Array.<number>} cp
  31360. */
  31361. function Region(name, geometries, cp) {
  31362. /**
  31363. * @type {string}
  31364. * @readOnly
  31365. */
  31366. this.name = name;
  31367. /**
  31368. * @type {Array.<Array>}
  31369. * @readOnly
  31370. */
  31371. this.geometries = geometries;
  31372. if (!cp) {
  31373. var rect = this.getBoundingRect();
  31374. cp = [
  31375. rect.x + rect.width / 2,
  31376. rect.y + rect.height / 2
  31377. ];
  31378. }
  31379. else {
  31380. cp = [cp[0], cp[1]];
  31381. }
  31382. /**
  31383. * @type {Array.<number>}
  31384. */
  31385. this.center = cp;
  31386. }
  31387. Region.prototype = {
  31388. constructor: Region,
  31389. properties: null,
  31390. /**
  31391. * @return {module:zrender/core/BoundingRect}
  31392. */
  31393. getBoundingRect: function () {
  31394. var rect = this._rect;
  31395. if (rect) {
  31396. return rect;
  31397. }
  31398. var MAX_NUMBER = Number.MAX_VALUE;
  31399. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  31400. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  31401. var min2 = [];
  31402. var max2 = [];
  31403. var geometries = this.geometries;
  31404. for (var i = 0; i < geometries.length; i++) {
  31405. // Only support polygon
  31406. if (geometries[i].type !== 'polygon') {
  31407. continue;
  31408. }
  31409. // Doesn't consider hole
  31410. var exterior = geometries[i].exterior;
  31411. fromPoints(exterior, min2, max2);
  31412. min(min$$1, min$$1, min2);
  31413. max(max$$1, max$$1, max2);
  31414. }
  31415. // No data
  31416. if (i === 0) {
  31417. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  31418. }
  31419. return (this._rect = new BoundingRect(
  31420. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  31421. ));
  31422. },
  31423. /**
  31424. * @param {<Array.<number>} coord
  31425. * @return {boolean}
  31426. */
  31427. contain: function (coord) {
  31428. var rect = this.getBoundingRect();
  31429. var geometries = this.geometries;
  31430. if (!rect.contain(coord[0], coord[1])) {
  31431. return false;
  31432. }
  31433. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  31434. // Only support polygon.
  31435. if (geometries[i].type !== 'polygon') {
  31436. continue;
  31437. }
  31438. var exterior = geometries[i].exterior;
  31439. var interiors = geometries[i].interiors;
  31440. if (contain$1(exterior, coord[0], coord[1])) {
  31441. // Not in the region if point is in the hole.
  31442. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31443. if (contain$1(interiors[k])) {
  31444. continue loopGeo;
  31445. }
  31446. }
  31447. return true;
  31448. }
  31449. }
  31450. return false;
  31451. },
  31452. transformTo: function (x, y, width, height) {
  31453. var rect = this.getBoundingRect();
  31454. var aspect = rect.width / rect.height;
  31455. if (!width) {
  31456. width = aspect * height;
  31457. }
  31458. else if (!height) {
  31459. height = width / aspect;
  31460. }
  31461. var target = new BoundingRect(x, y, width, height);
  31462. var transform = rect.calculateTransform(target);
  31463. var geometries = this.geometries;
  31464. for (var i = 0; i < geometries.length; i++) {
  31465. // Only support polygon.
  31466. if (geometries[i].type !== 'polygon') {
  31467. continue;
  31468. }
  31469. var exterior = geometries[i].exterior;
  31470. var interiors = geometries[i].interiors;
  31471. for (var p = 0; p < exterior.length; p++) {
  31472. applyTransform(exterior[p], exterior[p], transform);
  31473. }
  31474. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  31475. for (var p = 0; p < interiors[h].length; p++) {
  31476. applyTransform(interiors[h][p], interiors[h][p], transform);
  31477. }
  31478. }
  31479. }
  31480. rect = this._rect;
  31481. rect.copy(target);
  31482. // Update center
  31483. this.center = [
  31484. rect.x + rect.width / 2,
  31485. rect.y + rect.height / 2
  31486. ];
  31487. },
  31488. cloneShallow: function (name) {
  31489. name == null && (name = this.name);
  31490. var newRegion = new Region(name, this.geometries, this.center);
  31491. newRegion._rect = this._rect;
  31492. newRegion.transformTo = null; // Simply avoid to be called.
  31493. return newRegion;
  31494. }
  31495. };
  31496. /*
  31497. * Licensed to the Apache Software Foundation (ASF) under one
  31498. * or more contributor license agreements. See the NOTICE file
  31499. * distributed with this work for additional information
  31500. * regarding copyright ownership. The ASF licenses this file
  31501. * to you under the Apache License, Version 2.0 (the
  31502. * "License"); you may not use this file except in compliance
  31503. * with the License. You may obtain a copy of the License at
  31504. *
  31505. * http://www.apache.org/licenses/LICENSE-2.0
  31506. *
  31507. * Unless required by applicable law or agreed to in writing,
  31508. * software distributed under the License is distributed on an
  31509. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31510. * KIND, either express or implied. See the License for the
  31511. * specific language governing permissions and limitations
  31512. * under the License.
  31513. */
  31514. /**
  31515. * Parse and decode geo json
  31516. * @module echarts/coord/geo/parseGeoJson
  31517. */
  31518. function decode(json) {
  31519. if (!json.UTF8Encoding) {
  31520. return json;
  31521. }
  31522. var encodeScale = json.UTF8Scale;
  31523. if (encodeScale == null) {
  31524. encodeScale = 1024;
  31525. }
  31526. var features = json.features;
  31527. for (var f = 0; f < features.length; f++) {
  31528. var feature = features[f];
  31529. var geometry = feature.geometry;
  31530. var coordinates = geometry.coordinates;
  31531. var encodeOffsets = geometry.encodeOffsets;
  31532. for (var c = 0; c < coordinates.length; c++) {
  31533. var coordinate = coordinates[c];
  31534. if (geometry.type === 'Polygon') {
  31535. coordinates[c] = decodePolygon(
  31536. coordinate,
  31537. encodeOffsets[c],
  31538. encodeScale
  31539. );
  31540. }
  31541. else if (geometry.type === 'MultiPolygon') {
  31542. for (var c2 = 0; c2 < coordinate.length; c2++) {
  31543. var polygon = coordinate[c2];
  31544. coordinate[c2] = decodePolygon(
  31545. polygon,
  31546. encodeOffsets[c][c2],
  31547. encodeScale
  31548. );
  31549. }
  31550. }
  31551. }
  31552. }
  31553. // Has been decoded
  31554. json.UTF8Encoding = false;
  31555. return json;
  31556. }
  31557. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  31558. var result = [];
  31559. var prevX = encodeOffsets[0];
  31560. var prevY = encodeOffsets[1];
  31561. for (var i = 0; i < coordinate.length; i += 2) {
  31562. var x = coordinate.charCodeAt(i) - 64;
  31563. var y = coordinate.charCodeAt(i + 1) - 64;
  31564. // ZigZag decoding
  31565. x = (x >> 1) ^ (-(x & 1));
  31566. y = (y >> 1) ^ (-(y & 1));
  31567. // Delta deocding
  31568. x += prevX;
  31569. y += prevY;
  31570. prevX = x;
  31571. prevY = y;
  31572. // Dequantize
  31573. result.push([x / encodeScale, y / encodeScale]);
  31574. }
  31575. return result;
  31576. }
  31577. /**
  31578. * @alias module:echarts/coord/geo/parseGeoJson
  31579. * @param {Object} geoJson
  31580. * @return {module:zrender/container/Group}
  31581. */
  31582. var parseGeoJSON = function (geoJson) {
  31583. decode(geoJson);
  31584. return map(filter(geoJson.features, function (featureObj) {
  31585. // Output of mapshaper may have geometry null
  31586. return featureObj.geometry
  31587. && featureObj.properties
  31588. && featureObj.geometry.coordinates.length > 0;
  31589. }), function (featureObj) {
  31590. var properties = featureObj.properties;
  31591. var geo = featureObj.geometry;
  31592. var coordinates = geo.coordinates;
  31593. var geometries = [];
  31594. if (geo.type === 'Polygon') {
  31595. geometries.push({
  31596. type: 'polygon',
  31597. // According to the GeoJSON specification.
  31598. // First must be exterior, and the rest are all interior(holes).
  31599. exterior: coordinates[0],
  31600. interiors: coordinates.slice(1)
  31601. });
  31602. }
  31603. if (geo.type === 'MultiPolygon') {
  31604. each$1(coordinates, function (item) {
  31605. if (item[0]) {
  31606. geometries.push({
  31607. type: 'polygon',
  31608. exterior: item[0],
  31609. interiors: item.slice(1)
  31610. });
  31611. }
  31612. });
  31613. }
  31614. var region = new Region(
  31615. properties.name,
  31616. geometries,
  31617. properties.cp
  31618. );
  31619. region.properties = properties;
  31620. return region;
  31621. });
  31622. };
  31623. /*
  31624. * Licensed to the Apache Software Foundation (ASF) under one
  31625. * or more contributor license agreements. See the NOTICE file
  31626. * distributed with this work for additional information
  31627. * regarding copyright ownership. The ASF licenses this file
  31628. * to you under the Apache License, Version 2.0 (the
  31629. * "License"); you may not use this file except in compliance
  31630. * with the License. You may obtain a copy of the License at
  31631. *
  31632. * http://www.apache.org/licenses/LICENSE-2.0
  31633. *
  31634. * Unless required by applicable law or agreed to in writing,
  31635. * software distributed under the License is distributed on an
  31636. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31637. * KIND, either express or implied. See the License for the
  31638. * specific language governing permissions and limitations
  31639. * under the License.
  31640. */
  31641. var inner$6 = makeInner();
  31642. /**
  31643. * @param {module:echats/coord/Axis} axis
  31644. * @return {Object} {
  31645. * labels: [{
  31646. * formattedLabel: string,
  31647. * rawLabel: string,
  31648. * tickValue: number
  31649. * }, ...],
  31650. * labelCategoryInterval: number
  31651. * }
  31652. */
  31653. function createAxisLabels(axis) {
  31654. // Only ordinal scale support tick interval
  31655. return axis.type === 'category'
  31656. ? makeCategoryLabels(axis)
  31657. : makeRealNumberLabels(axis);
  31658. }
  31659. /**
  31660. * @param {module:echats/coord/Axis} axis
  31661. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31662. * @return {Object} {
  31663. * ticks: Array.<number>
  31664. * tickCategoryInterval: number
  31665. * }
  31666. */
  31667. function createAxisTicks(axis, tickModel) {
  31668. // Only ordinal scale support tick interval
  31669. return axis.type === 'category'
  31670. ? makeCategoryTicks(axis, tickModel)
  31671. : {ticks: axis.scale.getTicks()};
  31672. }
  31673. function makeCategoryLabels(axis) {
  31674. var labelModel = axis.getLabelModel();
  31675. var result = makeCategoryLabelsActually(axis, labelModel);
  31676. return (!labelModel.get('show') || axis.scale.isBlank())
  31677. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  31678. : result;
  31679. }
  31680. function makeCategoryLabelsActually(axis, labelModel) {
  31681. var labelsCache = getListCache(axis, 'labels');
  31682. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31683. var result = listCacheGet(labelsCache, optionLabelInterval);
  31684. if (result) {
  31685. return result;
  31686. }
  31687. var labels;
  31688. var numericLabelInterval;
  31689. if (isFunction$1(optionLabelInterval)) {
  31690. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31691. }
  31692. else {
  31693. numericLabelInterval = optionLabelInterval === 'auto'
  31694. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31695. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31696. }
  31697. // Cache to avoid calling interval function repeatly.
  31698. return listCacheSet(labelsCache, optionLabelInterval, {
  31699. labels: labels, labelCategoryInterval: numericLabelInterval
  31700. });
  31701. }
  31702. function makeCategoryTicks(axis, tickModel) {
  31703. var ticksCache = getListCache(axis, 'ticks');
  31704. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31705. var result = listCacheGet(ticksCache, optionTickInterval);
  31706. if (result) {
  31707. return result;
  31708. }
  31709. var ticks;
  31710. var tickCategoryInterval;
  31711. // Optimize for the case that large category data and no label displayed,
  31712. // we should not return all ticks.
  31713. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31714. ticks = [];
  31715. }
  31716. if (isFunction$1(optionTickInterval)) {
  31717. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31718. }
  31719. // Always use label interval by default despite label show. Consider this
  31720. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31721. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31722. else if (optionTickInterval === 'auto') {
  31723. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31724. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31725. ticks = map(labelsResult.labels, function (labelItem) {
  31726. return labelItem.tickValue;
  31727. });
  31728. }
  31729. else {
  31730. tickCategoryInterval = optionTickInterval;
  31731. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31732. }
  31733. // Cache to avoid calling interval function repeatly.
  31734. return listCacheSet(ticksCache, optionTickInterval, {
  31735. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  31736. });
  31737. }
  31738. function makeRealNumberLabels(axis) {
  31739. var ticks = axis.scale.getTicks();
  31740. var labelFormatter = makeLabelFormatter(axis);
  31741. return {
  31742. labels: map(ticks, function (tickValue, idx) {
  31743. return {
  31744. formattedLabel: labelFormatter(tickValue, idx),
  31745. rawLabel: axis.scale.getLabel(tickValue),
  31746. tickValue: tickValue
  31747. };
  31748. })
  31749. };
  31750. }
  31751. // Large category data calculation is performence sensitive, and ticks and label
  31752. // probably be fetched by multiple times. So we cache the result.
  31753. // axis is created each time during a ec process, so we do not need to clear cache.
  31754. function getListCache(axis, prop) {
  31755. // Because key can be funciton, and cache size always be small, we use array cache.
  31756. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  31757. }
  31758. function listCacheGet(cache, key) {
  31759. for (var i = 0; i < cache.length; i++) {
  31760. if (cache[i].key === key) {
  31761. return cache[i].value;
  31762. }
  31763. }
  31764. }
  31765. function listCacheSet(cache, key, value) {
  31766. cache.push({key: key, value: value});
  31767. return value;
  31768. }
  31769. function makeAutoCategoryInterval(axis) {
  31770. var result = inner$6(axis).autoInterval;
  31771. return result != null
  31772. ? result
  31773. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  31774. }
  31775. /**
  31776. * Calculate interval for category axis ticks and labels.
  31777. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31778. * should be implemented in axis.
  31779. */
  31780. function calculateCategoryInterval(axis) {
  31781. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31782. var labelFormatter = makeLabelFormatter(axis);
  31783. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  31784. var ordinalScale = axis.scale;
  31785. var ordinalExtent = ordinalScale.getExtent();
  31786. // Providing this method is for optimization:
  31787. // avoid generating a long array by `getTicks`
  31788. // in large category data case.
  31789. var tickCount = ordinalScale.count();
  31790. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  31791. return 0;
  31792. }
  31793. var step = 1;
  31794. // Simple optimization. Empirical value: tick count should less than 40.
  31795. if (tickCount > 40) {
  31796. step = Math.max(1, Math.floor(tickCount / 40));
  31797. }
  31798. var tickValue = ordinalExtent[0];
  31799. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  31800. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  31801. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  31802. var maxW = 0;
  31803. var maxH = 0;
  31804. // Caution: Performance sensitive for large category data.
  31805. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  31806. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31807. var width = 0;
  31808. var height = 0;
  31809. // Not precise, do not consider align and vertical align
  31810. // and each distance from axis line yet.
  31811. var rect = getBoundingRect(
  31812. labelFormatter(tickValue), params.font, 'center', 'top'
  31813. );
  31814. // Magic number
  31815. width = rect.width * 1.3;
  31816. height = rect.height * 1.3;
  31817. // Min size, void long loop.
  31818. maxW = Math.max(maxW, width, 7);
  31819. maxH = Math.max(maxH, height, 7);
  31820. }
  31821. var dw = maxW / unitW;
  31822. var dh = maxH / unitH;
  31823. // 0/0 is NaN, 1/0 is Infinity.
  31824. isNaN(dw) && (dw = Infinity);
  31825. isNaN(dh) && (dh = Infinity);
  31826. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  31827. var cache = inner$6(axis.model);
  31828. var axisExtent = axis.getExtent();
  31829. var lastAutoInterval = cache.lastAutoInterval;
  31830. var lastTickCount = cache.lastTickCount;
  31831. // Use cache to keep interval stable while moving zoom window,
  31832. // otherwise the calculated interval might jitter when the zoom
  31833. // window size is close to the interval-changing size.
  31834. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  31835. // The jitter will cause that sometimes the displayed labels are
  31836. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  31837. if (lastAutoInterval != null
  31838. && lastTickCount != null
  31839. && Math.abs(lastAutoInterval - interval) <= 1
  31840. && Math.abs(lastTickCount - tickCount) <= 1
  31841. // Always choose the bigger one, otherwise the critical
  31842. // point is not the same when zooming in or zooming out.
  31843. && lastAutoInterval > interval
  31844. // If the axis change is caused by chart resize, the cache should not
  31845. // be used. Otherwise some hiden labels might not be shown again.
  31846. && cache.axisExtend0 === axisExtent[0]
  31847. && cache.axisExtend1 === axisExtent[1]
  31848. ) {
  31849. interval = lastAutoInterval;
  31850. }
  31851. // Only update cache if cache not used, otherwise the
  31852. // changing of interval is too insensitive.
  31853. else {
  31854. cache.lastTickCount = tickCount;
  31855. cache.lastAutoInterval = interval;
  31856. cache.axisExtend0 = axisExtent[0];
  31857. cache.axisExtend1 = axisExtent[1];
  31858. }
  31859. return interval;
  31860. }
  31861. function fetchAutoCategoryIntervalCalculationParams(axis) {
  31862. var labelModel = axis.getLabelModel();
  31863. return {
  31864. axisRotate: axis.getRotate
  31865. ? axis.getRotate()
  31866. : (axis.isHorizontal && !axis.isHorizontal())
  31867. ? 90
  31868. : 0,
  31869. labelRotate: labelModel.get('rotate') || 0,
  31870. font: labelModel.getFont()
  31871. };
  31872. }
  31873. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  31874. var labelFormatter = makeLabelFormatter(axis);
  31875. var ordinalScale = axis.scale;
  31876. var ordinalExtent = ordinalScale.getExtent();
  31877. var labelModel = axis.getLabelModel();
  31878. var result = [];
  31879. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  31880. var step = Math.max((categoryInterval || 0) + 1, 1);
  31881. var startTick = ordinalExtent[0];
  31882. var tickCount = ordinalScale.count();
  31883. // Calculate start tick based on zero if possible to keep label consistent
  31884. // while zooming and moving while interval > 0. Otherwise the selection
  31885. // of displayable ticks and symbols probably keep changing.
  31886. // 3 is empirical value.
  31887. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  31888. startTick = Math.round(Math.ceil(startTick / step) * step);
  31889. }
  31890. // (1) Only add min max label here but leave overlap checking
  31891. // to render stage, which also ensure the returned list
  31892. // suitable for splitLine and splitArea rendering.
  31893. // (2) Scales except category always contain min max label so
  31894. // do not need to perform this process.
  31895. var showAllLabel = shouldShowAllLabels(axis);
  31896. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  31897. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  31898. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  31899. addItem(ordinalExtent[0]);
  31900. }
  31901. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  31902. var tickValue = startTick;
  31903. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31904. addItem(tickValue);
  31905. }
  31906. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  31907. addItem(ordinalExtent[1]);
  31908. }
  31909. function addItem(tVal) {
  31910. result.push(onlyTick
  31911. ? tVal
  31912. : {
  31913. formattedLabel: labelFormatter(tVal),
  31914. rawLabel: ordinalScale.getLabel(tVal),
  31915. tickValue: tVal
  31916. }
  31917. );
  31918. }
  31919. return result;
  31920. }
  31921. // When interval is function, the result `false` means ignore the tick.
  31922. // It is time consuming for large category data.
  31923. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  31924. var ordinalScale = axis.scale;
  31925. var labelFormatter = makeLabelFormatter(axis);
  31926. var result = [];
  31927. each$1(ordinalScale.getTicks(), function (tickValue) {
  31928. var rawLabel = ordinalScale.getLabel(tickValue);
  31929. if (categoryInterval(tickValue, rawLabel)) {
  31930. result.push(onlyTick
  31931. ? tickValue
  31932. : {
  31933. formattedLabel: labelFormatter(tickValue),
  31934. rawLabel: rawLabel,
  31935. tickValue: tickValue
  31936. }
  31937. );
  31938. }
  31939. });
  31940. return result;
  31941. }
  31942. /*
  31943. * Licensed to the Apache Software Foundation (ASF) under one
  31944. * or more contributor license agreements. See the NOTICE file
  31945. * distributed with this work for additional information
  31946. * regarding copyright ownership. The ASF licenses this file
  31947. * to you under the Apache License, Version 2.0 (the
  31948. * "License"); you may not use this file except in compliance
  31949. * with the License. You may obtain a copy of the License at
  31950. *
  31951. * http://www.apache.org/licenses/LICENSE-2.0
  31952. *
  31953. * Unless required by applicable law or agreed to in writing,
  31954. * software distributed under the License is distributed on an
  31955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31956. * KIND, either express or implied. See the License for the
  31957. * specific language governing permissions and limitations
  31958. * under the License.
  31959. */
  31960. var NORMALIZED_EXTENT = [0, 1];
  31961. /**
  31962. * Base class of Axis.
  31963. * @constructor
  31964. */
  31965. var Axis = function (dim, scale, extent) {
  31966. /**
  31967. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  31968. * @type {string}
  31969. */
  31970. this.dim = dim;
  31971. /**
  31972. * Axis scale
  31973. * @type {module:echarts/coord/scale/*}
  31974. */
  31975. this.scale = scale;
  31976. /**
  31977. * @type {Array.<number>}
  31978. * @private
  31979. */
  31980. this._extent = extent || [0, 0];
  31981. /**
  31982. * @type {boolean}
  31983. */
  31984. this.inverse = false;
  31985. /**
  31986. * Usually true when axis has a ordinal scale
  31987. * @type {boolean}
  31988. */
  31989. this.onBand = false;
  31990. };
  31991. Axis.prototype = {
  31992. constructor: Axis,
  31993. /**
  31994. * If axis extent contain given coord
  31995. * @param {number} coord
  31996. * @return {boolean}
  31997. */
  31998. contain: function (coord) {
  31999. var extent = this._extent;
  32000. var min = Math.min(extent[0], extent[1]);
  32001. var max = Math.max(extent[0], extent[1]);
  32002. return coord >= min && coord <= max;
  32003. },
  32004. /**
  32005. * If axis extent contain given data
  32006. * @param {number} data
  32007. * @return {boolean}
  32008. */
  32009. containData: function (data) {
  32010. return this.scale.contain(data);
  32011. },
  32012. /**
  32013. * Get coord extent.
  32014. * @return {Array.<number>}
  32015. */
  32016. getExtent: function () {
  32017. return this._extent.slice();
  32018. },
  32019. /**
  32020. * Get precision used for formatting
  32021. * @param {Array.<number>} [dataExtent]
  32022. * @return {number}
  32023. */
  32024. getPixelPrecision: function (dataExtent) {
  32025. return getPixelPrecision(
  32026. dataExtent || this.scale.getExtent(),
  32027. this._extent
  32028. );
  32029. },
  32030. /**
  32031. * Set coord extent
  32032. * @param {number} start
  32033. * @param {number} end
  32034. */
  32035. setExtent: function (start, end) {
  32036. var extent = this._extent;
  32037. extent[0] = start;
  32038. extent[1] = end;
  32039. },
  32040. /**
  32041. * Convert data to coord. Data is the rank if it has an ordinal scale
  32042. * @param {number} data
  32043. * @param {boolean} clamp
  32044. * @return {number}
  32045. */
  32046. dataToCoord: function (data, clamp) {
  32047. var extent = this._extent;
  32048. var scale = this.scale;
  32049. data = scale.normalize(data);
  32050. if (this.onBand && scale.type === 'ordinal') {
  32051. extent = extent.slice();
  32052. fixExtentWithBands(extent, scale.count());
  32053. }
  32054. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32055. },
  32056. /**
  32057. * Convert coord to data. Data is the rank if it has an ordinal scale
  32058. * @param {number} coord
  32059. * @param {boolean} clamp
  32060. * @return {number}
  32061. */
  32062. coordToData: function (coord, clamp) {
  32063. var extent = this._extent;
  32064. var scale = this.scale;
  32065. if (this.onBand && scale.type === 'ordinal') {
  32066. extent = extent.slice();
  32067. fixExtentWithBands(extent, scale.count());
  32068. }
  32069. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32070. return this.scale.scale(t);
  32071. },
  32072. /**
  32073. * Convert pixel point to data in axis
  32074. * @param {Array.<number>} point
  32075. * @param {boolean} clamp
  32076. * @return {number} data
  32077. */
  32078. pointToData: function (point, clamp) {
  32079. // Should be implemented in derived class if necessary.
  32080. },
  32081. /**
  32082. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32083. * `axis.getTicksCoords` considers `onBand`, which is used by
  32084. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32085. * @param {Object} [opt]
  32086. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  32087. * @param {boolean} [opt.clamp] If `true`, the first and the last
  32088. * tick must be at the axis end points. Otherwise, clip ticks
  32089. * that outside the axis extent.
  32090. * @return {Array.<Object>} [{
  32091. * coord: ...,
  32092. * tickValue: ...
  32093. * }, ...]
  32094. */
  32095. getTicksCoords: function (opt) {
  32096. opt = opt || {};
  32097. var tickModel = opt.tickModel || this.getTickModel();
  32098. var result = createAxisTicks(this, tickModel);
  32099. var ticks = result.ticks;
  32100. var ticksCoords = map(ticks, function (tickValue) {
  32101. return {
  32102. coord: this.dataToCoord(tickValue),
  32103. tickValue: tickValue
  32104. };
  32105. }, this);
  32106. var alignWithLabel = tickModel.get('alignWithLabel');
  32107. fixOnBandTicksCoords(
  32108. this, ticksCoords, alignWithLabel, opt.clamp
  32109. );
  32110. return ticksCoords;
  32111. },
  32112. /**
  32113. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  32114. */
  32115. getMinorTicksCoords: function () {
  32116. if (this.scale.type === 'ordinal') {
  32117. // Category axis doesn't support minor ticks
  32118. return [];
  32119. }
  32120. var minorTickModel = this.model.getModel('minorTick');
  32121. var splitNumber = minorTickModel.get('splitNumber');
  32122. // Protection.
  32123. if (!(splitNumber > 0 && splitNumber < 100)) {
  32124. splitNumber = 5;
  32125. }
  32126. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32127. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32128. return map(minorTicksGroup, function (minorTick) {
  32129. return {
  32130. coord: this.dataToCoord(minorTick),
  32131. tickValue: minorTick
  32132. };
  32133. }, this);
  32134. }, this);
  32135. return minorTicksCoords;
  32136. },
  32137. /**
  32138. * @return {Array.<Object>} [{
  32139. * formattedLabel: string,
  32140. * rawLabel: axis.scale.getLabel(tickValue)
  32141. * tickValue: number
  32142. * }, ...]
  32143. */
  32144. getViewLabels: function () {
  32145. return createAxisLabels(this).labels;
  32146. },
  32147. /**
  32148. * @return {module:echarts/coord/model/Model}
  32149. */
  32150. getLabelModel: function () {
  32151. return this.model.getModel('axisLabel');
  32152. },
  32153. /**
  32154. * Notice here we only get the default tick model. For splitLine
  32155. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32156. * manually when calling `getTicksCoords`.
  32157. * In GL, this method may be overrided to:
  32158. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32159. * @return {module:echarts/coord/model/Model}
  32160. */
  32161. getTickModel: function () {
  32162. return this.model.getModel('axisTick');
  32163. },
  32164. /**
  32165. * Get width of band
  32166. * @return {number}
  32167. */
  32168. getBandWidth: function () {
  32169. var axisExtent = this._extent;
  32170. var dataExtent = this.scale.getExtent();
  32171. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32172. // Fix #2728, avoid NaN when only one data.
  32173. len === 0 && (len = 1);
  32174. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32175. return Math.abs(size) / len;
  32176. },
  32177. /**
  32178. * @abstract
  32179. * @return {boolean} Is horizontal
  32180. */
  32181. isHorizontal: null,
  32182. /**
  32183. * @abstract
  32184. * @return {number} Get axis rotate, by degree.
  32185. */
  32186. getRotate: null,
  32187. /**
  32188. * Only be called in category axis.
  32189. * Can be overrided, consider other axes like in 3D.
  32190. * @return {number} Auto interval for cateogry axis tick and label
  32191. */
  32192. calculateCategoryInterval: function () {
  32193. return calculateCategoryInterval(this);
  32194. }
  32195. };
  32196. function fixExtentWithBands(extent, nTick) {
  32197. var size = extent[1] - extent[0];
  32198. var len = nTick;
  32199. var margin = size / len / 2;
  32200. extent[0] += margin;
  32201. extent[1] -= margin;
  32202. }
  32203. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32204. // |---1---|---2---|---3---|---4---|.
  32205. // So the displayed ticks and splitLine/splitArea should between
  32206. // each data item, otherwise cause misleading (e.g., split tow bars
  32207. // of a single data item when there are two bar series).
  32208. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32209. // splitLine/spliteArea should layout appropriately corresponding
  32210. // to displayed labels. (So we should not use `getBandWidth` in this
  32211. // case).
  32212. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32213. var ticksLen = ticksCoords.length;
  32214. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32215. return;
  32216. }
  32217. var axisExtent = axis.getExtent();
  32218. var last;
  32219. var diffSize;
  32220. if (ticksLen === 1) {
  32221. ticksCoords[0].coord = axisExtent[0];
  32222. last = ticksCoords[1] = {coord: axisExtent[0]};
  32223. }
  32224. else {
  32225. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32226. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32227. each$1(ticksCoords, function (ticksItem) {
  32228. ticksItem.coord -= shift / 2;
  32229. });
  32230. var dataExtent = axis.scale.getExtent();
  32231. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32232. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  32233. ticksCoords.push(last);
  32234. }
  32235. var inverse = axisExtent[0] > axisExtent[1];
  32236. // Handling clamp.
  32237. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32238. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  32239. }
  32240. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32241. ticksCoords.unshift({coord: axisExtent[0]});
  32242. }
  32243. if (littleThan(axisExtent[1], last.coord)) {
  32244. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  32245. }
  32246. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32247. ticksCoords.push({coord: axisExtent[1]});
  32248. }
  32249. function littleThan(a, b) {
  32250. // Avoid rounding error cause calculated tick coord different with extent.
  32251. // It may cause an extra unecessary tick added.
  32252. a = round$1(a);
  32253. b = round$1(b);
  32254. return inverse ? a > b : a < b;
  32255. }
  32256. }
  32257. /*
  32258. * Licensed to the Apache Software Foundation (ASF) under one
  32259. * or more contributor license agreements. See the NOTICE file
  32260. * distributed with this work for additional information
  32261. * regarding copyright ownership. The ASF licenses this file
  32262. * to you under the Apache License, Version 2.0 (the
  32263. * "License"); you may not use this file except in compliance
  32264. * with the License. You may obtain a copy of the License at
  32265. *
  32266. * http://www.apache.org/licenses/LICENSE-2.0
  32267. *
  32268. * Unless required by applicable law or agreed to in writing,
  32269. * software distributed under the License is distributed on an
  32270. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32271. * KIND, either express or implied. See the License for the
  32272. * specific language governing permissions and limitations
  32273. * under the License.
  32274. */
  32275. /**
  32276. * Do not mount those modules on 'src/echarts' for better tree shaking.
  32277. */
  32278. var parseGeoJson = parseGeoJSON;
  32279. var ecUtil = {};
  32280. each$1(
  32281. [
  32282. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  32283. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  32284. 'extend', 'defaults', 'clone', 'merge'
  32285. ],
  32286. function (name) {
  32287. ecUtil[name] = zrUtil[name];
  32288. }
  32289. );
  32290. var graphic$1 = {};
  32291. each$1(
  32292. [
  32293. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  32294. 'mergePath', 'resizePath', 'createIcon',
  32295. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  32296. 'getFont', 'updateProps', 'initProps', 'getTransform',
  32297. 'clipPointsByRect', 'clipRectByRect',
  32298. 'registerShape', 'getShapeClass',
  32299. 'Group',
  32300. 'Image',
  32301. 'Text',
  32302. 'Circle',
  32303. 'Sector',
  32304. 'Ring',
  32305. 'Polygon',
  32306. 'Polyline',
  32307. 'Rect',
  32308. 'Line',
  32309. 'BezierCurve',
  32310. 'Arc',
  32311. 'IncrementalDisplayable',
  32312. 'CompoundPath',
  32313. 'LinearGradient',
  32314. 'RadialGradient',
  32315. 'BoundingRect'
  32316. ],
  32317. function (name) {
  32318. graphic$1[name] = graphic[name];
  32319. }
  32320. );
  32321. /*
  32322. * Licensed to the Apache Software Foundation (ASF) under one
  32323. * or more contributor license agreements. See the NOTICE file
  32324. * distributed with this work for additional information
  32325. * regarding copyright ownership. The ASF licenses this file
  32326. * to you under the Apache License, Version 2.0 (the
  32327. * "License"); you may not use this file except in compliance
  32328. * with the License. You may obtain a copy of the License at
  32329. *
  32330. * http://www.apache.org/licenses/LICENSE-2.0
  32331. *
  32332. * Unless required by applicable law or agreed to in writing,
  32333. * software distributed under the License is distributed on an
  32334. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32335. * KIND, either express or implied. See the License for the
  32336. * specific language governing permissions and limitations
  32337. * under the License.
  32338. */
  32339. SeriesModel.extend({
  32340. type: 'series.line',
  32341. dependencies: ['grid', 'polar'],
  32342. getInitialData: function (option, ecModel) {
  32343. if (__DEV__) {
  32344. var coordSys = option.coordinateSystem;
  32345. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  32346. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  32347. }
  32348. }
  32349. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  32350. },
  32351. defaultOption: {
  32352. zlevel: 0,
  32353. z: 2,
  32354. coordinateSystem: 'cartesian2d',
  32355. legendHoverLink: true,
  32356. hoverAnimation: true,
  32357. // stack: null
  32358. // xAxisIndex: 0,
  32359. // yAxisIndex: 0,
  32360. // polarIndex: 0,
  32361. // If clip the overflow value
  32362. clip: true,
  32363. // cursor: null,
  32364. label: {
  32365. position: 'top'
  32366. },
  32367. // itemStyle: {
  32368. // },
  32369. lineStyle: {
  32370. width: 2,
  32371. type: 'solid'
  32372. },
  32373. // areaStyle: {
  32374. // origin of areaStyle. Valid values:
  32375. // `'auto'/null/undefined`: from axisLine to data
  32376. // `'start'`: from min to data
  32377. // `'end'`: from data to max
  32378. // origin: 'auto'
  32379. // },
  32380. // false, 'start', 'end', 'middle'
  32381. step: false,
  32382. // Disabled if step is true
  32383. smooth: false,
  32384. smoothMonotone: null,
  32385. symbol: 'emptyCircle',
  32386. symbolSize: 4,
  32387. symbolRotate: null,
  32388. showSymbol: true,
  32389. // `false`: follow the label interval strategy.
  32390. // `true`: show all symbols.
  32391. // `'auto'`: If possible, show all symbols, otherwise
  32392. // follow the label interval strategy.
  32393. showAllSymbol: 'auto',
  32394. // Whether to connect break point.
  32395. connectNulls: false,
  32396. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  32397. sampling: 'none',
  32398. animationEasing: 'linear',
  32399. // Disable progressive
  32400. progressive: 0,
  32401. hoverLayerThreshold: Infinity
  32402. }
  32403. });
  32404. /*
  32405. * Licensed to the Apache Software Foundation (ASF) under one
  32406. * or more contributor license agreements. See the NOTICE file
  32407. * distributed with this work for additional information
  32408. * regarding copyright ownership. The ASF licenses this file
  32409. * to you under the Apache License, Version 2.0 (the
  32410. * "License"); you may not use this file except in compliance
  32411. * with the License. You may obtain a copy of the License at
  32412. *
  32413. * http://www.apache.org/licenses/LICENSE-2.0
  32414. *
  32415. * Unless required by applicable law or agreed to in writing,
  32416. * software distributed under the License is distributed on an
  32417. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32418. * KIND, either express or implied. See the License for the
  32419. * specific language governing permissions and limitations
  32420. * under the License.
  32421. */
  32422. /**
  32423. * @param {module:echarts/data/List} data
  32424. * @param {number} dataIndex
  32425. * @return {string} label string. Not null/undefined
  32426. */
  32427. function getDefaultLabel(data, dataIndex) {
  32428. var labelDims = data.mapDimension('defaultedLabel', true);
  32429. var len = labelDims.length;
  32430. // Simple optimization (in lots of cases, label dims length is 1)
  32431. if (len === 1) {
  32432. return retrieveRawValue(data, dataIndex, labelDims[0]);
  32433. }
  32434. else if (len) {
  32435. var vals = [];
  32436. for (var i = 0; i < labelDims.length; i++) {
  32437. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  32438. vals.push(val);
  32439. }
  32440. return vals.join(' ');
  32441. }
  32442. }
  32443. /*
  32444. * Licensed to the Apache Software Foundation (ASF) under one
  32445. * or more contributor license agreements. See the NOTICE file
  32446. * distributed with this work for additional information
  32447. * regarding copyright ownership. The ASF licenses this file
  32448. * to you under the Apache License, Version 2.0 (the
  32449. * "License"); you may not use this file except in compliance
  32450. * with the License. You may obtain a copy of the License at
  32451. *
  32452. * http://www.apache.org/licenses/LICENSE-2.0
  32453. *
  32454. * Unless required by applicable law or agreed to in writing,
  32455. * software distributed under the License is distributed on an
  32456. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32457. * KIND, either express or implied. See the License for the
  32458. * specific language governing permissions and limitations
  32459. * under the License.
  32460. */
  32461. /**
  32462. * @module echarts/chart/helper/Symbol
  32463. */
  32464. /**
  32465. * @constructor
  32466. * @alias {module:echarts/chart/helper/Symbol}
  32467. * @param {module:echarts/data/List} data
  32468. * @param {number} idx
  32469. * @extends {module:zrender/graphic/Group}
  32470. */
  32471. function SymbolClz$1(data, idx, seriesScope) {
  32472. Group.call(this);
  32473. this.updateData(data, idx, seriesScope);
  32474. }
  32475. var symbolProto = SymbolClz$1.prototype;
  32476. /**
  32477. * @public
  32478. * @static
  32479. * @param {module:echarts/data/List} data
  32480. * @param {number} dataIndex
  32481. * @return {Array.<number>} [width, height]
  32482. */
  32483. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  32484. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  32485. return symbolSize instanceof Array
  32486. ? symbolSize.slice()
  32487. : [+symbolSize, +symbolSize];
  32488. };
  32489. function getScale(symbolSize) {
  32490. return [symbolSize[0] / 2, symbolSize[1] / 2];
  32491. }
  32492. function driftSymbol(dx, dy) {
  32493. this.parent.drift(dx, dy);
  32494. }
  32495. symbolProto._createSymbol = function (
  32496. symbolType,
  32497. data,
  32498. idx,
  32499. symbolSize,
  32500. keepAspect
  32501. ) {
  32502. // Remove paths created before
  32503. this.removeAll();
  32504. var color = data.getItemVisual(idx, 'color');
  32505. // var symbolPath = createSymbol(
  32506. // symbolType, -0.5, -0.5, 1, 1, color
  32507. // );
  32508. // If width/height are set too small (e.g., set to 1) on ios10
  32509. // and macOS Sierra, a circle stroke become a rect, no matter what
  32510. // the scale is set. So we set width/height as 2. See #4150.
  32511. var symbolPath = createSymbol(
  32512. symbolType, -1, -1, 2, 2, color, keepAspect
  32513. );
  32514. symbolPath.attr({
  32515. z2: 100,
  32516. culling: true,
  32517. scale: getScale(symbolSize)
  32518. });
  32519. // Rewrite drift method
  32520. symbolPath.drift = driftSymbol;
  32521. this._symbolType = symbolType;
  32522. this.add(symbolPath);
  32523. };
  32524. /**
  32525. * Stop animation
  32526. * @param {boolean} toLastFrame
  32527. */
  32528. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  32529. this.childAt(0).stopAnimation(toLastFrame);
  32530. };
  32531. /**
  32532. * FIXME:
  32533. * Caution: This method breaks the encapsulation of this module,
  32534. * but it indeed brings convenience. So do not use the method
  32535. * unless you detailedly know all the implements of `Symbol`,
  32536. * especially animation.
  32537. *
  32538. * Get symbol path element.
  32539. */
  32540. symbolProto.getSymbolPath = function () {
  32541. return this.childAt(0);
  32542. };
  32543. /**
  32544. * Get scale(aka, current symbol size).
  32545. * Including the change caused by animation
  32546. */
  32547. symbolProto.getScale = function () {
  32548. return this.childAt(0).scale;
  32549. };
  32550. /**
  32551. * Highlight symbol
  32552. */
  32553. symbolProto.highlight = function () {
  32554. this.childAt(0).trigger('emphasis');
  32555. };
  32556. /**
  32557. * Downplay symbol
  32558. */
  32559. symbolProto.downplay = function () {
  32560. this.childAt(0).trigger('normal');
  32561. };
  32562. /**
  32563. * @param {number} zlevel
  32564. * @param {number} z
  32565. */
  32566. symbolProto.setZ = function (zlevel, z) {
  32567. var symbolPath = this.childAt(0);
  32568. symbolPath.zlevel = zlevel;
  32569. symbolPath.z = z;
  32570. };
  32571. symbolProto.setDraggable = function (draggable) {
  32572. var symbolPath = this.childAt(0);
  32573. symbolPath.draggable = draggable;
  32574. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  32575. };
  32576. /**
  32577. * Update symbol properties
  32578. * @param {module:echarts/data/List} data
  32579. * @param {number} idx
  32580. * @param {Object} [seriesScope]
  32581. * @param {Object} [seriesScope.itemStyle]
  32582. * @param {Object} [seriesScope.hoverItemStyle]
  32583. * @param {Object} [seriesScope.symbolRotate]
  32584. * @param {Object} [seriesScope.symbolOffset]
  32585. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  32586. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  32587. * @param {boolean} [seriesScope.hoverAnimation]
  32588. * @param {Object} [seriesScope.cursorStyle]
  32589. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  32590. * @param {string} [seriesScope.symbolInnerColor]
  32591. * @param {Object} [seriesScope.fadeIn=false]
  32592. */
  32593. symbolProto.updateData = function (data, idx, seriesScope) {
  32594. this.silent = false;
  32595. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  32596. var seriesModel = data.hostModel;
  32597. var symbolSize = getSymbolSize(data, idx);
  32598. var isInit = symbolType !== this._symbolType;
  32599. if (isInit) {
  32600. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  32601. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  32602. }
  32603. else {
  32604. var symbolPath = this.childAt(0);
  32605. symbolPath.silent = false;
  32606. updateProps(symbolPath, {
  32607. scale: getScale(symbolSize)
  32608. }, seriesModel, idx);
  32609. }
  32610. this._updateCommon(data, idx, symbolSize, seriesScope);
  32611. if (isInit) {
  32612. var symbolPath = this.childAt(0);
  32613. var fadeIn = seriesScope && seriesScope.fadeIn;
  32614. var target = {scale: symbolPath.scale.slice()};
  32615. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  32616. symbolPath.scale = [0, 0];
  32617. fadeIn && (symbolPath.style.opacity = 0);
  32618. initProps(symbolPath, target, seriesModel, idx);
  32619. }
  32620. this._seriesModel = seriesModel;
  32621. };
  32622. // Update common properties
  32623. var normalStyleAccessPath = ['itemStyle'];
  32624. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  32625. var normalLabelAccessPath = ['label'];
  32626. var emphasisLabelAccessPath = ['emphasis', 'label'];
  32627. /**
  32628. * @param {module:echarts/data/List} data
  32629. * @param {number} idx
  32630. * @param {Array.<number>} symbolSize
  32631. * @param {Object} [seriesScope]
  32632. */
  32633. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  32634. var symbolPath = this.childAt(0);
  32635. var seriesModel = data.hostModel;
  32636. var color = data.getItemVisual(idx, 'color');
  32637. // Reset style
  32638. if (symbolPath.type !== 'image') {
  32639. symbolPath.useStyle({
  32640. strokeNoScale: true
  32641. });
  32642. }
  32643. else {
  32644. symbolPath.setStyle({
  32645. opacity: null,
  32646. shadowBlur: null,
  32647. shadowOffsetX: null,
  32648. shadowOffsetY: null,
  32649. shadowColor: null
  32650. });
  32651. }
  32652. var itemStyle = seriesScope && seriesScope.itemStyle;
  32653. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  32654. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  32655. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  32656. var labelModel = seriesScope && seriesScope.labelModel;
  32657. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  32658. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  32659. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  32660. if (!seriesScope || data.hasItemOption) {
  32661. var itemModel = (seriesScope && seriesScope.itemModel)
  32662. ? seriesScope.itemModel : data.getItemModel(idx);
  32663. // Color must be excluded.
  32664. // Because symbol provide setColor individually to set fill and stroke
  32665. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  32666. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  32667. symbolRotate = itemModel.getShallow('symbolRotate');
  32668. symbolOffset = itemModel.getShallow('symbolOffset');
  32669. labelModel = itemModel.getModel(normalLabelAccessPath);
  32670. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  32671. hoverAnimation = itemModel.getShallow('hoverAnimation');
  32672. cursorStyle = itemModel.getShallow('cursor');
  32673. }
  32674. else {
  32675. hoverItemStyle = extend({}, hoverItemStyle);
  32676. }
  32677. var elStyle = symbolPath.style;
  32678. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  32679. if (symbolOffset) {
  32680. symbolPath.attr('position', [
  32681. parsePercent$1(symbolOffset[0], symbolSize[0]),
  32682. parsePercent$1(symbolOffset[1], symbolSize[1])
  32683. ]);
  32684. }
  32685. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  32686. // PENDING setColor before setStyle!!!
  32687. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  32688. symbolPath.setStyle(itemStyle);
  32689. var opacity = data.getItemVisual(idx, 'opacity');
  32690. if (opacity != null) {
  32691. elStyle.opacity = opacity;
  32692. }
  32693. var liftZ = data.getItemVisual(idx, 'liftZ');
  32694. var z2Origin = symbolPath.__z2Origin;
  32695. if (liftZ != null) {
  32696. if (z2Origin == null) {
  32697. symbolPath.__z2Origin = symbolPath.z2;
  32698. symbolPath.z2 += liftZ;
  32699. }
  32700. }
  32701. else if (z2Origin != null) {
  32702. symbolPath.z2 = z2Origin;
  32703. symbolPath.__z2Origin = null;
  32704. }
  32705. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  32706. setLabelStyle(
  32707. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  32708. {
  32709. labelFetcher: seriesModel,
  32710. labelDataIndex: idx,
  32711. defaultText: getLabelDefaultText,
  32712. isRectText: true,
  32713. autoColor: color
  32714. }
  32715. );
  32716. // Do not execute util needed.
  32717. function getLabelDefaultText(idx, opt) {
  32718. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  32719. }
  32720. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  32721. symbolPath.hoverStyle = hoverItemStyle;
  32722. symbolPath.highDownOnUpdate = (
  32723. hoverAnimation && seriesModel.isAnimationEnabled()
  32724. ) ? highDownOnUpdate : null;
  32725. setHoverStyle(symbolPath);
  32726. };
  32727. function highDownOnUpdate(fromState, toState) {
  32728. // Do not support this hover animation util some scenario required.
  32729. // Animation can only be supported in hover layer when using `el.incremetal`.
  32730. if (this.incremental || this.useHoverLayer) {
  32731. return;
  32732. }
  32733. if (toState === 'emphasis') {
  32734. var scale = this.__symbolOriginalScale;
  32735. var ratio = scale[1] / scale[0];
  32736. var emphasisOpt = {
  32737. scale: [
  32738. Math.max(scale[0] * 1.1, scale[0] + 3),
  32739. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  32740. ]
  32741. };
  32742. // FIXME
  32743. // modify it after support stop specified animation.
  32744. // toState === fromState
  32745. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  32746. this.animateTo(emphasisOpt, 400, 'elasticOut');
  32747. }
  32748. else if (toState === 'normal') {
  32749. this.animateTo({
  32750. scale: this.__symbolOriginalScale
  32751. }, 400, 'elasticOut');
  32752. }
  32753. }
  32754. /**
  32755. * @param {Function} cb
  32756. * @param {Object} [opt]
  32757. * @param {Object} [opt.keepLabel=true]
  32758. */
  32759. symbolProto.fadeOut = function (cb, opt) {
  32760. var symbolPath = this.childAt(0);
  32761. // Avoid mistaken hover when fading out
  32762. this.silent = symbolPath.silent = true;
  32763. // Not show text when animating
  32764. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  32765. updateProps(
  32766. symbolPath,
  32767. {
  32768. style: {opacity: 0},
  32769. scale: [0, 0]
  32770. },
  32771. this._seriesModel,
  32772. this.dataIndex,
  32773. cb
  32774. );
  32775. };
  32776. inherits(SymbolClz$1, Group);
  32777. /*
  32778. * Licensed to the Apache Software Foundation (ASF) under one
  32779. * or more contributor license agreements. See the NOTICE file
  32780. * distributed with this work for additional information
  32781. * regarding copyright ownership. The ASF licenses this file
  32782. * to you under the Apache License, Version 2.0 (the
  32783. * "License"); you may not use this file except in compliance
  32784. * with the License. You may obtain a copy of the License at
  32785. *
  32786. * http://www.apache.org/licenses/LICENSE-2.0
  32787. *
  32788. * Unless required by applicable law or agreed to in writing,
  32789. * software distributed under the License is distributed on an
  32790. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32791. * KIND, either express or implied. See the License for the
  32792. * specific language governing permissions and limitations
  32793. * under the License.
  32794. */
  32795. /**
  32796. * @module echarts/chart/helper/SymbolDraw
  32797. */
  32798. /**
  32799. * @constructor
  32800. * @alias module:echarts/chart/helper/SymbolDraw
  32801. * @param {module:zrender/graphic/Group} [symbolCtor]
  32802. */
  32803. function SymbolDraw(symbolCtor) {
  32804. this.group = new Group();
  32805. this._symbolCtor = symbolCtor || SymbolClz$1;
  32806. }
  32807. var symbolDrawProto = SymbolDraw.prototype;
  32808. function symbolNeedsDraw(data, point, idx, opt) {
  32809. return point && !isNaN(point[0]) && !isNaN(point[1])
  32810. && !(opt.isIgnore && opt.isIgnore(idx))
  32811. // We do not set clipShape on group, because it will cut part of
  32812. // the symbol element shape. We use the same clip shape here as
  32813. // the line clip.
  32814. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  32815. && data.getItemVisual(idx, 'symbol') !== 'none';
  32816. }
  32817. /**
  32818. * Update symbols draw by new data
  32819. * @param {module:echarts/data/List} data
  32820. * @param {Object} [opt] Or isIgnore
  32821. * @param {Function} [opt.isIgnore]
  32822. * @param {Object} [opt.clipShape]
  32823. */
  32824. symbolDrawProto.updateData = function (data, opt) {
  32825. opt = normalizeUpdateOpt(opt);
  32826. var group = this.group;
  32827. var seriesModel = data.hostModel;
  32828. var oldData = this._data;
  32829. var SymbolCtor = this._symbolCtor;
  32830. var seriesScope = makeSeriesScope(data);
  32831. // There is no oldLineData only when first rendering or switching from
  32832. // stream mode to normal mode, where previous elements should be removed.
  32833. if (!oldData) {
  32834. group.removeAll();
  32835. }
  32836. data.diff(oldData)
  32837. .add(function (newIdx) {
  32838. var point = data.getItemLayout(newIdx);
  32839. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  32840. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  32841. symbolEl.attr('position', point);
  32842. data.setItemGraphicEl(newIdx, symbolEl);
  32843. group.add(symbolEl);
  32844. }
  32845. })
  32846. .update(function (newIdx, oldIdx) {
  32847. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  32848. var point = data.getItemLayout(newIdx);
  32849. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  32850. group.remove(symbolEl);
  32851. return;
  32852. }
  32853. if (!symbolEl) {
  32854. symbolEl = new SymbolCtor(data, newIdx);
  32855. symbolEl.attr('position', point);
  32856. }
  32857. else {
  32858. symbolEl.updateData(data, newIdx, seriesScope);
  32859. updateProps(symbolEl, {
  32860. position: point
  32861. }, seriesModel);
  32862. }
  32863. // Add back
  32864. group.add(symbolEl);
  32865. data.setItemGraphicEl(newIdx, symbolEl);
  32866. })
  32867. .remove(function (oldIdx) {
  32868. var el = oldData.getItemGraphicEl(oldIdx);
  32869. el && el.fadeOut(function () {
  32870. group.remove(el);
  32871. });
  32872. })
  32873. .execute();
  32874. this._data = data;
  32875. };
  32876. symbolDrawProto.isPersistent = function () {
  32877. return true;
  32878. };
  32879. symbolDrawProto.updateLayout = function () {
  32880. var data = this._data;
  32881. if (data) {
  32882. // Not use animation
  32883. data.eachItemGraphicEl(function (el, idx) {
  32884. var point = data.getItemLayout(idx);
  32885. el.attr('position', point);
  32886. });
  32887. }
  32888. };
  32889. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  32890. this._seriesScope = makeSeriesScope(data);
  32891. this._data = null;
  32892. this.group.removeAll();
  32893. };
  32894. /**
  32895. * Update symbols draw by new data
  32896. * @param {module:echarts/data/List} data
  32897. * @param {Object} [opt] Or isIgnore
  32898. * @param {Function} [opt.isIgnore]
  32899. * @param {Object} [opt.clipShape]
  32900. */
  32901. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  32902. opt = normalizeUpdateOpt(opt);
  32903. function updateIncrementalAndHover(el) {
  32904. if (!el.isGroup) {
  32905. el.incremental = el.useHoverLayer = true;
  32906. }
  32907. }
  32908. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  32909. var point = data.getItemLayout(idx);
  32910. if (symbolNeedsDraw(data, point, idx, opt)) {
  32911. var el = new this._symbolCtor(data, idx, this._seriesScope);
  32912. el.traverse(updateIncrementalAndHover);
  32913. el.attr('position', point);
  32914. this.group.add(el);
  32915. data.setItemGraphicEl(idx, el);
  32916. }
  32917. }
  32918. };
  32919. function normalizeUpdateOpt(opt) {
  32920. if (opt != null && !isObject$1(opt)) {
  32921. opt = {isIgnore: opt};
  32922. }
  32923. return opt || {};
  32924. }
  32925. symbolDrawProto.remove = function (enableAnimation) {
  32926. var group = this.group;
  32927. var data = this._data;
  32928. // Incremental model do not have this._data.
  32929. if (data && enableAnimation) {
  32930. data.eachItemGraphicEl(function (el) {
  32931. el.fadeOut(function () {
  32932. group.remove(el);
  32933. });
  32934. });
  32935. }
  32936. else {
  32937. group.removeAll();
  32938. }
  32939. };
  32940. function makeSeriesScope(data) {
  32941. var seriesModel = data.hostModel;
  32942. return {
  32943. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  32944. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  32945. symbolRotate: seriesModel.get('symbolRotate'),
  32946. symbolOffset: seriesModel.get('symbolOffset'),
  32947. hoverAnimation: seriesModel.get('hoverAnimation'),
  32948. labelModel: seriesModel.getModel('label'),
  32949. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  32950. cursorStyle: seriesModel.get('cursor')
  32951. };
  32952. }
  32953. /*
  32954. * Licensed to the Apache Software Foundation (ASF) under one
  32955. * or more contributor license agreements. See the NOTICE file
  32956. * distributed with this work for additional information
  32957. * regarding copyright ownership. The ASF licenses this file
  32958. * to you under the Apache License, Version 2.0 (the
  32959. * "License"); you may not use this file except in compliance
  32960. * with the License. You may obtain a copy of the License at
  32961. *
  32962. * http://www.apache.org/licenses/LICENSE-2.0
  32963. *
  32964. * Unless required by applicable law or agreed to in writing,
  32965. * software distributed under the License is distributed on an
  32966. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32967. * KIND, either express or implied. See the License for the
  32968. * specific language governing permissions and limitations
  32969. * under the License.
  32970. */
  32971. /**
  32972. * @param {Object} coordSys
  32973. * @param {module:echarts/data/List} data
  32974. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  32975. */
  32976. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  32977. var baseAxis = coordSys.getBaseAxis();
  32978. var valueAxis = coordSys.getOtherAxis(baseAxis);
  32979. var valueStart = getValueStart(valueAxis, valueOrigin);
  32980. var baseAxisDim = baseAxis.dim;
  32981. var valueAxisDim = valueAxis.dim;
  32982. var valueDim = data.mapDimension(valueAxisDim);
  32983. var baseDim = data.mapDimension(baseAxisDim);
  32984. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  32985. var dims = map(coordSys.dimensions, function (coordDim) {
  32986. return data.mapDimension(coordDim);
  32987. });
  32988. var stacked;
  32989. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  32990. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  32991. dims[0] = stackResultDim;
  32992. }
  32993. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  32994. dims[1] = stackResultDim;
  32995. }
  32996. return {
  32997. dataDimsForPoint: dims,
  32998. valueStart: valueStart,
  32999. valueAxisDim: valueAxisDim,
  33000. baseAxisDim: baseAxisDim,
  33001. stacked: !!stacked,
  33002. valueDim: valueDim,
  33003. baseDim: baseDim,
  33004. baseDataOffset: baseDataOffset,
  33005. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33006. };
  33007. }
  33008. function getValueStart(valueAxis, valueOrigin) {
  33009. var valueStart = 0;
  33010. var extent = valueAxis.scale.getExtent();
  33011. if (valueOrigin === 'start') {
  33012. valueStart = extent[0];
  33013. }
  33014. else if (valueOrigin === 'end') {
  33015. valueStart = extent[1];
  33016. }
  33017. // auto
  33018. else {
  33019. // Both positive
  33020. if (extent[0] > 0) {
  33021. valueStart = extent[0];
  33022. }
  33023. // Both negative
  33024. else if (extent[1] < 0) {
  33025. valueStart = extent[1];
  33026. }
  33027. // If is one positive, and one negative, onZero shall be true
  33028. }
  33029. return valueStart;
  33030. }
  33031. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  33032. var value = NaN;
  33033. if (dataCoordInfo.stacked) {
  33034. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  33035. }
  33036. if (isNaN(value)) {
  33037. value = dataCoordInfo.valueStart;
  33038. }
  33039. var baseDataOffset = dataCoordInfo.baseDataOffset;
  33040. var stackedData = [];
  33041. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  33042. stackedData[1 - baseDataOffset] = value;
  33043. return coordSys.dataToPoint(stackedData);
  33044. }
  33045. /*
  33046. * Licensed to the Apache Software Foundation (ASF) under one
  33047. * or more contributor license agreements. See the NOTICE file
  33048. * distributed with this work for additional information
  33049. * regarding copyright ownership. The ASF licenses this file
  33050. * to you under the Apache License, Version 2.0 (the
  33051. * "License"); you may not use this file except in compliance
  33052. * with the License. You may obtain a copy of the License at
  33053. *
  33054. * http://www.apache.org/licenses/LICENSE-2.0
  33055. *
  33056. * Unless required by applicable law or agreed to in writing,
  33057. * software distributed under the License is distributed on an
  33058. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33059. * KIND, either express or implied. See the License for the
  33060. * specific language governing permissions and limitations
  33061. * under the License.
  33062. */
  33063. // var arrayDiff = require('zrender/src/core/arrayDiff');
  33064. // 'zrender/src/core/arrayDiff' has been used before, but it did
  33065. // not do well in performance when roam with fixed dataZoom window.
  33066. // function convertToIntId(newIdList, oldIdList) {
  33067. // // Generate int id instead of string id.
  33068. // // Compare string maybe slow in score function of arrDiff
  33069. // // Assume id in idList are all unique
  33070. // var idIndicesMap = {};
  33071. // var idx = 0;
  33072. // for (var i = 0; i < newIdList.length; i++) {
  33073. // idIndicesMap[newIdList[i]] = idx;
  33074. // newIdList[i] = idx++;
  33075. // }
  33076. // for (var i = 0; i < oldIdList.length; i++) {
  33077. // var oldId = oldIdList[i];
  33078. // // Same with newIdList
  33079. // if (idIndicesMap[oldId]) {
  33080. // oldIdList[i] = idIndicesMap[oldId];
  33081. // }
  33082. // else {
  33083. // oldIdList[i] = idx++;
  33084. // }
  33085. // }
  33086. // }
  33087. function diffData(oldData, newData) {
  33088. var diffResult = [];
  33089. newData.diff(oldData)
  33090. .add(function (idx) {
  33091. diffResult.push({cmd: '+', idx: idx});
  33092. })
  33093. .update(function (newIdx, oldIdx) {
  33094. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  33095. })
  33096. .remove(function (idx) {
  33097. diffResult.push({cmd: '-', idx: idx});
  33098. })
  33099. .execute();
  33100. return diffResult;
  33101. }
  33102. var lineAnimationDiff = function (
  33103. oldData, newData,
  33104. oldStackedOnPoints, newStackedOnPoints,
  33105. oldCoordSys, newCoordSys,
  33106. oldValueOrigin, newValueOrigin
  33107. ) {
  33108. var diff = diffData(oldData, newData);
  33109. // var newIdList = newData.mapArray(newData.getId);
  33110. // var oldIdList = oldData.mapArray(oldData.getId);
  33111. // convertToIntId(newIdList, oldIdList);
  33112. // // FIXME One data ?
  33113. // diff = arrayDiff(oldIdList, newIdList);
  33114. var currPoints = [];
  33115. var nextPoints = [];
  33116. // Points for stacking base line
  33117. var currStackedPoints = [];
  33118. var nextStackedPoints = [];
  33119. var status = [];
  33120. var sortedIndices = [];
  33121. var rawIndices = [];
  33122. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  33123. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  33124. for (var i = 0; i < diff.length; i++) {
  33125. var diffItem = diff[i];
  33126. var pointAdded = true;
  33127. // FIXME, animation is not so perfect when dataZoom window moves fast
  33128. // Which is in case remvoing or add more than one data in the tail or head
  33129. switch (diffItem.cmd) {
  33130. case '=':
  33131. var currentPt = oldData.getItemLayout(diffItem.idx);
  33132. var nextPt = newData.getItemLayout(diffItem.idx1);
  33133. // If previous data is NaN, use next point directly
  33134. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  33135. currentPt = nextPt.slice();
  33136. }
  33137. currPoints.push(currentPt);
  33138. nextPoints.push(nextPt);
  33139. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  33140. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  33141. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  33142. break;
  33143. case '+':
  33144. var idx = diffItem.idx;
  33145. currPoints.push(
  33146. oldCoordSys.dataToPoint([
  33147. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  33148. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  33149. ])
  33150. );
  33151. nextPoints.push(newData.getItemLayout(idx).slice());
  33152. currStackedPoints.push(
  33153. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  33154. );
  33155. nextStackedPoints.push(newStackedOnPoints[idx]);
  33156. rawIndices.push(newData.getRawIndex(idx));
  33157. break;
  33158. case '-':
  33159. var idx = diffItem.idx;
  33160. var rawIndex = oldData.getRawIndex(idx);
  33161. // Data is replaced. In the case of dynamic data queue
  33162. // FIXME FIXME FIXME
  33163. if (rawIndex !== idx) {
  33164. currPoints.push(oldData.getItemLayout(idx));
  33165. nextPoints.push(newCoordSys.dataToPoint([
  33166. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  33167. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  33168. ]));
  33169. currStackedPoints.push(oldStackedOnPoints[idx]);
  33170. nextStackedPoints.push(
  33171. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  33172. );
  33173. rawIndices.push(rawIndex);
  33174. }
  33175. else {
  33176. pointAdded = false;
  33177. }
  33178. }
  33179. // Original indices
  33180. if (pointAdded) {
  33181. status.push(diffItem);
  33182. sortedIndices.push(sortedIndices.length);
  33183. }
  33184. }
  33185. // Diff result may be crossed if all items are changed
  33186. // Sort by data index
  33187. sortedIndices.sort(function (a, b) {
  33188. return rawIndices[a] - rawIndices[b];
  33189. });
  33190. var sortedCurrPoints = [];
  33191. var sortedNextPoints = [];
  33192. var sortedCurrStackedPoints = [];
  33193. var sortedNextStackedPoints = [];
  33194. var sortedStatus = [];
  33195. for (var i = 0; i < sortedIndices.length; i++) {
  33196. var idx = sortedIndices[i];
  33197. sortedCurrPoints[i] = currPoints[idx];
  33198. sortedNextPoints[i] = nextPoints[idx];
  33199. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  33200. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  33201. sortedStatus[i] = status[idx];
  33202. }
  33203. return {
  33204. current: sortedCurrPoints,
  33205. next: sortedNextPoints,
  33206. stackedOnCurrent: sortedCurrStackedPoints,
  33207. stackedOnNext: sortedNextStackedPoints,
  33208. status: sortedStatus
  33209. };
  33210. };
  33211. /*
  33212. * Licensed to the Apache Software Foundation (ASF) under one
  33213. * or more contributor license agreements. See the NOTICE file
  33214. * distributed with this work for additional information
  33215. * regarding copyright ownership. The ASF licenses this file
  33216. * to you under the Apache License, Version 2.0 (the
  33217. * "License"); you may not use this file except in compliance
  33218. * with the License. You may obtain a copy of the License at
  33219. *
  33220. * http://www.apache.org/licenses/LICENSE-2.0
  33221. *
  33222. * Unless required by applicable law or agreed to in writing,
  33223. * software distributed under the License is distributed on an
  33224. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33225. * KIND, either express or implied. See the License for the
  33226. * specific language governing permissions and limitations
  33227. * under the License.
  33228. */
  33229. // Poly path support NaN point
  33230. var vec2Min = min;
  33231. var vec2Max = max;
  33232. var scaleAndAdd$1 = scaleAndAdd;
  33233. var v2Copy = copy;
  33234. // Temporary variable
  33235. var v = [];
  33236. var cp0 = [];
  33237. var cp1 = [];
  33238. function isPointNull(p) {
  33239. return isNaN(p[0]) || isNaN(p[1]);
  33240. }
  33241. function drawSegment(
  33242. ctx, points, start, segLen, allLen,
  33243. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33244. ) {
  33245. // if (smoothMonotone == null) {
  33246. // if (isMono(points, 'x')) {
  33247. // return drawMono(ctx, points, start, segLen, allLen,
  33248. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  33249. // }
  33250. // else if (isMono(points, 'y')) {
  33251. // return drawMono(ctx, points, start, segLen, allLen,
  33252. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  33253. // }
  33254. // else {
  33255. // return drawNonMono.apply(this, arguments);
  33256. // }
  33257. // }
  33258. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  33259. // return drawMono.apply(this, arguments);
  33260. // }
  33261. // else {
  33262. // return drawNonMono.apply(this, arguments);
  33263. // }
  33264. if (smoothMonotone === 'none' || !smoothMonotone) {
  33265. return drawNonMono.apply(this, arguments);
  33266. }
  33267. else {
  33268. return drawMono.apply(this, arguments);
  33269. }
  33270. }
  33271. /**
  33272. * Check if points is in monotone.
  33273. *
  33274. * @param {number[][]} points Array of points which is in [x, y] form
  33275. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  33276. * dimension that is checking.
  33277. * If is 'none', `drawNonMono` should be
  33278. * called.
  33279. * If is undefined, either being monotone
  33280. * in 'x' or 'y' will call `drawMono`.
  33281. */
  33282. // function isMono(points, smoothMonotone) {
  33283. // if (points.length <= 1) {
  33284. // return true;
  33285. // }
  33286. // var dim = smoothMonotone === 'x' ? 0 : 1;
  33287. // var last = points[0][dim];
  33288. // var lastDiff = 0;
  33289. // for (var i = 1; i < points.length; ++i) {
  33290. // var diff = points[i][dim] - last;
  33291. // if (!isNaN(diff) && !isNaN(lastDiff)
  33292. // && diff !== 0 && lastDiff !== 0
  33293. // && ((diff >= 0) !== (lastDiff >= 0))
  33294. // ) {
  33295. // return false;
  33296. // }
  33297. // if (!isNaN(diff) && diff !== 0) {
  33298. // lastDiff = diff;
  33299. // last = points[i][dim];
  33300. // }
  33301. // }
  33302. // return true;
  33303. // }
  33304. /**
  33305. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  33306. * control points will be used. This should be used when points are monotone
  33307. * either in x or y dimension.
  33308. */
  33309. function drawMono(
  33310. ctx, points, start, segLen, allLen,
  33311. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33312. ) {
  33313. var prevIdx = 0;
  33314. var idx = start;
  33315. for (var k = 0; k < segLen; k++) {
  33316. var p = points[idx];
  33317. if (idx >= allLen || idx < 0) {
  33318. break;
  33319. }
  33320. if (isPointNull(p)) {
  33321. if (connectNulls) {
  33322. idx += dir;
  33323. continue;
  33324. }
  33325. break;
  33326. }
  33327. if (idx === start) {
  33328. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33329. }
  33330. else {
  33331. if (smooth > 0) {
  33332. var prevP = points[prevIdx];
  33333. var dim = smoothMonotone === 'y' ? 1 : 0;
  33334. // Length of control point to p, either in x or y, but not both
  33335. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  33336. v2Copy(cp0, prevP);
  33337. cp0[dim] = prevP[dim] + ctrlLen;
  33338. v2Copy(cp1, p);
  33339. cp1[dim] = p[dim] - ctrlLen;
  33340. ctx.bezierCurveTo(
  33341. cp0[0], cp0[1],
  33342. cp1[0], cp1[1],
  33343. p[0], p[1]
  33344. );
  33345. }
  33346. else {
  33347. ctx.lineTo(p[0], p[1]);
  33348. }
  33349. }
  33350. prevIdx = idx;
  33351. idx += dir;
  33352. }
  33353. return k;
  33354. }
  33355. /**
  33356. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  33357. * situations. This should be used when points are non-monotone neither in x or
  33358. * y dimension.
  33359. */
  33360. function drawNonMono(
  33361. ctx, points, start, segLen, allLen,
  33362. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33363. ) {
  33364. var prevIdx = 0;
  33365. var idx = start;
  33366. for (var k = 0; k < segLen; k++) {
  33367. var p = points[idx];
  33368. if (idx >= allLen || idx < 0) {
  33369. break;
  33370. }
  33371. if (isPointNull(p)) {
  33372. if (connectNulls) {
  33373. idx += dir;
  33374. continue;
  33375. }
  33376. break;
  33377. }
  33378. if (idx === start) {
  33379. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33380. v2Copy(cp0, p);
  33381. }
  33382. else {
  33383. if (smooth > 0) {
  33384. var nextIdx = idx + dir;
  33385. var nextP = points[nextIdx];
  33386. if (connectNulls) {
  33387. // Find next point not null
  33388. while (nextP && isPointNull(points[nextIdx])) {
  33389. nextIdx += dir;
  33390. nextP = points[nextIdx];
  33391. }
  33392. }
  33393. var ratioNextSeg = 0.5;
  33394. var prevP = points[prevIdx];
  33395. var nextP = points[nextIdx];
  33396. // Last point
  33397. if (!nextP || isPointNull(nextP)) {
  33398. v2Copy(cp1, p);
  33399. }
  33400. else {
  33401. // If next data is null in not connect case
  33402. if (isPointNull(nextP) && !connectNulls) {
  33403. nextP = p;
  33404. }
  33405. sub(v, nextP, prevP);
  33406. var lenPrevSeg;
  33407. var lenNextSeg;
  33408. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  33409. var dim = smoothMonotone === 'x' ? 0 : 1;
  33410. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  33411. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  33412. }
  33413. else {
  33414. lenPrevSeg = dist(p, prevP);
  33415. lenNextSeg = dist(p, nextP);
  33416. }
  33417. // Use ratio of seg length
  33418. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  33419. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  33420. }
  33421. // Smooth constraint
  33422. vec2Min(cp0, cp0, smoothMax);
  33423. vec2Max(cp0, cp0, smoothMin);
  33424. vec2Min(cp1, cp1, smoothMax);
  33425. vec2Max(cp1, cp1, smoothMin);
  33426. ctx.bezierCurveTo(
  33427. cp0[0], cp0[1],
  33428. cp1[0], cp1[1],
  33429. p[0], p[1]
  33430. );
  33431. // cp0 of next segment
  33432. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  33433. }
  33434. else {
  33435. ctx.lineTo(p[0], p[1]);
  33436. }
  33437. }
  33438. prevIdx = idx;
  33439. idx += dir;
  33440. }
  33441. return k;
  33442. }
  33443. function getBoundingBox(points, smoothConstraint) {
  33444. var ptMin = [Infinity, Infinity];
  33445. var ptMax = [-Infinity, -Infinity];
  33446. if (smoothConstraint) {
  33447. for (var i = 0; i < points.length; i++) {
  33448. var pt = points[i];
  33449. if (pt[0] < ptMin[0]) {
  33450. ptMin[0] = pt[0];
  33451. }
  33452. if (pt[1] < ptMin[1]) {
  33453. ptMin[1] = pt[1];
  33454. }
  33455. if (pt[0] > ptMax[0]) {
  33456. ptMax[0] = pt[0];
  33457. }
  33458. if (pt[1] > ptMax[1]) {
  33459. ptMax[1] = pt[1];
  33460. }
  33461. }
  33462. }
  33463. return {
  33464. min: smoothConstraint ? ptMin : ptMax,
  33465. max: smoothConstraint ? ptMax : ptMin
  33466. };
  33467. }
  33468. var Polyline$1 = Path.extend({
  33469. type: 'ec-polyline',
  33470. shape: {
  33471. points: [],
  33472. smooth: 0,
  33473. smoothConstraint: true,
  33474. smoothMonotone: null,
  33475. connectNulls: false
  33476. },
  33477. style: {
  33478. fill: null,
  33479. stroke: '#000'
  33480. },
  33481. brush: fixClipWithShadow(Path.prototype.brush),
  33482. buildPath: function (ctx, shape) {
  33483. var points = shape.points;
  33484. var i = 0;
  33485. var len$$1 = points.length;
  33486. var result = getBoundingBox(points, shape.smoothConstraint);
  33487. if (shape.connectNulls) {
  33488. // Must remove first and last null values avoid draw error in polygon
  33489. for (; len$$1 > 0; len$$1--) {
  33490. if (!isPointNull(points[len$$1 - 1])) {
  33491. break;
  33492. }
  33493. }
  33494. for (; i < len$$1; i++) {
  33495. if (!isPointNull(points[i])) {
  33496. break;
  33497. }
  33498. }
  33499. }
  33500. while (i < len$$1) {
  33501. i += drawSegment(
  33502. ctx, points, i, len$$1, len$$1,
  33503. 1, result.min, result.max, shape.smooth,
  33504. shape.smoothMonotone, shape.connectNulls
  33505. ) + 1;
  33506. }
  33507. }
  33508. });
  33509. var Polygon$1 = Path.extend({
  33510. type: 'ec-polygon',
  33511. shape: {
  33512. points: [],
  33513. // Offset between stacked base points and points
  33514. stackedOnPoints: [],
  33515. smooth: 0,
  33516. stackedOnSmooth: 0,
  33517. smoothConstraint: true,
  33518. smoothMonotone: null,
  33519. connectNulls: false
  33520. },
  33521. brush: fixClipWithShadow(Path.prototype.brush),
  33522. buildPath: function (ctx, shape) {
  33523. var points = shape.points;
  33524. var stackedOnPoints = shape.stackedOnPoints;
  33525. var i = 0;
  33526. var len$$1 = points.length;
  33527. var smoothMonotone = shape.smoothMonotone;
  33528. var bbox = getBoundingBox(points, shape.smoothConstraint);
  33529. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  33530. if (shape.connectNulls) {
  33531. // Must remove first and last null values avoid draw error in polygon
  33532. for (; len$$1 > 0; len$$1--) {
  33533. if (!isPointNull(points[len$$1 - 1])) {
  33534. break;
  33535. }
  33536. }
  33537. for (; i < len$$1; i++) {
  33538. if (!isPointNull(points[i])) {
  33539. break;
  33540. }
  33541. }
  33542. }
  33543. while (i < len$$1) {
  33544. var k = drawSegment(
  33545. ctx, points, i, len$$1, len$$1,
  33546. 1, bbox.min, bbox.max, shape.smooth,
  33547. smoothMonotone, shape.connectNulls
  33548. );
  33549. drawSegment(
  33550. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  33551. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  33552. smoothMonotone, shape.connectNulls
  33553. );
  33554. i += k + 1;
  33555. ctx.closePath();
  33556. }
  33557. }
  33558. });
  33559. /*
  33560. * Licensed to the Apache Software Foundation (ASF) under one
  33561. * or more contributor license agreements. See the NOTICE file
  33562. * distributed with this work for additional information
  33563. * regarding copyright ownership. The ASF licenses this file
  33564. * to you under the Apache License, Version 2.0 (the
  33565. * "License"); you may not use this file except in compliance
  33566. * with the License. You may obtain a copy of the License at
  33567. *
  33568. * http://www.apache.org/licenses/LICENSE-2.0
  33569. *
  33570. * Unless required by applicable law or agreed to in writing,
  33571. * software distributed under the License is distributed on an
  33572. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33573. * KIND, either express or implied. See the License for the
  33574. * specific language governing permissions and limitations
  33575. * under the License.
  33576. */
  33577. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  33578. var rect = cartesian.getArea();
  33579. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  33580. var x = rect.x;
  33581. var y = rect.y;
  33582. var width = rect.width;
  33583. var height = rect.height;
  33584. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  33585. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  33586. x -= lineWidth / 2;
  33587. y -= lineWidth / 2;
  33588. width += lineWidth;
  33589. height += lineWidth;
  33590. var clipPath = new Rect({
  33591. shape: {
  33592. x: x,
  33593. y: y,
  33594. width: width,
  33595. height: height
  33596. }
  33597. });
  33598. if (hasAnimation) {
  33599. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  33600. initProps(clipPath, {
  33601. shape: {
  33602. width: width,
  33603. height: height
  33604. }
  33605. }, seriesModel);
  33606. }
  33607. return clipPath;
  33608. }
  33609. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  33610. var sectorArea = polar.getArea();
  33611. // Avoid float number rounding error for symbol on the edge of axis extent.
  33612. var clipPath = new Sector({
  33613. shape: {
  33614. cx: round$1(polar.cx, 1),
  33615. cy: round$1(polar.cy, 1),
  33616. r0: round$1(sectorArea.r0, 1),
  33617. r: round$1(sectorArea.r, 1),
  33618. startAngle: sectorArea.startAngle,
  33619. endAngle: sectorArea.endAngle,
  33620. clockwise: sectorArea.clockwise
  33621. }
  33622. });
  33623. if (hasAnimation) {
  33624. clipPath.shape.endAngle = sectorArea.startAngle;
  33625. initProps(clipPath, {
  33626. shape: {
  33627. endAngle: sectorArea.endAngle
  33628. }
  33629. }, seriesModel);
  33630. }
  33631. return clipPath;
  33632. }
  33633. function createClipPath(coordSys, hasAnimation, seriesModel) {
  33634. if (!coordSys) {
  33635. return null;
  33636. }
  33637. else if (coordSys.type === 'polar') {
  33638. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33639. }
  33640. else if (coordSys.type === 'cartesian2d') {
  33641. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  33642. }
  33643. return null;
  33644. }
  33645. /*
  33646. * Licensed to the Apache Software Foundation (ASF) under one
  33647. * or more contributor license agreements. See the NOTICE file
  33648. * distributed with this work for additional information
  33649. * regarding copyright ownership. The ASF licenses this file
  33650. * to you under the Apache License, Version 2.0 (the
  33651. * "License"); you may not use this file except in compliance
  33652. * with the License. You may obtain a copy of the License at
  33653. *
  33654. * http://www.apache.org/licenses/LICENSE-2.0
  33655. *
  33656. * Unless required by applicable law or agreed to in writing,
  33657. * software distributed under the License is distributed on an
  33658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33659. * KIND, either express or implied. See the License for the
  33660. * specific language governing permissions and limitations
  33661. * under the License.
  33662. */
  33663. // FIXME step not support polar
  33664. function isPointsSame(points1, points2) {
  33665. if (points1.length !== points2.length) {
  33666. return;
  33667. }
  33668. for (var i = 0; i < points1.length; i++) {
  33669. var p1 = points1[i];
  33670. var p2 = points2[i];
  33671. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  33672. return;
  33673. }
  33674. }
  33675. return true;
  33676. }
  33677. function getSmooth(smooth) {
  33678. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  33679. }
  33680. /**
  33681. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  33682. * @param {module:echarts/data/List} data
  33683. * @param {Object} dataCoordInfo
  33684. * @param {Array.<Array.<number>>} points
  33685. */
  33686. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  33687. if (!dataCoordInfo.valueDim) {
  33688. return [];
  33689. }
  33690. var points = [];
  33691. for (var idx = 0, len = data.count(); idx < len; idx++) {
  33692. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  33693. }
  33694. return points;
  33695. }
  33696. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  33697. var baseAxis = coordSys.getBaseAxis();
  33698. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  33699. var stepPoints = [];
  33700. for (var i = 0; i < points.length - 1; i++) {
  33701. var nextPt = points[i + 1];
  33702. var pt = points[i];
  33703. stepPoints.push(pt);
  33704. var stepPt = [];
  33705. switch (stepTurnAt) {
  33706. case 'end':
  33707. stepPt[baseIndex] = nextPt[baseIndex];
  33708. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33709. // default is start
  33710. stepPoints.push(stepPt);
  33711. break;
  33712. case 'middle':
  33713. // default is start
  33714. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  33715. var stepPt2 = [];
  33716. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  33717. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33718. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  33719. stepPoints.push(stepPt);
  33720. stepPoints.push(stepPt2);
  33721. break;
  33722. default:
  33723. stepPt[baseIndex] = pt[baseIndex];
  33724. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  33725. // default is start
  33726. stepPoints.push(stepPt);
  33727. }
  33728. }
  33729. // Last points
  33730. points[i] && stepPoints.push(points[i]);
  33731. return stepPoints;
  33732. }
  33733. function getVisualGradient(data, coordSys) {
  33734. var visualMetaList = data.getVisual('visualMeta');
  33735. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  33736. // When data.count() is 0, gradient range can not be calculated.
  33737. return;
  33738. }
  33739. if (coordSys.type !== 'cartesian2d') {
  33740. if (__DEV__) {
  33741. console.warn('Visual map on line style is only supported on cartesian2d.');
  33742. }
  33743. return;
  33744. }
  33745. var coordDim;
  33746. var visualMeta;
  33747. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  33748. var dimIndex = visualMetaList[i].dimension;
  33749. var dimName = data.dimensions[dimIndex];
  33750. var dimInfo = data.getDimensionInfo(dimName);
  33751. coordDim = dimInfo && dimInfo.coordDim;
  33752. // Can only be x or y
  33753. if (coordDim === 'x' || coordDim === 'y') {
  33754. visualMeta = visualMetaList[i];
  33755. break;
  33756. }
  33757. }
  33758. if (!visualMeta) {
  33759. if (__DEV__) {
  33760. console.warn('Visual map on line style only support x or y dimension.');
  33761. }
  33762. return;
  33763. }
  33764. // If the area to be rendered is bigger than area defined by LinearGradient,
  33765. // the canvas spec prescribes that the color of the first stop and the last
  33766. // stop should be used. But if two stops are added at offset 0, in effect
  33767. // browsers use the color of the second stop to render area outside
  33768. // LinearGradient. So we can only infinitesimally extend area defined in
  33769. // LinearGradient to render `outerColors`.
  33770. var axis = coordSys.getAxis(coordDim);
  33771. // dataToCoor mapping may not be linear, but must be monotonic.
  33772. var colorStops = map(visualMeta.stops, function (stop) {
  33773. return {
  33774. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  33775. color: stop.color
  33776. };
  33777. });
  33778. var stopLen = colorStops.length;
  33779. var outerColors = visualMeta.outerColors.slice();
  33780. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  33781. colorStops.reverse();
  33782. outerColors.reverse();
  33783. }
  33784. var tinyExtent = 10; // Arbitrary value: 10px
  33785. var minCoord = colorStops[0].coord - tinyExtent;
  33786. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  33787. var coordSpan = maxCoord - minCoord;
  33788. if (coordSpan < 1e-3) {
  33789. return 'transparent';
  33790. }
  33791. each$1(colorStops, function (stop) {
  33792. stop.offset = (stop.coord - minCoord) / coordSpan;
  33793. });
  33794. colorStops.push({
  33795. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  33796. color: outerColors[1] || 'transparent'
  33797. });
  33798. colorStops.unshift({ // notice colorStops.length have been changed.
  33799. offset: stopLen ? colorStops[0].offset : 0.5,
  33800. color: outerColors[0] || 'transparent'
  33801. });
  33802. // zrUtil.each(colorStops, function (colorStop) {
  33803. // // Make sure each offset has rounded px to avoid not sharp edge
  33804. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  33805. // });
  33806. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  33807. gradient[coordDim] = minCoord;
  33808. gradient[coordDim + '2'] = maxCoord;
  33809. return gradient;
  33810. }
  33811. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  33812. var showAllSymbol = seriesModel.get('showAllSymbol');
  33813. var isAuto = showAllSymbol === 'auto';
  33814. if (showAllSymbol && !isAuto) {
  33815. return;
  33816. }
  33817. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  33818. if (!categoryAxis) {
  33819. return;
  33820. }
  33821. // Note that category label interval strategy might bring some weird effect
  33822. // in some scenario: users may wonder why some of the symbols are not
  33823. // displayed. So we show all symbols as possible as we can.
  33824. if (isAuto
  33825. // Simplify the logic, do not determine label overlap here.
  33826. && canShowAllSymbolForCategory(categoryAxis, data)
  33827. ) {
  33828. return;
  33829. }
  33830. // Otherwise follow the label interval strategy on category axis.
  33831. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  33832. var labelMap = {};
  33833. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  33834. labelMap[labelItem.tickValue] = 1;
  33835. });
  33836. return function (dataIndex) {
  33837. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  33838. };
  33839. }
  33840. function canShowAllSymbolForCategory(categoryAxis, data) {
  33841. // In mose cases, line is monotonous on category axis, and the label size
  33842. // is close with each other. So we check the symbol size and some of the
  33843. // label size alone with the category axis to estimate whether all symbol
  33844. // can be shown without overlap.
  33845. var axisExtent = categoryAxis.getExtent();
  33846. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  33847. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  33848. // Sampling some points, max 5.
  33849. var dataLen = data.count();
  33850. var step = Math.max(1, Math.round(dataLen / 5));
  33851. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  33852. if (SymbolClz$1.getSymbolSize(
  33853. data, dataIndex
  33854. // Only for cartesian, where `isHorizontal` exists.
  33855. )[categoryAxis.isHorizontal() ? 1 : 0]
  33856. // Empirical number
  33857. * 1.5 > availSize
  33858. ) {
  33859. return false;
  33860. }
  33861. }
  33862. return true;
  33863. }
  33864. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  33865. if (coordSys.type === 'cartesian2d') {
  33866. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  33867. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  33868. // Expand clip shape to avoid clipping when line value exceeds axis
  33869. if (!seriesModel.get('clip', true)) {
  33870. var rectShape = clipPath.shape;
  33871. var expandSize = Math.max(rectShape.width, rectShape.height);
  33872. if (isHorizontal) {
  33873. rectShape.y -= expandSize;
  33874. rectShape.height += expandSize * 2;
  33875. }
  33876. else {
  33877. rectShape.x -= expandSize;
  33878. rectShape.width += expandSize * 2;
  33879. }
  33880. }
  33881. return clipPath;
  33882. }
  33883. else {
  33884. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33885. }
  33886. }
  33887. Chart.extend({
  33888. type: 'line',
  33889. init: function () {
  33890. var lineGroup = new Group();
  33891. var symbolDraw = new SymbolDraw();
  33892. this.group.add(symbolDraw.group);
  33893. this._symbolDraw = symbolDraw;
  33894. this._lineGroup = lineGroup;
  33895. },
  33896. render: function (seriesModel, ecModel, api) {
  33897. var coordSys = seriesModel.coordinateSystem;
  33898. var group = this.group;
  33899. var data = seriesModel.getData();
  33900. var lineStyleModel = seriesModel.getModel('lineStyle');
  33901. var areaStyleModel = seriesModel.getModel('areaStyle');
  33902. var points = data.mapArray(data.getItemLayout);
  33903. var isCoordSysPolar = coordSys.type === 'polar';
  33904. var prevCoordSys = this._coordSys;
  33905. var symbolDraw = this._symbolDraw;
  33906. var polyline = this._polyline;
  33907. var polygon = this._polygon;
  33908. var lineGroup = this._lineGroup;
  33909. var hasAnimation = seriesModel.get('animation');
  33910. var isAreaChart = !areaStyleModel.isEmpty();
  33911. var valueOrigin = areaStyleModel.get('origin');
  33912. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  33913. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  33914. var showSymbol = seriesModel.get('showSymbol');
  33915. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  33916. && getIsIgnoreFunc(seriesModel, data, coordSys);
  33917. // Remove temporary symbols
  33918. var oldData = this._data;
  33919. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  33920. if (el.__temp) {
  33921. group.remove(el);
  33922. oldData.setItemGraphicEl(idx, null);
  33923. }
  33924. });
  33925. // Remove previous created symbols if showSymbol changed to false
  33926. if (!showSymbol) {
  33927. symbolDraw.remove();
  33928. }
  33929. group.add(lineGroup);
  33930. // FIXME step not support polar
  33931. var step = !isCoordSysPolar && seriesModel.get('step');
  33932. var clipShapeForSymbol;
  33933. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  33934. clipShapeForSymbol = coordSys.getArea();
  33935. // Avoid float number rounding error for symbol on the edge of axis extent.
  33936. // See #7913 and `test/dataZoom-clip.html`.
  33937. if (clipShapeForSymbol.width != null) {
  33938. clipShapeForSymbol.x -= 0.1;
  33939. clipShapeForSymbol.y -= 0.1;
  33940. clipShapeForSymbol.width += 0.2;
  33941. clipShapeForSymbol.height += 0.2;
  33942. }
  33943. else if (clipShapeForSymbol.r0) {
  33944. clipShapeForSymbol.r0 -= 0.5;
  33945. clipShapeForSymbol.r1 += 0.5;
  33946. }
  33947. }
  33948. this._clipShapeForSymbol = clipShapeForSymbol;
  33949. // Initialization animation or coordinate system changed
  33950. if (
  33951. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  33952. ) {
  33953. showSymbol && symbolDraw.updateData(data, {
  33954. isIgnore: isIgnoreFunc,
  33955. clipShape: clipShapeForSymbol
  33956. });
  33957. if (step) {
  33958. // TODO If stacked series is not step
  33959. points = turnPointsIntoStep(points, coordSys, step);
  33960. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  33961. }
  33962. polyline = this._newPolyline(points, coordSys, hasAnimation);
  33963. if (isAreaChart) {
  33964. polygon = this._newPolygon(
  33965. points, stackedOnPoints,
  33966. coordSys, hasAnimation
  33967. );
  33968. }
  33969. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  33970. }
  33971. else {
  33972. if (isAreaChart && !polygon) {
  33973. // If areaStyle is added
  33974. polygon = this._newPolygon(
  33975. points, stackedOnPoints,
  33976. coordSys, hasAnimation
  33977. );
  33978. }
  33979. else if (polygon && !isAreaChart) {
  33980. // If areaStyle is removed
  33981. lineGroup.remove(polygon);
  33982. polygon = this._polygon = null;
  33983. }
  33984. // Update clipPath
  33985. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  33986. // Always update, or it is wrong in the case turning on legend
  33987. // because points are not changed
  33988. showSymbol && symbolDraw.updateData(data, {
  33989. isIgnore: isIgnoreFunc,
  33990. clipShape: clipShapeForSymbol
  33991. });
  33992. // Stop symbol animation and sync with line points
  33993. // FIXME performance?
  33994. data.eachItemGraphicEl(function (el) {
  33995. el.stopAnimation(true);
  33996. });
  33997. // In the case data zoom triggerred refreshing frequently
  33998. // Data may not change if line has a category axis. So it should animate nothing
  33999. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  34000. || !isPointsSame(this._points, points)
  34001. ) {
  34002. if (hasAnimation) {
  34003. this._updateAnimation(
  34004. data, stackedOnPoints, coordSys, api, step, valueOrigin
  34005. );
  34006. }
  34007. else {
  34008. // Not do it in update with animation
  34009. if (step) {
  34010. // TODO If stacked series is not step
  34011. points = turnPointsIntoStep(points, coordSys, step);
  34012. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34013. }
  34014. polyline.setShape({
  34015. points: points
  34016. });
  34017. polygon && polygon.setShape({
  34018. points: points,
  34019. stackedOnPoints: stackedOnPoints
  34020. });
  34021. }
  34022. }
  34023. }
  34024. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  34025. polyline.useStyle(defaults(
  34026. // Use color in lineStyle first
  34027. lineStyleModel.getLineStyle(),
  34028. {
  34029. fill: 'none',
  34030. stroke: visualColor,
  34031. lineJoin: 'bevel'
  34032. }
  34033. ));
  34034. var smooth = seriesModel.get('smooth');
  34035. smooth = getSmooth(seriesModel.get('smooth'));
  34036. polyline.setShape({
  34037. smooth: smooth,
  34038. smoothMonotone: seriesModel.get('smoothMonotone'),
  34039. connectNulls: seriesModel.get('connectNulls')
  34040. });
  34041. if (polygon) {
  34042. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34043. var stackedOnSmooth = 0;
  34044. polygon.useStyle(defaults(
  34045. areaStyleModel.getAreaStyle(),
  34046. {
  34047. fill: visualColor,
  34048. opacity: 0.7,
  34049. lineJoin: 'bevel'
  34050. }
  34051. ));
  34052. if (stackedOnSeries) {
  34053. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34054. }
  34055. polygon.setShape({
  34056. smooth: smooth,
  34057. stackedOnSmooth: stackedOnSmooth,
  34058. smoothMonotone: seriesModel.get('smoothMonotone'),
  34059. connectNulls: seriesModel.get('connectNulls')
  34060. });
  34061. }
  34062. this._data = data;
  34063. // Save the coordinate system for transition animation when data changed
  34064. this._coordSys = coordSys;
  34065. this._stackedOnPoints = stackedOnPoints;
  34066. this._points = points;
  34067. this._step = step;
  34068. this._valueOrigin = valueOrigin;
  34069. },
  34070. dispose: function () {},
  34071. highlight: function (seriesModel, ecModel, api, payload) {
  34072. var data = seriesModel.getData();
  34073. var dataIndex = queryDataIndex(data, payload);
  34074. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34075. var symbol = data.getItemGraphicEl(dataIndex);
  34076. if (!symbol) {
  34077. // Create a temporary symbol if it is not exists
  34078. var pt = data.getItemLayout(dataIndex);
  34079. if (!pt) {
  34080. // Null data
  34081. return;
  34082. }
  34083. // fix #11360: should't draw symbol outside clipShapeForSymbol
  34084. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  34085. return;
  34086. }
  34087. symbol = new SymbolClz$1(data, dataIndex);
  34088. symbol.position = pt;
  34089. symbol.setZ(
  34090. seriesModel.get('zlevel'),
  34091. seriesModel.get('z')
  34092. );
  34093. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  34094. symbol.__temp = true;
  34095. data.setItemGraphicEl(dataIndex, symbol);
  34096. // Stop scale animation
  34097. symbol.stopSymbolAnimation(true);
  34098. this.group.add(symbol);
  34099. }
  34100. symbol.highlight();
  34101. }
  34102. else {
  34103. // Highlight whole series
  34104. Chart.prototype.highlight.call(
  34105. this, seriesModel, ecModel, api, payload
  34106. );
  34107. }
  34108. },
  34109. downplay: function (seriesModel, ecModel, api, payload) {
  34110. var data = seriesModel.getData();
  34111. var dataIndex = queryDataIndex(data, payload);
  34112. if (dataIndex != null && dataIndex >= 0) {
  34113. var symbol = data.getItemGraphicEl(dataIndex);
  34114. if (symbol) {
  34115. if (symbol.__temp) {
  34116. data.setItemGraphicEl(dataIndex, null);
  34117. this.group.remove(symbol);
  34118. }
  34119. else {
  34120. symbol.downplay();
  34121. }
  34122. }
  34123. }
  34124. else {
  34125. // FIXME
  34126. // can not downplay completely.
  34127. // Downplay whole series
  34128. Chart.prototype.downplay.call(
  34129. this, seriesModel, ecModel, api, payload
  34130. );
  34131. }
  34132. },
  34133. /**
  34134. * @param {module:zrender/container/Group} group
  34135. * @param {Array.<Array.<number>>} points
  34136. * @private
  34137. */
  34138. _newPolyline: function (points) {
  34139. var polyline = this._polyline;
  34140. // Remove previous created polyline
  34141. if (polyline) {
  34142. this._lineGroup.remove(polyline);
  34143. }
  34144. polyline = new Polyline$1({
  34145. shape: {
  34146. points: points
  34147. },
  34148. silent: true,
  34149. z2: 10
  34150. });
  34151. this._lineGroup.add(polyline);
  34152. this._polyline = polyline;
  34153. return polyline;
  34154. },
  34155. /**
  34156. * @param {module:zrender/container/Group} group
  34157. * @param {Array.<Array.<number>>} stackedOnPoints
  34158. * @param {Array.<Array.<number>>} points
  34159. * @private
  34160. */
  34161. _newPolygon: function (points, stackedOnPoints) {
  34162. var polygon = this._polygon;
  34163. // Remove previous created polygon
  34164. if (polygon) {
  34165. this._lineGroup.remove(polygon);
  34166. }
  34167. polygon = new Polygon$1({
  34168. shape: {
  34169. points: points,
  34170. stackedOnPoints: stackedOnPoints
  34171. },
  34172. silent: true
  34173. });
  34174. this._lineGroup.add(polygon);
  34175. this._polygon = polygon;
  34176. return polygon;
  34177. },
  34178. /**
  34179. * @private
  34180. */
  34181. // FIXME Two value axis
  34182. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34183. var polyline = this._polyline;
  34184. var polygon = this._polygon;
  34185. var seriesModel = data.hostModel;
  34186. var diff = lineAnimationDiff(
  34187. this._data, data,
  34188. this._stackedOnPoints, stackedOnPoints,
  34189. this._coordSys, coordSys,
  34190. this._valueOrigin, valueOrigin
  34191. );
  34192. var current = diff.current;
  34193. var stackedOnCurrent = diff.stackedOnCurrent;
  34194. var next = diff.next;
  34195. var stackedOnNext = diff.stackedOnNext;
  34196. if (step) {
  34197. // TODO If stacked series is not step
  34198. current = turnPointsIntoStep(diff.current, coordSys, step);
  34199. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34200. next = turnPointsIntoStep(diff.next, coordSys, step);
  34201. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34202. }
  34203. // `diff.current` is subset of `current` (which should be ensured by
  34204. // turnPointsIntoStep), so points in `__points` can be updated when
  34205. // points in `current` are update during animation.
  34206. polyline.shape.__points = diff.current;
  34207. polyline.shape.points = current;
  34208. updateProps(polyline, {
  34209. shape: {
  34210. points: next
  34211. }
  34212. }, seriesModel);
  34213. if (polygon) {
  34214. polygon.setShape({
  34215. points: current,
  34216. stackedOnPoints: stackedOnCurrent
  34217. });
  34218. updateProps(polygon, {
  34219. shape: {
  34220. points: next,
  34221. stackedOnPoints: stackedOnNext
  34222. }
  34223. }, seriesModel);
  34224. }
  34225. var updatedDataInfo = [];
  34226. var diffStatus = diff.status;
  34227. for (var i = 0; i < diffStatus.length; i++) {
  34228. var cmd = diffStatus[i].cmd;
  34229. if (cmd === '=') {
  34230. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  34231. if (el) {
  34232. updatedDataInfo.push({
  34233. el: el,
  34234. ptIdx: i // Index of points
  34235. });
  34236. }
  34237. }
  34238. }
  34239. if (polyline.animators && polyline.animators.length) {
  34240. polyline.animators[0].during(function () {
  34241. for (var i = 0; i < updatedDataInfo.length; i++) {
  34242. var el = updatedDataInfo[i].el;
  34243. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  34244. }
  34245. });
  34246. }
  34247. },
  34248. remove: function (ecModel) {
  34249. var group = this.group;
  34250. var oldData = this._data;
  34251. this._lineGroup.removeAll();
  34252. this._symbolDraw.remove(true);
  34253. // Remove temporary created elements when highlighting
  34254. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34255. if (el.__temp) {
  34256. group.remove(el);
  34257. oldData.setItemGraphicEl(idx, null);
  34258. }
  34259. });
  34260. this._polyline =
  34261. this._polygon =
  34262. this._coordSys =
  34263. this._points =
  34264. this._stackedOnPoints =
  34265. this._data = null;
  34266. }
  34267. });
  34268. /*
  34269. * Licensed to the Apache Software Foundation (ASF) under one
  34270. * or more contributor license agreements. See the NOTICE file
  34271. * distributed with this work for additional information
  34272. * regarding copyright ownership. The ASF licenses this file
  34273. * to you under the Apache License, Version 2.0 (the
  34274. * "License"); you may not use this file except in compliance
  34275. * with the License. You may obtain a copy of the License at
  34276. *
  34277. * http://www.apache.org/licenses/LICENSE-2.0
  34278. *
  34279. * Unless required by applicable law or agreed to in writing,
  34280. * software distributed under the License is distributed on an
  34281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34282. * KIND, either express or implied. See the License for the
  34283. * specific language governing permissions and limitations
  34284. * under the License.
  34285. */
  34286. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  34287. // Encoding visual for all series include which is filtered for legend drawing
  34288. return {
  34289. seriesType: seriesType,
  34290. // For legend.
  34291. performRawSeries: true,
  34292. reset: function (seriesModel, ecModel, api) {
  34293. var data = seriesModel.getData();
  34294. var symbolType = seriesModel.get('symbol');
  34295. var symbolSize = seriesModel.get('symbolSize');
  34296. var keepAspect = seriesModel.get('symbolKeepAspect');
  34297. var hasSymbolTypeCallback = isFunction$1(symbolType);
  34298. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  34299. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback;
  34300. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  34301. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  34302. data.setVisual({
  34303. legendSymbol: legendSymbol || seriesSymbol,
  34304. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  34305. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  34306. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  34307. // some cases but generally it is not recommanded.
  34308. symbol: seriesSymbol,
  34309. symbolSize: seriesSymbolSize,
  34310. symbolKeepAspect: keepAspect
  34311. });
  34312. // Only visible series has each data be visual encoded
  34313. if (ecModel.isSeriesFiltered(seriesModel)) {
  34314. return;
  34315. }
  34316. function dataEach(data, idx) {
  34317. if (hasCallback) {
  34318. var rawValue = seriesModel.getRawValue(idx);
  34319. var params = seriesModel.getDataParams(idx);
  34320. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  34321. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  34322. }
  34323. if (data.hasItemOption) {
  34324. var itemModel = data.getItemModel(idx);
  34325. var itemSymbolType = itemModel.getShallow('symbol', true);
  34326. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  34327. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  34328. // If has item symbol
  34329. if (itemSymbolType != null) {
  34330. data.setItemVisual(idx, 'symbol', itemSymbolType);
  34331. }
  34332. if (itemSymbolSize != null) {
  34333. // PENDING Transform symbolSize ?
  34334. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  34335. }
  34336. if (itemSymbolKeepAspect != null) {
  34337. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  34338. }
  34339. }
  34340. }
  34341. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  34342. }
  34343. };
  34344. };
  34345. /*
  34346. * Licensed to the Apache Software Foundation (ASF) under one
  34347. * or more contributor license agreements. See the NOTICE file
  34348. * distributed with this work for additional information
  34349. * regarding copyright ownership. The ASF licenses this file
  34350. * to you under the Apache License, Version 2.0 (the
  34351. * "License"); you may not use this file except in compliance
  34352. * with the License. You may obtain a copy of the License at
  34353. *
  34354. * http://www.apache.org/licenses/LICENSE-2.0
  34355. *
  34356. * Unless required by applicable law or agreed to in writing,
  34357. * software distributed under the License is distributed on an
  34358. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34359. * KIND, either express or implied. See the License for the
  34360. * specific language governing permissions and limitations
  34361. * under the License.
  34362. */
  34363. /* global Float32Array */
  34364. var pointsLayout = function (seriesType) {
  34365. return {
  34366. seriesType: seriesType,
  34367. plan: createRenderPlanner(),
  34368. reset: function (seriesModel) {
  34369. var data = seriesModel.getData();
  34370. var coordSys = seriesModel.coordinateSystem;
  34371. var pipelineContext = seriesModel.pipelineContext;
  34372. var isLargeRender = pipelineContext.large;
  34373. if (!coordSys) {
  34374. return;
  34375. }
  34376. var dims = map(coordSys.dimensions, function (dim) {
  34377. return data.mapDimension(dim);
  34378. }).slice(0, 2);
  34379. var dimLen = dims.length;
  34380. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  34381. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  34382. dims[0] = stackResultDim;
  34383. }
  34384. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  34385. dims[1] = stackResultDim;
  34386. }
  34387. function progress(params, data) {
  34388. var segCount = params.end - params.start;
  34389. var points = isLargeRender && new Float32Array(segCount * dimLen);
  34390. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  34391. var point;
  34392. if (dimLen === 1) {
  34393. var x = data.get(dims[0], i);
  34394. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  34395. }
  34396. else {
  34397. var x = tmpIn[0] = data.get(dims[0], i);
  34398. var y = tmpIn[1] = data.get(dims[1], i);
  34399. // Also {Array.<number>}, not undefined to avoid if...else... statement
  34400. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  34401. }
  34402. if (isLargeRender) {
  34403. points[offset++] = point ? point[0] : NaN;
  34404. points[offset++] = point ? point[1] : NaN;
  34405. }
  34406. else {
  34407. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  34408. }
  34409. }
  34410. isLargeRender && data.setLayout('symbolPoints', points);
  34411. }
  34412. return dimLen && {progress: progress};
  34413. }
  34414. };
  34415. };
  34416. /*
  34417. * Licensed to the Apache Software Foundation (ASF) under one
  34418. * or more contributor license agreements. See the NOTICE file
  34419. * distributed with this work for additional information
  34420. * regarding copyright ownership. The ASF licenses this file
  34421. * to you under the Apache License, Version 2.0 (the
  34422. * "License"); you may not use this file except in compliance
  34423. * with the License. You may obtain a copy of the License at
  34424. *
  34425. * http://www.apache.org/licenses/LICENSE-2.0
  34426. *
  34427. * Unless required by applicable law or agreed to in writing,
  34428. * software distributed under the License is distributed on an
  34429. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34430. * KIND, either express or implied. See the License for the
  34431. * specific language governing permissions and limitations
  34432. * under the License.
  34433. */
  34434. var samplers = {
  34435. average: function (frame) {
  34436. var sum = 0;
  34437. var count = 0;
  34438. for (var i = 0; i < frame.length; i++) {
  34439. if (!isNaN(frame[i])) {
  34440. sum += frame[i];
  34441. count++;
  34442. }
  34443. }
  34444. // Return NaN if count is 0
  34445. return count === 0 ? NaN : sum / count;
  34446. },
  34447. sum: function (frame) {
  34448. var sum = 0;
  34449. for (var i = 0; i < frame.length; i++) {
  34450. // Ignore NaN
  34451. sum += frame[i] || 0;
  34452. }
  34453. return sum;
  34454. },
  34455. max: function (frame) {
  34456. var max = -Infinity;
  34457. for (var i = 0; i < frame.length; i++) {
  34458. frame[i] > max && (max = frame[i]);
  34459. }
  34460. // NaN will cause illegal axis extent.
  34461. return isFinite(max) ? max : NaN;
  34462. },
  34463. min: function (frame) {
  34464. var min = Infinity;
  34465. for (var i = 0; i < frame.length; i++) {
  34466. frame[i] < min && (min = frame[i]);
  34467. }
  34468. // NaN will cause illegal axis extent.
  34469. return isFinite(min) ? min : NaN;
  34470. },
  34471. // TODO
  34472. // Median
  34473. nearest: function (frame) {
  34474. return frame[0];
  34475. }
  34476. };
  34477. var indexSampler = function (frame, value) {
  34478. return Math.round(frame.length / 2);
  34479. };
  34480. var dataSample = function (seriesType) {
  34481. return {
  34482. seriesType: seriesType,
  34483. modifyOutputEnd: true,
  34484. reset: function (seriesModel, ecModel, api) {
  34485. var data = seriesModel.getData();
  34486. var sampling = seriesModel.get('sampling');
  34487. var coordSys = seriesModel.coordinateSystem;
  34488. // Only cartesian2d support down sampling
  34489. if (coordSys.type === 'cartesian2d' && sampling) {
  34490. var baseAxis = coordSys.getBaseAxis();
  34491. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34492. var extent = baseAxis.getExtent();
  34493. // Coordinste system has been resized
  34494. var size = extent[1] - extent[0];
  34495. var rate = Math.round(data.count() / size);
  34496. if (rate > 1) {
  34497. var sampler;
  34498. if (typeof sampling === 'string') {
  34499. sampler = samplers[sampling];
  34500. }
  34501. else if (typeof sampling === 'function') {
  34502. sampler = sampling;
  34503. }
  34504. if (sampler) {
  34505. // Only support sample the first dim mapped from value axis.
  34506. seriesModel.setData(data.downSample(
  34507. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  34508. ));
  34509. }
  34510. }
  34511. }
  34512. }
  34513. };
  34514. };
  34515. /*
  34516. * Licensed to the Apache Software Foundation (ASF) under one
  34517. * or more contributor license agreements. See the NOTICE file
  34518. * distributed with this work for additional information
  34519. * regarding copyright ownership. The ASF licenses this file
  34520. * to you under the Apache License, Version 2.0 (the
  34521. * "License"); you may not use this file except in compliance
  34522. * with the License. You may obtain a copy of the License at
  34523. *
  34524. * http://www.apache.org/licenses/LICENSE-2.0
  34525. *
  34526. * Unless required by applicable law or agreed to in writing,
  34527. * software distributed under the License is distributed on an
  34528. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34529. * KIND, either express or implied. See the License for the
  34530. * specific language governing permissions and limitations
  34531. * under the License.
  34532. */
  34533. /**
  34534. * Cartesian coordinate system
  34535. * @module echarts/coord/Cartesian
  34536. *
  34537. */
  34538. function dimAxisMapper(dim) {
  34539. return this._axes[dim];
  34540. }
  34541. /**
  34542. * @alias module:echarts/coord/Cartesian
  34543. * @constructor
  34544. */
  34545. var Cartesian = function (name) {
  34546. this._axes = {};
  34547. this._dimList = [];
  34548. /**
  34549. * @type {string}
  34550. */
  34551. this.name = name || '';
  34552. };
  34553. Cartesian.prototype = {
  34554. constructor: Cartesian,
  34555. type: 'cartesian',
  34556. /**
  34557. * Get axis
  34558. * @param {number|string} dim
  34559. * @return {module:echarts/coord/Cartesian~Axis}
  34560. */
  34561. getAxis: function (dim) {
  34562. return this._axes[dim];
  34563. },
  34564. /**
  34565. * Get axes list
  34566. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  34567. */
  34568. getAxes: function () {
  34569. return map(this._dimList, dimAxisMapper, this);
  34570. },
  34571. /**
  34572. * Get axes list by given scale type
  34573. */
  34574. getAxesByScale: function (scaleType) {
  34575. scaleType = scaleType.toLowerCase();
  34576. return filter(
  34577. this.getAxes(),
  34578. function (axis) {
  34579. return axis.scale.type === scaleType;
  34580. }
  34581. );
  34582. },
  34583. /**
  34584. * Add axis
  34585. * @param {module:echarts/coord/Cartesian.Axis}
  34586. */
  34587. addAxis: function (axis) {
  34588. var dim = axis.dim;
  34589. this._axes[dim] = axis;
  34590. this._dimList.push(dim);
  34591. },
  34592. /**
  34593. * Convert data to coord in nd space
  34594. * @param {Array.<number>|Object.<string, number>} val
  34595. * @return {Array.<number>|Object.<string, number>}
  34596. */
  34597. dataToCoord: function (val) {
  34598. return this._dataCoordConvert(val, 'dataToCoord');
  34599. },
  34600. /**
  34601. * Convert coord in nd space to data
  34602. * @param {Array.<number>|Object.<string, number>} val
  34603. * @return {Array.<number>|Object.<string, number>}
  34604. */
  34605. coordToData: function (val) {
  34606. return this._dataCoordConvert(val, 'coordToData');
  34607. },
  34608. _dataCoordConvert: function (input, method) {
  34609. var dimList = this._dimList;
  34610. var output = input instanceof Array ? [] : {};
  34611. for (var i = 0; i < dimList.length; i++) {
  34612. var dim = dimList[i];
  34613. var axis = this._axes[dim];
  34614. output[dim] = axis[method](input[dim]);
  34615. }
  34616. return output;
  34617. }
  34618. };
  34619. /*
  34620. * Licensed to the Apache Software Foundation (ASF) under one
  34621. * or more contributor license agreements. See the NOTICE file
  34622. * distributed with this work for additional information
  34623. * regarding copyright ownership. The ASF licenses this file
  34624. * to you under the Apache License, Version 2.0 (the
  34625. * "License"); you may not use this file except in compliance
  34626. * with the License. You may obtain a copy of the License at
  34627. *
  34628. * http://www.apache.org/licenses/LICENSE-2.0
  34629. *
  34630. * Unless required by applicable law or agreed to in writing,
  34631. * software distributed under the License is distributed on an
  34632. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34633. * KIND, either express or implied. See the License for the
  34634. * specific language governing permissions and limitations
  34635. * under the License.
  34636. */
  34637. function Cartesian2D(name) {
  34638. Cartesian.call(this, name);
  34639. }
  34640. Cartesian2D.prototype = {
  34641. constructor: Cartesian2D,
  34642. type: 'cartesian2d',
  34643. /**
  34644. * @type {Array.<string>}
  34645. * @readOnly
  34646. */
  34647. dimensions: ['x', 'y'],
  34648. /**
  34649. * Base axis will be used on stacking.
  34650. *
  34651. * @return {module:echarts/coord/cartesian/Axis2D}
  34652. */
  34653. getBaseAxis: function () {
  34654. return this.getAxesByScale('ordinal')[0]
  34655. || this.getAxesByScale('time')[0]
  34656. || this.getAxis('x');
  34657. },
  34658. /**
  34659. * If contain point
  34660. * @param {Array.<number>} point
  34661. * @return {boolean}
  34662. */
  34663. containPoint: function (point) {
  34664. var axisX = this.getAxis('x');
  34665. var axisY = this.getAxis('y');
  34666. return axisX.contain(axisX.toLocalCoord(point[0]))
  34667. && axisY.contain(axisY.toLocalCoord(point[1]));
  34668. },
  34669. /**
  34670. * If contain data
  34671. * @param {Array.<number>} data
  34672. * @return {boolean}
  34673. */
  34674. containData: function (data) {
  34675. return this.getAxis('x').containData(data[0])
  34676. && this.getAxis('y').containData(data[1]);
  34677. },
  34678. /**
  34679. * @param {Array.<number>} data
  34680. * @param {Array.<number>} out
  34681. * @return {Array.<number>}
  34682. */
  34683. dataToPoint: function (data, reserved, out) {
  34684. var xAxis = this.getAxis('x');
  34685. var yAxis = this.getAxis('y');
  34686. out = out || [];
  34687. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  34688. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  34689. return out;
  34690. },
  34691. /**
  34692. * @param {Array.<number>} data
  34693. * @param {Array.<number>} out
  34694. * @return {Array.<number>}
  34695. */
  34696. clampData: function (data, out) {
  34697. var xScale = this.getAxis('x').scale;
  34698. var yScale = this.getAxis('y').scale;
  34699. var xAxisExtent = xScale.getExtent();
  34700. var yAxisExtent = yScale.getExtent();
  34701. var x = xScale.parse(data[0]);
  34702. var y = yScale.parse(data[1]);
  34703. out = out || [];
  34704. out[0] = Math.min(
  34705. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  34706. Math.max(xAxisExtent[0], xAxisExtent[1])
  34707. );
  34708. out[1] = Math.min(
  34709. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  34710. Math.max(yAxisExtent[0], yAxisExtent[1])
  34711. );
  34712. return out;
  34713. },
  34714. /**
  34715. * @param {Array.<number>} point
  34716. * @param {Array.<number>} out
  34717. * @return {Array.<number>}
  34718. */
  34719. pointToData: function (point, out) {
  34720. var xAxis = this.getAxis('x');
  34721. var yAxis = this.getAxis('y');
  34722. out = out || [];
  34723. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  34724. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  34725. return out;
  34726. },
  34727. /**
  34728. * Get other axis
  34729. * @param {module:echarts/coord/cartesian/Axis2D} axis
  34730. */
  34731. getOtherAxis: function (axis) {
  34732. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  34733. },
  34734. /**
  34735. * Get rect area of cartesian.
  34736. * Area will have a contain function to determine if a point is in the coordinate system.
  34737. * @return {BoundingRect}
  34738. */
  34739. getArea: function () {
  34740. var xExtent = this.getAxis('x').getGlobalExtent();
  34741. var yExtent = this.getAxis('y').getGlobalExtent();
  34742. var x = Math.min(xExtent[0], xExtent[1]);
  34743. var y = Math.min(yExtent[0], yExtent[1]);
  34744. var width = Math.max(xExtent[0], xExtent[1]) - x;
  34745. var height = Math.max(yExtent[0], yExtent[1]) - y;
  34746. var rect = new BoundingRect(x, y, width, height);
  34747. return rect;
  34748. }
  34749. };
  34750. inherits(Cartesian2D, Cartesian);
  34751. /*
  34752. * Licensed to the Apache Software Foundation (ASF) under one
  34753. * or more contributor license agreements. See the NOTICE file
  34754. * distributed with this work for additional information
  34755. * regarding copyright ownership. The ASF licenses this file
  34756. * to you under the Apache License, Version 2.0 (the
  34757. * "License"); you may not use this file except in compliance
  34758. * with the License. You may obtain a copy of the License at
  34759. *
  34760. * http://www.apache.org/licenses/LICENSE-2.0
  34761. *
  34762. * Unless required by applicable law or agreed to in writing,
  34763. * software distributed under the License is distributed on an
  34764. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34765. * KIND, either express or implied. See the License for the
  34766. * specific language governing permissions and limitations
  34767. * under the License.
  34768. */
  34769. /**
  34770. * Extend axis 2d
  34771. * @constructor module:echarts/coord/cartesian/Axis2D
  34772. * @extends {module:echarts/coord/cartesian/Axis}
  34773. * @param {string} dim
  34774. * @param {*} scale
  34775. * @param {Array.<number>} coordExtent
  34776. * @param {string} axisType
  34777. * @param {string} position
  34778. */
  34779. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  34780. Axis.call(this, dim, scale, coordExtent);
  34781. /**
  34782. * Axis type
  34783. * - 'category'
  34784. * - 'value'
  34785. * - 'time'
  34786. * - 'log'
  34787. * @type {string}
  34788. */
  34789. this.type = axisType || 'value';
  34790. /**
  34791. * Axis position
  34792. * - 'top'
  34793. * - 'bottom'
  34794. * - 'left'
  34795. * - 'right'
  34796. */
  34797. this.position = position || 'bottom';
  34798. };
  34799. Axis2D.prototype = {
  34800. constructor: Axis2D,
  34801. /**
  34802. * Index of axis, can be used as key
  34803. */
  34804. index: 0,
  34805. /**
  34806. * Implemented in <module:echarts/coord/cartesian/Grid>.
  34807. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  34808. * If not on zero of other axis, return null/undefined.
  34809. * If no axes, return an empty array.
  34810. */
  34811. getAxesOnZeroOf: null,
  34812. /**
  34813. * Axis model
  34814. * @param {module:echarts/coord/cartesian/AxisModel}
  34815. */
  34816. model: null,
  34817. isHorizontal: function () {
  34818. var position = this.position;
  34819. return position === 'top' || position === 'bottom';
  34820. },
  34821. /**
  34822. * Each item cooresponds to this.getExtent(), which
  34823. * means globalExtent[0] may greater than globalExtent[1],
  34824. * unless `asc` is input.
  34825. *
  34826. * @param {boolean} [asc]
  34827. * @return {Array.<number>}
  34828. */
  34829. getGlobalExtent: function (asc) {
  34830. var ret = this.getExtent();
  34831. ret[0] = this.toGlobalCoord(ret[0]);
  34832. ret[1] = this.toGlobalCoord(ret[1]);
  34833. asc && ret[0] > ret[1] && ret.reverse();
  34834. return ret;
  34835. },
  34836. getOtherAxis: function () {
  34837. this.grid.getOtherAxis();
  34838. },
  34839. /**
  34840. * @override
  34841. */
  34842. pointToData: function (point, clamp) {
  34843. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  34844. },
  34845. /**
  34846. * Transform global coord to local coord,
  34847. * i.e. var localCoord = axis.toLocalCoord(80);
  34848. * designate by module:echarts/coord/cartesian/Grid.
  34849. * @type {Function}
  34850. */
  34851. toLocalCoord: null,
  34852. /**
  34853. * Transform global coord to local coord,
  34854. * i.e. var globalCoord = axis.toLocalCoord(40);
  34855. * designate by module:echarts/coord/cartesian/Grid.
  34856. * @type {Function}
  34857. */
  34858. toGlobalCoord: null
  34859. };
  34860. inherits(Axis2D, Axis);
  34861. /*
  34862. * Licensed to the Apache Software Foundation (ASF) under one
  34863. * or more contributor license agreements. See the NOTICE file
  34864. * distributed with this work for additional information
  34865. * regarding copyright ownership. The ASF licenses this file
  34866. * to you under the Apache License, Version 2.0 (the
  34867. * "License"); you may not use this file except in compliance
  34868. * with the License. You may obtain a copy of the License at
  34869. *
  34870. * http://www.apache.org/licenses/LICENSE-2.0
  34871. *
  34872. * Unless required by applicable law or agreed to in writing,
  34873. * software distributed under the License is distributed on an
  34874. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34875. * KIND, either express or implied. See the License for the
  34876. * specific language governing permissions and limitations
  34877. * under the License.
  34878. */
  34879. var defaultOption = {
  34880. show: true,
  34881. zlevel: 0,
  34882. z: 0,
  34883. // Inverse the axis.
  34884. inverse: false,
  34885. // Axis name displayed.
  34886. name: '',
  34887. // 'start' | 'middle' | 'end'
  34888. nameLocation: 'end',
  34889. // By degree. By defualt auto rotate by nameLocation.
  34890. nameRotate: null,
  34891. nameTruncate: {
  34892. maxWidth: null,
  34893. ellipsis: '...',
  34894. placeholder: '.'
  34895. },
  34896. // Use global text style by default.
  34897. nameTextStyle: {},
  34898. // The gap between axisName and axisLine.
  34899. nameGap: 15,
  34900. // Default `false` to support tooltip.
  34901. silent: false,
  34902. // Default `false` to avoid legacy user event listener fail.
  34903. triggerEvent: false,
  34904. tooltip: {
  34905. show: false
  34906. },
  34907. axisPointer: {},
  34908. axisLine: {
  34909. show: true,
  34910. onZero: true,
  34911. onZeroAxisIndex: null,
  34912. lineStyle: {
  34913. color: '#333',
  34914. width: 1,
  34915. type: 'solid'
  34916. },
  34917. // The arrow at both ends the the axis.
  34918. symbol: ['none', 'none'],
  34919. symbolSize: [10, 15]
  34920. },
  34921. axisTick: {
  34922. show: true,
  34923. // Whether axisTick is inside the grid or outside the grid.
  34924. inside: false,
  34925. // The length of axisTick.
  34926. length: 5,
  34927. lineStyle: {
  34928. width: 1
  34929. }
  34930. },
  34931. axisLabel: {
  34932. show: true,
  34933. // Whether axisLabel is inside the grid or outside the grid.
  34934. inside: false,
  34935. rotate: 0,
  34936. // true | false | null/undefined (auto)
  34937. showMinLabel: null,
  34938. // true | false | null/undefined (auto)
  34939. showMaxLabel: null,
  34940. margin: 8,
  34941. // formatter: null,
  34942. fontSize: 12
  34943. },
  34944. splitLine: {
  34945. show: true,
  34946. lineStyle: {
  34947. color: ['#ccc'],
  34948. width: 1,
  34949. type: 'solid'
  34950. }
  34951. },
  34952. splitArea: {
  34953. show: false,
  34954. areaStyle: {
  34955. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  34956. }
  34957. }
  34958. };
  34959. var axisDefault = {};
  34960. axisDefault.categoryAxis = merge({
  34961. // The gap at both ends of the axis. For categoryAxis, boolean.
  34962. boundaryGap: true,
  34963. // Set false to faster category collection.
  34964. // Only usefull in the case like: category is
  34965. // ['2012-01-01', '2012-01-02', ...], where the input
  34966. // data has been ensured not duplicate and is large data.
  34967. // null means "auto":
  34968. // if axis.data provided, do not deduplication,
  34969. // else do deduplication.
  34970. deduplication: null,
  34971. // splitArea: {
  34972. // show: false
  34973. // },
  34974. splitLine: {
  34975. show: false
  34976. },
  34977. axisTick: {
  34978. // If tick is align with label when boundaryGap is true
  34979. alignWithLabel: false,
  34980. interval: 'auto'
  34981. },
  34982. axisLabel: {
  34983. interval: 'auto'
  34984. }
  34985. }, defaultOption);
  34986. axisDefault.valueAxis = merge({
  34987. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  34988. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  34989. boundaryGap: [0, 0],
  34990. // TODO
  34991. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  34992. // Min value of the axis. can be:
  34993. // + a number
  34994. // + 'dataMin': use the min value in data.
  34995. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  34996. // min: null,
  34997. // Max value of the axis. can be:
  34998. // + a number
  34999. // + 'dataMax': use the max value in data.
  35000. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  35001. // max: null,
  35002. // Readonly prop, specifies start value of the range when using data zoom.
  35003. // rangeStart: null
  35004. // Readonly prop, specifies end value of the range when using data zoom.
  35005. // rangeEnd: null
  35006. // Optional value can be:
  35007. // + `false`: always include value 0.
  35008. // + `true`: the extent do not consider value 0.
  35009. // scale: false,
  35010. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  35011. splitNumber: 5,
  35012. // Interval specifies the span of the ticks is mandatorily.
  35013. // interval: null
  35014. // Specify min interval when auto calculate tick interval.
  35015. // minInterval: null
  35016. // Specify max interval when auto calculate tick interval.
  35017. // maxInterval: null
  35018. minorTick: {
  35019. // Minor tick, not available for cateogry axis.
  35020. show: false,
  35021. // Split number of minor ticks. The value should be in range of (0, 100)
  35022. splitNumber: 5,
  35023. // Lenght of minor tick
  35024. length: 3,
  35025. // Same inside with axisTick
  35026. // Line style
  35027. lineStyle: {
  35028. // Default to be same with axisTick
  35029. }
  35030. },
  35031. minorSplitLine: {
  35032. show: false,
  35033. lineStyle: {
  35034. color: '#eee',
  35035. width: 1
  35036. }
  35037. }
  35038. }, defaultOption);
  35039. axisDefault.timeAxis = defaults({
  35040. scale: true,
  35041. min: 'dataMin',
  35042. max: 'dataMax'
  35043. }, axisDefault.valueAxis);
  35044. axisDefault.logAxis = defaults({
  35045. scale: true,
  35046. logBase: 10
  35047. }, axisDefault.valueAxis);
  35048. /*
  35049. * Licensed to the Apache Software Foundation (ASF) under one
  35050. * or more contributor license agreements. See the NOTICE file
  35051. * distributed with this work for additional information
  35052. * regarding copyright ownership. The ASF licenses this file
  35053. * to you under the Apache License, Version 2.0 (the
  35054. * "License"); you may not use this file except in compliance
  35055. * with the License. You may obtain a copy of the License at
  35056. *
  35057. * http://www.apache.org/licenses/LICENSE-2.0
  35058. *
  35059. * Unless required by applicable law or agreed to in writing,
  35060. * software distributed under the License is distributed on an
  35061. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35062. * KIND, either express or implied. See the License for the
  35063. * specific language governing permissions and limitations
  35064. * under the License.
  35065. */
  35066. // FIXME axisType is fixed ?
  35067. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  35068. /**
  35069. * Generate sub axis model class
  35070. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  35071. * @param {module:echarts/model/Component} BaseAxisModelClass
  35072. * @param {Function} axisTypeDefaulter
  35073. * @param {Object} [extraDefaultOption]
  35074. */
  35075. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  35076. each$1(AXIS_TYPES, function (axisType) {
  35077. BaseAxisModelClass.extend({
  35078. /**
  35079. * @readOnly
  35080. */
  35081. type: axisName + 'Axis.' + axisType,
  35082. mergeDefaultAndTheme: function (option, ecModel) {
  35083. var layoutMode = this.layoutMode;
  35084. var inputPositionParams = layoutMode
  35085. ? getLayoutParams(option) : {};
  35086. var themeModel = ecModel.getTheme();
  35087. merge(option, themeModel.get(axisType + 'Axis'));
  35088. merge(option, this.getDefaultOption());
  35089. option.type = axisTypeDefaulter(axisName, option);
  35090. if (layoutMode) {
  35091. mergeLayoutParam(option, inputPositionParams, layoutMode);
  35092. }
  35093. },
  35094. /**
  35095. * @override
  35096. */
  35097. optionUpdated: function () {
  35098. var thisOption = this.option;
  35099. if (thisOption.type === 'category') {
  35100. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  35101. }
  35102. },
  35103. /**
  35104. * Should not be called before all of 'getInitailData' finished.
  35105. * Because categories are collected during initializing data.
  35106. */
  35107. getCategories: function (rawData) {
  35108. var option = this.option;
  35109. // FIXME
  35110. // warning if called before all of 'getInitailData' finished.
  35111. if (option.type === 'category') {
  35112. if (rawData) {
  35113. return option.data;
  35114. }
  35115. return this.__ordinalMeta.categories;
  35116. }
  35117. },
  35118. getOrdinalMeta: function () {
  35119. return this.__ordinalMeta;
  35120. },
  35121. defaultOption: mergeAll(
  35122. [
  35123. {},
  35124. axisDefault[axisType + 'Axis'],
  35125. extraDefaultOption
  35126. ],
  35127. true
  35128. )
  35129. });
  35130. });
  35131. ComponentModel.registerSubTypeDefaulter(
  35132. axisName + 'Axis',
  35133. curry(axisTypeDefaulter, axisName)
  35134. );
  35135. };
  35136. /*
  35137. * Licensed to the Apache Software Foundation (ASF) under one
  35138. * or more contributor license agreements. See the NOTICE file
  35139. * distributed with this work for additional information
  35140. * regarding copyright ownership. The ASF licenses this file
  35141. * to you under the Apache License, Version 2.0 (the
  35142. * "License"); you may not use this file except in compliance
  35143. * with the License. You may obtain a copy of the License at
  35144. *
  35145. * http://www.apache.org/licenses/LICENSE-2.0
  35146. *
  35147. * Unless required by applicable law or agreed to in writing,
  35148. * software distributed under the License is distributed on an
  35149. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35150. * KIND, either express or implied. See the License for the
  35151. * specific language governing permissions and limitations
  35152. * under the License.
  35153. */
  35154. var AxisModel = ComponentModel.extend({
  35155. type: 'cartesian2dAxis',
  35156. /**
  35157. * @type {module:echarts/coord/cartesian/Axis2D}
  35158. */
  35159. axis: null,
  35160. /**
  35161. * @override
  35162. */
  35163. init: function () {
  35164. AxisModel.superApply(this, 'init', arguments);
  35165. this.resetRange();
  35166. },
  35167. /**
  35168. * @override
  35169. */
  35170. mergeOption: function () {
  35171. AxisModel.superApply(this, 'mergeOption', arguments);
  35172. this.resetRange();
  35173. },
  35174. /**
  35175. * @override
  35176. */
  35177. restoreData: function () {
  35178. AxisModel.superApply(this, 'restoreData', arguments);
  35179. this.resetRange();
  35180. },
  35181. /**
  35182. * @override
  35183. * @return {module:echarts/model/Component}
  35184. */
  35185. getCoordSysModel: function () {
  35186. return this.ecModel.queryComponents({
  35187. mainType: 'grid',
  35188. index: this.option.gridIndex,
  35189. id: this.option.gridId
  35190. })[0];
  35191. }
  35192. });
  35193. function getAxisType(axisDim, option) {
  35194. // Default axis with data is category axis
  35195. return option.type || (option.data ? 'category' : 'value');
  35196. }
  35197. merge(AxisModel.prototype, axisModelCommonMixin);
  35198. var extraOption = {
  35199. // gridIndex: 0,
  35200. // gridId: '',
  35201. // Offset is for multiple axis on the same position
  35202. offset: 0
  35203. };
  35204. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  35205. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  35206. /*
  35207. * Licensed to the Apache Software Foundation (ASF) under one
  35208. * or more contributor license agreements. See the NOTICE file
  35209. * distributed with this work for additional information
  35210. * regarding copyright ownership. The ASF licenses this file
  35211. * to you under the Apache License, Version 2.0 (the
  35212. * "License"); you may not use this file except in compliance
  35213. * with the License. You may obtain a copy of the License at
  35214. *
  35215. * http://www.apache.org/licenses/LICENSE-2.0
  35216. *
  35217. * Unless required by applicable law or agreed to in writing,
  35218. * software distributed under the License is distributed on an
  35219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35220. * KIND, either express or implied. See the License for the
  35221. * specific language governing permissions and limitations
  35222. * under the License.
  35223. */
  35224. // Grid 是在有直角坐标系的时候必须要存在的
  35225. // 所以这里也要被 Cartesian2D 依赖
  35226. ComponentModel.extend({
  35227. type: 'grid',
  35228. dependencies: ['xAxis', 'yAxis'],
  35229. layoutMode: 'box',
  35230. /**
  35231. * @type {module:echarts/coord/cartesian/Grid}
  35232. */
  35233. coordinateSystem: null,
  35234. defaultOption: {
  35235. show: false,
  35236. zlevel: 0,
  35237. z: 0,
  35238. left: '10%',
  35239. top: 60,
  35240. right: '10%',
  35241. bottom: 60,
  35242. // If grid size contain label
  35243. containLabel: false,
  35244. // width: {totalWidth} - left - right,
  35245. // height: {totalHeight} - top - bottom,
  35246. backgroundColor: 'rgba(0,0,0,0)',
  35247. borderWidth: 1,
  35248. borderColor: '#ccc'
  35249. }
  35250. });
  35251. /*
  35252. * Licensed to the Apache Software Foundation (ASF) under one
  35253. * or more contributor license agreements. See the NOTICE file
  35254. * distributed with this work for additional information
  35255. * regarding copyright ownership. The ASF licenses this file
  35256. * to you under the Apache License, Version 2.0 (the
  35257. * "License"); you may not use this file except in compliance
  35258. * with the License. You may obtain a copy of the License at
  35259. *
  35260. * http://www.apache.org/licenses/LICENSE-2.0
  35261. *
  35262. * Unless required by applicable law or agreed to in writing,
  35263. * software distributed under the License is distributed on an
  35264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35265. * KIND, either express or implied. See the License for the
  35266. * specific language governing permissions and limitations
  35267. * under the License.
  35268. */
  35269. /**
  35270. * Grid is a region which contains at most 4 cartesian systems
  35271. *
  35272. * TODO Default cartesian
  35273. */
  35274. // Depends on GridModel, AxisModel, which performs preprocess.
  35275. /**
  35276. * Check if the axis is used in the specified grid
  35277. * @inner
  35278. */
  35279. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  35280. return axisModel.getCoordSysModel() === gridModel;
  35281. }
  35282. function Grid(gridModel, ecModel, api) {
  35283. /**
  35284. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  35285. * @private
  35286. */
  35287. this._coordsMap = {};
  35288. /**
  35289. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  35290. * @private
  35291. */
  35292. this._coordsList = [];
  35293. /**
  35294. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  35295. * @private
  35296. */
  35297. this._axesMap = {};
  35298. /**
  35299. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  35300. * @private
  35301. */
  35302. this._axesList = [];
  35303. this._initCartesian(gridModel, ecModel, api);
  35304. this.model = gridModel;
  35305. }
  35306. var gridProto = Grid.prototype;
  35307. gridProto.type = 'grid';
  35308. gridProto.axisPointerEnabled = true;
  35309. gridProto.getRect = function () {
  35310. return this._rect;
  35311. };
  35312. gridProto.update = function (ecModel, api) {
  35313. var axesMap = this._axesMap;
  35314. this._updateScale(ecModel, this.model);
  35315. each$1(axesMap.x, function (xAxis) {
  35316. niceScaleExtent(xAxis.scale, xAxis.model);
  35317. });
  35318. each$1(axesMap.y, function (yAxis) {
  35319. niceScaleExtent(yAxis.scale, yAxis.model);
  35320. });
  35321. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  35322. var onZeroRecords = {};
  35323. each$1(axesMap.x, function (xAxis) {
  35324. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  35325. });
  35326. each$1(axesMap.y, function (yAxis) {
  35327. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  35328. });
  35329. // Resize again if containLabel is enabled
  35330. // FIXME It may cause getting wrong grid size in data processing stage
  35331. this.resize(this.model, api);
  35332. };
  35333. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  35334. axis.getAxesOnZeroOf = function () {
  35335. // TODO: onZero of multiple axes.
  35336. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  35337. };
  35338. // onZero can not be enabled in these two situations:
  35339. // 1. When any other axis is a category axis.
  35340. // 2. When no axis is cross 0 point.
  35341. var otherAxes = axesMap[otherAxisDim];
  35342. var otherAxisOnZeroOf;
  35343. var axisModel = axis.model;
  35344. var onZero = axisModel.get('axisLine.onZero');
  35345. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  35346. if (!onZero) {
  35347. return;
  35348. }
  35349. // If target axis is specified.
  35350. if (onZeroAxisIndex != null) {
  35351. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  35352. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  35353. }
  35354. }
  35355. else {
  35356. // Find the first available other axis.
  35357. for (var idx in otherAxes) {
  35358. if (otherAxes.hasOwnProperty(idx)
  35359. && canOnZeroToAxis(otherAxes[idx])
  35360. // Consider that two Y axes on one value axis,
  35361. // if both onZero, the two Y axes overlap.
  35362. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  35363. ) {
  35364. otherAxisOnZeroOf = otherAxes[idx];
  35365. break;
  35366. }
  35367. }
  35368. }
  35369. if (otherAxisOnZeroOf) {
  35370. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  35371. }
  35372. function getOnZeroRecordKey(axis) {
  35373. return axis.dim + '_' + axis.index;
  35374. }
  35375. }
  35376. function canOnZeroToAxis(axis) {
  35377. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  35378. }
  35379. /**
  35380. * Resize the grid
  35381. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35382. * @param {module:echarts/ExtensionAPI} api
  35383. */
  35384. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  35385. var gridRect = getLayoutRect(
  35386. gridModel.getBoxLayoutParams(), {
  35387. width: api.getWidth(),
  35388. height: api.getHeight()
  35389. });
  35390. this._rect = gridRect;
  35391. var axesList = this._axesList;
  35392. adjustAxes();
  35393. // Minus label size
  35394. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  35395. each$1(axesList, function (axis) {
  35396. if (!axis.model.get('axisLabel.inside')) {
  35397. var labelUnionRect = estimateLabelUnionRect(axis);
  35398. if (labelUnionRect) {
  35399. var dim = axis.isHorizontal() ? 'height' : 'width';
  35400. var margin = axis.model.get('axisLabel.margin');
  35401. gridRect[dim] -= labelUnionRect[dim] + margin;
  35402. if (axis.position === 'top') {
  35403. gridRect.y += labelUnionRect.height + margin;
  35404. }
  35405. else if (axis.position === 'left') {
  35406. gridRect.x += labelUnionRect.width + margin;
  35407. }
  35408. }
  35409. }
  35410. });
  35411. adjustAxes();
  35412. }
  35413. function adjustAxes() {
  35414. each$1(axesList, function (axis) {
  35415. var isHorizontal = axis.isHorizontal();
  35416. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  35417. var idx = axis.inverse ? 1 : 0;
  35418. axis.setExtent(extent[idx], extent[1 - idx]);
  35419. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  35420. });
  35421. }
  35422. };
  35423. /**
  35424. * @param {string} axisType
  35425. * @param {number} [axisIndex]
  35426. */
  35427. gridProto.getAxis = function (axisType, axisIndex) {
  35428. var axesMapOnDim = this._axesMap[axisType];
  35429. if (axesMapOnDim != null) {
  35430. if (axisIndex == null) {
  35431. // Find first axis
  35432. for (var name in axesMapOnDim) {
  35433. if (axesMapOnDim.hasOwnProperty(name)) {
  35434. return axesMapOnDim[name];
  35435. }
  35436. }
  35437. }
  35438. return axesMapOnDim[axisIndex];
  35439. }
  35440. };
  35441. /**
  35442. * @return {Array.<module:echarts/coord/Axis>}
  35443. */
  35444. gridProto.getAxes = function () {
  35445. return this._axesList.slice();
  35446. };
  35447. /**
  35448. * Usage:
  35449. * grid.getCartesian(xAxisIndex, yAxisIndex);
  35450. * grid.getCartesian(xAxisIndex);
  35451. * grid.getCartesian(null, yAxisIndex);
  35452. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  35453. *
  35454. * @param {number|Object} [xAxisIndex]
  35455. * @param {number} [yAxisIndex]
  35456. */
  35457. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  35458. if (xAxisIndex != null && yAxisIndex != null) {
  35459. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35460. return this._coordsMap[key];
  35461. }
  35462. if (isObject$1(xAxisIndex)) {
  35463. yAxisIndex = xAxisIndex.yAxisIndex;
  35464. xAxisIndex = xAxisIndex.xAxisIndex;
  35465. }
  35466. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  35467. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  35468. if (coordList[i].getAxis('x').index === xAxisIndex
  35469. || coordList[i].getAxis('y').index === yAxisIndex
  35470. ) {
  35471. return coordList[i];
  35472. }
  35473. }
  35474. };
  35475. gridProto.getCartesians = function () {
  35476. return this._coordsList.slice();
  35477. };
  35478. /**
  35479. * @implements
  35480. * see {module:echarts/CoodinateSystem}
  35481. */
  35482. gridProto.convertToPixel = function (ecModel, finder, value) {
  35483. var target = this._findConvertTarget(ecModel, finder);
  35484. return target.cartesian
  35485. ? target.cartesian.dataToPoint(value)
  35486. : target.axis
  35487. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  35488. : null;
  35489. };
  35490. /**
  35491. * @implements
  35492. * see {module:echarts/CoodinateSystem}
  35493. */
  35494. gridProto.convertFromPixel = function (ecModel, finder, value) {
  35495. var target = this._findConvertTarget(ecModel, finder);
  35496. return target.cartesian
  35497. ? target.cartesian.pointToData(value)
  35498. : target.axis
  35499. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  35500. : null;
  35501. };
  35502. /**
  35503. * @inner
  35504. */
  35505. gridProto._findConvertTarget = function (ecModel, finder) {
  35506. var seriesModel = finder.seriesModel;
  35507. var xAxisModel = finder.xAxisModel
  35508. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  35509. var yAxisModel = finder.yAxisModel
  35510. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  35511. var gridModel = finder.gridModel;
  35512. var coordsList = this._coordsList;
  35513. var cartesian;
  35514. var axis;
  35515. if (seriesModel) {
  35516. cartesian = seriesModel.coordinateSystem;
  35517. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  35518. }
  35519. else if (xAxisModel && yAxisModel) {
  35520. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  35521. }
  35522. else if (xAxisModel) {
  35523. axis = this.getAxis('x', xAxisModel.componentIndex);
  35524. }
  35525. else if (yAxisModel) {
  35526. axis = this.getAxis('y', yAxisModel.componentIndex);
  35527. }
  35528. // Lowest priority.
  35529. else if (gridModel) {
  35530. var grid = gridModel.coordinateSystem;
  35531. if (grid === this) {
  35532. cartesian = this._coordsList[0];
  35533. }
  35534. }
  35535. return {cartesian: cartesian, axis: axis};
  35536. };
  35537. /**
  35538. * @implements
  35539. * see {module:echarts/CoodinateSystem}
  35540. */
  35541. gridProto.containPoint = function (point) {
  35542. var coord = this._coordsList[0];
  35543. if (coord) {
  35544. return coord.containPoint(point);
  35545. }
  35546. };
  35547. /**
  35548. * Initialize cartesian coordinate systems
  35549. * @private
  35550. */
  35551. gridProto._initCartesian = function (gridModel, ecModel, api) {
  35552. var axisPositionUsed = {
  35553. left: false,
  35554. right: false,
  35555. top: false,
  35556. bottom: false
  35557. };
  35558. var axesMap = {
  35559. x: {},
  35560. y: {}
  35561. };
  35562. var axesCount = {
  35563. x: 0,
  35564. y: 0
  35565. };
  35566. /// Create axis
  35567. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  35568. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  35569. if (!axesCount.x || !axesCount.y) {
  35570. // Roll back when there no either x or y axis
  35571. this._axesMap = {};
  35572. this._axesList = [];
  35573. return;
  35574. }
  35575. this._axesMap = axesMap;
  35576. /// Create cartesian2d
  35577. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  35578. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  35579. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35580. var cartesian = new Cartesian2D(key);
  35581. cartesian.grid = this;
  35582. cartesian.model = gridModel;
  35583. this._coordsMap[key] = cartesian;
  35584. this._coordsList.push(cartesian);
  35585. cartesian.addAxis(xAxis);
  35586. cartesian.addAxis(yAxis);
  35587. }, this);
  35588. }, this);
  35589. function createAxisCreator(axisType) {
  35590. return function (axisModel, idx) {
  35591. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  35592. return;
  35593. }
  35594. var axisPosition = axisModel.get('position');
  35595. if (axisType === 'x') {
  35596. // Fix position
  35597. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  35598. // Default bottom of X
  35599. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  35600. }
  35601. }
  35602. else {
  35603. // Fix position
  35604. if (axisPosition !== 'left' && axisPosition !== 'right') {
  35605. // Default left of Y
  35606. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  35607. }
  35608. }
  35609. axisPositionUsed[axisPosition] = true;
  35610. var axis = new Axis2D(
  35611. axisType, createScaleByModel(axisModel),
  35612. [0, 0],
  35613. axisModel.get('type'),
  35614. axisPosition
  35615. );
  35616. var isCategory = axis.type === 'category';
  35617. axis.onBand = isCategory && axisModel.get('boundaryGap');
  35618. axis.inverse = axisModel.get('inverse');
  35619. // Inject axis into axisModel
  35620. axisModel.axis = axis;
  35621. // Inject axisModel into axis
  35622. axis.model = axisModel;
  35623. // Inject grid info axis
  35624. axis.grid = this;
  35625. // Index of axis, can be used as key
  35626. axis.index = idx;
  35627. this._axesList.push(axis);
  35628. axesMap[axisType][idx] = axis;
  35629. axesCount[axisType]++;
  35630. };
  35631. }
  35632. };
  35633. /**
  35634. * Update cartesian properties from series
  35635. * @param {module:echarts/model/Option} option
  35636. * @private
  35637. */
  35638. gridProto._updateScale = function (ecModel, gridModel) {
  35639. // Reset scale
  35640. each$1(this._axesList, function (axis) {
  35641. axis.scale.setExtent(Infinity, -Infinity);
  35642. });
  35643. ecModel.eachSeries(function (seriesModel) {
  35644. if (isCartesian2D(seriesModel)) {
  35645. var axesModels = findAxesModels(seriesModel, ecModel);
  35646. var xAxisModel = axesModels[0];
  35647. var yAxisModel = axesModels[1];
  35648. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  35649. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  35650. ) {
  35651. return;
  35652. }
  35653. var cartesian = this.getCartesian(
  35654. xAxisModel.componentIndex, yAxisModel.componentIndex
  35655. );
  35656. var data = seriesModel.getData();
  35657. var xAxis = cartesian.getAxis('x');
  35658. var yAxis = cartesian.getAxis('y');
  35659. if (data.type === 'list') {
  35660. unionExtent(data, xAxis, seriesModel);
  35661. unionExtent(data, yAxis, seriesModel);
  35662. }
  35663. }
  35664. }, this);
  35665. function unionExtent(data, axis, seriesModel) {
  35666. each$1(data.mapDimension(axis.dim, true), function (dim) {
  35667. axis.scale.unionExtentFromData(
  35668. // For example, the extent of the orginal dimension
  35669. // is [0.1, 0.5], the extent of the `stackResultDimension`
  35670. // is [7, 9], the final extent should not include [0.1, 0.5].
  35671. data, getStackedDimension(data, dim)
  35672. );
  35673. });
  35674. }
  35675. };
  35676. /**
  35677. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  35678. * @return {Object} {baseAxes: [], otherAxes: []}
  35679. */
  35680. gridProto.getTooltipAxes = function (dim) {
  35681. var baseAxes = [];
  35682. var otherAxes = [];
  35683. each$1(this.getCartesians(), function (cartesian) {
  35684. var baseAxis = (dim != null && dim !== 'auto')
  35685. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  35686. var otherAxis = cartesian.getOtherAxis(baseAxis);
  35687. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  35688. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  35689. });
  35690. return {baseAxes: baseAxes, otherAxes: otherAxes};
  35691. };
  35692. /**
  35693. * @inner
  35694. */
  35695. function updateAxisTransform(axis, coordBase) {
  35696. var axisExtent = axis.getExtent();
  35697. var axisExtentSum = axisExtent[0] + axisExtent[1];
  35698. // Fast transform
  35699. axis.toGlobalCoord = axis.dim === 'x'
  35700. ? function (coord) {
  35701. return coord + coordBase;
  35702. }
  35703. : function (coord) {
  35704. return axisExtentSum - coord + coordBase;
  35705. };
  35706. axis.toLocalCoord = axis.dim === 'x'
  35707. ? function (coord) {
  35708. return coord - coordBase;
  35709. }
  35710. : function (coord) {
  35711. return axisExtentSum - coord + coordBase;
  35712. };
  35713. }
  35714. var axesTypes = ['xAxis', 'yAxis'];
  35715. /**
  35716. * @inner
  35717. */
  35718. function findAxesModels(seriesModel, ecModel) {
  35719. return map(axesTypes, function (axisType) {
  35720. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  35721. if (__DEV__) {
  35722. if (!axisModel) {
  35723. throw new Error(axisType + ' "' + retrieve(
  35724. seriesModel.get(axisType + 'Index'),
  35725. seriesModel.get(axisType + 'Id'),
  35726. 0
  35727. ) + '" not found');
  35728. }
  35729. }
  35730. return axisModel;
  35731. });
  35732. }
  35733. /**
  35734. * @inner
  35735. */
  35736. function isCartesian2D(seriesModel) {
  35737. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  35738. }
  35739. Grid.create = function (ecModel, api) {
  35740. var grids = [];
  35741. ecModel.eachComponent('grid', function (gridModel, idx) {
  35742. var grid = new Grid(gridModel, ecModel, api);
  35743. grid.name = 'grid_' + idx;
  35744. // dataSampling requires axis extent, so resize
  35745. // should be performed in create stage.
  35746. grid.resize(gridModel, api, true);
  35747. gridModel.coordinateSystem = grid;
  35748. grids.push(grid);
  35749. });
  35750. // Inject the coordinateSystems into seriesModel
  35751. ecModel.eachSeries(function (seriesModel) {
  35752. if (!isCartesian2D(seriesModel)) {
  35753. return;
  35754. }
  35755. var axesModels = findAxesModels(seriesModel, ecModel);
  35756. var xAxisModel = axesModels[0];
  35757. var yAxisModel = axesModels[1];
  35758. var gridModel = xAxisModel.getCoordSysModel();
  35759. if (__DEV__) {
  35760. if (!gridModel) {
  35761. throw new Error(
  35762. 'Grid "' + retrieve(
  35763. xAxisModel.get('gridIndex'),
  35764. xAxisModel.get('gridId'),
  35765. 0
  35766. ) + '" not found'
  35767. );
  35768. }
  35769. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  35770. throw new Error('xAxis and yAxis must use the same grid');
  35771. }
  35772. }
  35773. var grid = gridModel.coordinateSystem;
  35774. seriesModel.coordinateSystem = grid.getCartesian(
  35775. xAxisModel.componentIndex, yAxisModel.componentIndex
  35776. );
  35777. });
  35778. return grids;
  35779. };
  35780. // For deciding which dimensions to use when creating list data
  35781. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  35782. CoordinateSystemManager.register('cartesian2d', Grid);
  35783. /*
  35784. * Licensed to the Apache Software Foundation (ASF) under one
  35785. * or more contributor license agreements. See the NOTICE file
  35786. * distributed with this work for additional information
  35787. * regarding copyright ownership. The ASF licenses this file
  35788. * to you under the Apache License, Version 2.0 (the
  35789. * "License"); you may not use this file except in compliance
  35790. * with the License. You may obtain a copy of the License at
  35791. *
  35792. * http://www.apache.org/licenses/LICENSE-2.0
  35793. *
  35794. * Unless required by applicable law or agreed to in writing,
  35795. * software distributed under the License is distributed on an
  35796. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35797. * KIND, either express or implied. See the License for the
  35798. * specific language governing permissions and limitations
  35799. * under the License.
  35800. */
  35801. var PI$2 = Math.PI;
  35802. /**
  35803. * A final axis is translated and rotated from a "standard axis".
  35804. * So opt.position and opt.rotation is required.
  35805. *
  35806. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  35807. * for example: (0, 0) ------------> (0, 50)
  35808. *
  35809. * nameDirection or tickDirection or labelDirection is 1 means tick
  35810. * or label is below the standard axis, whereas is -1 means above
  35811. * the standard axis. labelOffset means offset between label and axis,
  35812. * which is useful when 'onZero', where axisLabel is in the grid and
  35813. * label in outside grid.
  35814. *
  35815. * Tips: like always,
  35816. * positive rotation represents anticlockwise, and negative rotation
  35817. * represents clockwise.
  35818. * The direction of position coordinate is the same as the direction
  35819. * of screen coordinate.
  35820. *
  35821. * Do not need to consider axis 'inverse', which is auto processed by
  35822. * axis extent.
  35823. *
  35824. * @param {module:zrender/container/Group} group
  35825. * @param {Object} axisModel
  35826. * @param {Object} opt Standard axis parameters.
  35827. * @param {Array.<number>} opt.position [x, y]
  35828. * @param {number} opt.rotation by radian
  35829. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  35830. * @param {number} [opt.tickDirection=1] 1 or -1
  35831. * @param {number} [opt.labelDirection=1] 1 or -1
  35832. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  35833. * @param {string} [opt.axisLabelShow] default get from axisModel.
  35834. * @param {string} [opt.axisName] default get from axisModel.
  35835. * @param {number} [opt.axisNameAvailableWidth]
  35836. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  35837. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  35838. * @param {number} [opt.nameTruncateMaxWidth]
  35839. */
  35840. var AxisBuilder = function (axisModel, opt) {
  35841. /**
  35842. * @readOnly
  35843. */
  35844. this.opt = opt;
  35845. /**
  35846. * @readOnly
  35847. */
  35848. this.axisModel = axisModel;
  35849. // Default value
  35850. defaults(
  35851. opt,
  35852. {
  35853. labelOffset: 0,
  35854. nameDirection: 1,
  35855. tickDirection: 1,
  35856. labelDirection: 1,
  35857. silent: true
  35858. }
  35859. );
  35860. /**
  35861. * @readOnly
  35862. */
  35863. this.group = new Group();
  35864. // FIXME Not use a seperate text group?
  35865. var dumbGroup = new Group({
  35866. position: opt.position.slice(),
  35867. rotation: opt.rotation
  35868. });
  35869. // this.group.add(dumbGroup);
  35870. // this._dumbGroup = dumbGroup;
  35871. dumbGroup.updateTransform();
  35872. this._transform = dumbGroup.transform;
  35873. this._dumbGroup = dumbGroup;
  35874. };
  35875. AxisBuilder.prototype = {
  35876. constructor: AxisBuilder,
  35877. hasBuilder: function (name) {
  35878. return !!builders[name];
  35879. },
  35880. add: function (name) {
  35881. builders[name].call(this);
  35882. },
  35883. getGroup: function () {
  35884. return this.group;
  35885. }
  35886. };
  35887. var builders = {
  35888. /**
  35889. * @private
  35890. */
  35891. axisLine: function () {
  35892. var opt = this.opt;
  35893. var axisModel = this.axisModel;
  35894. if (!axisModel.get('axisLine.show')) {
  35895. return;
  35896. }
  35897. var extent = this.axisModel.axis.getExtent();
  35898. var matrix = this._transform;
  35899. var pt1 = [extent[0], 0];
  35900. var pt2 = [extent[1], 0];
  35901. if (matrix) {
  35902. applyTransform(pt1, pt1, matrix);
  35903. applyTransform(pt2, pt2, matrix);
  35904. }
  35905. var lineStyle = extend(
  35906. {
  35907. lineCap: 'round'
  35908. },
  35909. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  35910. );
  35911. this.group.add(new Line({
  35912. // Id for animation
  35913. anid: 'line',
  35914. subPixelOptimize: true,
  35915. shape: {
  35916. x1: pt1[0],
  35917. y1: pt1[1],
  35918. x2: pt2[0],
  35919. y2: pt2[1]
  35920. },
  35921. style: lineStyle,
  35922. strokeContainThreshold: opt.strokeContainThreshold || 5,
  35923. silent: true,
  35924. z2: 1
  35925. }));
  35926. var arrows = axisModel.get('axisLine.symbol');
  35927. var arrowSize = axisModel.get('axisLine.symbolSize');
  35928. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  35929. if (typeof arrowOffset === 'number') {
  35930. arrowOffset = [arrowOffset, arrowOffset];
  35931. }
  35932. if (arrows != null) {
  35933. if (typeof arrows === 'string') {
  35934. // Use the same arrow for start and end point
  35935. arrows = [arrows, arrows];
  35936. }
  35937. if (typeof arrowSize === 'string'
  35938. || typeof arrowSize === 'number'
  35939. ) {
  35940. // Use the same size for width and height
  35941. arrowSize = [arrowSize, arrowSize];
  35942. }
  35943. var symbolWidth = arrowSize[0];
  35944. var symbolHeight = arrowSize[1];
  35945. each$1([{
  35946. rotate: opt.rotation + Math.PI / 2,
  35947. offset: arrowOffset[0],
  35948. r: 0
  35949. }, {
  35950. rotate: opt.rotation - Math.PI / 2,
  35951. offset: arrowOffset[1],
  35952. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  35953. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  35954. }], function (point, index) {
  35955. if (arrows[index] !== 'none' && arrows[index] != null) {
  35956. var symbol = createSymbol(
  35957. arrows[index],
  35958. -symbolWidth / 2,
  35959. -symbolHeight / 2,
  35960. symbolWidth,
  35961. symbolHeight,
  35962. lineStyle.stroke,
  35963. true
  35964. );
  35965. // Calculate arrow position with offset
  35966. var r = point.r + point.offset;
  35967. var pos = [
  35968. pt1[0] + r * Math.cos(opt.rotation),
  35969. pt1[1] - r * Math.sin(opt.rotation)
  35970. ];
  35971. symbol.attr({
  35972. rotation: point.rotate,
  35973. position: pos,
  35974. silent: true,
  35975. z2: 11
  35976. });
  35977. this.group.add(symbol);
  35978. }
  35979. }, this);
  35980. }
  35981. },
  35982. /**
  35983. * @private
  35984. */
  35985. axisTickLabel: function () {
  35986. var axisModel = this.axisModel;
  35987. var opt = this.opt;
  35988. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  35989. var labelEls = buildAxisLabel(this, axisModel, opt);
  35990. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  35991. buildAxisMinorTicks(this, axisModel, opt);
  35992. },
  35993. /**
  35994. * @private
  35995. */
  35996. axisName: function () {
  35997. var opt = this.opt;
  35998. var axisModel = this.axisModel;
  35999. var name = retrieve(opt.axisName, axisModel.get('name'));
  36000. if (!name) {
  36001. return;
  36002. }
  36003. var nameLocation = axisModel.get('nameLocation');
  36004. var nameDirection = opt.nameDirection;
  36005. var textStyleModel = axisModel.getModel('nameTextStyle');
  36006. var gap = axisModel.get('nameGap') || 0;
  36007. var extent = this.axisModel.axis.getExtent();
  36008. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  36009. var pos = [
  36010. nameLocation === 'start'
  36011. ? extent[0] - gapSignal * gap
  36012. : nameLocation === 'end'
  36013. ? extent[1] + gapSignal * gap
  36014. : (extent[0] + extent[1]) / 2, // 'middle'
  36015. // Reuse labelOffset.
  36016. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  36017. ];
  36018. var labelLayout;
  36019. var nameRotation = axisModel.get('nameRotate');
  36020. if (nameRotation != null) {
  36021. nameRotation = nameRotation * PI$2 / 180; // To radian.
  36022. }
  36023. var axisNameAvailableWidth;
  36024. if (isNameLocationCenter(nameLocation)) {
  36025. labelLayout = innerTextLayout(
  36026. opt.rotation,
  36027. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  36028. nameDirection
  36029. );
  36030. }
  36031. else {
  36032. labelLayout = endTextLayout(
  36033. opt, nameLocation, nameRotation || 0, extent
  36034. );
  36035. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  36036. if (axisNameAvailableWidth != null) {
  36037. axisNameAvailableWidth = Math.abs(
  36038. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  36039. );
  36040. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  36041. }
  36042. }
  36043. var textFont = textStyleModel.getFont();
  36044. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  36045. var ellipsis = truncateOpt.ellipsis;
  36046. var maxWidth = retrieve(
  36047. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  36048. );
  36049. // FIXME
  36050. // truncate rich text? (consider performance)
  36051. var truncatedText = (ellipsis != null && maxWidth != null)
  36052. ? truncateText$1(
  36053. name, maxWidth, textFont, ellipsis,
  36054. {minChar: 2, placeholder: truncateOpt.placeholder}
  36055. )
  36056. : name;
  36057. var tooltipOpt = axisModel.get('tooltip', true);
  36058. var mainType = axisModel.mainType;
  36059. var formatterParams = {
  36060. componentType: mainType,
  36061. name: name,
  36062. $vars: ['name']
  36063. };
  36064. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  36065. var textEl = new Text({
  36066. // Id for animation
  36067. anid: 'name',
  36068. __fullText: name,
  36069. __truncatedText: truncatedText,
  36070. position: pos,
  36071. rotation: labelLayout.rotation,
  36072. silent: isLabelSilent(axisModel),
  36073. z2: 1,
  36074. tooltip: (tooltipOpt && tooltipOpt.show)
  36075. ? extend({
  36076. content: name,
  36077. formatter: function () {
  36078. return name;
  36079. },
  36080. formatterParams: formatterParams
  36081. }, tooltipOpt)
  36082. : null
  36083. });
  36084. setTextStyle(textEl.style, textStyleModel, {
  36085. text: truncatedText,
  36086. textFont: textFont,
  36087. textFill: textStyleModel.getTextColor()
  36088. || axisModel.get('axisLine.lineStyle.color'),
  36089. textAlign: textStyleModel.get('align')
  36090. || labelLayout.textAlign,
  36091. textVerticalAlign: textStyleModel.get('verticalAlign')
  36092. || labelLayout.textVerticalAlign
  36093. });
  36094. if (axisModel.get('triggerEvent')) {
  36095. textEl.eventData = makeAxisEventDataBase(axisModel);
  36096. textEl.eventData.targetType = 'axisName';
  36097. textEl.eventData.name = name;
  36098. }
  36099. // FIXME
  36100. this._dumbGroup.add(textEl);
  36101. textEl.updateTransform();
  36102. this.group.add(textEl);
  36103. textEl.decomposeTransform();
  36104. }
  36105. };
  36106. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  36107. var eventData = {
  36108. componentType: axisModel.mainType,
  36109. componentIndex: axisModel.componentIndex
  36110. };
  36111. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  36112. return eventData;
  36113. };
  36114. /**
  36115. * @public
  36116. * @static
  36117. * @param {Object} opt
  36118. * @param {number} axisRotation in radian
  36119. * @param {number} textRotation in radian
  36120. * @param {number} direction
  36121. * @return {Object} {
  36122. * rotation, // according to axis
  36123. * textAlign,
  36124. * textVerticalAlign
  36125. * }
  36126. */
  36127. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  36128. var rotationDiff = remRadian(textRotation - axisRotation);
  36129. var textAlign;
  36130. var textVerticalAlign;
  36131. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  36132. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  36133. textAlign = 'center';
  36134. }
  36135. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  36136. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  36137. textAlign = 'center';
  36138. }
  36139. else {
  36140. textVerticalAlign = 'middle';
  36141. if (rotationDiff > 0 && rotationDiff < PI$2) {
  36142. textAlign = direction > 0 ? 'right' : 'left';
  36143. }
  36144. else {
  36145. textAlign = direction > 0 ? 'left' : 'right';
  36146. }
  36147. }
  36148. return {
  36149. rotation: rotationDiff,
  36150. textAlign: textAlign,
  36151. textVerticalAlign: textVerticalAlign
  36152. };
  36153. };
  36154. function endTextLayout(opt, textPosition, textRotate, extent) {
  36155. var rotationDiff = remRadian(textRotate - opt.rotation);
  36156. var textAlign;
  36157. var textVerticalAlign;
  36158. var inverse = extent[0] > extent[1];
  36159. var onLeft = (textPosition === 'start' && !inverse)
  36160. || (textPosition !== 'start' && inverse);
  36161. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  36162. textVerticalAlign = onLeft ? 'bottom' : 'top';
  36163. textAlign = 'center';
  36164. }
  36165. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  36166. textVerticalAlign = onLeft ? 'top' : 'bottom';
  36167. textAlign = 'center';
  36168. }
  36169. else {
  36170. textVerticalAlign = 'middle';
  36171. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  36172. textAlign = onLeft ? 'left' : 'right';
  36173. }
  36174. else {
  36175. textAlign = onLeft ? 'right' : 'left';
  36176. }
  36177. }
  36178. return {
  36179. rotation: rotationDiff,
  36180. textAlign: textAlign,
  36181. textVerticalAlign: textVerticalAlign
  36182. };
  36183. }
  36184. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  36185. var tooltipOpt = axisModel.get('tooltip');
  36186. return axisModel.get('silent')
  36187. // Consider mouse cursor, add these restrictions.
  36188. || !(
  36189. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  36190. );
  36191. };
  36192. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  36193. if (shouldShowAllLabels(axisModel.axis)) {
  36194. return;
  36195. }
  36196. // If min or max are user set, we need to check
  36197. // If the tick on min(max) are overlap on their neighbour tick
  36198. // If they are overlapped, we need to hide the min(max) tick label
  36199. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  36200. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  36201. // FIXME
  36202. // Have not consider onBand yet, where tick els is more than label els.
  36203. labelEls = labelEls || [];
  36204. tickEls = tickEls || [];
  36205. var firstLabel = labelEls[0];
  36206. var nextLabel = labelEls[1];
  36207. var lastLabel = labelEls[labelEls.length - 1];
  36208. var prevLabel = labelEls[labelEls.length - 2];
  36209. var firstTick = tickEls[0];
  36210. var nextTick = tickEls[1];
  36211. var lastTick = tickEls[tickEls.length - 1];
  36212. var prevTick = tickEls[tickEls.length - 2];
  36213. if (showMinLabel === false) {
  36214. ignoreEl(firstLabel);
  36215. ignoreEl(firstTick);
  36216. }
  36217. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  36218. if (showMinLabel) {
  36219. ignoreEl(nextLabel);
  36220. ignoreEl(nextTick);
  36221. }
  36222. else {
  36223. ignoreEl(firstLabel);
  36224. ignoreEl(firstTick);
  36225. }
  36226. }
  36227. if (showMaxLabel === false) {
  36228. ignoreEl(lastLabel);
  36229. ignoreEl(lastTick);
  36230. }
  36231. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  36232. if (showMaxLabel) {
  36233. ignoreEl(prevLabel);
  36234. ignoreEl(prevTick);
  36235. }
  36236. else {
  36237. ignoreEl(lastLabel);
  36238. ignoreEl(lastTick);
  36239. }
  36240. }
  36241. }
  36242. function ignoreEl(el) {
  36243. el && (el.ignore = true);
  36244. }
  36245. function isTwoLabelOverlapped(current, next, labelLayout) {
  36246. // current and next has the same rotation.
  36247. var firstRect = current && current.getBoundingRect().clone();
  36248. var nextRect = next && next.getBoundingRect().clone();
  36249. if (!firstRect || !nextRect) {
  36250. return;
  36251. }
  36252. // When checking intersect of two rotated labels, we use mRotationBack
  36253. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  36254. var mRotationBack = identity([]);
  36255. rotate(mRotationBack, mRotationBack, -current.rotation);
  36256. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  36257. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  36258. return firstRect.intersect(nextRect);
  36259. }
  36260. function isNameLocationCenter(nameLocation) {
  36261. return nameLocation === 'middle' || nameLocation === 'center';
  36262. }
  36263. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  36264. var tickEls = [];
  36265. var pt1 = [];
  36266. var pt2 = [];
  36267. for (var i = 0; i < ticksCoords.length; i++) {
  36268. var tickCoord = ticksCoords[i].coord;
  36269. pt1[0] = tickCoord;
  36270. pt1[1] = 0;
  36271. pt2[0] = tickCoord;
  36272. pt2[1] = tickEndCoord;
  36273. if (tickTransform) {
  36274. applyTransform(pt1, pt1, tickTransform);
  36275. applyTransform(pt2, pt2, tickTransform);
  36276. }
  36277. // Tick line, Not use group transform to have better line draw
  36278. var tickEl = new Line({
  36279. // Id for animation
  36280. anid: aniid + '_' + ticksCoords[i].tickValue,
  36281. subPixelOptimize: true,
  36282. shape: {
  36283. x1: pt1[0],
  36284. y1: pt1[1],
  36285. x2: pt2[0],
  36286. y2: pt2[1]
  36287. },
  36288. style: tickLineStyle,
  36289. z2: 2,
  36290. silent: true
  36291. });
  36292. tickEls.push(tickEl);
  36293. }
  36294. return tickEls;
  36295. }
  36296. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  36297. var axis = axisModel.axis;
  36298. var tickModel = axisModel.getModel('axisTick');
  36299. if (!tickModel.get('show') || axis.scale.isBlank()) {
  36300. return;
  36301. }
  36302. var lineStyleModel = tickModel.getModel('lineStyle');
  36303. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  36304. var ticksCoords = axis.getTicksCoords();
  36305. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  36306. lineStyleModel.getLineStyle(),
  36307. {
  36308. stroke: axisModel.get('axisLine.lineStyle.color')
  36309. }
  36310. ), 'ticks');
  36311. for (var i = 0; i < ticksEls.length; i++) {
  36312. axisBuilder.group.add(ticksEls[i]);
  36313. }
  36314. return ticksEls;
  36315. }
  36316. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  36317. var axis = axisModel.axis;
  36318. var minorTickModel = axisModel.getModel('minorTick');
  36319. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  36320. return;
  36321. }
  36322. var minorTicksCoords = axis.getMinorTicksCoords();
  36323. if (!minorTicksCoords.length) {
  36324. return;
  36325. }
  36326. var lineStyleModel = minorTickModel.getModel('lineStyle');
  36327. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  36328. var minorTickLineStyle = defaults(
  36329. lineStyleModel.getLineStyle(),
  36330. defaults(
  36331. axisModel.getModel('axisTick').getLineStyle(),
  36332. {
  36333. stroke: axisModel.get('axisLine.lineStyle.color')
  36334. }
  36335. )
  36336. );
  36337. for (var i = 0; i < minorTicksCoords.length; i++) {
  36338. var minorTicksEls = createTicks(
  36339. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  36340. );
  36341. for (var k = 0; k < minorTicksEls.length; k++) {
  36342. axisBuilder.group.add(minorTicksEls[k]);
  36343. }
  36344. }
  36345. }
  36346. function buildAxisLabel(axisBuilder, axisModel, opt) {
  36347. var axis = axisModel.axis;
  36348. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  36349. if (!show || axis.scale.isBlank()) {
  36350. return;
  36351. }
  36352. var labelModel = axisModel.getModel('axisLabel');
  36353. var labelMargin = labelModel.get('margin');
  36354. var labels = axis.getViewLabels();
  36355. // Special label rotate.
  36356. var labelRotation = (
  36357. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  36358. ) * PI$2 / 180;
  36359. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  36360. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  36361. var labelEls = [];
  36362. var silent = isLabelSilent(axisModel);
  36363. var triggerEvent = axisModel.get('triggerEvent');
  36364. each$1(labels, function (labelItem, index) {
  36365. var tickValue = labelItem.tickValue;
  36366. var formattedLabel = labelItem.formattedLabel;
  36367. var rawLabel = labelItem.rawLabel;
  36368. var itemLabelModel = labelModel;
  36369. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  36370. itemLabelModel = new Model(
  36371. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  36372. );
  36373. }
  36374. var textColor = itemLabelModel.getTextColor()
  36375. || axisModel.get('axisLine.lineStyle.color');
  36376. var tickCoord = axis.dataToCoord(tickValue);
  36377. var pos = [
  36378. tickCoord,
  36379. opt.labelOffset + opt.labelDirection * labelMargin
  36380. ];
  36381. var textEl = new Text({
  36382. // Id for animation
  36383. anid: 'label_' + tickValue,
  36384. position: pos,
  36385. rotation: labelLayout.rotation,
  36386. silent: silent,
  36387. z2: 10
  36388. });
  36389. setTextStyle(textEl.style, itemLabelModel, {
  36390. text: formattedLabel,
  36391. textAlign: itemLabelModel.getShallow('align', true)
  36392. || labelLayout.textAlign,
  36393. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  36394. || itemLabelModel.getShallow('baseline', true)
  36395. || labelLayout.textVerticalAlign,
  36396. textFill: typeof textColor === 'function'
  36397. ? textColor(
  36398. // (1) In category axis with data zoom, tick is not the original
  36399. // index of axis.data. So tick should not be exposed to user
  36400. // in category axis.
  36401. // (2) Compatible with previous version, which always use formatted label as
  36402. // input. But in interval scale the formatted label is like '223,445', which
  36403. // maked user repalce ','. So we modify it to return original val but remain
  36404. // it as 'string' to avoid error in replacing.
  36405. axis.type === 'category'
  36406. ? rawLabel
  36407. : axis.type === 'value'
  36408. ? tickValue + ''
  36409. : tickValue,
  36410. index
  36411. )
  36412. : textColor
  36413. });
  36414. // Pack data for mouse event
  36415. if (triggerEvent) {
  36416. textEl.eventData = makeAxisEventDataBase(axisModel);
  36417. textEl.eventData.targetType = 'axisLabel';
  36418. textEl.eventData.value = rawLabel;
  36419. }
  36420. // FIXME
  36421. axisBuilder._dumbGroup.add(textEl);
  36422. textEl.updateTransform();
  36423. labelEls.push(textEl);
  36424. axisBuilder.group.add(textEl);
  36425. textEl.decomposeTransform();
  36426. });
  36427. return labelEls;
  36428. }
  36429. /*
  36430. * Licensed to the Apache Software Foundation (ASF) under one
  36431. * or more contributor license agreements. See the NOTICE file
  36432. * distributed with this work for additional information
  36433. * regarding copyright ownership. The ASF licenses this file
  36434. * to you under the Apache License, Version 2.0 (the
  36435. * "License"); you may not use this file except in compliance
  36436. * with the License. You may obtain a copy of the License at
  36437. *
  36438. * http://www.apache.org/licenses/LICENSE-2.0
  36439. *
  36440. * Unless required by applicable law or agreed to in writing,
  36441. * software distributed under the License is distributed on an
  36442. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36443. * KIND, either express or implied. See the License for the
  36444. * specific language governing permissions and limitations
  36445. * under the License.
  36446. */
  36447. var each$6 = each$1;
  36448. var curry$1 = curry;
  36449. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  36450. // allAxesInfo should be updated when setOption performed.
  36451. function collect(ecModel, api) {
  36452. var result = {
  36453. /**
  36454. * key: makeKey(axis.model)
  36455. * value: {
  36456. * axis,
  36457. * coordSys,
  36458. * axisPointerModel,
  36459. * triggerTooltip,
  36460. * involveSeries,
  36461. * snap,
  36462. * seriesModels,
  36463. * seriesDataCount
  36464. * }
  36465. */
  36466. axesInfo: {},
  36467. seriesInvolved: false,
  36468. /**
  36469. * key: makeKey(coordSys.model)
  36470. * value: Object: key makeKey(axis.model), value: axisInfo
  36471. */
  36472. coordSysAxesInfo: {},
  36473. coordSysMap: {}
  36474. };
  36475. collectAxesInfo(result, ecModel, api);
  36476. // Check seriesInvolved for performance, in case too many series in some chart.
  36477. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  36478. return result;
  36479. }
  36480. function collectAxesInfo(result, ecModel, api) {
  36481. var globalTooltipModel = ecModel.getComponent('tooltip');
  36482. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  36483. // links can only be set on global.
  36484. var linksOption = globalAxisPointerModel.get('link', true) || [];
  36485. var linkGroups = [];
  36486. // Collect axes info.
  36487. each$6(api.getCoordinateSystems(), function (coordSys) {
  36488. // Some coordinate system do not support axes, like geo.
  36489. if (!coordSys.axisPointerEnabled) {
  36490. return;
  36491. }
  36492. var coordSysKey = makeKey(coordSys.model);
  36493. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  36494. result.coordSysMap[coordSysKey] = coordSys;
  36495. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  36496. // for user. So we enable seting tooltip on coordSys model.
  36497. var coordSysModel = coordSys.model;
  36498. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  36499. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  36500. // If axis tooltip used, choose tooltip axis for each coordSys.
  36501. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  36502. if (coordSys.getTooltipAxes
  36503. && globalTooltipModel
  36504. // If tooltip.showContent is set as false, tooltip will not
  36505. // show but axisPointer will show as normal.
  36506. && baseTooltipModel.get('show')
  36507. ) {
  36508. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  36509. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  36510. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  36511. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  36512. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  36513. if (triggerAxis || cross) {
  36514. each$6(tooltipAxes.baseAxes, curry$1(
  36515. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  36516. ));
  36517. }
  36518. if (cross) {
  36519. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  36520. }
  36521. }
  36522. // fromTooltip: true | false | 'cross'
  36523. // triggerTooltip: true | false | null
  36524. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  36525. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  36526. var axisPointerShow = axisPointerModel.get('show');
  36527. if (!axisPointerShow || (
  36528. axisPointerShow === 'auto'
  36529. && !fromTooltip
  36530. && !isHandleTrigger(axisPointerModel)
  36531. )) {
  36532. return;
  36533. }
  36534. if (triggerTooltip == null) {
  36535. triggerTooltip = axisPointerModel.get('triggerTooltip');
  36536. }
  36537. axisPointerModel = fromTooltip
  36538. ? makeAxisPointerModel(
  36539. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  36540. fromTooltip, triggerTooltip
  36541. )
  36542. : axisPointerModel;
  36543. var snap = axisPointerModel.get('snap');
  36544. var key = makeKey(axis.model);
  36545. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  36546. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  36547. var axisInfo = result.axesInfo[key] = {
  36548. key: key,
  36549. axis: axis,
  36550. coordSys: coordSys,
  36551. axisPointerModel: axisPointerModel,
  36552. triggerTooltip: triggerTooltip,
  36553. involveSeries: involveSeries,
  36554. snap: snap,
  36555. useHandle: isHandleTrigger(axisPointerModel),
  36556. seriesModels: []
  36557. };
  36558. axesInfoInCoordSys[key] = axisInfo;
  36559. result.seriesInvolved |= involveSeries;
  36560. var groupIndex = getLinkGroupIndex(linksOption, axis);
  36561. if (groupIndex != null) {
  36562. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  36563. linkGroup.axesInfo[key] = axisInfo;
  36564. linkGroup.mapper = linksOption[groupIndex].mapper;
  36565. axisInfo.linkGroup = linkGroup;
  36566. }
  36567. }
  36568. });
  36569. }
  36570. function makeAxisPointerModel(
  36571. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  36572. ) {
  36573. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  36574. var volatileOption = {};
  36575. each$6(
  36576. [
  36577. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  36578. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  36579. ],
  36580. function (field) {
  36581. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  36582. }
  36583. );
  36584. // category axis do not auto snap, otherwise some tick that do not
  36585. // has value can not be hovered. value/time/log axis default snap if
  36586. // triggered from tooltip and trigger tooltip.
  36587. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  36588. // Compatibel with previous behavior, tooltip axis do not show label by default.
  36589. // Only these properties can be overrided from tooltip to axisPointer.
  36590. if (tooltipAxisPointerModel.get('type') === 'cross') {
  36591. volatileOption.type = 'line';
  36592. }
  36593. var labelOption = volatileOption.label || (volatileOption.label = {});
  36594. // Follow the convention, do not show label when triggered by tooltip by default.
  36595. labelOption.show == null && (labelOption.show = false);
  36596. if (fromTooltip === 'cross') {
  36597. // When 'cross', both axes show labels.
  36598. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  36599. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  36600. // If triggerTooltip, this is a base axis, which should better not use cross style
  36601. // (cross style is dashed by default)
  36602. if (!triggerTooltip) {
  36603. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  36604. crossStyle && defaults(labelOption, crossStyle.textStyle);
  36605. }
  36606. }
  36607. return axis.model.getModel(
  36608. 'axisPointer',
  36609. new Model(volatileOption, globalAxisPointerModel, ecModel)
  36610. );
  36611. }
  36612. function collectSeriesInfo(result, ecModel) {
  36613. // Prepare data for axis trigger
  36614. ecModel.eachSeries(function (seriesModel) {
  36615. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  36616. var coordSys = seriesModel.coordinateSystem;
  36617. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  36618. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  36619. if (!coordSys
  36620. || seriesTooltipTrigger === 'none'
  36621. || seriesTooltipTrigger === false
  36622. || seriesTooltipTrigger === 'item'
  36623. || seriesTooltipShow === false
  36624. || seriesModel.get('axisPointer.show', true) === false
  36625. ) {
  36626. return;
  36627. }
  36628. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  36629. var axis = axisInfo.axis;
  36630. if (coordSys.getAxis(axis.dim) === axis) {
  36631. axisInfo.seriesModels.push(seriesModel);
  36632. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  36633. axisInfo.seriesDataCount += seriesModel.getData().count();
  36634. }
  36635. });
  36636. }, this);
  36637. }
  36638. /**
  36639. * For example:
  36640. * {
  36641. * axisPointer: {
  36642. * links: [{
  36643. * xAxisIndex: [2, 4],
  36644. * yAxisIndex: 'all'
  36645. * }, {
  36646. * xAxisId: ['a5', 'a7'],
  36647. * xAxisName: 'xxx'
  36648. * }]
  36649. * }
  36650. * }
  36651. */
  36652. function getLinkGroupIndex(linksOption, axis) {
  36653. var axisModel = axis.model;
  36654. var dim = axis.dim;
  36655. for (var i = 0; i < linksOption.length; i++) {
  36656. var linkOption = linksOption[i] || {};
  36657. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  36658. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  36659. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  36660. ) {
  36661. return i;
  36662. }
  36663. }
  36664. }
  36665. function checkPropInLink(linkPropValue, axisPropValue) {
  36666. return linkPropValue === 'all'
  36667. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  36668. || linkPropValue === axisPropValue;
  36669. }
  36670. function fixValue(axisModel) {
  36671. var axisInfo = getAxisInfo(axisModel);
  36672. if (!axisInfo) {
  36673. return;
  36674. }
  36675. var axisPointerModel = axisInfo.axisPointerModel;
  36676. var scale = axisInfo.axis.scale;
  36677. var option = axisPointerModel.option;
  36678. var status = axisPointerModel.get('status');
  36679. var value = axisPointerModel.get('value');
  36680. // Parse init value for category and time axis.
  36681. if (value != null) {
  36682. value = scale.parse(value);
  36683. }
  36684. var useHandle = isHandleTrigger(axisPointerModel);
  36685. // If `handle` used, `axisPointer` will always be displayed, so value
  36686. // and status should be initialized.
  36687. if (status == null) {
  36688. option.status = useHandle ? 'show' : 'hide';
  36689. }
  36690. var extent = scale.getExtent().slice();
  36691. extent[0] > extent[1] && extent.reverse();
  36692. if (// Pick a value on axis when initializing.
  36693. value == null
  36694. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  36695. // where we should re-pick a value to keep `handle` displaying normally.
  36696. || value > extent[1]
  36697. ) {
  36698. // Make handle displayed on the end of the axis when init, which looks better.
  36699. value = extent[1];
  36700. }
  36701. if (value < extent[0]) {
  36702. value = extent[0];
  36703. }
  36704. option.value = value;
  36705. if (useHandle) {
  36706. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  36707. }
  36708. }
  36709. function getAxisInfo(axisModel) {
  36710. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  36711. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  36712. }
  36713. function getAxisPointerModel(axisModel) {
  36714. var axisInfo = getAxisInfo(axisModel);
  36715. return axisInfo && axisInfo.axisPointerModel;
  36716. }
  36717. function isHandleTrigger(axisPointerModel) {
  36718. return !!axisPointerModel.get('handle.show');
  36719. }
  36720. /**
  36721. * @param {module:echarts/model/Model} model
  36722. * @return {string} unique key
  36723. */
  36724. function makeKey(model) {
  36725. return model.type + '||' + model.id;
  36726. }
  36727. /*
  36728. * Licensed to the Apache Software Foundation (ASF) under one
  36729. * or more contributor license agreements. See the NOTICE file
  36730. * distributed with this work for additional information
  36731. * regarding copyright ownership. The ASF licenses this file
  36732. * to you under the Apache License, Version 2.0 (the
  36733. * "License"); you may not use this file except in compliance
  36734. * with the License. You may obtain a copy of the License at
  36735. *
  36736. * http://www.apache.org/licenses/LICENSE-2.0
  36737. *
  36738. * Unless required by applicable law or agreed to in writing,
  36739. * software distributed under the License is distributed on an
  36740. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36741. * KIND, either express or implied. See the License for the
  36742. * specific language governing permissions and limitations
  36743. * under the License.
  36744. */
  36745. /**
  36746. * Base class of AxisView.
  36747. */
  36748. var AxisView = extendComponentView({
  36749. type: 'axis',
  36750. /**
  36751. * @private
  36752. */
  36753. _axisPointer: null,
  36754. /**
  36755. * @protected
  36756. * @type {string}
  36757. */
  36758. axisPointerClass: null,
  36759. /**
  36760. * @override
  36761. */
  36762. render: function (axisModel, ecModel, api, payload) {
  36763. // FIXME
  36764. // This process should proformed after coordinate systems updated
  36765. // (axis scale updated), and should be performed each time update.
  36766. // So put it here temporarily, although it is not appropriate to
  36767. // put a model-writing procedure in `view`.
  36768. this.axisPointerClass && fixValue(axisModel);
  36769. AxisView.superApply(this, 'render', arguments);
  36770. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  36771. },
  36772. /**
  36773. * Action handler.
  36774. * @public
  36775. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  36776. * @param {module:echarts/model/Global} ecModel
  36777. * @param {module:echarts/ExtensionAPI} api
  36778. * @param {Object} payload
  36779. */
  36780. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  36781. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  36782. },
  36783. /**
  36784. * @override
  36785. */
  36786. remove: function (ecModel, api) {
  36787. var axisPointer = this._axisPointer;
  36788. axisPointer && axisPointer.remove(api);
  36789. AxisView.superApply(this, 'remove', arguments);
  36790. },
  36791. /**
  36792. * @override
  36793. */
  36794. dispose: function (ecModel, api) {
  36795. disposeAxisPointer(this, api);
  36796. AxisView.superApply(this, 'dispose', arguments);
  36797. }
  36798. });
  36799. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  36800. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  36801. if (!Clazz) {
  36802. return;
  36803. }
  36804. var axisPointerModel = getAxisPointerModel(axisModel);
  36805. axisPointerModel
  36806. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  36807. .render(axisModel, axisPointerModel, api, forceRender)
  36808. : disposeAxisPointer(axisView, api);
  36809. }
  36810. function disposeAxisPointer(axisView, ecModel, api) {
  36811. var axisPointer = axisView._axisPointer;
  36812. axisPointer && axisPointer.dispose(ecModel, api);
  36813. axisView._axisPointer = null;
  36814. }
  36815. var axisPointerClazz = [];
  36816. AxisView.registerAxisPointerClass = function (type, clazz) {
  36817. if (__DEV__) {
  36818. if (axisPointerClazz[type]) {
  36819. throw new Error('axisPointer ' + type + ' exists');
  36820. }
  36821. }
  36822. axisPointerClazz[type] = clazz;
  36823. };
  36824. AxisView.getAxisPointerClass = function (type) {
  36825. return type && axisPointerClazz[type];
  36826. };
  36827. /*
  36828. * Licensed to the Apache Software Foundation (ASF) under one
  36829. * or more contributor license agreements. See the NOTICE file
  36830. * distributed with this work for additional information
  36831. * regarding copyright ownership. The ASF licenses this file
  36832. * to you under the Apache License, Version 2.0 (the
  36833. * "License"); you may not use this file except in compliance
  36834. * with the License. You may obtain a copy of the License at
  36835. *
  36836. * http://www.apache.org/licenses/LICENSE-2.0
  36837. *
  36838. * Unless required by applicable law or agreed to in writing,
  36839. * software distributed under the License is distributed on an
  36840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36841. * KIND, either express or implied. See the License for the
  36842. * specific language governing permissions and limitations
  36843. * under the License.
  36844. */
  36845. /**
  36846. * Can only be called after coordinate system creation stage.
  36847. * (Can be called before coordinate system update stage).
  36848. *
  36849. * @param {Object} opt {labelInside}
  36850. * @return {Object} {
  36851. * position, rotation, labelDirection, labelOffset,
  36852. * tickDirection, labelRotate, z2
  36853. * }
  36854. */
  36855. function layout$1(gridModel, axisModel, opt) {
  36856. opt = opt || {};
  36857. var grid = gridModel.coordinateSystem;
  36858. var axis = axisModel.axis;
  36859. var layout = {};
  36860. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  36861. var rawAxisPosition = axis.position;
  36862. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  36863. var axisDim = axis.dim;
  36864. var rect = grid.getRect();
  36865. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  36866. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  36867. var axisOffset = axisModel.get('offset') || 0;
  36868. var posBound = axisDim === 'x'
  36869. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  36870. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  36871. if (otherAxisOnZeroOf) {
  36872. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  36873. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  36874. }
  36875. // Axis position
  36876. layout.position = [
  36877. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  36878. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  36879. ];
  36880. // Axis rotation
  36881. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  36882. // Tick and label direction, x y is axisDim
  36883. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  36884. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  36885. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  36886. if (axisModel.get('axisTick.inside')) {
  36887. layout.tickDirection = -layout.tickDirection;
  36888. }
  36889. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  36890. layout.labelDirection = -layout.labelDirection;
  36891. }
  36892. // Special label rotation
  36893. var labelRotate = axisModel.get('axisLabel.rotate');
  36894. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  36895. // Over splitLine and splitArea
  36896. layout.z2 = 1;
  36897. return layout;
  36898. }
  36899. /*
  36900. * Licensed to the Apache Software Foundation (ASF) under one
  36901. * or more contributor license agreements. See the NOTICE file
  36902. * distributed with this work for additional information
  36903. * regarding copyright ownership. The ASF licenses this file
  36904. * to you under the Apache License, Version 2.0 (the
  36905. * "License"); you may not use this file except in compliance
  36906. * with the License. You may obtain a copy of the License at
  36907. *
  36908. * http://www.apache.org/licenses/LICENSE-2.0
  36909. *
  36910. * Unless required by applicable law or agreed to in writing,
  36911. * software distributed under the License is distributed on an
  36912. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36913. * KIND, either express or implied. See the License for the
  36914. * specific language governing permissions and limitations
  36915. * under the License.
  36916. */
  36917. var axisBuilderAttrs = [
  36918. 'axisLine', 'axisTickLabel', 'axisName'
  36919. ];
  36920. var selfBuilderAttrs = [
  36921. 'splitArea', 'splitLine', 'minorSplitLine'
  36922. ];
  36923. var CartesianAxisView = AxisView.extend({
  36924. type: 'cartesianAxis',
  36925. axisPointerClass: 'CartesianAxisPointer',
  36926. /**
  36927. * @override
  36928. */
  36929. render: function (axisModel, ecModel, api, payload) {
  36930. this.group.removeAll();
  36931. var oldAxisGroup = this._axisGroup;
  36932. this._axisGroup = new Group();
  36933. this.group.add(this._axisGroup);
  36934. if (!axisModel.get('show')) {
  36935. return;
  36936. }
  36937. var gridModel = axisModel.getCoordSysModel();
  36938. var layout = layout$1(gridModel, axisModel);
  36939. var axisBuilder = new AxisBuilder(axisModel, layout);
  36940. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  36941. this._axisGroup.add(axisBuilder.getGroup());
  36942. each$1(selfBuilderAttrs, function (name) {
  36943. if (axisModel.get(name + '.show')) {
  36944. this['_' + name](axisModel, gridModel);
  36945. }
  36946. }, this);
  36947. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  36948. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  36949. },
  36950. remove: function () {
  36951. this._splitAreaColors = null;
  36952. },
  36953. /**
  36954. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  36955. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  36956. * @private
  36957. */
  36958. _splitLine: function (axisModel, gridModel) {
  36959. var axis = axisModel.axis;
  36960. if (axis.scale.isBlank()) {
  36961. return;
  36962. }
  36963. var splitLineModel = axisModel.getModel('splitLine');
  36964. var lineStyleModel = splitLineModel.getModel('lineStyle');
  36965. var lineColors = lineStyleModel.get('color');
  36966. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  36967. var gridRect = gridModel.coordinateSystem.getRect();
  36968. var isHorizontal = axis.isHorizontal();
  36969. var lineCount = 0;
  36970. var ticksCoords = axis.getTicksCoords({
  36971. tickModel: splitLineModel
  36972. });
  36973. var p1 = [];
  36974. var p2 = [];
  36975. var lineStyle = lineStyleModel.getLineStyle();
  36976. for (var i = 0; i < ticksCoords.length; i++) {
  36977. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  36978. if (isHorizontal) {
  36979. p1[0] = tickCoord;
  36980. p1[1] = gridRect.y;
  36981. p2[0] = tickCoord;
  36982. p2[1] = gridRect.y + gridRect.height;
  36983. }
  36984. else {
  36985. p1[0] = gridRect.x;
  36986. p1[1] = tickCoord;
  36987. p2[0] = gridRect.x + gridRect.width;
  36988. p2[1] = tickCoord;
  36989. }
  36990. var colorIndex = (lineCount++) % lineColors.length;
  36991. var tickValue = ticksCoords[i].tickValue;
  36992. this._axisGroup.add(new Line({
  36993. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  36994. subPixelOptimize: true,
  36995. shape: {
  36996. x1: p1[0],
  36997. y1: p1[1],
  36998. x2: p2[0],
  36999. y2: p2[1]
  37000. },
  37001. style: defaults({
  37002. stroke: lineColors[colorIndex]
  37003. }, lineStyle),
  37004. silent: true
  37005. }));
  37006. }
  37007. },
  37008. /**
  37009. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37010. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37011. * @private
  37012. */
  37013. _minorSplitLine: function (axisModel, gridModel) {
  37014. var axis = axisModel.axis;
  37015. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  37016. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  37017. var gridRect = gridModel.coordinateSystem.getRect();
  37018. var isHorizontal = axis.isHorizontal();
  37019. var minorTicksCoords = axis.getMinorTicksCoords();
  37020. if (!minorTicksCoords.length) {
  37021. return;
  37022. }
  37023. var p1 = [];
  37024. var p2 = [];
  37025. var lineStyle = lineStyleModel.getLineStyle();
  37026. for (var i = 0; i < minorTicksCoords.length; i++) {
  37027. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  37028. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  37029. if (isHorizontal) {
  37030. p1[0] = tickCoord;
  37031. p1[1] = gridRect.y;
  37032. p2[0] = tickCoord;
  37033. p2[1] = gridRect.y + gridRect.height;
  37034. }
  37035. else {
  37036. p1[0] = gridRect.x;
  37037. p1[1] = tickCoord;
  37038. p2[0] = gridRect.x + gridRect.width;
  37039. p2[1] = tickCoord;
  37040. }
  37041. this._axisGroup.add(new Line({
  37042. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  37043. subPixelOptimize: true,
  37044. shape: {
  37045. x1: p1[0],
  37046. y1: p1[1],
  37047. x2: p2[0],
  37048. y2: p2[1]
  37049. },
  37050. style: lineStyle,
  37051. silent: true
  37052. }));
  37053. }
  37054. }
  37055. },
  37056. /**
  37057. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37058. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37059. * @private
  37060. */
  37061. _splitArea: function (axisModel, gridModel) {
  37062. var axis = axisModel.axis;
  37063. if (axis.scale.isBlank()) {
  37064. return;
  37065. }
  37066. var splitAreaModel = axisModel.getModel('splitArea');
  37067. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  37068. var areaColors = areaStyleModel.get('color');
  37069. var gridRect = gridModel.coordinateSystem.getRect();
  37070. var ticksCoords = axis.getTicksCoords({
  37071. tickModel: splitAreaModel,
  37072. clamp: true
  37073. });
  37074. if (!ticksCoords.length) {
  37075. return;
  37076. }
  37077. // For Making appropriate splitArea animation, the color and anid
  37078. // should be corresponding to previous one if possible.
  37079. var areaColorsLen = areaColors.length;
  37080. var lastSplitAreaColors = this._splitAreaColors;
  37081. var newSplitAreaColors = createHashMap();
  37082. var colorIndex = 0;
  37083. if (lastSplitAreaColors) {
  37084. for (var i = 0; i < ticksCoords.length; i++) {
  37085. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  37086. if (cIndex != null) {
  37087. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  37088. break;
  37089. }
  37090. }
  37091. }
  37092. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  37093. var areaStyle = areaStyleModel.getAreaStyle();
  37094. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  37095. for (var i = 1; i < ticksCoords.length; i++) {
  37096. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37097. var x;
  37098. var y;
  37099. var width;
  37100. var height;
  37101. if (axis.isHorizontal()) {
  37102. x = prev;
  37103. y = gridRect.y;
  37104. width = tickCoord - x;
  37105. height = gridRect.height;
  37106. prev = x + width;
  37107. }
  37108. else {
  37109. x = gridRect.x;
  37110. y = prev;
  37111. width = gridRect.width;
  37112. height = tickCoord - y;
  37113. prev = y + height;
  37114. }
  37115. var tickValue = ticksCoords[i - 1].tickValue;
  37116. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  37117. this._axisGroup.add(new Rect({
  37118. anid: tickValue != null ? 'area_' + tickValue : null,
  37119. shape: {
  37120. x: x,
  37121. y: y,
  37122. width: width,
  37123. height: height
  37124. },
  37125. style: defaults({
  37126. fill: areaColors[colorIndex]
  37127. }, areaStyle),
  37128. silent: true
  37129. }));
  37130. colorIndex = (colorIndex + 1) % areaColorsLen;
  37131. }
  37132. this._splitAreaColors = newSplitAreaColors;
  37133. }
  37134. });
  37135. CartesianAxisView.extend({
  37136. type: 'xAxis'
  37137. });
  37138. CartesianAxisView.extend({
  37139. type: 'yAxis'
  37140. });
  37141. /*
  37142. * Licensed to the Apache Software Foundation (ASF) under one
  37143. * or more contributor license agreements. See the NOTICE file
  37144. * distributed with this work for additional information
  37145. * regarding copyright ownership. The ASF licenses this file
  37146. * to you under the Apache License, Version 2.0 (the
  37147. * "License"); you may not use this file except in compliance
  37148. * with the License. You may obtain a copy of the License at
  37149. *
  37150. * http://www.apache.org/licenses/LICENSE-2.0
  37151. *
  37152. * Unless required by applicable law or agreed to in writing,
  37153. * software distributed under the License is distributed on an
  37154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37155. * KIND, either express or implied. See the License for the
  37156. * specific language governing permissions and limitations
  37157. * under the License.
  37158. */
  37159. /*
  37160. * Licensed to the Apache Software Foundation (ASF) under one
  37161. * or more contributor license agreements. See the NOTICE file
  37162. * distributed with this work for additional information
  37163. * regarding copyright ownership. The ASF licenses this file
  37164. * to you under the Apache License, Version 2.0 (the
  37165. * "License"); you may not use this file except in compliance
  37166. * with the License. You may obtain a copy of the License at
  37167. *
  37168. * http://www.apache.org/licenses/LICENSE-2.0
  37169. *
  37170. * Unless required by applicable law or agreed to in writing,
  37171. * software distributed under the License is distributed on an
  37172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37173. * KIND, either express or implied. See the License for the
  37174. * specific language governing permissions and limitations
  37175. * under the License.
  37176. */
  37177. // Grid view
  37178. extendComponentView({
  37179. type: 'grid',
  37180. render: function (gridModel, ecModel) {
  37181. this.group.removeAll();
  37182. if (gridModel.get('show')) {
  37183. this.group.add(new Rect({
  37184. shape: gridModel.coordinateSystem.getRect(),
  37185. style: defaults({
  37186. fill: gridModel.get('backgroundColor')
  37187. }, gridModel.getItemStyle()),
  37188. silent: true,
  37189. z2: -1
  37190. }));
  37191. }
  37192. }
  37193. });
  37194. registerPreprocessor(function (option) {
  37195. // Only create grid when need
  37196. if (option.xAxis && option.yAxis && !option.grid) {
  37197. option.grid = {};
  37198. }
  37199. });
  37200. /*
  37201. * Licensed to the Apache Software Foundation (ASF) under one
  37202. * or more contributor license agreements. See the NOTICE file
  37203. * distributed with this work for additional information
  37204. * regarding copyright ownership. The ASF licenses this file
  37205. * to you under the Apache License, Version 2.0 (the
  37206. * "License"); you may not use this file except in compliance
  37207. * with the License. You may obtain a copy of the License at
  37208. *
  37209. * http://www.apache.org/licenses/LICENSE-2.0
  37210. *
  37211. * Unless required by applicable law or agreed to in writing,
  37212. * software distributed under the License is distributed on an
  37213. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37214. * KIND, either express or implied. See the License for the
  37215. * specific language governing permissions and limitations
  37216. * under the License.
  37217. */
  37218. // In case developer forget to include grid component
  37219. registerVisual(visualSymbol('line', 'circle', 'line'));
  37220. registerLayout(pointsLayout('line'));
  37221. // Down sample after filter
  37222. registerProcessor(
  37223. PRIORITY.PROCESSOR.STATISTIC,
  37224. dataSample('line')
  37225. );
  37226. /*
  37227. * Licensed to the Apache Software Foundation (ASF) under one
  37228. * or more contributor license agreements. See the NOTICE file
  37229. * distributed with this work for additional information
  37230. * regarding copyright ownership. The ASF licenses this file
  37231. * to you under the Apache License, Version 2.0 (the
  37232. * "License"); you may not use this file except in compliance
  37233. * with the License. You may obtain a copy of the License at
  37234. *
  37235. * http://www.apache.org/licenses/LICENSE-2.0
  37236. *
  37237. * Unless required by applicable law or agreed to in writing,
  37238. * software distributed under the License is distributed on an
  37239. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37240. * KIND, either express or implied. See the License for the
  37241. * specific language governing permissions and limitations
  37242. * under the License.
  37243. */
  37244. var BaseBarSeries = SeriesModel.extend({
  37245. type: 'series.__base_bar__',
  37246. getInitialData: function (option, ecModel) {
  37247. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  37248. },
  37249. getMarkerPosition: function (value) {
  37250. var coordSys = this.coordinateSystem;
  37251. if (coordSys) {
  37252. // PENDING if clamp ?
  37253. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  37254. var data = this.getData();
  37255. var offset = data.getLayout('offset');
  37256. var size = data.getLayout('size');
  37257. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  37258. pt[offsetIndex] += offset + size / 2;
  37259. return pt;
  37260. }
  37261. return [NaN, NaN];
  37262. },
  37263. defaultOption: {
  37264. zlevel: 0, // 一级层叠
  37265. z: 2, // 二级层叠
  37266. coordinateSystem: 'cartesian2d',
  37267. legendHoverLink: true,
  37268. // stack: null
  37269. // Cartesian coordinate system
  37270. // xAxisIndex: 0,
  37271. // yAxisIndex: 0,
  37272. // 最小高度改为0
  37273. barMinHeight: 0,
  37274. // 最小角度为0,仅对极坐标系下的柱状图有效
  37275. barMinAngle: 0,
  37276. // cursor: null,
  37277. large: false,
  37278. largeThreshold: 400,
  37279. progressive: 3e3,
  37280. progressiveChunkMode: 'mod',
  37281. // barMaxWidth: null,
  37282. // In cartesian, the default value is 1. Otherwise null.
  37283. // barMinWidth: null,
  37284. // 默认自适应
  37285. // barWidth: null,
  37286. // 柱间距离,默认为柱形宽度的30%,可设固定值
  37287. // barGap: '30%',
  37288. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  37289. // barCategoryGap: '20%',
  37290. // label: {
  37291. // show: false
  37292. // },
  37293. itemStyle: {},
  37294. emphasis: {}
  37295. }
  37296. });
  37297. /*
  37298. * Licensed to the Apache Software Foundation (ASF) under one
  37299. * or more contributor license agreements. See the NOTICE file
  37300. * distributed with this work for additional information
  37301. * regarding copyright ownership. The ASF licenses this file
  37302. * to you under the Apache License, Version 2.0 (the
  37303. * "License"); you may not use this file except in compliance
  37304. * with the License. You may obtain a copy of the License at
  37305. *
  37306. * http://www.apache.org/licenses/LICENSE-2.0
  37307. *
  37308. * Unless required by applicable law or agreed to in writing,
  37309. * software distributed under the License is distributed on an
  37310. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37311. * KIND, either express or implied. See the License for the
  37312. * specific language governing permissions and limitations
  37313. * under the License.
  37314. */
  37315. BaseBarSeries.extend({
  37316. type: 'series.bar',
  37317. dependencies: ['grid', 'polar'],
  37318. brushSelector: 'rect',
  37319. /**
  37320. * @override
  37321. */
  37322. getProgressive: function () {
  37323. // Do not support progressive in normal mode.
  37324. return this.get('large')
  37325. ? this.get('progressive')
  37326. : false;
  37327. },
  37328. /**
  37329. * @override
  37330. */
  37331. getProgressiveThreshold: function () {
  37332. // Do not support progressive in normal mode.
  37333. var progressiveThreshold = this.get('progressiveThreshold');
  37334. var largeThreshold = this.get('largeThreshold');
  37335. if (largeThreshold > progressiveThreshold) {
  37336. progressiveThreshold = largeThreshold;
  37337. }
  37338. return progressiveThreshold;
  37339. },
  37340. defaultOption: {
  37341. // If clipped
  37342. // Only available on cartesian2d
  37343. clip: true,
  37344. // If use caps on two sides of bars
  37345. // Only available on tangential polar bar
  37346. roundCap: false
  37347. }
  37348. });
  37349. /*
  37350. * Licensed to the Apache Software Foundation (ASF) under one
  37351. * or more contributor license agreements. See the NOTICE file
  37352. * distributed with this work for additional information
  37353. * regarding copyright ownership. The ASF licenses this file
  37354. * to you under the Apache License, Version 2.0 (the
  37355. * "License"); you may not use this file except in compliance
  37356. * with the License. You may obtain a copy of the License at
  37357. *
  37358. * http://www.apache.org/licenses/LICENSE-2.0
  37359. *
  37360. * Unless required by applicable law or agreed to in writing,
  37361. * software distributed under the License is distributed on an
  37362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37363. * KIND, either express or implied. See the License for the
  37364. * specific language governing permissions and limitations
  37365. * under the License.
  37366. */
  37367. function setLabel(
  37368. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  37369. ) {
  37370. var labelModel = itemModel.getModel('label');
  37371. var hoverLabelModel = itemModel.getModel('emphasis.label');
  37372. setLabelStyle(
  37373. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  37374. {
  37375. labelFetcher: seriesModel,
  37376. labelDataIndex: dataIndex,
  37377. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37378. isRectText: true,
  37379. autoColor: color
  37380. }
  37381. );
  37382. fixPosition(normalStyle);
  37383. fixPosition(hoverStyle);
  37384. }
  37385. function fixPosition(style, labelPositionOutside) {
  37386. if (style.textPosition === 'outside') {
  37387. style.textPosition = labelPositionOutside;
  37388. }
  37389. }
  37390. /*
  37391. * Licensed to the Apache Software Foundation (ASF) under one
  37392. * or more contributor license agreements. See the NOTICE file
  37393. * distributed with this work for additional information
  37394. * regarding copyright ownership. The ASF licenses this file
  37395. * to you under the Apache License, Version 2.0 (the
  37396. * "License"); you may not use this file except in compliance
  37397. * with the License. You may obtain a copy of the License at
  37398. *
  37399. * http://www.apache.org/licenses/LICENSE-2.0
  37400. *
  37401. * Unless required by applicable law or agreed to in writing,
  37402. * software distributed under the License is distributed on an
  37403. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37404. * KIND, either express or implied. See the License for the
  37405. * specific language governing permissions and limitations
  37406. * under the License.
  37407. */
  37408. var getBarItemStyle = makeStyleMapper(
  37409. [
  37410. ['fill', 'color'],
  37411. ['stroke', 'borderColor'],
  37412. ['lineWidth', 'borderWidth'],
  37413. // Compatitable with 2
  37414. ['stroke', 'barBorderColor'],
  37415. ['lineWidth', 'barBorderWidth'],
  37416. ['opacity'],
  37417. ['shadowBlur'],
  37418. ['shadowOffsetX'],
  37419. ['shadowOffsetY'],
  37420. ['shadowColor']
  37421. ]
  37422. );
  37423. var barItemStyle = {
  37424. getBarItemStyle: function (excludes) {
  37425. var style = getBarItemStyle(this, excludes);
  37426. if (this.getBorderLineDash) {
  37427. var lineDash = this.getBorderLineDash();
  37428. lineDash && (style.lineDash = lineDash);
  37429. }
  37430. return style;
  37431. }
  37432. };
  37433. /*
  37434. * Licensed to the Apache Software Foundation (ASF) under one
  37435. * or more contributor license agreements. See the NOTICE file
  37436. * distributed with this work for additional information
  37437. * regarding copyright ownership. The ASF licenses this file
  37438. * to you under the Apache License, Version 2.0 (the
  37439. * "License"); you may not use this file except in compliance
  37440. * with the License. You may obtain a copy of the License at
  37441. *
  37442. * http://www.apache.org/licenses/LICENSE-2.0
  37443. *
  37444. * Unless required by applicable law or agreed to in writing,
  37445. * software distributed under the License is distributed on an
  37446. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37447. * KIND, either express or implied. See the License for the
  37448. * specific language governing permissions and limitations
  37449. * under the License.
  37450. */
  37451. /**
  37452. * Sausage: similar to sector, but have half circle on both sides
  37453. * @public
  37454. */
  37455. var Sausage = extendShape({
  37456. type: 'sausage',
  37457. shape: {
  37458. cx: 0,
  37459. cy: 0,
  37460. r0: 0,
  37461. r: 0,
  37462. startAngle: 0,
  37463. endAngle: Math.PI * 2,
  37464. clockwise: true
  37465. },
  37466. buildPath: function (ctx, shape) {
  37467. var x = shape.cx;
  37468. var y = shape.cy;
  37469. var r0 = Math.max(shape.r0 || 0, 0);
  37470. var r = Math.max(shape.r, 0);
  37471. var dr = (r - r0) * 0.5;
  37472. var rCenter = r0 + dr;
  37473. var startAngle = shape.startAngle;
  37474. var endAngle = shape.endAngle;
  37475. var clockwise = shape.clockwise;
  37476. var unitStartX = Math.cos(startAngle);
  37477. var unitStartY = Math.sin(startAngle);
  37478. var unitEndX = Math.cos(endAngle);
  37479. var unitEndY = Math.sin(endAngle);
  37480. var lessThanCircle = clockwise
  37481. ? endAngle - startAngle < Math.PI * 2
  37482. : startAngle - endAngle < Math.PI * 2;
  37483. if (lessThanCircle) {
  37484. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  37485. ctx.arc(
  37486. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  37487. -Math.PI + startAngle, startAngle, !clockwise
  37488. );
  37489. }
  37490. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  37491. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  37492. ctx.arc(
  37493. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  37494. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  37495. );
  37496. if (r0 !== 0) {
  37497. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  37498. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  37499. }
  37500. ctx.closePath();
  37501. }
  37502. });
  37503. /*
  37504. * Licensed to the Apache Software Foundation (ASF) under one
  37505. * or more contributor license agreements. See the NOTICE file
  37506. * distributed with this work for additional information
  37507. * regarding copyright ownership. The ASF licenses this file
  37508. * to you under the Apache License, Version 2.0 (the
  37509. * "License"); you may not use this file except in compliance
  37510. * with the License. You may obtain a copy of the License at
  37511. *
  37512. * http://www.apache.org/licenses/LICENSE-2.0
  37513. *
  37514. * Unless required by applicable law or agreed to in writing,
  37515. * software distributed under the License is distributed on an
  37516. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37517. * KIND, either express or implied. See the License for the
  37518. * specific language governing permissions and limitations
  37519. * under the License.
  37520. */
  37521. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  37522. var _eventPos = [0, 0];
  37523. // FIXME
  37524. // Just for compatible with ec2.
  37525. extend(Model.prototype, barItemStyle);
  37526. function getClipArea(coord, data) {
  37527. var coordSysClipArea = coord.getArea && coord.getArea();
  37528. if (coord.type === 'cartesian2d') {
  37529. var baseAxis = coord.getBaseAxis();
  37530. // When boundaryGap is false or using time axis. bar may exceed the grid.
  37531. // We should not clip this part.
  37532. // See test/bar2.html
  37533. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  37534. var expandWidth = data.getLayout('bandWidth');
  37535. if (baseAxis.isHorizontal()) {
  37536. coordSysClipArea.x -= expandWidth;
  37537. coordSysClipArea.width += expandWidth * 2;
  37538. }
  37539. else {
  37540. coordSysClipArea.y -= expandWidth;
  37541. coordSysClipArea.height += expandWidth * 2;
  37542. }
  37543. }
  37544. }
  37545. return coordSysClipArea;
  37546. }
  37547. extendChartView({
  37548. type: 'bar',
  37549. render: function (seriesModel, ecModel, api) {
  37550. this._updateDrawMode(seriesModel);
  37551. var coordinateSystemType = seriesModel.get('coordinateSystem');
  37552. if (coordinateSystemType === 'cartesian2d'
  37553. || coordinateSystemType === 'polar'
  37554. ) {
  37555. this._isLargeDraw
  37556. ? this._renderLarge(seriesModel, ecModel, api)
  37557. : this._renderNormal(seriesModel, ecModel, api);
  37558. }
  37559. else if (__DEV__) {
  37560. console.warn('Only cartesian2d and polar supported for bar.');
  37561. }
  37562. return this.group;
  37563. },
  37564. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37565. this._clear();
  37566. this._updateDrawMode(seriesModel);
  37567. },
  37568. incrementalRender: function (params, seriesModel, ecModel, api) {
  37569. // Do not support progressive in normal mode.
  37570. this._incrementalRenderLarge(params, seriesModel);
  37571. },
  37572. _updateDrawMode: function (seriesModel) {
  37573. var isLargeDraw = seriesModel.pipelineContext.large;
  37574. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  37575. this._isLargeDraw = isLargeDraw;
  37576. this._clear();
  37577. }
  37578. },
  37579. _renderNormal: function (seriesModel, ecModel, api) {
  37580. var group = this.group;
  37581. var data = seriesModel.getData();
  37582. var oldData = this._data;
  37583. var coord = seriesModel.coordinateSystem;
  37584. var baseAxis = coord.getBaseAxis();
  37585. var isHorizontalOrRadial;
  37586. if (coord.type === 'cartesian2d') {
  37587. isHorizontalOrRadial = baseAxis.isHorizontal();
  37588. }
  37589. else if (coord.type === 'polar') {
  37590. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37591. }
  37592. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  37593. var needsClip = seriesModel.get('clip', true);
  37594. var coordSysClipArea = getClipArea(coord, data);
  37595. // If there is clipPath created in large mode. Remove it.
  37596. group.removeClipPath();
  37597. // We don't use clipPath in normal mode because we needs a perfect animation
  37598. // And don't want the label are clipped.
  37599. var roundCap = seriesModel.get('roundCap', true);
  37600. data.diff(oldData)
  37601. .add(function (dataIndex) {
  37602. if (!data.hasValue(dataIndex)) {
  37603. return;
  37604. }
  37605. var itemModel = data.getItemModel(dataIndex);
  37606. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  37607. if (needsClip) {
  37608. // Clip will modify the layout params.
  37609. // And return a boolean to determine if the shape are fully clipped.
  37610. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37611. if (isClipped) {
  37612. group.remove(el);
  37613. return;
  37614. }
  37615. }
  37616. var el = elementCreator[coord.type](
  37617. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  37618. );
  37619. data.setItemGraphicEl(dataIndex, el);
  37620. group.add(el);
  37621. updateStyle(
  37622. el, data, dataIndex, itemModel, layout,
  37623. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37624. );
  37625. })
  37626. .update(function (newIndex, oldIndex) {
  37627. var el = oldData.getItemGraphicEl(oldIndex);
  37628. if (!data.hasValue(newIndex)) {
  37629. group.remove(el);
  37630. return;
  37631. }
  37632. var itemModel = data.getItemModel(newIndex);
  37633. var layout = getLayout[coord.type](data, newIndex, itemModel);
  37634. if (needsClip) {
  37635. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37636. if (isClipped) {
  37637. group.remove(el);
  37638. return;
  37639. }
  37640. }
  37641. if (el) {
  37642. updateProps(el, {shape: layout}, animationModel, newIndex);
  37643. }
  37644. else {
  37645. el = elementCreator[coord.type](
  37646. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  37647. );
  37648. }
  37649. data.setItemGraphicEl(newIndex, el);
  37650. // Add back
  37651. group.add(el);
  37652. updateStyle(
  37653. el, data, newIndex, itemModel, layout,
  37654. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37655. );
  37656. })
  37657. .remove(function (dataIndex) {
  37658. var el = oldData.getItemGraphicEl(dataIndex);
  37659. if (coord.type === 'cartesian2d') {
  37660. el && removeRect(dataIndex, animationModel, el);
  37661. }
  37662. else {
  37663. el && removeSector(dataIndex, animationModel, el);
  37664. }
  37665. })
  37666. .execute();
  37667. this._data = data;
  37668. },
  37669. _renderLarge: function (seriesModel, ecModel, api) {
  37670. this._clear();
  37671. createLarge(seriesModel, this.group);
  37672. // Use clipPath in large mode.
  37673. var clipPath = seriesModel.get('clip', true)
  37674. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  37675. : null;
  37676. if (clipPath) {
  37677. this.group.setClipPath(clipPath);
  37678. }
  37679. else {
  37680. this.group.removeClipPath();
  37681. }
  37682. },
  37683. _incrementalRenderLarge: function (params, seriesModel) {
  37684. createLarge(seriesModel, this.group, true);
  37685. },
  37686. dispose: noop,
  37687. remove: function (ecModel) {
  37688. this._clear(ecModel);
  37689. },
  37690. _clear: function (ecModel) {
  37691. var group = this.group;
  37692. var data = this._data;
  37693. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  37694. data.eachItemGraphicEl(function (el) {
  37695. if (el.type === 'sector') {
  37696. removeSector(el.dataIndex, ecModel, el);
  37697. }
  37698. else {
  37699. removeRect(el.dataIndex, ecModel, el);
  37700. }
  37701. });
  37702. }
  37703. else {
  37704. group.removeAll();
  37705. }
  37706. this._data = null;
  37707. }
  37708. });
  37709. var mathMax$4 = Math.max;
  37710. var mathMin$4 = Math.min;
  37711. var clip = {
  37712. cartesian2d: function (coordSysBoundingRect, layout) {
  37713. var signWidth = layout.width < 0 ? -1 : 1;
  37714. var signHeight = layout.height < 0 ? -1 : 1;
  37715. // Needs positive width and height
  37716. if (signWidth < 0) {
  37717. layout.x += layout.width;
  37718. layout.width = -layout.width;
  37719. }
  37720. if (signHeight < 0) {
  37721. layout.y += layout.height;
  37722. layout.height = -layout.height;
  37723. }
  37724. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  37725. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  37726. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  37727. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  37728. layout.x = x;
  37729. layout.y = y;
  37730. layout.width = x2 - x;
  37731. layout.height = y2 - y;
  37732. var clipped = layout.width < 0 || layout.height < 0;
  37733. // Reverse back
  37734. if (signWidth < 0) {
  37735. layout.x += layout.width;
  37736. layout.width = -layout.width;
  37737. }
  37738. if (signHeight < 0) {
  37739. layout.y += layout.height;
  37740. layout.height = -layout.height;
  37741. }
  37742. return clipped;
  37743. },
  37744. polar: function (coordSysClipArea) {
  37745. return false;
  37746. }
  37747. };
  37748. var elementCreator = {
  37749. cartesian2d: function (
  37750. dataIndex, layout, isHorizontal,
  37751. animationModel, isUpdate
  37752. ) {
  37753. var rect = new Rect({shape: extend({}, layout)});
  37754. // Animation
  37755. if (animationModel) {
  37756. var rectShape = rect.shape;
  37757. var animateProperty = isHorizontal ? 'height' : 'width';
  37758. var animateTarget = {};
  37759. rectShape[animateProperty] = 0;
  37760. animateTarget[animateProperty] = layout[animateProperty];
  37761. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  37762. shape: animateTarget
  37763. }, animationModel, dataIndex);
  37764. }
  37765. return rect;
  37766. },
  37767. polar: function (
  37768. dataIndex, layout, isRadial,
  37769. animationModel, isUpdate, roundCap
  37770. ) {
  37771. // Keep the same logic with bar in catesion: use end value to control
  37772. // direction. Notice that if clockwise is true (by default), the sector
  37773. // will always draw clockwisely, no matter whether endAngle is greater
  37774. // or less than startAngle.
  37775. var clockwise = layout.startAngle < layout.endAngle;
  37776. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  37777. var sector = new ShapeClass({
  37778. shape: defaults({clockwise: clockwise}, layout)
  37779. });
  37780. // Animation
  37781. if (animationModel) {
  37782. var sectorShape = sector.shape;
  37783. var animateProperty = isRadial ? 'r' : 'endAngle';
  37784. var animateTarget = {};
  37785. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  37786. animateTarget[animateProperty] = layout[animateProperty];
  37787. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  37788. shape: animateTarget
  37789. }, animationModel, dataIndex);
  37790. }
  37791. return sector;
  37792. }
  37793. };
  37794. function removeRect(dataIndex, animationModel, el) {
  37795. // Not show text when animating
  37796. el.style.text = null;
  37797. updateProps(el, {
  37798. shape: {
  37799. width: 0
  37800. }
  37801. }, animationModel, dataIndex, function () {
  37802. el.parent && el.parent.remove(el);
  37803. });
  37804. }
  37805. function removeSector(dataIndex, animationModel, el) {
  37806. // Not show text when animating
  37807. el.style.text = null;
  37808. updateProps(el, {
  37809. shape: {
  37810. r: el.shape.r0
  37811. }
  37812. }, animationModel, dataIndex, function () {
  37813. el.parent && el.parent.remove(el);
  37814. });
  37815. }
  37816. var getLayout = {
  37817. cartesian2d: function (data, dataIndex, itemModel) {
  37818. var layout = data.getItemLayout(dataIndex);
  37819. var fixedLineWidth = getLineWidth(itemModel, layout);
  37820. // fix layout with lineWidth
  37821. var signX = layout.width > 0 ? 1 : -1;
  37822. var signY = layout.height > 0 ? 1 : -1;
  37823. return {
  37824. x: layout.x + signX * fixedLineWidth / 2,
  37825. y: layout.y + signY * fixedLineWidth / 2,
  37826. width: layout.width - signX * fixedLineWidth,
  37827. height: layout.height - signY * fixedLineWidth
  37828. };
  37829. },
  37830. polar: function (data, dataIndex, itemModel) {
  37831. var layout = data.getItemLayout(dataIndex);
  37832. return {
  37833. cx: layout.cx,
  37834. cy: layout.cy,
  37835. r0: layout.r0,
  37836. r: layout.r,
  37837. startAngle: layout.startAngle,
  37838. endAngle: layout.endAngle
  37839. };
  37840. }
  37841. };
  37842. function isZeroOnPolar(layout) {
  37843. return layout.startAngle != null
  37844. && layout.endAngle != null
  37845. && layout.startAngle === layout.endAngle;
  37846. }
  37847. function updateStyle(
  37848. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  37849. ) {
  37850. var color = data.getItemVisual(dataIndex, 'color');
  37851. var opacity = data.getItemVisual(dataIndex, 'opacity');
  37852. var stroke = data.getVisual('borderColor');
  37853. var itemStyleModel = itemModel.getModel('itemStyle');
  37854. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  37855. if (!isPolar) {
  37856. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  37857. }
  37858. el.useStyle(defaults(
  37859. {
  37860. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  37861. fill: isZeroOnPolar(layout) ? 'none' : color,
  37862. opacity: opacity
  37863. },
  37864. itemStyleModel.getBarItemStyle()
  37865. ));
  37866. var cursorStyle = itemModel.getShallow('cursor');
  37867. cursorStyle && el.attr('cursor', cursorStyle);
  37868. var labelPositionOutside = isHorizontal
  37869. ? (layout.height > 0 ? 'bottom' : 'top')
  37870. : (layout.width > 0 ? 'left' : 'right');
  37871. if (!isPolar) {
  37872. setLabel(
  37873. el.style, hoverStyle, itemModel, color,
  37874. seriesModel, dataIndex, labelPositionOutside
  37875. );
  37876. }
  37877. if (isZeroOnPolar(layout)) {
  37878. hoverStyle.fill = hoverStyle.stroke = 'none';
  37879. }
  37880. setHoverStyle(el, hoverStyle);
  37881. }
  37882. // In case width or height are too small.
  37883. function getLineWidth(itemModel, rawLayout) {
  37884. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  37885. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  37886. }
  37887. var LargePath = Path.extend({
  37888. type: 'largeBar',
  37889. shape: {points: []},
  37890. buildPath: function (ctx, shape) {
  37891. // Drawing lines is more efficient than drawing
  37892. // a whole line or drawing rects.
  37893. var points = shape.points;
  37894. var startPoint = this.__startPoint;
  37895. var baseDimIdx = this.__baseDimIdx;
  37896. for (var i = 0; i < points.length; i += 2) {
  37897. startPoint[baseDimIdx] = points[i + baseDimIdx];
  37898. ctx.moveTo(startPoint[0], startPoint[1]);
  37899. ctx.lineTo(points[i], points[i + 1]);
  37900. }
  37901. }
  37902. });
  37903. function createLarge(seriesModel, group, incremental) {
  37904. // TODO support polar
  37905. var data = seriesModel.getData();
  37906. var startPoint = [];
  37907. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  37908. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  37909. var el = new LargePath({
  37910. shape: {points: data.getLayout('largePoints')},
  37911. incremental: !!incremental,
  37912. __startPoint: startPoint,
  37913. __baseDimIdx: baseDimIdx,
  37914. __largeDataIndices: data.getLayout('largeDataIndices'),
  37915. __barWidth: data.getLayout('barWidth')
  37916. });
  37917. group.add(el);
  37918. setLargeStyle(el, seriesModel, data);
  37919. // Enable tooltip and user mouse/touch event handlers.
  37920. el.seriesIndex = seriesModel.seriesIndex;
  37921. if (!seriesModel.get('silent')) {
  37922. el.on('mousedown', largePathUpdateDataIndex);
  37923. el.on('mousemove', largePathUpdateDataIndex);
  37924. }
  37925. }
  37926. // Use throttle to avoid frequently traverse to find dataIndex.
  37927. var largePathUpdateDataIndex = throttle(function (event) {
  37928. var largePath = this;
  37929. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  37930. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  37931. }, 30, false);
  37932. function largePathFindDataIndex(largePath, x, y) {
  37933. var baseDimIdx = largePath.__baseDimIdx;
  37934. var valueDimIdx = 1 - baseDimIdx;
  37935. var points = largePath.shape.points;
  37936. var largeDataIndices = largePath.__largeDataIndices;
  37937. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  37938. var startValueVal = largePath.__startPoint[valueDimIdx];
  37939. _eventPos[0] = x;
  37940. _eventPos[1] = y;
  37941. var pointerBaseVal = _eventPos[baseDimIdx];
  37942. var pointerValueVal = _eventPos[1 - baseDimIdx];
  37943. var baseLowerBound = pointerBaseVal - barWidthHalf;
  37944. var baseUpperBound = pointerBaseVal + barWidthHalf;
  37945. for (var i = 0, len = points.length / 2; i < len; i++) {
  37946. var ii = i * 2;
  37947. var barBaseVal = points[ii + baseDimIdx];
  37948. var barValueVal = points[ii + valueDimIdx];
  37949. if (
  37950. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  37951. && (
  37952. startValueVal <= barValueVal
  37953. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  37954. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  37955. )
  37956. ) {
  37957. return largeDataIndices[i];
  37958. }
  37959. }
  37960. return -1;
  37961. }
  37962. function setLargeStyle(el, seriesModel, data) {
  37963. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  37964. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  37965. el.useStyle(itemStyle);
  37966. el.style.fill = null;
  37967. el.style.stroke = borderColor;
  37968. el.style.lineWidth = data.getLayout('barWidth');
  37969. }
  37970. /*
  37971. * Licensed to the Apache Software Foundation (ASF) under one
  37972. * or more contributor license agreements. See the NOTICE file
  37973. * distributed with this work for additional information
  37974. * regarding copyright ownership. The ASF licenses this file
  37975. * to you under the Apache License, Version 2.0 (the
  37976. * "License"); you may not use this file except in compliance
  37977. * with the License. You may obtain a copy of the License at
  37978. *
  37979. * http://www.apache.org/licenses/LICENSE-2.0
  37980. *
  37981. * Unless required by applicable law or agreed to in writing,
  37982. * software distributed under the License is distributed on an
  37983. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37984. * KIND, either express or implied. See the License for the
  37985. * specific language governing permissions and limitations
  37986. * under the License.
  37987. */
  37988. // In case developer forget to include grid component
  37989. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  37990. // Use higher prority to avoid to be blocked by other overall layout, which do not
  37991. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  37992. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  37993. registerVisual({
  37994. seriesType: 'bar',
  37995. reset: function (seriesModel) {
  37996. // Visual coding for legend
  37997. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  37998. }
  37999. });
  38000. /*
  38001. * Licensed to the Apache Software Foundation (ASF) under one
  38002. * or more contributor license agreements. See the NOTICE file
  38003. * distributed with this work for additional information
  38004. * regarding copyright ownership. The ASF licenses this file
  38005. * to you under the Apache License, Version 2.0 (the
  38006. * "License"); you may not use this file except in compliance
  38007. * with the License. You may obtain a copy of the License at
  38008. *
  38009. * http://www.apache.org/licenses/LICENSE-2.0
  38010. *
  38011. * Unless required by applicable law or agreed to in writing,
  38012. * software distributed under the License is distributed on an
  38013. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38014. * KIND, either express or implied. See the License for the
  38015. * specific language governing permissions and limitations
  38016. * under the License.
  38017. */
  38018. /**
  38019. * [Usage]:
  38020. * (1)
  38021. * createListSimply(seriesModel, ['value']);
  38022. * (2)
  38023. * createListSimply(seriesModel, {
  38024. * coordDimensions: ['value'],
  38025. * dimensionsCount: 5
  38026. * });
  38027. *
  38028. * @param {module:echarts/model/Series} seriesModel
  38029. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  38030. * The options in opt, see `echarts/data/helper/createDimensions`
  38031. * @param {Array.<string>} [nameList]
  38032. * @return {module:echarts/data/List}
  38033. */
  38034. var createListSimply = function (seriesModel, opt, nameList) {
  38035. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  38036. var source = seriesModel.getSource();
  38037. var dimensionsInfo = createDimensions(source, opt);
  38038. var list = new List(dimensionsInfo, seriesModel);
  38039. list.initData(source, nameList);
  38040. return list;
  38041. };
  38042. /*
  38043. * Licensed to the Apache Software Foundation (ASF) under one
  38044. * or more contributor license agreements. See the NOTICE file
  38045. * distributed with this work for additional information
  38046. * regarding copyright ownership. The ASF licenses this file
  38047. * to you under the Apache License, Version 2.0 (the
  38048. * "License"); you may not use this file except in compliance
  38049. * with the License. You may obtain a copy of the License at
  38050. *
  38051. * http://www.apache.org/licenses/LICENSE-2.0
  38052. *
  38053. * Unless required by applicable law or agreed to in writing,
  38054. * software distributed under the License is distributed on an
  38055. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38056. * KIND, either express or implied. See the License for the
  38057. * specific language governing permissions and limitations
  38058. * under the License.
  38059. */
  38060. /**
  38061. * Data selectable mixin for chart series.
  38062. * To eanble data select, option of series must have `selectedMode`.
  38063. * And each data item will use `selected` to toggle itself selected status
  38064. */
  38065. var dataSelectableMixin = {
  38066. /**
  38067. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  38068. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  38069. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  38070. */
  38071. updateSelectedMap: function (targetList) {
  38072. this._targetList = isArray(targetList) ? targetList.slice() : [];
  38073. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  38074. targetMap.set(target.name, target);
  38075. return targetMap;
  38076. }, createHashMap());
  38077. },
  38078. /**
  38079. * Either name or id should be passed as input here.
  38080. * If both of them are defined, id is used.
  38081. *
  38082. * @param {string|undefined} name name of data
  38083. * @param {number|undefined} id dataIndex of data
  38084. */
  38085. // PENGING If selectedMode is null ?
  38086. select: function (name, id) {
  38087. var target = id != null
  38088. ? this._targetList[id]
  38089. : this._selectTargetMap.get(name);
  38090. var selectedMode = this.get('selectedMode');
  38091. if (selectedMode === 'single') {
  38092. this._selectTargetMap.each(function (target) {
  38093. target.selected = false;
  38094. });
  38095. }
  38096. target && (target.selected = true);
  38097. },
  38098. /**
  38099. * Either name or id should be passed as input here.
  38100. * If both of them are defined, id is used.
  38101. *
  38102. * @param {string|undefined} name name of data
  38103. * @param {number|undefined} id dataIndex of data
  38104. */
  38105. unSelect: function (name, id) {
  38106. var target = id != null
  38107. ? this._targetList[id]
  38108. : this._selectTargetMap.get(name);
  38109. // var selectedMode = this.get('selectedMode');
  38110. // selectedMode !== 'single' && target && (target.selected = false);
  38111. target && (target.selected = false);
  38112. },
  38113. /**
  38114. * Either name or id should be passed as input here.
  38115. * If both of them are defined, id is used.
  38116. *
  38117. * @param {string|undefined} name name of data
  38118. * @param {number|undefined} id dataIndex of data
  38119. */
  38120. toggleSelected: function (name, id) {
  38121. var target = id != null
  38122. ? this._targetList[id]
  38123. : this._selectTargetMap.get(name);
  38124. if (target != null) {
  38125. this[target.selected ? 'unSelect' : 'select'](name, id);
  38126. return target.selected;
  38127. }
  38128. },
  38129. /**
  38130. * Either name or id should be passed as input here.
  38131. * If both of them are defined, id is used.
  38132. *
  38133. * @param {string|undefined} name name of data
  38134. * @param {number|undefined} id dataIndex of data
  38135. */
  38136. isSelected: function (name, id) {
  38137. var target = id != null
  38138. ? this._targetList[id]
  38139. : this._selectTargetMap.get(name);
  38140. return target && target.selected;
  38141. }
  38142. };
  38143. /*
  38144. * Licensed to the Apache Software Foundation (ASF) under one
  38145. * or more contributor license agreements. See the NOTICE file
  38146. * distributed with this work for additional information
  38147. * regarding copyright ownership. The ASF licenses this file
  38148. * to you under the Apache License, Version 2.0 (the
  38149. * "License"); you may not use this file except in compliance
  38150. * with the License. You may obtain a copy of the License at
  38151. *
  38152. * http://www.apache.org/licenses/LICENSE-2.0
  38153. *
  38154. * Unless required by applicable law or agreed to in writing,
  38155. * software distributed under the License is distributed on an
  38156. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38157. * KIND, either express or implied. See the License for the
  38158. * specific language governing permissions and limitations
  38159. * under the License.
  38160. */
  38161. /**
  38162. * LegendVisualProvider is an bridge that pick encoded color from data and
  38163. * provide to the legend component.
  38164. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  38165. * @param {Function} getRawData Function to get raw data before filtered.
  38166. */
  38167. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  38168. this.getAllNames = function () {
  38169. var rawData = getRawData();
  38170. // We find the name from the raw data. In case it's filtered by the legend component.
  38171. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38172. return rawData.mapArray(rawData.getName);
  38173. };
  38174. this.containName = function (name) {
  38175. var rawData = getRawData();
  38176. return rawData.indexOfName(name) >= 0;
  38177. };
  38178. this.indexOfName = function (name) {
  38179. // Only get data when necessary.
  38180. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38181. // Invoking Series#getData immediately will throw an error.
  38182. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38183. return dataWithEncodedVisual.indexOfName(name);
  38184. };
  38185. this.getItemVisual = function (dataIndex, key) {
  38186. // Get encoded visual properties from final filtered data.
  38187. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38188. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38189. };
  38190. }
  38191. /*
  38192. * Licensed to the Apache Software Foundation (ASF) under one
  38193. * or more contributor license agreements. See the NOTICE file
  38194. * distributed with this work for additional information
  38195. * regarding copyright ownership. The ASF licenses this file
  38196. * to you under the Apache License, Version 2.0 (the
  38197. * "License"); you may not use this file except in compliance
  38198. * with the License. You may obtain a copy of the License at
  38199. *
  38200. * http://www.apache.org/licenses/LICENSE-2.0
  38201. *
  38202. * Unless required by applicable law or agreed to in writing,
  38203. * software distributed under the License is distributed on an
  38204. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38205. * KIND, either express or implied. See the License for the
  38206. * specific language governing permissions and limitations
  38207. * under the License.
  38208. */
  38209. var PieSeries = extendSeriesModel({
  38210. type: 'series.pie',
  38211. // Overwrite
  38212. init: function (option) {
  38213. PieSeries.superApply(this, 'init', arguments);
  38214. // Enable legend selection for each data item
  38215. // Use a function instead of direct access because data reference may changed
  38216. this.legendVisualProvider = new LegendVisualProvider(
  38217. bind(this.getData, this), bind(this.getRawData, this)
  38218. );
  38219. this.updateSelectedMap(this._createSelectableList());
  38220. this._defaultLabelLine(option);
  38221. },
  38222. // Overwrite
  38223. mergeOption: function (newOption) {
  38224. PieSeries.superCall(this, 'mergeOption', newOption);
  38225. this.updateSelectedMap(this._createSelectableList());
  38226. },
  38227. getInitialData: function (option, ecModel) {
  38228. return createListSimply(this, {
  38229. coordDimensions: ['value'],
  38230. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38231. });
  38232. },
  38233. _createSelectableList: function () {
  38234. var data = this.getRawData();
  38235. var valueDim = data.mapDimension('value');
  38236. var targetList = [];
  38237. for (var i = 0, len = data.count(); i < len; i++) {
  38238. targetList.push({
  38239. name: data.getName(i),
  38240. value: data.get(valueDim, i),
  38241. selected: retrieveRawAttr(data, i, 'selected')
  38242. });
  38243. }
  38244. return targetList;
  38245. },
  38246. // Overwrite
  38247. getDataParams: function (dataIndex) {
  38248. var data = this.getData();
  38249. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  38250. // FIXME toFixed?
  38251. var valueList = [];
  38252. data.each(data.mapDimension('value'), function (value) {
  38253. valueList.push(value);
  38254. });
  38255. params.percent = getPercentWithPrecision(
  38256. valueList,
  38257. dataIndex,
  38258. data.hostModel.get('percentPrecision')
  38259. );
  38260. params.$vars.push('percent');
  38261. return params;
  38262. },
  38263. _defaultLabelLine: function (option) {
  38264. // Extend labelLine emphasis
  38265. defaultEmphasis(option, 'labelLine', ['show']);
  38266. var labelLineNormalOpt = option.labelLine;
  38267. var labelLineEmphasisOpt = option.emphasis.labelLine;
  38268. // Not show label line if `label.normal.show = false`
  38269. labelLineNormalOpt.show = labelLineNormalOpt.show
  38270. && option.label.show;
  38271. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  38272. && option.emphasis.label.show;
  38273. },
  38274. defaultOption: {
  38275. zlevel: 0,
  38276. z: 2,
  38277. legendHoverLink: true,
  38278. hoverAnimation: true,
  38279. // 默认全局居中
  38280. center: ['50%', '50%'],
  38281. radius: [0, '75%'],
  38282. // 默认顺时针
  38283. clockwise: true,
  38284. startAngle: 90,
  38285. // 最小角度改为0
  38286. minAngle: 0,
  38287. // If the angle of a sector less than `minShowLabelAngle`,
  38288. // the label will not be displayed.
  38289. minShowLabelAngle: 0,
  38290. // 选中时扇区偏移量
  38291. selectedOffset: 10,
  38292. // 高亮扇区偏移量
  38293. hoverOffset: 10,
  38294. // If use strategy to avoid label overlapping
  38295. avoidLabelOverlap: true,
  38296. // 选择模式,默认关闭,可选single,multiple
  38297. // selectedMode: false,
  38298. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38299. // roseType: null,
  38300. percentPrecision: 2,
  38301. // If still show when all data zero.
  38302. stillShowZeroSum: true,
  38303. // cursor: null,
  38304. left: 0,
  38305. top: 0,
  38306. right: 0,
  38307. bottom: 0,
  38308. width: null,
  38309. height: null,
  38310. label: {
  38311. // If rotate around circle
  38312. rotate: false,
  38313. show: true,
  38314. // 'outer', 'inside', 'center'
  38315. position: 'outer',
  38316. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38317. alignTo: 'none',
  38318. // Closest distance between label and chart edge.
  38319. // Works only position is 'outer' and alignTo is 'edge'.
  38320. margin: '25%',
  38321. // Works only position is 'outer' and alignTo is not 'edge'.
  38322. bleedMargin: 10,
  38323. // Distance between text and label line.
  38324. distanceToLabelLine: 5
  38325. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38326. // 默认使用全局文本样式,详见TEXTSTYLE
  38327. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38328. },
  38329. // Enabled when label.normal.position is 'outer'
  38330. labelLine: {
  38331. show: true,
  38332. // 引导线两段中的第一段长度
  38333. length: 15,
  38334. // 引导线两段中的第二段长度
  38335. length2: 15,
  38336. smooth: false,
  38337. lineStyle: {
  38338. // color: 各异,
  38339. width: 1,
  38340. type: 'solid'
  38341. }
  38342. },
  38343. itemStyle: {
  38344. borderWidth: 1
  38345. },
  38346. // Animation type. Valid values: expansion, scale
  38347. animationType: 'expansion',
  38348. // Animation type when update. Valid values: transition, expansion
  38349. animationTypeUpdate: 'transition',
  38350. animationEasing: 'cubicOut'
  38351. }
  38352. });
  38353. mixin(PieSeries, dataSelectableMixin);
  38354. /*
  38355. * Licensed to the Apache Software Foundation (ASF) under one
  38356. * or more contributor license agreements. See the NOTICE file
  38357. * distributed with this work for additional information
  38358. * regarding copyright ownership. The ASF licenses this file
  38359. * to you under the Apache License, Version 2.0 (the
  38360. * "License"); you may not use this file except in compliance
  38361. * with the License. You may obtain a copy of the License at
  38362. *
  38363. * http://www.apache.org/licenses/LICENSE-2.0
  38364. *
  38365. * Unless required by applicable law or agreed to in writing,
  38366. * software distributed under the License is distributed on an
  38367. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38368. * KIND, either express or implied. See the License for the
  38369. * specific language governing permissions and limitations
  38370. * under the License.
  38371. */
  38372. /**
  38373. * @param {module:echarts/model/Series} seriesModel
  38374. * @param {boolean} hasAnimation
  38375. * @inner
  38376. */
  38377. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  38378. var data = seriesModel.getData();
  38379. var dataIndex = this.dataIndex;
  38380. var name = data.getName(dataIndex);
  38381. var selectedOffset = seriesModel.get('selectedOffset');
  38382. api.dispatchAction({
  38383. type: 'pieToggleSelect',
  38384. from: uid,
  38385. name: name,
  38386. seriesId: seriesModel.id
  38387. });
  38388. data.each(function (idx) {
  38389. toggleItemSelected(
  38390. data.getItemGraphicEl(idx),
  38391. data.getItemLayout(idx),
  38392. seriesModel.isSelected(data.getName(idx)),
  38393. selectedOffset,
  38394. hasAnimation
  38395. );
  38396. });
  38397. }
  38398. /**
  38399. * @param {module:zrender/graphic/Sector} el
  38400. * @param {Object} layout
  38401. * @param {boolean} isSelected
  38402. * @param {number} selectedOffset
  38403. * @param {boolean} hasAnimation
  38404. * @inner
  38405. */
  38406. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  38407. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38408. var dx = Math.cos(midAngle);
  38409. var dy = Math.sin(midAngle);
  38410. var offset = isSelected ? selectedOffset : 0;
  38411. var position = [dx * offset, dy * offset];
  38412. hasAnimation
  38413. // animateTo will stop revious animation like update transition
  38414. ? el.animate()
  38415. .when(200, {
  38416. position: position
  38417. })
  38418. .start('bounceOut')
  38419. : el.attr('position', position);
  38420. }
  38421. /**
  38422. * Piece of pie including Sector, Label, LabelLine
  38423. * @constructor
  38424. * @extends {module:zrender/graphic/Group}
  38425. */
  38426. function PiePiece(data, idx) {
  38427. Group.call(this);
  38428. var sector = new Sector({
  38429. z2: 2
  38430. });
  38431. var polyline = new Polyline();
  38432. var text = new Text();
  38433. this.add(sector);
  38434. this.add(polyline);
  38435. this.add(text);
  38436. this.updateData(data, idx, true);
  38437. }
  38438. var piePieceProto = PiePiece.prototype;
  38439. piePieceProto.updateData = function (data, idx, firstCreate) {
  38440. var sector = this.childAt(0);
  38441. var labelLine = this.childAt(1);
  38442. var labelText = this.childAt(2);
  38443. var seriesModel = data.hostModel;
  38444. var itemModel = data.getItemModel(idx);
  38445. var layout = data.getItemLayout(idx);
  38446. var sectorShape = extend({}, layout);
  38447. sectorShape.label = null;
  38448. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  38449. if (firstCreate) {
  38450. sector.setShape(sectorShape);
  38451. var animationType = seriesModel.getShallow('animationType');
  38452. if (animationType === 'scale') {
  38453. sector.shape.r = layout.r0;
  38454. initProps(sector, {
  38455. shape: {
  38456. r: layout.r
  38457. }
  38458. }, seriesModel, idx);
  38459. }
  38460. // Expansion
  38461. else {
  38462. sector.shape.endAngle = layout.startAngle;
  38463. updateProps(sector, {
  38464. shape: {
  38465. endAngle: layout.endAngle
  38466. }
  38467. }, seriesModel, idx);
  38468. }
  38469. }
  38470. else {
  38471. if (animationTypeUpdate === 'expansion') {
  38472. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  38473. sector.setShape(sectorShape);
  38474. }
  38475. else {
  38476. // Transition animation from the old shape
  38477. updateProps(sector, {
  38478. shape: sectorShape
  38479. }, seriesModel, idx);
  38480. }
  38481. }
  38482. // Update common style
  38483. var visualColor = data.getItemVisual(idx, 'color');
  38484. sector.useStyle(
  38485. defaults(
  38486. {
  38487. lineJoin: 'bevel',
  38488. fill: visualColor
  38489. },
  38490. itemModel.getModel('itemStyle').getItemStyle()
  38491. )
  38492. );
  38493. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38494. var cursorStyle = itemModel.getShallow('cursor');
  38495. cursorStyle && sector.attr('cursor', cursorStyle);
  38496. // Toggle selected
  38497. toggleItemSelected(
  38498. this,
  38499. data.getItemLayout(idx),
  38500. seriesModel.isSelected(null, idx),
  38501. seriesModel.get('selectedOffset'),
  38502. seriesModel.get('animation')
  38503. );
  38504. // Label and text animation should be applied only for transition type animation when update
  38505. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  38506. this._updateLabel(data, idx, withAnimation);
  38507. this.highDownOnUpdate = (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled())
  38508. ? function (fromState, toState) {
  38509. if (toState === 'emphasis') {
  38510. labelLine.ignore = labelLine.hoverIgnore;
  38511. labelText.ignore = labelText.hoverIgnore;
  38512. // Sector may has animation of updating data. Force to move to the last frame
  38513. // Or it may stopped on the wrong shape
  38514. sector.stopAnimation(true);
  38515. sector.animateTo({
  38516. shape: {
  38517. r: layout.r + seriesModel.get('hoverOffset')
  38518. }
  38519. }, 300, 'elasticOut');
  38520. }
  38521. else {
  38522. labelLine.ignore = labelLine.normalIgnore;
  38523. labelText.ignore = labelText.normalIgnore;
  38524. sector.stopAnimation(true);
  38525. sector.animateTo({
  38526. shape: {
  38527. r: layout.r
  38528. }
  38529. }, 300, 'elasticOut');
  38530. }
  38531. }
  38532. : null;
  38533. setHoverStyle(this);
  38534. };
  38535. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  38536. var labelLine = this.childAt(1);
  38537. var labelText = this.childAt(2);
  38538. var seriesModel = data.hostModel;
  38539. var itemModel = data.getItemModel(idx);
  38540. var layout = data.getItemLayout(idx);
  38541. var labelLayout = layout.label;
  38542. var visualColor = data.getItemVisual(idx, 'color');
  38543. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  38544. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  38545. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  38546. return;
  38547. }
  38548. var targetLineShape = {
  38549. points: labelLayout.linePoints || [
  38550. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  38551. ]
  38552. };
  38553. var targetTextStyle = {
  38554. x: labelLayout.x,
  38555. y: labelLayout.y
  38556. };
  38557. if (withAnimation) {
  38558. updateProps(labelLine, {
  38559. shape: targetLineShape
  38560. }, seriesModel, idx);
  38561. updateProps(labelText, {
  38562. style: targetTextStyle
  38563. }, seriesModel, idx);
  38564. }
  38565. else {
  38566. labelLine.attr({
  38567. shape: targetLineShape
  38568. });
  38569. labelText.attr({
  38570. style: targetTextStyle
  38571. });
  38572. }
  38573. labelText.attr({
  38574. rotation: labelLayout.rotation,
  38575. origin: [labelLayout.x, labelLayout.y],
  38576. z2: 10
  38577. });
  38578. var labelModel = itemModel.getModel('label');
  38579. var labelHoverModel = itemModel.getModel('emphasis.label');
  38580. var labelLineModel = itemModel.getModel('labelLine');
  38581. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  38582. var visualColor = data.getItemVisual(idx, 'color');
  38583. setLabelStyle(
  38584. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  38585. {
  38586. labelFetcher: data.hostModel,
  38587. labelDataIndex: idx,
  38588. defaultText: labelLayout.text,
  38589. autoColor: visualColor,
  38590. useInsideStyle: !!labelLayout.inside
  38591. },
  38592. {
  38593. textAlign: labelLayout.textAlign,
  38594. textVerticalAlign: labelLayout.verticalAlign,
  38595. opacity: data.getItemVisual(idx, 'opacity')
  38596. }
  38597. );
  38598. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  38599. labelText.hoverIgnore = !labelHoverModel.get('show');
  38600. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  38601. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  38602. // Default use item visual color
  38603. labelLine.setStyle({
  38604. stroke: visualColor,
  38605. opacity: data.getItemVisual(idx, 'opacity')
  38606. });
  38607. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  38608. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  38609. var smooth = labelLineModel.get('smooth');
  38610. if (smooth && smooth === true) {
  38611. smooth = 0.4;
  38612. }
  38613. labelLine.setShape({
  38614. smooth: smooth
  38615. });
  38616. };
  38617. inherits(PiePiece, Group);
  38618. // Pie view
  38619. var PieView = Chart.extend({
  38620. type: 'pie',
  38621. init: function () {
  38622. var sectorGroup = new Group();
  38623. this._sectorGroup = sectorGroup;
  38624. },
  38625. render: function (seriesModel, ecModel, api, payload) {
  38626. if (payload && (payload.from === this.uid)) {
  38627. return;
  38628. }
  38629. var data = seriesModel.getData();
  38630. var oldData = this._data;
  38631. var group = this.group;
  38632. var hasAnimation = ecModel.get('animation');
  38633. var isFirstRender = !oldData;
  38634. var animationType = seriesModel.get('animationType');
  38635. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  38636. var onSectorClick = curry(
  38637. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  38638. );
  38639. var selectedMode = seriesModel.get('selectedMode');
  38640. data.diff(oldData)
  38641. .add(function (idx) {
  38642. var piePiece = new PiePiece(data, idx);
  38643. // Default expansion animation
  38644. if (isFirstRender && animationType !== 'scale') {
  38645. piePiece.eachChild(function (child) {
  38646. child.stopAnimation(true);
  38647. });
  38648. }
  38649. selectedMode && piePiece.on('click', onSectorClick);
  38650. data.setItemGraphicEl(idx, piePiece);
  38651. group.add(piePiece);
  38652. })
  38653. .update(function (newIdx, oldIdx) {
  38654. var piePiece = oldData.getItemGraphicEl(oldIdx);
  38655. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  38656. piePiece.eachChild(function (child) {
  38657. child.stopAnimation(true);
  38658. });
  38659. }
  38660. piePiece.updateData(data, newIdx);
  38661. piePiece.off('click');
  38662. selectedMode && piePiece.on('click', onSectorClick);
  38663. group.add(piePiece);
  38664. data.setItemGraphicEl(newIdx, piePiece);
  38665. })
  38666. .remove(function (idx) {
  38667. var piePiece = oldData.getItemGraphicEl(idx);
  38668. group.remove(piePiece);
  38669. })
  38670. .execute();
  38671. if (
  38672. hasAnimation && data.count() > 0
  38673. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  38674. ) {
  38675. var shape = data.getItemLayout(0);
  38676. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  38677. shape = data.getItemLayout(s);
  38678. }
  38679. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  38680. var removeClipPath = bind(group.removeClipPath, group);
  38681. group.setClipPath(this._createClipPath(
  38682. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  38683. ));
  38684. }
  38685. else {
  38686. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  38687. group.removeClipPath();
  38688. }
  38689. this._data = data;
  38690. },
  38691. dispose: function () {},
  38692. _createClipPath: function (
  38693. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  38694. ) {
  38695. var clipPath = new Sector({
  38696. shape: {
  38697. cx: cx,
  38698. cy: cy,
  38699. r0: 0,
  38700. r: r,
  38701. startAngle: startAngle,
  38702. endAngle: startAngle,
  38703. clockwise: clockwise
  38704. }
  38705. });
  38706. var initOrUpdate = isFirstRender ? initProps : updateProps;
  38707. initOrUpdate(clipPath, {
  38708. shape: {
  38709. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  38710. }
  38711. }, seriesModel, cb);
  38712. return clipPath;
  38713. },
  38714. /**
  38715. * @implement
  38716. */
  38717. containPoint: function (point, seriesModel) {
  38718. var data = seriesModel.getData();
  38719. var itemLayout = data.getItemLayout(0);
  38720. if (itemLayout) {
  38721. var dx = point[0] - itemLayout.cx;
  38722. var dy = point[1] - itemLayout.cy;
  38723. var radius = Math.sqrt(dx * dx + dy * dy);
  38724. return radius <= itemLayout.r && radius >= itemLayout.r0;
  38725. }
  38726. }
  38727. });
  38728. /*
  38729. * Licensed to the Apache Software Foundation (ASF) under one
  38730. * or more contributor license agreements. See the NOTICE file
  38731. * distributed with this work for additional information
  38732. * regarding copyright ownership. The ASF licenses this file
  38733. * to you under the Apache License, Version 2.0 (the
  38734. * "License"); you may not use this file except in compliance
  38735. * with the License. You may obtain a copy of the License at
  38736. *
  38737. * http://www.apache.org/licenses/LICENSE-2.0
  38738. *
  38739. * Unless required by applicable law or agreed to in writing,
  38740. * software distributed under the License is distributed on an
  38741. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38742. * KIND, either express or implied. See the License for the
  38743. * specific language governing permissions and limitations
  38744. * under the License.
  38745. */
  38746. var createDataSelectAction = function (seriesType, actionInfos) {
  38747. each$1(actionInfos, function (actionInfo) {
  38748. actionInfo.update = 'updateView';
  38749. /**
  38750. * @payload
  38751. * @property {string} seriesName
  38752. * @property {string} name
  38753. */
  38754. registerAction(actionInfo, function (payload, ecModel) {
  38755. var selected = {};
  38756. ecModel.eachComponent(
  38757. {mainType: 'series', subType: seriesType, query: payload},
  38758. function (seriesModel) {
  38759. if (seriesModel[actionInfo.method]) {
  38760. seriesModel[actionInfo.method](
  38761. payload.name,
  38762. payload.dataIndex
  38763. );
  38764. }
  38765. var data = seriesModel.getData();
  38766. // Create selected map
  38767. data.each(function (idx) {
  38768. var name = data.getName(idx);
  38769. selected[name] = seriesModel.isSelected(name)
  38770. || false;
  38771. });
  38772. }
  38773. );
  38774. return {
  38775. name: payload.name,
  38776. selected: selected,
  38777. seriesId: payload.seriesId
  38778. };
  38779. });
  38780. });
  38781. };
  38782. /*
  38783. * Licensed to the Apache Software Foundation (ASF) under one
  38784. * or more contributor license agreements. See the NOTICE file
  38785. * distributed with this work for additional information
  38786. * regarding copyright ownership. The ASF licenses this file
  38787. * to you under the Apache License, Version 2.0 (the
  38788. * "License"); you may not use this file except in compliance
  38789. * with the License. You may obtain a copy of the License at
  38790. *
  38791. * http://www.apache.org/licenses/LICENSE-2.0
  38792. *
  38793. * Unless required by applicable law or agreed to in writing,
  38794. * software distributed under the License is distributed on an
  38795. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38796. * KIND, either express or implied. See the License for the
  38797. * specific language governing permissions and limitations
  38798. * under the License.
  38799. */
  38800. // Pick color from palette for each data item.
  38801. // Applicable for charts that require applying color palette
  38802. // in data level (like pie, funnel, chord).
  38803. var dataColor = function (seriesType) {
  38804. return {
  38805. getTargetSeries: function (ecModel) {
  38806. // Pie and funnel may use diferrent scope
  38807. var paletteScope = {};
  38808. var seiresModelMap = createHashMap();
  38809. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  38810. seriesModel.__paletteScope = paletteScope;
  38811. seiresModelMap.set(seriesModel.uid, seriesModel);
  38812. });
  38813. return seiresModelMap;
  38814. },
  38815. reset: function (seriesModel, ecModel) {
  38816. var dataAll = seriesModel.getRawData();
  38817. var idxMap = {};
  38818. var data = seriesModel.getData();
  38819. data.each(function (idx) {
  38820. var rawIdx = data.getRawIndex(idx);
  38821. idxMap[rawIdx] = idx;
  38822. });
  38823. dataAll.each(function (rawIdx) {
  38824. var filteredIdx = idxMap[rawIdx];
  38825. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  38826. var singleDataColor = filteredIdx != null
  38827. && data.getItemVisual(filteredIdx, 'color', true);
  38828. var singleDataBorderColor = filteredIdx != null
  38829. && data.getItemVisual(filteredIdx, 'borderColor', true);
  38830. var itemModel;
  38831. if (!singleDataColor || !singleDataBorderColor) {
  38832. // FIXME Performance
  38833. itemModel = dataAll.getItemModel(rawIdx);
  38834. }
  38835. if (!singleDataColor) {
  38836. var color = itemModel.get('itemStyle.color')
  38837. || seriesModel.getColorFromPalette(
  38838. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  38839. dataAll.count()
  38840. );
  38841. // Data is not filtered
  38842. if (filteredIdx != null) {
  38843. data.setItemVisual(filteredIdx, 'color', color);
  38844. }
  38845. }
  38846. if (!singleDataBorderColor) {
  38847. var borderColor = itemModel.get('itemStyle.borderColor');
  38848. // Data is not filtered
  38849. if (filteredIdx != null) {
  38850. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  38851. }
  38852. }
  38853. });
  38854. }
  38855. };
  38856. };
  38857. /*
  38858. * Licensed to the Apache Software Foundation (ASF) under one
  38859. * or more contributor license agreements. See the NOTICE file
  38860. * distributed with this work for additional information
  38861. * regarding copyright ownership. The ASF licenses this file
  38862. * to you under the Apache License, Version 2.0 (the
  38863. * "License"); you may not use this file except in compliance
  38864. * with the License. You may obtain a copy of the License at
  38865. *
  38866. * http://www.apache.org/licenses/LICENSE-2.0
  38867. *
  38868. * Unless required by applicable law or agreed to in writing,
  38869. * software distributed under the License is distributed on an
  38870. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38871. * KIND, either express or implied. See the License for the
  38872. * specific language governing permissions and limitations
  38873. * under the License.
  38874. */
  38875. // FIXME emphasis label position is not same with normal label position
  38876. var RADIAN$1 = Math.PI / 180;
  38877. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  38878. list.sort(function (a, b) {
  38879. return a.y - b.y;
  38880. });
  38881. function shiftDown(start, end, delta, dir) {
  38882. for (var j = start; j < end; j++) {
  38883. if (list[j].y + delta > viewTop + viewHeight) {
  38884. break;
  38885. }
  38886. list[j].y += delta;
  38887. if (j > start
  38888. && j + 1 < end
  38889. && list[j + 1].y > list[j].y + list[j].height
  38890. ) {
  38891. shiftUp(j, delta / 2);
  38892. return;
  38893. }
  38894. }
  38895. shiftUp(end - 1, delta / 2);
  38896. }
  38897. function shiftUp(end, delta) {
  38898. for (var j = end; j >= 0; j--) {
  38899. if (list[j].y - delta < viewTop) {
  38900. break;
  38901. }
  38902. list[j].y -= delta;
  38903. if (j > 0
  38904. && list[j].y > list[j - 1].y + list[j - 1].height
  38905. ) {
  38906. break;
  38907. }
  38908. }
  38909. }
  38910. function changeX(list, isDownList, cx, cy, r, dir) {
  38911. var lastDeltaX = dir > 0
  38912. ? isDownList // right-side
  38913. ? Number.MAX_VALUE // down
  38914. : 0 // up
  38915. : isDownList // left-side
  38916. ? Number.MAX_VALUE // down
  38917. : 0; // up
  38918. for (var i = 0, l = list.length; i < l; i++) {
  38919. if (list[i].labelAlignTo !== 'none') {
  38920. continue;
  38921. }
  38922. var deltaY = Math.abs(list[i].y - cy);
  38923. var length = list[i].len;
  38924. var length2 = list[i].len2;
  38925. var deltaX = (deltaY < r + length)
  38926. ? Math.sqrt(
  38927. (r + length + length2) * (r + length + length2)
  38928. - deltaY * deltaY
  38929. )
  38930. : Math.abs(list[i].x - cx);
  38931. if (isDownList && deltaX >= lastDeltaX) {
  38932. // right-down, left-down
  38933. deltaX = lastDeltaX - 10;
  38934. }
  38935. if (!isDownList && deltaX <= lastDeltaX) {
  38936. // right-up, left-up
  38937. deltaX = lastDeltaX + 10;
  38938. }
  38939. list[i].x = cx + deltaX * dir;
  38940. lastDeltaX = deltaX;
  38941. }
  38942. }
  38943. var lastY = 0;
  38944. var delta;
  38945. var len = list.length;
  38946. var upList = [];
  38947. var downList = [];
  38948. for (var i = 0; i < len; i++) {
  38949. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  38950. var dx = list[i].x - farthestX;
  38951. list[i].linePoints[1][0] += dx;
  38952. list[i].x = farthestX;
  38953. }
  38954. delta = list[i].y - lastY;
  38955. if (delta < 0) {
  38956. shiftDown(i, len, -delta, dir);
  38957. }
  38958. lastY = list[i].y + list[i].height;
  38959. }
  38960. if (viewHeight - lastY < 0) {
  38961. shiftUp(len - 1, lastY - viewHeight);
  38962. }
  38963. for (var i = 0; i < len; i++) {
  38964. if (list[i].y >= cy) {
  38965. downList.push(list[i]);
  38966. }
  38967. else {
  38968. upList.push(list[i]);
  38969. }
  38970. }
  38971. changeX(upList, false, cx, cy, r, dir);
  38972. changeX(downList, true, cx, cy, r, dir);
  38973. }
  38974. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  38975. var leftList = [];
  38976. var rightList = [];
  38977. var leftmostX = Number.MAX_VALUE;
  38978. var rightmostX = -Number.MAX_VALUE;
  38979. for (var i = 0; i < labelLayoutList.length; i++) {
  38980. if (isPositionCenter(labelLayoutList[i])) {
  38981. continue;
  38982. }
  38983. if (labelLayoutList[i].x < cx) {
  38984. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  38985. leftList.push(labelLayoutList[i]);
  38986. }
  38987. else {
  38988. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  38989. rightList.push(labelLayoutList[i]);
  38990. }
  38991. }
  38992. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  38993. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  38994. for (var i = 0; i < labelLayoutList.length; i++) {
  38995. var layout = labelLayoutList[i];
  38996. if (isPositionCenter(layout)) {
  38997. continue;
  38998. }
  38999. var linePoints = layout.linePoints;
  39000. if (linePoints) {
  39001. var isAlignToEdge = layout.labelAlignTo === 'edge';
  39002. var realTextWidth = layout.textRect.width;
  39003. var targetTextWidth;
  39004. if (isAlignToEdge) {
  39005. if (layout.x < cx) {
  39006. targetTextWidth = linePoints[2][0] - layout.labelDistance
  39007. - viewLeft - layout.labelMargin;
  39008. }
  39009. else {
  39010. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  39011. - linePoints[2][0] - layout.labelDistance;
  39012. }
  39013. }
  39014. else {
  39015. if (layout.x < cx) {
  39016. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  39017. }
  39018. else {
  39019. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  39020. }
  39021. }
  39022. if (targetTextWidth < layout.textRect.width) {
  39023. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  39024. if (layout.labelAlignTo === 'edge') {
  39025. realTextWidth = getWidth(layout.text, layout.font);
  39026. }
  39027. }
  39028. var dist = linePoints[1][0] - linePoints[2][0];
  39029. if (isAlignToEdge) {
  39030. if (layout.x < cx) {
  39031. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  39032. }
  39033. else {
  39034. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  39035. - realTextWidth - layout.labelDistance;
  39036. }
  39037. }
  39038. else {
  39039. if (layout.x < cx) {
  39040. linePoints[2][0] = layout.x + layout.labelDistance;
  39041. }
  39042. else {
  39043. linePoints[2][0] = layout.x - layout.labelDistance;
  39044. }
  39045. linePoints[1][0] = linePoints[2][0] + dist;
  39046. }
  39047. linePoints[1][1] = linePoints[2][1] = layout.y;
  39048. }
  39049. }
  39050. }
  39051. function isPositionCenter(layout) {
  39052. // Not change x for center label
  39053. return layout.position === 'center';
  39054. }
  39055. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39056. var data = seriesModel.getData();
  39057. var labelLayoutList = [];
  39058. var cx;
  39059. var cy;
  39060. var hasLabelRotate = false;
  39061. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  39062. data.each(function (idx) {
  39063. var layout = data.getItemLayout(idx);
  39064. var itemModel = data.getItemModel(idx);
  39065. var labelModel = itemModel.getModel('label');
  39066. // Use position in normal or emphasis
  39067. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  39068. var labelDistance = labelModel.get('distanceToLabelLine');
  39069. var labelAlignTo = labelModel.get('alignTo');
  39070. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  39071. var bleedMargin = labelModel.get('bleedMargin');
  39072. var font = labelModel.getFont();
  39073. var labelLineModel = itemModel.getModel('labelLine');
  39074. var labelLineLen = labelLineModel.get('length');
  39075. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  39076. var labelLineLen2 = labelLineModel.get('length2');
  39077. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  39078. if (layout.angle < minShowLabelRadian) {
  39079. return;
  39080. }
  39081. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  39082. var dx = Math.cos(midAngle);
  39083. var dy = Math.sin(midAngle);
  39084. var textX;
  39085. var textY;
  39086. var linePoints;
  39087. var textAlign;
  39088. cx = layout.cx;
  39089. cy = layout.cy;
  39090. var text = seriesModel.getFormattedLabel(idx, 'normal')
  39091. || data.getName(idx);
  39092. var textRect = getBoundingRect(
  39093. text, font, textAlign, 'top'
  39094. );
  39095. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  39096. if (labelPosition === 'center') {
  39097. textX = layout.cx;
  39098. textY = layout.cy;
  39099. textAlign = 'center';
  39100. }
  39101. else {
  39102. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  39103. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  39104. textX = x1 + dx * 3;
  39105. textY = y1 + dy * 3;
  39106. if (!isLabelInside) {
  39107. // For roseType
  39108. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  39109. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  39110. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  39111. var y3 = y2;
  39112. if (labelAlignTo === 'edge') {
  39113. // Adjust textX because text align of edge is opposite
  39114. textX = dx < 0
  39115. ? viewLeft + labelMargin
  39116. : viewLeft + viewWidth - labelMargin;
  39117. }
  39118. else {
  39119. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  39120. }
  39121. textY = y3;
  39122. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  39123. }
  39124. textAlign = isLabelInside
  39125. ? 'center'
  39126. : (labelAlignTo === 'edge'
  39127. ? (dx > 0 ? 'right' : 'left')
  39128. : (dx > 0 ? 'left' : 'right'));
  39129. }
  39130. var labelRotate;
  39131. var rotate = labelModel.get('rotate');
  39132. if (typeof rotate === 'number') {
  39133. labelRotate = rotate * (Math.PI / 180);
  39134. }
  39135. else {
  39136. labelRotate = rotate
  39137. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  39138. : 0;
  39139. }
  39140. hasLabelRotate = !!labelRotate;
  39141. layout.label = {
  39142. x: textX,
  39143. y: textY,
  39144. position: labelPosition,
  39145. height: textRect.height,
  39146. len: labelLineLen,
  39147. len2: labelLineLen2,
  39148. linePoints: linePoints,
  39149. textAlign: textAlign,
  39150. verticalAlign: 'middle',
  39151. rotation: labelRotate,
  39152. inside: isLabelInside,
  39153. labelDistance: labelDistance,
  39154. labelAlignTo: labelAlignTo,
  39155. labelMargin:labelMargin,
  39156. bleedMargin: bleedMargin,
  39157. textRect: textRect,
  39158. text: text,
  39159. font: font
  39160. };
  39161. // Not layout the inside label
  39162. if (!isLabelInside) {
  39163. labelLayoutList.push(layout.label);
  39164. }
  39165. });
  39166. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  39167. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  39168. }
  39169. };
  39170. /*
  39171. * Licensed to the Apache Software Foundation (ASF) under one
  39172. * or more contributor license agreements. See the NOTICE file
  39173. * distributed with this work for additional information
  39174. * regarding copyright ownership. The ASF licenses this file
  39175. * to you under the Apache License, Version 2.0 (the
  39176. * "License"); you may not use this file except in compliance
  39177. * with the License. You may obtain a copy of the License at
  39178. *
  39179. * http://www.apache.org/licenses/LICENSE-2.0
  39180. *
  39181. * Unless required by applicable law or agreed to in writing,
  39182. * software distributed under the License is distributed on an
  39183. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39184. * KIND, either express or implied. See the License for the
  39185. * specific language governing permissions and limitations
  39186. * under the License.
  39187. */
  39188. var PI2$4 = Math.PI * 2;
  39189. var RADIAN = Math.PI / 180;
  39190. function getViewRect(seriesModel, api) {
  39191. return getLayoutRect(
  39192. seriesModel.getBoxLayoutParams(), {
  39193. width: api.getWidth(),
  39194. height: api.getHeight()
  39195. }
  39196. );
  39197. }
  39198. var pieLayout = function (seriesType, ecModel, api, payload) {
  39199. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39200. var data = seriesModel.getData();
  39201. var valueDim = data.mapDimension('value');
  39202. var viewRect = getViewRect(seriesModel, api);
  39203. var center = seriesModel.get('center');
  39204. var radius = seriesModel.get('radius');
  39205. if (!isArray(radius)) {
  39206. radius = [0, radius];
  39207. }
  39208. if (!isArray(center)) {
  39209. center = [center, center];
  39210. }
  39211. var width = parsePercent$1(viewRect.width, api.getWidth());
  39212. var height = parsePercent$1(viewRect.height, api.getHeight());
  39213. var size = Math.min(width, height);
  39214. var cx = parsePercent$1(center[0], width) + viewRect.x;
  39215. var cy = parsePercent$1(center[1], height) + viewRect.y;
  39216. var r0 = parsePercent$1(radius[0], size / 2);
  39217. var r = parsePercent$1(radius[1], size / 2);
  39218. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  39219. var minAngle = seriesModel.get('minAngle') * RADIAN;
  39220. var validDataCount = 0;
  39221. data.each(valueDim, function (value) {
  39222. !isNaN(value) && validDataCount++;
  39223. });
  39224. var sum = data.getSum(valueDim);
  39225. // Sum may be 0
  39226. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  39227. var clockwise = seriesModel.get('clockwise');
  39228. var roseType = seriesModel.get('roseType');
  39229. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  39230. // [0...max]
  39231. var extent = data.getDataExtent(valueDim);
  39232. extent[0] = 0;
  39233. // In the case some sector angle is smaller than minAngle
  39234. var restAngle = PI2$4;
  39235. var valueSumLargerThanMinAngle = 0;
  39236. var currentAngle = startAngle;
  39237. var dir = clockwise ? 1 : -1;
  39238. data.each(valueDim, function (value, idx) {
  39239. var angle;
  39240. if (isNaN(value)) {
  39241. data.setItemLayout(idx, {
  39242. angle: NaN,
  39243. startAngle: NaN,
  39244. endAngle: NaN,
  39245. clockwise: clockwise,
  39246. cx: cx,
  39247. cy: cy,
  39248. r0: r0,
  39249. r: roseType
  39250. ? NaN
  39251. : r,
  39252. viewRect: viewRect
  39253. });
  39254. return;
  39255. }
  39256. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  39257. if (roseType !== 'area') {
  39258. angle = (sum === 0 && stillShowZeroSum)
  39259. ? unitRadian : (value * unitRadian);
  39260. }
  39261. else {
  39262. angle = PI2$4 / validDataCount;
  39263. }
  39264. if (angle < minAngle) {
  39265. angle = minAngle;
  39266. restAngle -= minAngle;
  39267. }
  39268. else {
  39269. valueSumLargerThanMinAngle += value;
  39270. }
  39271. var endAngle = currentAngle + dir * angle;
  39272. data.setItemLayout(idx, {
  39273. angle: angle,
  39274. startAngle: currentAngle,
  39275. endAngle: endAngle,
  39276. clockwise: clockwise,
  39277. cx: cx,
  39278. cy: cy,
  39279. r0: r0,
  39280. r: roseType
  39281. ? linearMap(value, extent, [r0, r])
  39282. : r,
  39283. viewRect: viewRect
  39284. });
  39285. currentAngle = endAngle;
  39286. });
  39287. // Some sector is constrained by minAngle
  39288. // Rest sectors needs recalculate angle
  39289. if (restAngle < PI2$4 && validDataCount) {
  39290. // Average the angle if rest angle is not enough after all angles is
  39291. // Constrained by minAngle
  39292. if (restAngle <= 1e-3) {
  39293. var angle = PI2$4 / validDataCount;
  39294. data.each(valueDim, function (value, idx) {
  39295. if (!isNaN(value)) {
  39296. var layout = data.getItemLayout(idx);
  39297. layout.angle = angle;
  39298. layout.startAngle = startAngle + dir * idx * angle;
  39299. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  39300. }
  39301. });
  39302. }
  39303. else {
  39304. unitRadian = restAngle / valueSumLargerThanMinAngle;
  39305. currentAngle = startAngle;
  39306. data.each(valueDim, function (value, idx) {
  39307. if (!isNaN(value)) {
  39308. var layout = data.getItemLayout(idx);
  39309. var angle = layout.angle === minAngle
  39310. ? minAngle : value * unitRadian;
  39311. layout.startAngle = currentAngle;
  39312. layout.endAngle = currentAngle + dir * angle;
  39313. currentAngle += dir * angle;
  39314. }
  39315. });
  39316. }
  39317. }
  39318. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  39319. });
  39320. };
  39321. /*
  39322. * Licensed to the Apache Software Foundation (ASF) under one
  39323. * or more contributor license agreements. See the NOTICE file
  39324. * distributed with this work for additional information
  39325. * regarding copyright ownership. The ASF licenses this file
  39326. * to you under the Apache License, Version 2.0 (the
  39327. * "License"); you may not use this file except in compliance
  39328. * with the License. You may obtain a copy of the License at
  39329. *
  39330. * http://www.apache.org/licenses/LICENSE-2.0
  39331. *
  39332. * Unless required by applicable law or agreed to in writing,
  39333. * software distributed under the License is distributed on an
  39334. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39335. * KIND, either express or implied. See the License for the
  39336. * specific language governing permissions and limitations
  39337. * under the License.
  39338. */
  39339. var dataFilter = function (seriesType) {
  39340. return {
  39341. seriesType: seriesType,
  39342. reset: function (seriesModel, ecModel) {
  39343. var legendModels = ecModel.findComponents({
  39344. mainType: 'legend'
  39345. });
  39346. if (!legendModels || !legendModels.length) {
  39347. return;
  39348. }
  39349. var data = seriesModel.getData();
  39350. data.filterSelf(function (idx) {
  39351. var name = data.getName(idx);
  39352. // If in any legend component the status is not selected.
  39353. for (var i = 0; i < legendModels.length; i++) {
  39354. if (!legendModels[i].isSelected(name)) {
  39355. return false;
  39356. }
  39357. }
  39358. return true;
  39359. });
  39360. }
  39361. };
  39362. };
  39363. /*
  39364. * Licensed to the Apache Software Foundation (ASF) under one
  39365. * or more contributor license agreements. See the NOTICE file
  39366. * distributed with this work for additional information
  39367. * regarding copyright ownership. The ASF licenses this file
  39368. * to you under the Apache License, Version 2.0 (the
  39369. * "License"); you may not use this file except in compliance
  39370. * with the License. You may obtain a copy of the License at
  39371. *
  39372. * http://www.apache.org/licenses/LICENSE-2.0
  39373. *
  39374. * Unless required by applicable law or agreed to in writing,
  39375. * software distributed under the License is distributed on an
  39376. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39377. * KIND, either express or implied. See the License for the
  39378. * specific language governing permissions and limitations
  39379. * under the License.
  39380. */
  39381. createDataSelectAction('pie', [{
  39382. type: 'pieToggleSelect',
  39383. event: 'pieselectchanged',
  39384. method: 'toggleSelected'
  39385. }, {
  39386. type: 'pieSelect',
  39387. event: 'pieselected',
  39388. method: 'select'
  39389. }, {
  39390. type: 'pieUnSelect',
  39391. event: 'pieunselected',
  39392. method: 'unSelect'
  39393. }]);
  39394. registerVisual(dataColor('pie'));
  39395. registerLayout(curry(pieLayout, 'pie'));
  39396. registerProcessor(dataFilter('pie'));
  39397. /*
  39398. * Licensed to the Apache Software Foundation (ASF) under one
  39399. * or more contributor license agreements. See the NOTICE file
  39400. * distributed with this work for additional information
  39401. * regarding copyright ownership. The ASF licenses this file
  39402. * to you under the Apache License, Version 2.0 (the
  39403. * "License"); you may not use this file except in compliance
  39404. * with the License. You may obtain a copy of the License at
  39405. *
  39406. * http://www.apache.org/licenses/LICENSE-2.0
  39407. *
  39408. * Unless required by applicable law or agreed to in writing,
  39409. * software distributed under the License is distributed on an
  39410. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39411. * KIND, either express or implied. See the License for the
  39412. * specific language governing permissions and limitations
  39413. * under the License.
  39414. */
  39415. SeriesModel.extend({
  39416. type: 'series.scatter',
  39417. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  39418. getInitialData: function (option, ecModel) {
  39419. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  39420. },
  39421. brushSelector: 'point',
  39422. getProgressive: function () {
  39423. var progressive = this.option.progressive;
  39424. if (progressive == null) {
  39425. // PENDING
  39426. return this.option.large ? 5e3 : this.get('progressive');
  39427. }
  39428. return progressive;
  39429. },
  39430. getProgressiveThreshold: function () {
  39431. var progressiveThreshold = this.option.progressiveThreshold;
  39432. if (progressiveThreshold == null) {
  39433. // PENDING
  39434. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  39435. }
  39436. return progressiveThreshold;
  39437. },
  39438. defaultOption: {
  39439. coordinateSystem: 'cartesian2d',
  39440. zlevel: 0,
  39441. z: 2,
  39442. legendHoverLink: true,
  39443. hoverAnimation: true,
  39444. // Cartesian coordinate system
  39445. // xAxisIndex: 0,
  39446. // yAxisIndex: 0,
  39447. // Polar coordinate system
  39448. // polarIndex: 0,
  39449. // Geo coordinate system
  39450. // geoIndex: 0,
  39451. // symbol: null, // 图形类型
  39452. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  39453. // symbolRotate: null, // 图形旋转控制
  39454. large: false,
  39455. // Available when large is true
  39456. largeThreshold: 2000,
  39457. // cursor: null,
  39458. // label: {
  39459. // show: false
  39460. // distance: 5,
  39461. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  39462. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  39463. // 'inside'|'left'|'right'|'top'|'bottom'
  39464. // 默认使用全局文本样式,详见TEXTSTYLE
  39465. // },
  39466. itemStyle: {
  39467. opacity: 0.8
  39468. // color: 各异
  39469. },
  39470. // If clip the overflow graphics
  39471. // Works on cartesian / polar series
  39472. clip: true
  39473. // progressive: null
  39474. }
  39475. });
  39476. /*
  39477. * Licensed to the Apache Software Foundation (ASF) under one
  39478. * or more contributor license agreements. See the NOTICE file
  39479. * distributed with this work for additional information
  39480. * regarding copyright ownership. The ASF licenses this file
  39481. * to you under the Apache License, Version 2.0 (the
  39482. * "License"); you may not use this file except in compliance
  39483. * with the License. You may obtain a copy of the License at
  39484. *
  39485. * http://www.apache.org/licenses/LICENSE-2.0
  39486. *
  39487. * Unless required by applicable law or agreed to in writing,
  39488. * software distributed under the License is distributed on an
  39489. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39490. * KIND, either express or implied. See the License for the
  39491. * specific language governing permissions and limitations
  39492. * under the License.
  39493. */
  39494. /* global Float32Array */
  39495. // TODO Batch by color
  39496. var BOOST_SIZE_THRESHOLD = 4;
  39497. var LargeSymbolPath = extendShape({
  39498. shape: {
  39499. points: null
  39500. },
  39501. symbolProxy: null,
  39502. softClipShape: null,
  39503. buildPath: function (path, shape) {
  39504. var points = shape.points;
  39505. var size = shape.size;
  39506. var symbolProxy = this.symbolProxy;
  39507. var symbolProxyShape = symbolProxy.shape;
  39508. var ctx = path.getContext ? path.getContext() : path;
  39509. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  39510. // Do draw in afterBrush.
  39511. if (canBoost) {
  39512. return;
  39513. }
  39514. for (var i = 0; i < points.length;) {
  39515. var x = points[i++];
  39516. var y = points[i++];
  39517. if (isNaN(x) || isNaN(y)) {
  39518. continue;
  39519. }
  39520. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39521. continue;
  39522. }
  39523. symbolProxyShape.x = x - size[0] / 2;
  39524. symbolProxyShape.y = y - size[1] / 2;
  39525. symbolProxyShape.width = size[0];
  39526. symbolProxyShape.height = size[1];
  39527. symbolProxy.buildPath(path, symbolProxyShape, true);
  39528. }
  39529. },
  39530. afterBrush: function (ctx) {
  39531. var shape = this.shape;
  39532. var points = shape.points;
  39533. var size = shape.size;
  39534. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  39535. if (!canBoost) {
  39536. return;
  39537. }
  39538. this.setTransform(ctx);
  39539. // PENDING If style or other canvas status changed?
  39540. for (var i = 0; i < points.length;) {
  39541. var x = points[i++];
  39542. var y = points[i++];
  39543. if (isNaN(x) || isNaN(y)) {
  39544. continue;
  39545. }
  39546. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39547. continue;
  39548. }
  39549. // fillRect is faster than building a rect path and draw.
  39550. // And it support light globalCompositeOperation.
  39551. ctx.fillRect(
  39552. x - size[0] / 2, y - size[1] / 2,
  39553. size[0], size[1]
  39554. );
  39555. }
  39556. this.restoreTransform(ctx);
  39557. },
  39558. findDataIndex: function (x, y) {
  39559. // TODO ???
  39560. // Consider transform
  39561. var shape = this.shape;
  39562. var points = shape.points;
  39563. var size = shape.size;
  39564. var w = Math.max(size[0], 4);
  39565. var h = Math.max(size[1], 4);
  39566. // Not consider transform
  39567. // Treat each element as a rect
  39568. // top down traverse
  39569. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  39570. var i = idx * 2;
  39571. var x0 = points[i] - w / 2;
  39572. var y0 = points[i + 1] - h / 2;
  39573. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  39574. return idx;
  39575. }
  39576. }
  39577. return -1;
  39578. }
  39579. });
  39580. function LargeSymbolDraw() {
  39581. this.group = new Group();
  39582. }
  39583. var largeSymbolProto = LargeSymbolDraw.prototype;
  39584. largeSymbolProto.isPersistent = function () {
  39585. return !this._incremental;
  39586. };
  39587. /**
  39588. * Update symbols draw by new data
  39589. * @param {module:echarts/data/List} data
  39590. * @param {Object} opt
  39591. * @param {Object} [opt.clipShape]
  39592. */
  39593. largeSymbolProto.updateData = function (data, opt) {
  39594. this.group.removeAll();
  39595. var symbolEl = new LargeSymbolPath({
  39596. rectHover: true,
  39597. cursor: 'default'
  39598. });
  39599. symbolEl.setShape({
  39600. points: data.getLayout('symbolPoints')
  39601. });
  39602. this._setCommon(symbolEl, data, false, opt);
  39603. this.group.add(symbolEl);
  39604. this._incremental = null;
  39605. };
  39606. largeSymbolProto.updateLayout = function (data) {
  39607. if (this._incremental) {
  39608. return;
  39609. }
  39610. var points = data.getLayout('symbolPoints');
  39611. this.group.eachChild(function (child) {
  39612. if (child.startIndex != null) {
  39613. var len = (child.endIndex - child.startIndex) * 2;
  39614. var byteOffset = child.startIndex * 4 * 2;
  39615. points = new Float32Array(points.buffer, byteOffset, len);
  39616. }
  39617. child.setShape('points', points);
  39618. });
  39619. };
  39620. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  39621. this.group.removeAll();
  39622. this._clearIncremental();
  39623. // Only use incremental displayables when data amount is larger than 2 million.
  39624. // PENDING Incremental data?
  39625. if (data.count() > 2e6) {
  39626. if (!this._incremental) {
  39627. this._incremental = new IncrementalDisplayble({
  39628. silent: true
  39629. });
  39630. }
  39631. this.group.add(this._incremental);
  39632. }
  39633. else {
  39634. this._incremental = null;
  39635. }
  39636. };
  39637. largeSymbolProto.incrementalUpdate = function (taskParams, data, opt) {
  39638. var symbolEl;
  39639. if (this._incremental) {
  39640. symbolEl = new LargeSymbolPath();
  39641. this._incremental.addDisplayable(symbolEl, true);
  39642. }
  39643. else {
  39644. symbolEl = new LargeSymbolPath({
  39645. rectHover: true,
  39646. cursor: 'default',
  39647. startIndex: taskParams.start,
  39648. endIndex: taskParams.end
  39649. });
  39650. symbolEl.incremental = true;
  39651. this.group.add(symbolEl);
  39652. }
  39653. symbolEl.setShape({
  39654. points: data.getLayout('symbolPoints')
  39655. });
  39656. this._setCommon(symbolEl, data, !!this._incremental, opt);
  39657. };
  39658. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental, opt) {
  39659. var hostModel = data.hostModel;
  39660. opt = opt || {};
  39661. // TODO
  39662. // if (data.hasItemVisual.symbolSize) {
  39663. // // TODO typed array?
  39664. // symbolEl.setShape('sizes', data.mapArray(
  39665. // function (idx) {
  39666. // var size = data.getItemVisual(idx, 'symbolSize');
  39667. // return (size instanceof Array) ? size : [size, size];
  39668. // }
  39669. // ));
  39670. // }
  39671. // else {
  39672. var size = data.getVisual('symbolSize');
  39673. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  39674. // }
  39675. symbolEl.softClipShape = opt.clipShape || null;
  39676. // Create symbolProxy to build path for each data
  39677. symbolEl.symbolProxy = createSymbol(
  39678. data.getVisual('symbol'), 0, 0, 0, 0
  39679. );
  39680. // Use symbolProxy setColor method
  39681. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  39682. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  39683. symbolEl.useStyle(
  39684. // Draw shadow when doing fillRect is extremely slow.
  39685. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  39686. );
  39687. var visualColor = data.getVisual('color');
  39688. if (visualColor) {
  39689. symbolEl.setColor(visualColor);
  39690. }
  39691. if (!isIncremental) {
  39692. // Enable tooltip
  39693. // PENDING May have performance issue when path is extremely large
  39694. symbolEl.seriesIndex = hostModel.seriesIndex;
  39695. symbolEl.on('mousemove', function (e) {
  39696. symbolEl.dataIndex = null;
  39697. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  39698. if (dataIndex >= 0) {
  39699. // Provide dataIndex for tooltip
  39700. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  39701. }
  39702. });
  39703. }
  39704. };
  39705. largeSymbolProto.remove = function () {
  39706. this._clearIncremental();
  39707. this._incremental = null;
  39708. this.group.removeAll();
  39709. };
  39710. largeSymbolProto._clearIncremental = function () {
  39711. var incremental = this._incremental;
  39712. if (incremental) {
  39713. incremental.clearDisplaybles();
  39714. }
  39715. };
  39716. /*
  39717. * Licensed to the Apache Software Foundation (ASF) under one
  39718. * or more contributor license agreements. See the NOTICE file
  39719. * distributed with this work for additional information
  39720. * regarding copyright ownership. The ASF licenses this file
  39721. * to you under the Apache License, Version 2.0 (the
  39722. * "License"); you may not use this file except in compliance
  39723. * with the License. You may obtain a copy of the License at
  39724. *
  39725. * http://www.apache.org/licenses/LICENSE-2.0
  39726. *
  39727. * Unless required by applicable law or agreed to in writing,
  39728. * software distributed under the License is distributed on an
  39729. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39730. * KIND, either express or implied. See the License for the
  39731. * specific language governing permissions and limitations
  39732. * under the License.
  39733. */
  39734. extendChartView({
  39735. type: 'scatter',
  39736. render: function (seriesModel, ecModel, api) {
  39737. var data = seriesModel.getData();
  39738. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39739. symbolDraw.updateData(data, {
  39740. // TODO
  39741. // If this parameter should be a shape or a bounding volume
  39742. // shape will be more general.
  39743. // But bounding volume like bounding rect will be much faster in the contain calculation
  39744. clipShape: this._getClipShape(seriesModel)
  39745. });
  39746. this._finished = true;
  39747. },
  39748. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  39749. var data = seriesModel.getData();
  39750. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39751. symbolDraw.incrementalPrepareUpdate(data);
  39752. this._finished = false;
  39753. },
  39754. incrementalRender: function (taskParams, seriesModel, ecModel) {
  39755. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  39756. clipShape: this._getClipShape(seriesModel)
  39757. });
  39758. this._finished = taskParams.end === seriesModel.getData().count();
  39759. },
  39760. updateTransform: function (seriesModel, ecModel, api) {
  39761. var data = seriesModel.getData();
  39762. // Must mark group dirty and make sure the incremental layer will be cleared
  39763. // PENDING
  39764. this.group.dirty();
  39765. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  39766. return {
  39767. update: true
  39768. };
  39769. }
  39770. else {
  39771. var res = pointsLayout().reset(seriesModel);
  39772. if (res.progress) {
  39773. res.progress({ start: 0, end: data.count() }, data);
  39774. }
  39775. this._symbolDraw.updateLayout(data);
  39776. }
  39777. },
  39778. _getClipShape: function (seriesModel) {
  39779. var coordSys = seriesModel.coordinateSystem;
  39780. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  39781. return seriesModel.get('clip', true) ? clipArea : null;
  39782. },
  39783. _updateSymbolDraw: function (data, seriesModel) {
  39784. var symbolDraw = this._symbolDraw;
  39785. var pipelineContext = seriesModel.pipelineContext;
  39786. var isLargeDraw = pipelineContext.large;
  39787. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  39788. symbolDraw && symbolDraw.remove();
  39789. symbolDraw = this._symbolDraw = isLargeDraw
  39790. ? new LargeSymbolDraw()
  39791. : new SymbolDraw();
  39792. this._isLargeDraw = isLargeDraw;
  39793. this.group.removeAll();
  39794. }
  39795. this.group.add(symbolDraw.group);
  39796. return symbolDraw;
  39797. },
  39798. remove: function (ecModel, api) {
  39799. this._symbolDraw && this._symbolDraw.remove(true);
  39800. this._symbolDraw = null;
  39801. },
  39802. dispose: function () {}
  39803. });
  39804. /*
  39805. * Licensed to the Apache Software Foundation (ASF) under one
  39806. * or more contributor license agreements. See the NOTICE file
  39807. * distributed with this work for additional information
  39808. * regarding copyright ownership. The ASF licenses this file
  39809. * to you under the Apache License, Version 2.0 (the
  39810. * "License"); you may not use this file except in compliance
  39811. * with the License. You may obtain a copy of the License at
  39812. *
  39813. * http://www.apache.org/licenses/LICENSE-2.0
  39814. *
  39815. * Unless required by applicable law or agreed to in writing,
  39816. * software distributed under the License is distributed on an
  39817. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39818. * KIND, either express or implied. See the License for the
  39819. * specific language governing permissions and limitations
  39820. * under the License.
  39821. */
  39822. // import * as zrUtil from 'zrender/src/core/util';
  39823. // In case developer forget to include grid component
  39824. registerVisual(visualSymbol('scatter', 'circle'));
  39825. registerLayout(pointsLayout('scatter'));
  39826. // echarts.registerProcessor(function (ecModel, api) {
  39827. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  39828. // var data = seriesModel.getData();
  39829. // var coordSys = seriesModel.coordinateSystem;
  39830. // if (coordSys.type !== 'geo') {
  39831. // return;
  39832. // }
  39833. // var startPt = coordSys.pointToData([0, 0]);
  39834. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  39835. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  39836. // return data.mapDimension(dim);
  39837. // });
  39838. // var range = {};
  39839. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  39840. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  39841. // data.selectRange(range);
  39842. // });
  39843. // });
  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. var _nonShapeGraphicElements = {
  39863. // Reserved but not supported in graphic component.
  39864. path: null,
  39865. compoundPath: null,
  39866. // Supported in graphic component.
  39867. group: Group,
  39868. image: ZImage,
  39869. text: Text
  39870. };
  39871. // -------------
  39872. // Preprocessor
  39873. // -------------
  39874. registerPreprocessor(function (option) {
  39875. var graphicOption = option.graphic;
  39876. // Convert
  39877. // {graphic: [{left: 10, type: 'circle'}, ...]}
  39878. // or
  39879. // {graphic: {left: 10, type: 'circle'}}
  39880. // to
  39881. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  39882. if (isArray(graphicOption)) {
  39883. if (!graphicOption[0] || !graphicOption[0].elements) {
  39884. option.graphic = [{elements: graphicOption}];
  39885. }
  39886. else {
  39887. // Only one graphic instance can be instantiated. (We dont
  39888. // want that too many views are created in echarts._viewMap)
  39889. option.graphic = [option.graphic[0]];
  39890. }
  39891. }
  39892. else if (graphicOption && !graphicOption.elements) {
  39893. option.graphic = [{elements: [graphicOption]}];
  39894. }
  39895. });
  39896. // ------
  39897. // Model
  39898. // ------
  39899. var GraphicModel = extendComponentModel({
  39900. type: 'graphic',
  39901. defaultOption: {
  39902. // Extra properties for each elements:
  39903. //
  39904. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  39905. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  39906. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  39907. // This mechanism is useful when you want to position a group/element
  39908. // against the right side or the center of this container.
  39909. //
  39910. // width/height: (can only be pixel value, default 0)
  39911. // Only be used to specify contianer(group) size, if needed. And
  39912. // can not be percentage value (like '33%'). See the reason in the
  39913. // layout algorithm below.
  39914. //
  39915. // bounding: (enum: 'all' (default) | 'raw')
  39916. // Specify how to calculate boundingRect when locating.
  39917. // 'all': Get uioned and transformed boundingRect
  39918. // from both itself and its descendants.
  39919. // This mode simplies confining a group of elements in the bounding
  39920. // of their ancester container (e.g., using 'right: 0').
  39921. // 'raw': Only use the boundingRect of itself and before transformed.
  39922. // This mode is similar to css behavior, which is useful when you
  39923. // want an element to be able to overflow its container. (Consider
  39924. // a rotated circle needs to be located in a corner.)
  39925. // info: custom info. enables user to mount some info on elements and use them
  39926. // in event handlers. Update them only when user specified, otherwise, remain.
  39927. // Note: elements is always behind its ancestors in this elements array.
  39928. elements: [],
  39929. parentId: null
  39930. },
  39931. /**
  39932. * Save el options for the sake of the performance (only update modified graphics).
  39933. * The order is the same as those in option. (ancesters -> descendants)
  39934. *
  39935. * @private
  39936. * @type {Array.<Object>}
  39937. */
  39938. _elOptionsToUpdate: null,
  39939. /**
  39940. * @override
  39941. */
  39942. mergeOption: function (option) {
  39943. // Prevent default merge to elements
  39944. var elements = this.option.elements;
  39945. this.option.elements = null;
  39946. GraphicModel.superApply(this, 'mergeOption', arguments);
  39947. this.option.elements = elements;
  39948. },
  39949. /**
  39950. * @override
  39951. */
  39952. optionUpdated: function (newOption, isInit) {
  39953. var thisOption = this.option;
  39954. var newList = (isInit ? thisOption : newOption).elements;
  39955. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  39956. var flattenedList = [];
  39957. this._flatten(newList, flattenedList);
  39958. var mappingResult = mappingToExists(existList, flattenedList);
  39959. makeIdAndName(mappingResult);
  39960. // Clear elOptionsToUpdate
  39961. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  39962. each$1(mappingResult, function (resultItem, index) {
  39963. var newElOption = resultItem.option;
  39964. if (__DEV__) {
  39965. assert$1(
  39966. isObject$1(newElOption) || resultItem.exist,
  39967. 'Empty graphic option definition'
  39968. );
  39969. }
  39970. if (!newElOption) {
  39971. return;
  39972. }
  39973. elOptionsToUpdate.push(newElOption);
  39974. setKeyInfoToNewElOption(resultItem, newElOption);
  39975. mergeNewElOptionToExist(existList, index, newElOption);
  39976. setLayoutInfoToExist(existList[index], newElOption);
  39977. }, this);
  39978. // Clean
  39979. for (var i = existList.length - 1; i >= 0; i--) {
  39980. if (existList[i] == null) {
  39981. existList.splice(i, 1);
  39982. }
  39983. else {
  39984. // $action should be volatile, otherwise option gotten from
  39985. // `getOption` will contain unexpected $action.
  39986. delete existList[i].$action;
  39987. }
  39988. }
  39989. },
  39990. /**
  39991. * Convert
  39992. * [{
  39993. * type: 'group',
  39994. * id: 'xx',
  39995. * children: [{type: 'circle'}, {type: 'polygon'}]
  39996. * }]
  39997. * to
  39998. * [
  39999. * {type: 'group', id: 'xx'},
  40000. * {type: 'circle', parentId: 'xx'},
  40001. * {type: 'polygon', parentId: 'xx'}
  40002. * ]
  40003. *
  40004. * @private
  40005. * @param {Array.<Object>} optionList option list
  40006. * @param {Array.<Object>} result result of flatten
  40007. * @param {Object} parentOption parent option
  40008. */
  40009. _flatten: function (optionList, result, parentOption) {
  40010. each$1(optionList, function (option) {
  40011. if (!option) {
  40012. return;
  40013. }
  40014. if (parentOption) {
  40015. option.parentOption = parentOption;
  40016. }
  40017. result.push(option);
  40018. var children = option.children;
  40019. if (option.type === 'group' && children) {
  40020. this._flatten(children, result, option);
  40021. }
  40022. // Deleting for JSON output, and for not affecting group creation.
  40023. delete option.children;
  40024. }, this);
  40025. },
  40026. // FIXME
  40027. // Pass to view using payload? setOption has a payload?
  40028. useElOptionsToUpdate: function () {
  40029. var els = this._elOptionsToUpdate;
  40030. // Clear to avoid render duplicately when zooming.
  40031. this._elOptionsToUpdate = null;
  40032. return els;
  40033. }
  40034. });
  40035. // -----
  40036. // View
  40037. // -----
  40038. extendComponentView({
  40039. type: 'graphic',
  40040. /**
  40041. * @override
  40042. */
  40043. init: function (ecModel, api) {
  40044. /**
  40045. * @private
  40046. * @type {module:zrender/core/util.HashMap}
  40047. */
  40048. this._elMap = createHashMap();
  40049. /**
  40050. * @private
  40051. * @type {module:echarts/graphic/GraphicModel}
  40052. */
  40053. this._lastGraphicModel;
  40054. },
  40055. /**
  40056. * @override
  40057. */
  40058. render: function (graphicModel, ecModel, api) {
  40059. // Having leveraged between use cases and algorithm complexity, a very
  40060. // simple layout mechanism is used:
  40061. // The size(width/height) can be determined by itself or its parent (not
  40062. // implemented yet), but can not by its children. (Top-down travel)
  40063. // The location(x/y) can be determined by the bounding rect of itself
  40064. // (can including its descendants or not) and the size of its parent.
  40065. // (Bottom-up travel)
  40066. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  40067. // view will be reused.
  40068. if (graphicModel !== this._lastGraphicModel) {
  40069. this._clear();
  40070. }
  40071. this._lastGraphicModel = graphicModel;
  40072. this._updateElements(graphicModel);
  40073. this._relocate(graphicModel, api);
  40074. },
  40075. /**
  40076. * Update graphic elements.
  40077. *
  40078. * @private
  40079. * @param {Object} graphicModel graphic model
  40080. */
  40081. _updateElements: function (graphicModel) {
  40082. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  40083. if (!elOptionsToUpdate) {
  40084. return;
  40085. }
  40086. var elMap = this._elMap;
  40087. var rootGroup = this.group;
  40088. // Top-down tranverse to assign graphic settings to each elements.
  40089. each$1(elOptionsToUpdate, function (elOption) {
  40090. var $action = elOption.$action;
  40091. var id = elOption.id;
  40092. var existEl = elMap.get(id);
  40093. var parentId = elOption.parentId;
  40094. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  40095. var elOptionStyle = elOption.style;
  40096. if (elOption.type === 'text' && elOptionStyle) {
  40097. // In top/bottom mode, textVerticalAlign should not be used, which cause
  40098. // inaccurately locating.
  40099. if (elOption.hv && elOption.hv[1]) {
  40100. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  40101. }
  40102. // Compatible with previous setting: both support fill and textFill,
  40103. // stroke and textStroke.
  40104. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  40105. elOptionStyle.textFill = elOptionStyle.fill
  40106. );
  40107. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  40108. elOptionStyle.textStroke = elOptionStyle.stroke
  40109. );
  40110. }
  40111. // Remove unnecessary props to avoid potential problems.
  40112. var elOptionCleaned = getCleanedElOption(elOption);
  40113. // For simple, do not support parent change, otherwise reorder is needed.
  40114. if (__DEV__) {
  40115. existEl && assert$1(
  40116. targetElParent === existEl.parent,
  40117. 'Changing parent is not supported.'
  40118. );
  40119. }
  40120. if (!$action || $action === 'merge') {
  40121. existEl
  40122. ? existEl.attr(elOptionCleaned)
  40123. : createEl(id, targetElParent, elOptionCleaned, elMap);
  40124. }
  40125. else if ($action === 'replace') {
  40126. removeEl(existEl, elMap);
  40127. createEl(id, targetElParent, elOptionCleaned, elMap);
  40128. }
  40129. else if ($action === 'remove') {
  40130. removeEl(existEl, elMap);
  40131. }
  40132. var el = elMap.get(id);
  40133. if (el) {
  40134. el.__ecGraphicWidthOption = elOption.width;
  40135. el.__ecGraphicHeightOption = elOption.height;
  40136. setEventData(el, graphicModel, elOption);
  40137. }
  40138. });
  40139. },
  40140. /**
  40141. * Locate graphic elements.
  40142. *
  40143. * @private
  40144. * @param {Object} graphicModel graphic model
  40145. * @param {module:echarts/ExtensionAPI} api extension API
  40146. */
  40147. _relocate: function (graphicModel, api) {
  40148. var elOptions = graphicModel.option.elements;
  40149. var rootGroup = this.group;
  40150. var elMap = this._elMap;
  40151. var apiWidth = api.getWidth();
  40152. var apiHeight = api.getHeight();
  40153. // Top-down to calculate percentage width/height of group
  40154. for (var i = 0; i < elOptions.length; i++) {
  40155. var elOption = elOptions[i];
  40156. var el = elMap.get(elOption.id);
  40157. if (!el || !el.isGroup) {
  40158. continue;
  40159. }
  40160. var parentEl = el.parent;
  40161. var isParentRoot = parentEl === rootGroup;
  40162. // Like 'position:absolut' in css, default 0.
  40163. el.__ecGraphicWidth = parsePercent$1(
  40164. el.__ecGraphicWidthOption,
  40165. isParentRoot ? apiWidth : parentEl.__ecGraphicWidth
  40166. ) || 0;
  40167. el.__ecGraphicHeight = parsePercent$1(
  40168. el.__ecGraphicHeightOption,
  40169. isParentRoot ? apiHeight : parentEl.__ecGraphicHeight
  40170. ) || 0;
  40171. }
  40172. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  40173. for (var i = elOptions.length - 1; i >= 0; i--) {
  40174. var elOption = elOptions[i];
  40175. var el = elMap.get(elOption.id);
  40176. if (!el) {
  40177. continue;
  40178. }
  40179. var parentEl = el.parent;
  40180. var containerInfo = parentEl === rootGroup
  40181. ? {
  40182. width: apiWidth,
  40183. height: apiHeight
  40184. }
  40185. : {
  40186. width: parentEl.__ecGraphicWidth,
  40187. height: parentEl.__ecGraphicHeight
  40188. };
  40189. // PENDING
  40190. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  40191. // does not include the rect of [0, 0, group.width, group.height], which
  40192. // is probably weird for users. Should we make a break change for it?
  40193. positionElement(
  40194. el, elOption, containerInfo, null,
  40195. {hv: elOption.hv, boundingMode: elOption.bounding}
  40196. );
  40197. }
  40198. },
  40199. /**
  40200. * Clear all elements.
  40201. *
  40202. * @private
  40203. */
  40204. _clear: function () {
  40205. var elMap = this._elMap;
  40206. elMap.each(function (el) {
  40207. removeEl(el, elMap);
  40208. });
  40209. this._elMap = createHashMap();
  40210. },
  40211. /**
  40212. * @override
  40213. */
  40214. dispose: function () {
  40215. this._clear();
  40216. }
  40217. });
  40218. function createEl(id, targetElParent, elOption, elMap) {
  40219. var graphicType = elOption.type;
  40220. if (__DEV__) {
  40221. assert$1(graphicType, 'graphic type MUST be set');
  40222. }
  40223. var Clz = _nonShapeGraphicElements.hasOwnProperty(graphicType)
  40224. // Those graphic elements are not shapes. They should not be
  40225. // overwritten by users, so do them first.
  40226. ? _nonShapeGraphicElements[graphicType]
  40227. : getShapeClass(graphicType);
  40228. if (__DEV__) {
  40229. assert$1(Clz, 'graphic type can not be found');
  40230. }
  40231. var el = new Clz(elOption);
  40232. targetElParent.add(el);
  40233. elMap.set(id, el);
  40234. el.__ecGraphicId = id;
  40235. }
  40236. function removeEl(existEl, elMap) {
  40237. var existElParent = existEl && existEl.parent;
  40238. if (existElParent) {
  40239. existEl.type === 'group' && existEl.traverse(function (el) {
  40240. removeEl(el, elMap);
  40241. });
  40242. elMap.removeKey(existEl.__ecGraphicId);
  40243. existElParent.remove(existEl);
  40244. }
  40245. }
  40246. // Remove unnecessary props to avoid potential problems.
  40247. function getCleanedElOption(elOption) {
  40248. elOption = extend({}, elOption);
  40249. each$1(
  40250. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  40251. function (name) {
  40252. delete elOption[name];
  40253. }
  40254. );
  40255. return elOption;
  40256. }
  40257. function isSetLoc(obj, props) {
  40258. var isSet;
  40259. each$1(props, function (prop) {
  40260. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  40261. });
  40262. return isSet;
  40263. }
  40264. function setKeyInfoToNewElOption(resultItem, newElOption) {
  40265. var existElOption = resultItem.exist;
  40266. // Set id and type after id assigned.
  40267. newElOption.id = resultItem.keyInfo.id;
  40268. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  40269. // Set parent id if not specified
  40270. if (newElOption.parentId == null) {
  40271. var newElParentOption = newElOption.parentOption;
  40272. if (newElParentOption) {
  40273. newElOption.parentId = newElParentOption.id;
  40274. }
  40275. else if (existElOption) {
  40276. newElOption.parentId = existElOption.parentId;
  40277. }
  40278. }
  40279. // Clear
  40280. newElOption.parentOption = null;
  40281. }
  40282. function mergeNewElOptionToExist(existList, index, newElOption) {
  40283. // Update existing options, for `getOption` feature.
  40284. var newElOptCopy = extend({}, newElOption);
  40285. var existElOption = existList[index];
  40286. var $action = newElOption.$action || 'merge';
  40287. if ($action === 'merge') {
  40288. if (existElOption) {
  40289. if (__DEV__) {
  40290. var newType = newElOption.type;
  40291. assert$1(
  40292. !newType || existElOption.type === newType,
  40293. 'Please set $action: "replace" to change `type`'
  40294. );
  40295. }
  40296. // We can ensure that newElOptCopy and existElOption are not
  40297. // the same object, so `merge` will not change newElOptCopy.
  40298. merge(existElOption, newElOptCopy, true);
  40299. // Rigid body, use ignoreSize.
  40300. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  40301. // Will be used in render.
  40302. copyLayoutParams(newElOption, existElOption);
  40303. }
  40304. else {
  40305. existList[index] = newElOptCopy;
  40306. }
  40307. }
  40308. else if ($action === 'replace') {
  40309. existList[index] = newElOptCopy;
  40310. }
  40311. else if ($action === 'remove') {
  40312. // null will be cleaned later.
  40313. existElOption && (existList[index] = null);
  40314. }
  40315. }
  40316. function setLayoutInfoToExist(existItem, newElOption) {
  40317. if (!existItem) {
  40318. return;
  40319. }
  40320. existItem.hv = newElOption.hv = [
  40321. // Rigid body, dont care `width`.
  40322. isSetLoc(newElOption, ['left', 'right']),
  40323. // Rigid body, dont care `height`.
  40324. isSetLoc(newElOption, ['top', 'bottom'])
  40325. ];
  40326. // Give default group size. Otherwise layout error may occur.
  40327. if (existItem.type === 'group') {
  40328. existItem.width == null && (existItem.width = newElOption.width = 0);
  40329. existItem.height == null && (existItem.height = newElOption.height = 0);
  40330. }
  40331. }
  40332. function setEventData(el, graphicModel, elOption) {
  40333. var eventData = el.eventData;
  40334. // Simple optimize for large amount of elements that no need event.
  40335. if (!el.silent && !el.ignore && !eventData) {
  40336. eventData = el.eventData = {
  40337. componentType: 'graphic',
  40338. componentIndex: graphicModel.componentIndex,
  40339. name: el.name
  40340. };
  40341. }
  40342. // `elOption.info` enables user to mount some info on
  40343. // elements and use them in event handlers.
  40344. if (eventData) {
  40345. eventData.info = el.info;
  40346. }
  40347. }
  40348. /*
  40349. * Licensed to the Apache Software Foundation (ASF) under one
  40350. * or more contributor license agreements. See the NOTICE file
  40351. * distributed with this work for additional information
  40352. * regarding copyright ownership. The ASF licenses this file
  40353. * to you under the Apache License, Version 2.0 (the
  40354. * "License"); you may not use this file except in compliance
  40355. * with the License. You may obtain a copy of the License at
  40356. *
  40357. * http://www.apache.org/licenses/LICENSE-2.0
  40358. *
  40359. * Unless required by applicable law or agreed to in writing,
  40360. * software distributed under the License is distributed on an
  40361. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40362. * KIND, either express or implied. See the License for the
  40363. * specific language governing permissions and limitations
  40364. * under the License.
  40365. */
  40366. /**
  40367. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  40368. * @param {module:echarts/model/Global} ecModel
  40369. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  40370. */
  40371. var findPointFromSeries = function (finder, ecModel) {
  40372. var point = [];
  40373. var seriesIndex = finder.seriesIndex;
  40374. var seriesModel;
  40375. if (seriesIndex == null || !(
  40376. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  40377. )) {
  40378. return {point: []};
  40379. }
  40380. var data = seriesModel.getData();
  40381. var dataIndex = queryDataIndex(data, finder);
  40382. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  40383. return {point: []};
  40384. }
  40385. var el = data.getItemGraphicEl(dataIndex);
  40386. var coordSys = seriesModel.coordinateSystem;
  40387. if (seriesModel.getTooltipPosition) {
  40388. point = seriesModel.getTooltipPosition(dataIndex) || [];
  40389. }
  40390. else if (coordSys && coordSys.dataToPoint) {
  40391. point = coordSys.dataToPoint(
  40392. data.getValues(
  40393. map(coordSys.dimensions, function (dim) {
  40394. return data.mapDimension(dim);
  40395. }), dataIndex, true
  40396. )
  40397. ) || [];
  40398. }
  40399. else if (el) {
  40400. // Use graphic bounding rect
  40401. var rect = el.getBoundingRect().clone();
  40402. rect.applyTransform(el.transform);
  40403. point = [
  40404. rect.x + rect.width / 2,
  40405. rect.y + rect.height / 2
  40406. ];
  40407. }
  40408. return {point: point, el: el};
  40409. };
  40410. /*
  40411. * Licensed to the Apache Software Foundation (ASF) under one
  40412. * or more contributor license agreements. See the NOTICE file
  40413. * distributed with this work for additional information
  40414. * regarding copyright ownership. The ASF licenses this file
  40415. * to you under the Apache License, Version 2.0 (the
  40416. * "License"); you may not use this file except in compliance
  40417. * with the License. You may obtain a copy of the License at
  40418. *
  40419. * http://www.apache.org/licenses/LICENSE-2.0
  40420. *
  40421. * Unless required by applicable law or agreed to in writing,
  40422. * software distributed under the License is distributed on an
  40423. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40424. * KIND, either express or implied. See the License for the
  40425. * specific language governing permissions and limitations
  40426. * under the License.
  40427. */
  40428. var each$7 = each$1;
  40429. var curry$2 = curry;
  40430. var inner$7 = makeInner();
  40431. /**
  40432. * Basic logic: check all axis, if they do not demand show/highlight,
  40433. * then hide/downplay them.
  40434. *
  40435. * @param {Object} coordSysAxesInfo
  40436. * @param {Object} payload
  40437. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  40438. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  40439. * trigger axisPointer and tooltip.
  40440. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  40441. * trigger axisPointer and tooltip.
  40442. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  40443. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  40444. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  40445. * [{
  40446. * axisDim: 'x'|'y'|'angle'|...,
  40447. * axisIndex: ...,
  40448. * value: ...
  40449. * }, ...]
  40450. * @param {Function} [payload.dispatchAction]
  40451. * @param {Object} [payload.tooltipOption]
  40452. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  40453. * which can be specified in dispatchAction
  40454. * @param {module:echarts/model/Global} ecModel
  40455. * @param {module:echarts/ExtensionAPI} api
  40456. * @return {Object} content of event obj for echarts.connect.
  40457. */
  40458. var axisTrigger = function (payload, ecModel, api) {
  40459. var currTrigger = payload.currTrigger;
  40460. var point = [payload.x, payload.y];
  40461. var finder = payload;
  40462. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  40463. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  40464. // Pending
  40465. // See #6121. But we are not able to reproduce it yet.
  40466. if (!coordSysAxesInfo) {
  40467. return;
  40468. }
  40469. if (illegalPoint(point)) {
  40470. // Used in the default behavior of `connection`: use the sample seriesIndex
  40471. // and dataIndex. And also used in the tooltipView trigger.
  40472. point = findPointFromSeries({
  40473. seriesIndex: finder.seriesIndex,
  40474. // Do not use dataIndexInside from other ec instance.
  40475. // FIXME: auto detect it?
  40476. dataIndex: finder.dataIndex
  40477. }, ecModel).point;
  40478. }
  40479. var isIllegalPoint = illegalPoint(point);
  40480. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  40481. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  40482. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  40483. // and dataIndex.
  40484. var inputAxesInfo = finder.axesInfo;
  40485. var axesInfo = coordSysAxesInfo.axesInfo;
  40486. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  40487. var outputFinder = {};
  40488. var showValueMap = {};
  40489. var dataByCoordSys = {list: [], map: {}};
  40490. var updaters = {
  40491. showPointer: curry$2(showPointer, showValueMap),
  40492. showTooltip: curry$2(showTooltip, dataByCoordSys)
  40493. };
  40494. // Process for triggered axes.
  40495. each$7(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  40496. // If a point given, it must be contained by the coordinate system.
  40497. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  40498. each$7(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  40499. var axis = axisInfo.axis;
  40500. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  40501. // If no inputAxesInfo, no axis is restricted.
  40502. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  40503. var val = inputAxisInfo && inputAxisInfo.value;
  40504. if (val == null && !isIllegalPoint) {
  40505. val = axis.pointToData(point);
  40506. }
  40507. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  40508. }
  40509. });
  40510. });
  40511. // Process for linked axes.
  40512. var linkTriggers = {};
  40513. each$7(axesInfo, function (tarAxisInfo, tarKey) {
  40514. var linkGroup = tarAxisInfo.linkGroup;
  40515. // If axis has been triggered in the previous stage, it should not be triggered by link.
  40516. if (linkGroup && !showValueMap[tarKey]) {
  40517. each$7(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  40518. var srcValItem = showValueMap[srcKey];
  40519. // If srcValItem exist, source axis is triggered, so link to target axis.
  40520. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  40521. var val = srcValItem.value;
  40522. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  40523. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  40524. )));
  40525. linkTriggers[tarAxisInfo.key] = val;
  40526. }
  40527. });
  40528. }
  40529. });
  40530. each$7(linkTriggers, function (val, tarKey) {
  40531. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  40532. });
  40533. updateModelActually(showValueMap, axesInfo, outputFinder);
  40534. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  40535. dispatchHighDownActually(axesInfo, dispatchAction, api);
  40536. return outputFinder;
  40537. };
  40538. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  40539. var axis = axisInfo.axis;
  40540. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  40541. return;
  40542. }
  40543. if (!axisInfo.involveSeries) {
  40544. updaters.showPointer(axisInfo, newValue);
  40545. return;
  40546. }
  40547. // Heavy calculation. So put it after axis.containData checking.
  40548. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  40549. var payloadBatch = payloadInfo.payloadBatch;
  40550. var snapToValue = payloadInfo.snapToValue;
  40551. // Fill content of event obj for echarts.connect.
  40552. // By defualt use the first involved series data as a sample to connect.
  40553. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  40554. extend(outputFinder, payloadBatch[0]);
  40555. }
  40556. // If no linkSource input, this process is for collecting link
  40557. // target, where snap should not be accepted.
  40558. if (!dontSnap && axisInfo.snap) {
  40559. if (axis.containData(snapToValue) && snapToValue != null) {
  40560. newValue = snapToValue;
  40561. }
  40562. }
  40563. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  40564. // Tooltip should always be snapToValue, otherwise there will be
  40565. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  40566. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  40567. }
  40568. function buildPayloadsBySeries(value, axisInfo) {
  40569. var axis = axisInfo.axis;
  40570. var dim = axis.dim;
  40571. var snapToValue = value;
  40572. var payloadBatch = [];
  40573. var minDist = Number.MAX_VALUE;
  40574. var minDiff = -1;
  40575. each$7(axisInfo.seriesModels, function (series, idx) {
  40576. var dataDim = series.getData().mapDimension(dim, true);
  40577. var seriesNestestValue;
  40578. var dataIndices;
  40579. if (series.getAxisTooltipData) {
  40580. var result = series.getAxisTooltipData(dataDim, value, axis);
  40581. dataIndices = result.dataIndices;
  40582. seriesNestestValue = result.nestestValue;
  40583. }
  40584. else {
  40585. dataIndices = series.getData().indicesOfNearest(
  40586. dataDim[0],
  40587. value,
  40588. // Add a threshold to avoid find the wrong dataIndex
  40589. // when data length is not same.
  40590. // false,
  40591. axis.type === 'category' ? 0.5 : null
  40592. );
  40593. if (!dataIndices.length) {
  40594. return;
  40595. }
  40596. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  40597. }
  40598. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  40599. return;
  40600. }
  40601. var diff = value - seriesNestestValue;
  40602. var dist = Math.abs(diff);
  40603. // Consider category case
  40604. if (dist <= minDist) {
  40605. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  40606. minDist = dist;
  40607. minDiff = diff;
  40608. snapToValue = seriesNestestValue;
  40609. payloadBatch.length = 0;
  40610. }
  40611. each$7(dataIndices, function (dataIndex) {
  40612. payloadBatch.push({
  40613. seriesIndex: series.seriesIndex,
  40614. dataIndexInside: dataIndex,
  40615. dataIndex: series.getData().getRawIndex(dataIndex)
  40616. });
  40617. });
  40618. }
  40619. });
  40620. return {
  40621. payloadBatch: payloadBatch,
  40622. snapToValue: snapToValue
  40623. };
  40624. }
  40625. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  40626. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  40627. }
  40628. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  40629. var payloadBatch = payloadInfo.payloadBatch;
  40630. var axis = axisInfo.axis;
  40631. var axisModel = axis.model;
  40632. var axisPointerModel = axisInfo.axisPointerModel;
  40633. // If no data, do not create anything in dataByCoordSys,
  40634. // whose length will be used to judge whether dispatch action.
  40635. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  40636. return;
  40637. }
  40638. var coordSysModel = axisInfo.coordSys.model;
  40639. var coordSysKey = makeKey(coordSysModel);
  40640. var coordSysItem = dataByCoordSys.map[coordSysKey];
  40641. if (!coordSysItem) {
  40642. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  40643. coordSysId: coordSysModel.id,
  40644. coordSysIndex: coordSysModel.componentIndex,
  40645. coordSysType: coordSysModel.type,
  40646. coordSysMainType: coordSysModel.mainType,
  40647. dataByAxis: []
  40648. };
  40649. dataByCoordSys.list.push(coordSysItem);
  40650. }
  40651. coordSysItem.dataByAxis.push({
  40652. axisDim: axis.dim,
  40653. axisIndex: axisModel.componentIndex,
  40654. axisType: axisModel.type,
  40655. axisId: axisModel.id,
  40656. value: value,
  40657. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  40658. // depends that all models have been updated. So it should not be performed
  40659. // here. Considering axisPointerModel used here is volatile, which is hard
  40660. // to be retrieve in TooltipView, we prepare parameters here.
  40661. valueLabelOpt: {
  40662. precision: axisPointerModel.get('label.precision'),
  40663. formatter: axisPointerModel.get('label.formatter')
  40664. },
  40665. seriesDataIndices: payloadBatch.slice()
  40666. });
  40667. }
  40668. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  40669. var outputAxesInfo = outputFinder.axesInfo = [];
  40670. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  40671. each$7(axesInfo, function (axisInfo, key) {
  40672. var option = axisInfo.axisPointerModel.option;
  40673. var valItem = showValueMap[key];
  40674. if (valItem) {
  40675. !axisInfo.useHandle && (option.status = 'show');
  40676. option.value = valItem.value;
  40677. // For label formatter param and highlight.
  40678. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  40679. }
  40680. // When always show (e.g., handle used), remain
  40681. // original value and status.
  40682. else {
  40683. // If hide, value still need to be set, consider
  40684. // click legend to toggle axis blank.
  40685. !axisInfo.useHandle && (option.status = 'hide');
  40686. }
  40687. // If status is 'hide', should be no info in payload.
  40688. option.status === 'show' && outputAxesInfo.push({
  40689. axisDim: axisInfo.axis.dim,
  40690. axisIndex: axisInfo.axis.model.componentIndex,
  40691. value: option.value
  40692. });
  40693. });
  40694. }
  40695. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  40696. // Basic logic: If no showTip required, hideTip will be dispatched.
  40697. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  40698. dispatchAction({type: 'hideTip'});
  40699. return;
  40700. }
  40701. // In most case only one axis (or event one series is used). It is
  40702. // convinient to fetch payload.seriesIndex and payload.dataIndex
  40703. // dirtectly. So put the first seriesIndex and dataIndex of the first
  40704. // axis on the payload.
  40705. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  40706. dispatchAction({
  40707. type: 'showTip',
  40708. escapeConnect: true,
  40709. x: point[0],
  40710. y: point[1],
  40711. tooltipOption: payload.tooltipOption,
  40712. position: payload.position,
  40713. dataIndexInside: sampleItem.dataIndexInside,
  40714. dataIndex: sampleItem.dataIndex,
  40715. seriesIndex: sampleItem.seriesIndex,
  40716. dataByCoordSys: dataByCoordSys.list
  40717. });
  40718. }
  40719. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  40720. // FIXME
  40721. // highlight status modification shoule be a stage of main process?
  40722. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  40723. var zr = api.getZr();
  40724. var highDownKey = 'axisPointerLastHighlights';
  40725. var lastHighlights = inner$7(zr)[highDownKey] || {};
  40726. var newHighlights = inner$7(zr)[highDownKey] = {};
  40727. // Update highlight/downplay status according to axisPointer model.
  40728. // Build hash map and remove duplicate incidentally.
  40729. each$7(axesInfo, function (axisInfo, key) {
  40730. var option = axisInfo.axisPointerModel.option;
  40731. option.status === 'show' && each$7(option.seriesDataIndices, function (batchItem) {
  40732. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  40733. newHighlights[key] = batchItem;
  40734. });
  40735. });
  40736. // Diff.
  40737. var toHighlight = [];
  40738. var toDownplay = [];
  40739. each$1(lastHighlights, function (batchItem, key) {
  40740. !newHighlights[key] && toDownplay.push(batchItem);
  40741. });
  40742. each$1(newHighlights, function (batchItem, key) {
  40743. !lastHighlights[key] && toHighlight.push(batchItem);
  40744. });
  40745. toDownplay.length && api.dispatchAction({
  40746. type: 'downplay', escapeConnect: true, batch: toDownplay
  40747. });
  40748. toHighlight.length && api.dispatchAction({
  40749. type: 'highlight', escapeConnect: true, batch: toHighlight
  40750. });
  40751. }
  40752. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  40753. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  40754. var inputAxisInfo = inputAxesInfo[i];
  40755. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  40756. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  40757. ) {
  40758. return inputAxisInfo;
  40759. }
  40760. }
  40761. }
  40762. function makeMapperParam(axisInfo) {
  40763. var axisModel = axisInfo.axis.model;
  40764. var item = {};
  40765. var dim = item.axisDim = axisInfo.axis.dim;
  40766. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  40767. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  40768. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  40769. return item;
  40770. }
  40771. function illegalPoint(point) {
  40772. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  40773. }
  40774. /*
  40775. * Licensed to the Apache Software Foundation (ASF) under one
  40776. * or more contributor license agreements. See the NOTICE file
  40777. * distributed with this work for additional information
  40778. * regarding copyright ownership. The ASF licenses this file
  40779. * to you under the Apache License, Version 2.0 (the
  40780. * "License"); you may not use this file except in compliance
  40781. * with the License. You may obtain a copy of the License at
  40782. *
  40783. * http://www.apache.org/licenses/LICENSE-2.0
  40784. *
  40785. * Unless required by applicable law or agreed to in writing,
  40786. * software distributed under the License is distributed on an
  40787. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40788. * KIND, either express or implied. See the License for the
  40789. * specific language governing permissions and limitations
  40790. * under the License.
  40791. */
  40792. var AxisPointerModel = extendComponentModel({
  40793. type: 'axisPointer',
  40794. coordSysAxesInfo: null,
  40795. defaultOption: {
  40796. // 'auto' means that show when triggered by tooltip or handle.
  40797. show: 'auto',
  40798. // 'click' | 'mousemove' | 'none'
  40799. triggerOn: null, // set default in AxisPonterView.js
  40800. zlevel: 0,
  40801. z: 50,
  40802. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  40803. // axispointer triggered by tootip determine snap automatically,
  40804. // see `modelHelper`.
  40805. snap: false,
  40806. triggerTooltip: true,
  40807. value: null,
  40808. status: null, // Init value depends on whether handle is used.
  40809. // [group0, group1, ...]
  40810. // Each group can be: {
  40811. // mapper: function () {},
  40812. // singleTooltip: 'multiple', // 'multiple' or 'single'
  40813. // xAxisId: ...,
  40814. // yAxisName: ...,
  40815. // angleAxisIndex: ...
  40816. // }
  40817. // mapper: can be ignored.
  40818. // input: {axisInfo, value}
  40819. // output: {axisInfo, value}
  40820. link: [],
  40821. // Do not set 'auto' here, otherwise global animation: false
  40822. // will not effect at this axispointer.
  40823. animation: null,
  40824. animationDurationUpdate: 200,
  40825. lineStyle: {
  40826. color: '#aaa',
  40827. width: 1,
  40828. type: 'solid'
  40829. },
  40830. shadowStyle: {
  40831. color: 'rgba(150,150,150,0.3)'
  40832. },
  40833. label: {
  40834. show: true,
  40835. formatter: null, // string | Function
  40836. precision: 'auto', // Or a number like 0, 1, 2 ...
  40837. margin: 3,
  40838. color: '#fff',
  40839. padding: [5, 7, 5, 7],
  40840. backgroundColor: 'auto', // default: axis line color
  40841. borderColor: null,
  40842. borderWidth: 0,
  40843. shadowBlur: 3,
  40844. shadowColor: '#aaa'
  40845. // Considering applicability, common style should
  40846. // better not have shadowOffset.
  40847. // shadowOffsetX: 0,
  40848. // shadowOffsetY: 2
  40849. },
  40850. handle: {
  40851. show: false,
  40852. /* eslint-disable */
  40853. 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
  40854. /* eslint-enable */
  40855. size: 45,
  40856. // handle margin is from symbol center to axis, which is stable when circular move.
  40857. margin: 50,
  40858. // color: '#1b8bbd'
  40859. // color: '#2f4554'
  40860. color: '#333',
  40861. shadowBlur: 3,
  40862. shadowColor: '#aaa',
  40863. shadowOffsetX: 0,
  40864. shadowOffsetY: 2,
  40865. // For mobile performance
  40866. throttle: 40
  40867. }
  40868. }
  40869. });
  40870. /*
  40871. * Licensed to the Apache Software Foundation (ASF) under one
  40872. * or more contributor license agreements. See the NOTICE file
  40873. * distributed with this work for additional information
  40874. * regarding copyright ownership. The ASF licenses this file
  40875. * to you under the Apache License, Version 2.0 (the
  40876. * "License"); you may not use this file except in compliance
  40877. * with the License. You may obtain a copy of the License at
  40878. *
  40879. * http://www.apache.org/licenses/LICENSE-2.0
  40880. *
  40881. * Unless required by applicable law or agreed to in writing,
  40882. * software distributed under the License is distributed on an
  40883. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40884. * KIND, either express or implied. See the License for the
  40885. * specific language governing permissions and limitations
  40886. * under the License.
  40887. */
  40888. var inner$8 = makeInner();
  40889. var each$8 = each$1;
  40890. /**
  40891. * @param {string} key
  40892. * @param {module:echarts/ExtensionAPI} api
  40893. * @param {Function} handler
  40894. * param: {string} currTrigger
  40895. * param: {Array.<number>} point
  40896. */
  40897. function register(key, api, handler) {
  40898. if (env$1.node) {
  40899. return;
  40900. }
  40901. var zr = api.getZr();
  40902. inner$8(zr).records || (inner$8(zr).records = {});
  40903. initGlobalListeners(zr, api);
  40904. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  40905. record.handler = handler;
  40906. }
  40907. function initGlobalListeners(zr, api) {
  40908. if (inner$8(zr).initialized) {
  40909. return;
  40910. }
  40911. inner$8(zr).initialized = true;
  40912. useHandler('click', curry(doEnter, 'click'));
  40913. useHandler('mousemove', curry(doEnter, 'mousemove'));
  40914. // useHandler('mouseout', onLeave);
  40915. useHandler('globalout', onLeave);
  40916. function useHandler(eventType, cb) {
  40917. zr.on(eventType, function (e) {
  40918. var dis = makeDispatchAction(api);
  40919. each$8(inner$8(zr).records, function (record) {
  40920. record && cb(record, e, dis.dispatchAction);
  40921. });
  40922. dispatchTooltipFinally(dis.pendings, api);
  40923. });
  40924. }
  40925. }
  40926. function dispatchTooltipFinally(pendings, api) {
  40927. var showLen = pendings.showTip.length;
  40928. var hideLen = pendings.hideTip.length;
  40929. var actuallyPayload;
  40930. if (showLen) {
  40931. actuallyPayload = pendings.showTip[showLen - 1];
  40932. }
  40933. else if (hideLen) {
  40934. actuallyPayload = pendings.hideTip[hideLen - 1];
  40935. }
  40936. if (actuallyPayload) {
  40937. actuallyPayload.dispatchAction = null;
  40938. api.dispatchAction(actuallyPayload);
  40939. }
  40940. }
  40941. function onLeave(record, e, dispatchAction) {
  40942. record.handler('leave', null, dispatchAction);
  40943. }
  40944. function doEnter(currTrigger, record, e, dispatchAction) {
  40945. record.handler(currTrigger, e, dispatchAction);
  40946. }
  40947. function makeDispatchAction(api) {
  40948. var pendings = {
  40949. showTip: [],
  40950. hideTip: []
  40951. };
  40952. // FIXME
  40953. // better approach?
  40954. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  40955. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  40956. // So we have to add "final stage" to merge those dispatched actions.
  40957. var dispatchAction = function (payload) {
  40958. var pendingList = pendings[payload.type];
  40959. if (pendingList) {
  40960. pendingList.push(payload);
  40961. }
  40962. else {
  40963. payload.dispatchAction = dispatchAction;
  40964. api.dispatchAction(payload);
  40965. }
  40966. };
  40967. return {
  40968. dispatchAction: dispatchAction,
  40969. pendings: pendings
  40970. };
  40971. }
  40972. /**
  40973. * @param {string} key
  40974. * @param {module:echarts/ExtensionAPI} api
  40975. */
  40976. function unregister(key, api) {
  40977. if (env$1.node) {
  40978. return;
  40979. }
  40980. var zr = api.getZr();
  40981. var record = (inner$8(zr).records || {})[key];
  40982. if (record) {
  40983. inner$8(zr).records[key] = null;
  40984. }
  40985. }
  40986. /*
  40987. * Licensed to the Apache Software Foundation (ASF) under one
  40988. * or more contributor license agreements. See the NOTICE file
  40989. * distributed with this work for additional information
  40990. * regarding copyright ownership. The ASF licenses this file
  40991. * to you under the Apache License, Version 2.0 (the
  40992. * "License"); you may not use this file except in compliance
  40993. * with the License. You may obtain a copy of the License at
  40994. *
  40995. * http://www.apache.org/licenses/LICENSE-2.0
  40996. *
  40997. * Unless required by applicable law or agreed to in writing,
  40998. * software distributed under the License is distributed on an
  40999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41000. * KIND, either express or implied. See the License for the
  41001. * specific language governing permissions and limitations
  41002. * under the License.
  41003. */
  41004. var AxisPointerView = extendComponentView({
  41005. type: 'axisPointer',
  41006. render: function (globalAxisPointerModel, ecModel, api) {
  41007. var globalTooltipModel = ecModel.getComponent('tooltip');
  41008. var triggerOn = globalAxisPointerModel.get('triggerOn')
  41009. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  41010. // Register global listener in AxisPointerView to enable
  41011. // AxisPointerView to be independent to Tooltip.
  41012. register(
  41013. 'axisPointer',
  41014. api,
  41015. function (currTrigger, e, dispatchAction) {
  41016. // If 'none', it is not controlled by mouse totally.
  41017. if (triggerOn !== 'none'
  41018. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  41019. ) {
  41020. dispatchAction({
  41021. type: 'updateAxisPointer',
  41022. currTrigger: currTrigger,
  41023. x: e && e.offsetX,
  41024. y: e && e.offsetY
  41025. });
  41026. }
  41027. }
  41028. );
  41029. },
  41030. /**
  41031. * @override
  41032. */
  41033. remove: function (ecModel, api) {
  41034. unregister(api.getZr(), 'axisPointer');
  41035. AxisPointerView.superApply(this._model, 'remove', arguments);
  41036. },
  41037. /**
  41038. * @override
  41039. */
  41040. dispose: function (ecModel, api) {
  41041. unregister('axisPointer', api);
  41042. AxisPointerView.superApply(this._model, 'dispose', arguments);
  41043. }
  41044. });
  41045. /*
  41046. * Licensed to the Apache Software Foundation (ASF) under one
  41047. * or more contributor license agreements. See the NOTICE file
  41048. * distributed with this work for additional information
  41049. * regarding copyright ownership. The ASF licenses this file
  41050. * to you under the Apache License, Version 2.0 (the
  41051. * "License"); you may not use this file except in compliance
  41052. * with the License. You may obtain a copy of the License at
  41053. *
  41054. * http://www.apache.org/licenses/LICENSE-2.0
  41055. *
  41056. * Unless required by applicable law or agreed to in writing,
  41057. * software distributed under the License is distributed on an
  41058. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41059. * KIND, either express or implied. See the License for the
  41060. * specific language governing permissions and limitations
  41061. * under the License.
  41062. */
  41063. var inner$9 = makeInner();
  41064. var clone$4 = clone;
  41065. var bind$1 = bind;
  41066. /**
  41067. * Base axis pointer class in 2D.
  41068. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  41069. */
  41070. function BaseAxisPointer() {
  41071. }
  41072. BaseAxisPointer.prototype = {
  41073. /**
  41074. * @private
  41075. */
  41076. _group: null,
  41077. /**
  41078. * @private
  41079. */
  41080. _lastGraphicKey: null,
  41081. /**
  41082. * @private
  41083. */
  41084. _handle: null,
  41085. /**
  41086. * @private
  41087. */
  41088. _dragging: false,
  41089. /**
  41090. * @private
  41091. */
  41092. _lastValue: null,
  41093. /**
  41094. * @private
  41095. */
  41096. _lastStatus: null,
  41097. /**
  41098. * @private
  41099. */
  41100. _payloadInfo: null,
  41101. /**
  41102. * In px, arbitrary value. Do not set too small,
  41103. * no animation is ok for most cases.
  41104. * @protected
  41105. */
  41106. animationThreshold: 15,
  41107. /**
  41108. * @implement
  41109. */
  41110. render: function (axisModel, axisPointerModel, api, forceRender) {
  41111. var value = axisPointerModel.get('value');
  41112. var status = axisPointerModel.get('status');
  41113. // Bind them to `this`, not in closure, otherwise they will not
  41114. // be replaced when user calling setOption in not merge mode.
  41115. this._axisModel = axisModel;
  41116. this._axisPointerModel = axisPointerModel;
  41117. this._api = api;
  41118. // Optimize: `render` will be called repeatly during mouse move.
  41119. // So it is power consuming if performing `render` each time,
  41120. // especially on mobile device.
  41121. if (!forceRender
  41122. && this._lastValue === value
  41123. && this._lastStatus === status
  41124. ) {
  41125. return;
  41126. }
  41127. this._lastValue = value;
  41128. this._lastStatus = status;
  41129. var group = this._group;
  41130. var handle = this._handle;
  41131. if (!status || status === 'hide') {
  41132. // Do not clear here, for animation better.
  41133. group && group.hide();
  41134. handle && handle.hide();
  41135. return;
  41136. }
  41137. group && group.show();
  41138. handle && handle.show();
  41139. // Otherwise status is 'show'
  41140. var elOption = {};
  41141. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  41142. // Enable change axis pointer type.
  41143. var graphicKey = elOption.graphicKey;
  41144. if (graphicKey !== this._lastGraphicKey) {
  41145. this.clear(api);
  41146. }
  41147. this._lastGraphicKey = graphicKey;
  41148. var moveAnimation = this._moveAnimation =
  41149. this.determineAnimation(axisModel, axisPointerModel);
  41150. if (!group) {
  41151. group = this._group = new Group();
  41152. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  41153. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  41154. api.getZr().add(group);
  41155. }
  41156. else {
  41157. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  41158. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  41159. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  41160. }
  41161. updateMandatoryProps(group, axisPointerModel, true);
  41162. this._renderHandle(value);
  41163. },
  41164. /**
  41165. * @implement
  41166. */
  41167. remove: function (api) {
  41168. this.clear(api);
  41169. },
  41170. /**
  41171. * @implement
  41172. */
  41173. dispose: function (api) {
  41174. this.clear(api);
  41175. },
  41176. /**
  41177. * @protected
  41178. */
  41179. determineAnimation: function (axisModel, axisPointerModel) {
  41180. var animation = axisPointerModel.get('animation');
  41181. var axis = axisModel.axis;
  41182. var isCategoryAxis = axis.type === 'category';
  41183. var useSnap = axisPointerModel.get('snap');
  41184. // Value axis without snap always do not snap.
  41185. if (!useSnap && !isCategoryAxis) {
  41186. return false;
  41187. }
  41188. if (animation === 'auto' || animation == null) {
  41189. var animationThreshold = this.animationThreshold;
  41190. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  41191. return true;
  41192. }
  41193. // It is important to auto animation when snap used. Consider if there is
  41194. // a dataZoom, animation will be disabled when too many points exist, while
  41195. // it will be enabled for better visual effect when little points exist.
  41196. if (useSnap) {
  41197. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  41198. var axisExtent = axis.getExtent();
  41199. // Approximate band width
  41200. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  41201. }
  41202. return false;
  41203. }
  41204. return animation === true;
  41205. },
  41206. /**
  41207. * add {pointer, label, graphicKey} to elOption
  41208. * @protected
  41209. */
  41210. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  41211. // Shoule be implemenented by sub-class.
  41212. },
  41213. /**
  41214. * @protected
  41215. */
  41216. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  41217. var pointerOption = elOption.pointer;
  41218. if (pointerOption) {
  41219. var pointerEl = inner$9(group).pointerEl = new graphic[pointerOption.type](
  41220. clone$4(elOption.pointer)
  41221. );
  41222. group.add(pointerEl);
  41223. }
  41224. },
  41225. /**
  41226. * @protected
  41227. */
  41228. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  41229. if (elOption.label) {
  41230. var labelEl = inner$9(group).labelEl = new Rect(
  41231. clone$4(elOption.label)
  41232. );
  41233. group.add(labelEl);
  41234. updateLabelShowHide(labelEl, axisPointerModel);
  41235. }
  41236. },
  41237. /**
  41238. * @protected
  41239. */
  41240. updatePointerEl: function (group, elOption, updateProps$$1) {
  41241. var pointerEl = inner$9(group).pointerEl;
  41242. if (pointerEl && elOption.pointer) {
  41243. pointerEl.setStyle(elOption.pointer.style);
  41244. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  41245. }
  41246. },
  41247. /**
  41248. * @protected
  41249. */
  41250. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  41251. var labelEl = inner$9(group).labelEl;
  41252. if (labelEl) {
  41253. labelEl.setStyle(elOption.label.style);
  41254. updateProps$$1(labelEl, {
  41255. // Consider text length change in vertical axis, animation should
  41256. // be used on shape, otherwise the effect will be weird.
  41257. shape: elOption.label.shape,
  41258. position: elOption.label.position
  41259. });
  41260. updateLabelShowHide(labelEl, axisPointerModel);
  41261. }
  41262. },
  41263. /**
  41264. * @private
  41265. */
  41266. _renderHandle: function (value) {
  41267. if (this._dragging || !this.updateHandleTransform) {
  41268. return;
  41269. }
  41270. var axisPointerModel = this._axisPointerModel;
  41271. var zr = this._api.getZr();
  41272. var handle = this._handle;
  41273. var handleModel = axisPointerModel.getModel('handle');
  41274. var status = axisPointerModel.get('status');
  41275. if (!handleModel.get('show') || !status || status === 'hide') {
  41276. handle && zr.remove(handle);
  41277. this._handle = null;
  41278. return;
  41279. }
  41280. var isInit;
  41281. if (!this._handle) {
  41282. isInit = true;
  41283. handle = this._handle = createIcon(
  41284. handleModel.get('icon'),
  41285. {
  41286. cursor: 'move',
  41287. draggable: true,
  41288. onmousemove: function (e) {
  41289. // Fot mobile devicem, prevent screen slider on the button.
  41290. stop(e.event);
  41291. },
  41292. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  41293. drift: bind$1(this._onHandleDragMove, this),
  41294. ondragend: bind$1(this._onHandleDragEnd, this)
  41295. }
  41296. );
  41297. zr.add(handle);
  41298. }
  41299. updateMandatoryProps(handle, axisPointerModel, false);
  41300. // update style
  41301. var includeStyles = [
  41302. 'color', 'borderColor', 'borderWidth', 'opacity',
  41303. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  41304. ];
  41305. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  41306. // update position
  41307. var handleSize = handleModel.get('size');
  41308. if (!isArray(handleSize)) {
  41309. handleSize = [handleSize, handleSize];
  41310. }
  41311. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  41312. createOrUpdate(
  41313. this,
  41314. '_doDispatchAxisPointer',
  41315. handleModel.get('throttle') || 0,
  41316. 'fixRate'
  41317. );
  41318. this._moveHandleToValue(value, isInit);
  41319. },
  41320. /**
  41321. * @private
  41322. */
  41323. _moveHandleToValue: function (value, isInit) {
  41324. updateProps$1(
  41325. this._axisPointerModel,
  41326. !isInit && this._moveAnimation,
  41327. this._handle,
  41328. getHandleTransProps(this.getHandleTransform(
  41329. value, this._axisModel, this._axisPointerModel
  41330. ))
  41331. );
  41332. },
  41333. /**
  41334. * @private
  41335. */
  41336. _onHandleDragMove: function (dx, dy) {
  41337. var handle = this._handle;
  41338. if (!handle) {
  41339. return;
  41340. }
  41341. this._dragging = true;
  41342. // Persistent for throttle.
  41343. var trans = this.updateHandleTransform(
  41344. getHandleTransProps(handle),
  41345. [dx, dy],
  41346. this._axisModel,
  41347. this._axisPointerModel
  41348. );
  41349. this._payloadInfo = trans;
  41350. handle.stopAnimation();
  41351. handle.attr(getHandleTransProps(trans));
  41352. inner$9(handle).lastProp = null;
  41353. this._doDispatchAxisPointer();
  41354. },
  41355. /**
  41356. * Throttled method.
  41357. * @private
  41358. */
  41359. _doDispatchAxisPointer: function () {
  41360. var handle = this._handle;
  41361. if (!handle) {
  41362. return;
  41363. }
  41364. var payloadInfo = this._payloadInfo;
  41365. var axisModel = this._axisModel;
  41366. this._api.dispatchAction({
  41367. type: 'updateAxisPointer',
  41368. x: payloadInfo.cursorPoint[0],
  41369. y: payloadInfo.cursorPoint[1],
  41370. tooltipOption: payloadInfo.tooltipOption,
  41371. axesInfo: [{
  41372. axisDim: axisModel.axis.dim,
  41373. axisIndex: axisModel.componentIndex
  41374. }]
  41375. });
  41376. },
  41377. /**
  41378. * @private
  41379. */
  41380. _onHandleDragEnd: function (moveAnimation) {
  41381. this._dragging = false;
  41382. var handle = this._handle;
  41383. if (!handle) {
  41384. return;
  41385. }
  41386. var value = this._axisPointerModel.get('value');
  41387. // Consider snap or categroy axis, handle may be not consistent with
  41388. // axisPointer. So move handle to align the exact value position when
  41389. // drag ended.
  41390. this._moveHandleToValue(value);
  41391. // For the effect: tooltip will be shown when finger holding on handle
  41392. // button, and will be hidden after finger left handle button.
  41393. this._api.dispatchAction({
  41394. type: 'hideTip'
  41395. });
  41396. },
  41397. /**
  41398. * Should be implemenented by sub-class if support `handle`.
  41399. * @protected
  41400. * @param {number} value
  41401. * @param {module:echarts/model/Model} axisModel
  41402. * @param {module:echarts/model/Model} axisPointerModel
  41403. * @return {Object} {position: [x, y], rotation: 0}
  41404. */
  41405. getHandleTransform: null,
  41406. /**
  41407. * * Should be implemenented by sub-class if support `handle`.
  41408. * @protected
  41409. * @param {Object} transform {position, rotation}
  41410. * @param {Array.<number>} delta [dx, dy]
  41411. * @param {module:echarts/model/Model} axisModel
  41412. * @param {module:echarts/model/Model} axisPointerModel
  41413. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  41414. */
  41415. updateHandleTransform: null,
  41416. /**
  41417. * @private
  41418. */
  41419. clear: function (api) {
  41420. this._lastValue = null;
  41421. this._lastStatus = null;
  41422. var zr = api.getZr();
  41423. var group = this._group;
  41424. var handle = this._handle;
  41425. if (zr && group) {
  41426. this._lastGraphicKey = null;
  41427. group && zr.remove(group);
  41428. handle && zr.remove(handle);
  41429. this._group = null;
  41430. this._handle = null;
  41431. this._payloadInfo = null;
  41432. }
  41433. },
  41434. /**
  41435. * @protected
  41436. */
  41437. doClear: function () {
  41438. // Implemented by sub-class if necessary.
  41439. },
  41440. /**
  41441. * @protected
  41442. * @param {Array.<number>} xy
  41443. * @param {Array.<number>} wh
  41444. * @param {number} [xDimIndex=0] or 1
  41445. */
  41446. buildLabel: function (xy, wh, xDimIndex) {
  41447. xDimIndex = xDimIndex || 0;
  41448. return {
  41449. x: xy[xDimIndex],
  41450. y: xy[1 - xDimIndex],
  41451. width: wh[xDimIndex],
  41452. height: wh[1 - xDimIndex]
  41453. };
  41454. }
  41455. };
  41456. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  41457. function updateProps$1(animationModel, moveAnimation, el, props) {
  41458. // Animation optimize.
  41459. if (!propsEqual(inner$9(el).lastProp, props)) {
  41460. inner$9(el).lastProp = props;
  41461. moveAnimation
  41462. ? updateProps(el, props, animationModel)
  41463. : (el.stopAnimation(), el.attr(props));
  41464. }
  41465. }
  41466. function propsEqual(lastProps, newProps) {
  41467. if (isObject$1(lastProps) && isObject$1(newProps)) {
  41468. var equals = true;
  41469. each$1(newProps, function (item, key) {
  41470. equals = equals && propsEqual(lastProps[key], item);
  41471. });
  41472. return !!equals;
  41473. }
  41474. else {
  41475. return lastProps === newProps;
  41476. }
  41477. }
  41478. function updateLabelShowHide(labelEl, axisPointerModel) {
  41479. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  41480. }
  41481. function getHandleTransProps(trans) {
  41482. return {
  41483. position: trans.position.slice(),
  41484. rotation: trans.rotation || 0
  41485. };
  41486. }
  41487. function updateMandatoryProps(group, axisPointerModel, silent) {
  41488. var z = axisPointerModel.get('z');
  41489. var zlevel = axisPointerModel.get('zlevel');
  41490. group && group.traverse(function (el) {
  41491. if (el.type !== 'group') {
  41492. z != null && (el.z = z);
  41493. zlevel != null && (el.zlevel = zlevel);
  41494. el.silent = silent;
  41495. }
  41496. });
  41497. }
  41498. enableClassExtend(BaseAxisPointer);
  41499. /*
  41500. * Licensed to the Apache Software Foundation (ASF) under one
  41501. * or more contributor license agreements. See the NOTICE file
  41502. * distributed with this work for additional information
  41503. * regarding copyright ownership. The ASF licenses this file
  41504. * to you under the Apache License, Version 2.0 (the
  41505. * "License"); you may not use this file except in compliance
  41506. * with the License. You may obtain a copy of the License at
  41507. *
  41508. * http://www.apache.org/licenses/LICENSE-2.0
  41509. *
  41510. * Unless required by applicable law or agreed to in writing,
  41511. * software distributed under the License is distributed on an
  41512. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41513. * KIND, either express or implied. See the License for the
  41514. * specific language governing permissions and limitations
  41515. * under the License.
  41516. */
  41517. /**
  41518. * @param {module:echarts/model/Model} axisPointerModel
  41519. */
  41520. function buildElStyle(axisPointerModel) {
  41521. var axisPointerType = axisPointerModel.get('type');
  41522. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  41523. var style;
  41524. if (axisPointerType === 'line') {
  41525. style = styleModel.getLineStyle();
  41526. style.fill = null;
  41527. }
  41528. else if (axisPointerType === 'shadow') {
  41529. style = styleModel.getAreaStyle();
  41530. style.stroke = null;
  41531. }
  41532. return style;
  41533. }
  41534. /**
  41535. * @param {Function} labelPos {align, verticalAlign, position}
  41536. */
  41537. function buildLabelElOption(
  41538. elOption, axisModel, axisPointerModel, api, labelPos
  41539. ) {
  41540. var value = axisPointerModel.get('value');
  41541. var text = getValueLabel(
  41542. value, axisModel.axis, axisModel.ecModel,
  41543. axisPointerModel.get('seriesDataIndices'),
  41544. {
  41545. precision: axisPointerModel.get('label.precision'),
  41546. formatter: axisPointerModel.get('label.formatter')
  41547. }
  41548. );
  41549. var labelModel = axisPointerModel.getModel('label');
  41550. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  41551. var font = labelModel.getFont();
  41552. var textRect = getBoundingRect(text, font);
  41553. var position = labelPos.position;
  41554. var width = textRect.width + paddings[1] + paddings[3];
  41555. var height = textRect.height + paddings[0] + paddings[2];
  41556. // Adjust by align.
  41557. var align = labelPos.align;
  41558. align === 'right' && (position[0] -= width);
  41559. align === 'center' && (position[0] -= width / 2);
  41560. var verticalAlign = labelPos.verticalAlign;
  41561. verticalAlign === 'bottom' && (position[1] -= height);
  41562. verticalAlign === 'middle' && (position[1] -= height / 2);
  41563. // Not overflow ec container
  41564. confineInContainer(position, width, height, api);
  41565. var bgColor = labelModel.get('backgroundColor');
  41566. if (!bgColor || bgColor === 'auto') {
  41567. bgColor = axisModel.get('axisLine.lineStyle.color');
  41568. }
  41569. elOption.label = {
  41570. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  41571. position: position.slice(),
  41572. // TODO: rich
  41573. style: {
  41574. text: text,
  41575. textFont: font,
  41576. textFill: labelModel.getTextColor(),
  41577. textPosition: 'inside',
  41578. textPadding: paddings,
  41579. fill: bgColor,
  41580. stroke: labelModel.get('borderColor') || 'transparent',
  41581. lineWidth: labelModel.get('borderWidth') || 0,
  41582. shadowBlur: labelModel.get('shadowBlur'),
  41583. shadowColor: labelModel.get('shadowColor'),
  41584. shadowOffsetX: labelModel.get('shadowOffsetX'),
  41585. shadowOffsetY: labelModel.get('shadowOffsetY')
  41586. },
  41587. // Lable should be over axisPointer.
  41588. z2: 10
  41589. };
  41590. }
  41591. // Do not overflow ec container
  41592. function confineInContainer(position, width, height, api) {
  41593. var viewWidth = api.getWidth();
  41594. var viewHeight = api.getHeight();
  41595. position[0] = Math.min(position[0] + width, viewWidth) - width;
  41596. position[1] = Math.min(position[1] + height, viewHeight) - height;
  41597. position[0] = Math.max(position[0], 0);
  41598. position[1] = Math.max(position[1], 0);
  41599. }
  41600. /**
  41601. * @param {number} value
  41602. * @param {module:echarts/coord/Axis} axis
  41603. * @param {module:echarts/model/Global} ecModel
  41604. * @param {Object} opt
  41605. * @param {Array.<Object>} seriesDataIndices
  41606. * @param {number|string} opt.precision 'auto' or a number
  41607. * @param {string|Function} opt.formatter label formatter
  41608. */
  41609. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  41610. value = axis.scale.parse(value);
  41611. var text = axis.scale.getLabel(
  41612. // If `precision` is set, width can be fixed (like '12.00500'), which
  41613. // helps to debounce when when moving label.
  41614. value, {precision: opt.precision}
  41615. );
  41616. var formatter = opt.formatter;
  41617. if (formatter) {
  41618. var params = {
  41619. value: getAxisRawValue(axis, value),
  41620. axisDimension: axis.dim,
  41621. axisIndex: axis.index,
  41622. seriesData: []
  41623. };
  41624. each$1(seriesDataIndices, function (idxItem) {
  41625. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  41626. var dataIndex = idxItem.dataIndexInside;
  41627. var dataParams = series && series.getDataParams(dataIndex);
  41628. dataParams && params.seriesData.push(dataParams);
  41629. });
  41630. if (isString(formatter)) {
  41631. text = formatter.replace('{value}', text);
  41632. }
  41633. else if (isFunction$1(formatter)) {
  41634. text = formatter(params);
  41635. }
  41636. }
  41637. return text;
  41638. }
  41639. /**
  41640. * @param {module:echarts/coord/Axis} axis
  41641. * @param {number} value
  41642. * @param {Object} layoutInfo {
  41643. * rotation, position, labelOffset, labelDirection, labelMargin
  41644. * }
  41645. */
  41646. function getTransformedPosition(axis, value, layoutInfo) {
  41647. var transform = create$1();
  41648. rotate(transform, transform, layoutInfo.rotation);
  41649. translate(transform, transform, layoutInfo.position);
  41650. return applyTransform$1([
  41651. axis.dataToCoord(value),
  41652. (layoutInfo.labelOffset || 0)
  41653. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  41654. ], transform);
  41655. }
  41656. function buildCartesianSingleLabelElOption(
  41657. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  41658. ) {
  41659. var textLayout = AxisBuilder.innerTextLayout(
  41660. layoutInfo.rotation, 0, layoutInfo.labelDirection
  41661. );
  41662. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  41663. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  41664. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  41665. align: textLayout.textAlign,
  41666. verticalAlign: textLayout.textVerticalAlign
  41667. });
  41668. }
  41669. /**
  41670. * @param {Array.<number>} p1
  41671. * @param {Array.<number>} p2
  41672. * @param {number} [xDimIndex=0] or 1
  41673. */
  41674. function makeLineShape(p1, p2, xDimIndex) {
  41675. xDimIndex = xDimIndex || 0;
  41676. return {
  41677. x1: p1[xDimIndex],
  41678. y1: p1[1 - xDimIndex],
  41679. x2: p2[xDimIndex],
  41680. y2: p2[1 - xDimIndex]
  41681. };
  41682. }
  41683. /**
  41684. * @param {Array.<number>} xy
  41685. * @param {Array.<number>} wh
  41686. * @param {number} [xDimIndex=0] or 1
  41687. */
  41688. function makeRectShape(xy, wh, xDimIndex) {
  41689. xDimIndex = xDimIndex || 0;
  41690. return {
  41691. x: xy[xDimIndex],
  41692. y: xy[1 - xDimIndex],
  41693. width: wh[xDimIndex],
  41694. height: wh[1 - xDimIndex]
  41695. };
  41696. }
  41697. /*
  41698. * Licensed to the Apache Software Foundation (ASF) under one
  41699. * or more contributor license agreements. See the NOTICE file
  41700. * distributed with this work for additional information
  41701. * regarding copyright ownership. The ASF licenses this file
  41702. * to you under the Apache License, Version 2.0 (the
  41703. * "License"); you may not use this file except in compliance
  41704. * with the License. You may obtain a copy of the License at
  41705. *
  41706. * http://www.apache.org/licenses/LICENSE-2.0
  41707. *
  41708. * Unless required by applicable law or agreed to in writing,
  41709. * software distributed under the License is distributed on an
  41710. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41711. * KIND, either express or implied. See the License for the
  41712. * specific language governing permissions and limitations
  41713. * under the License.
  41714. */
  41715. var CartesianAxisPointer = BaseAxisPointer.extend({
  41716. /**
  41717. * @override
  41718. */
  41719. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  41720. var axis = axisModel.axis;
  41721. var grid = axis.grid;
  41722. var axisPointerType = axisPointerModel.get('type');
  41723. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  41724. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  41725. if (axisPointerType && axisPointerType !== 'none') {
  41726. var elStyle = buildElStyle(axisPointerModel);
  41727. var pointerOption = pointerShapeBuilder[axisPointerType](
  41728. axis, pixelValue, otherExtent
  41729. );
  41730. pointerOption.style = elStyle;
  41731. elOption.graphicKey = pointerOption.type;
  41732. elOption.pointer = pointerOption;
  41733. }
  41734. var layoutInfo = layout$1(grid.model, axisModel);
  41735. buildCartesianSingleLabelElOption(
  41736. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  41737. );
  41738. },
  41739. /**
  41740. * @override
  41741. */
  41742. getHandleTransform: function (value, axisModel, axisPointerModel) {
  41743. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  41744. labelInside: false
  41745. });
  41746. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  41747. return {
  41748. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  41749. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  41750. };
  41751. },
  41752. /**
  41753. * @override
  41754. */
  41755. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  41756. var axis = axisModel.axis;
  41757. var grid = axis.grid;
  41758. var axisExtent = axis.getGlobalExtent(true);
  41759. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  41760. var dimIndex = axis.dim === 'x' ? 0 : 1;
  41761. var currPosition = transform.position;
  41762. currPosition[dimIndex] += delta[dimIndex];
  41763. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  41764. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  41765. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  41766. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  41767. cursorPoint[dimIndex] = currPosition[dimIndex];
  41768. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  41769. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  41770. return {
  41771. position: currPosition,
  41772. rotation: transform.rotation,
  41773. cursorPoint: cursorPoint,
  41774. tooltipOption: tooltipOptions[dimIndex]
  41775. };
  41776. }
  41777. });
  41778. function getCartesian(grid, axis) {
  41779. var opt = {};
  41780. opt[axis.dim + 'AxisIndex'] = axis.index;
  41781. return grid.getCartesian(opt);
  41782. }
  41783. var pointerShapeBuilder = {
  41784. line: function (axis, pixelValue, otherExtent) {
  41785. var targetShape = makeLineShape(
  41786. [pixelValue, otherExtent[0]],
  41787. [pixelValue, otherExtent[1]],
  41788. getAxisDimIndex(axis)
  41789. );
  41790. return {
  41791. type: 'Line',
  41792. subPixelOptimize: true,
  41793. shape: targetShape
  41794. };
  41795. },
  41796. shadow: function (axis, pixelValue, otherExtent) {
  41797. var bandWidth = Math.max(1, axis.getBandWidth());
  41798. var span = otherExtent[1] - otherExtent[0];
  41799. return {
  41800. type: 'Rect',
  41801. shape: makeRectShape(
  41802. [pixelValue - bandWidth / 2, otherExtent[0]],
  41803. [bandWidth, span],
  41804. getAxisDimIndex(axis)
  41805. )
  41806. };
  41807. }
  41808. };
  41809. function getAxisDimIndex(axis) {
  41810. return axis.dim === 'x' ? 0 : 1;
  41811. }
  41812. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  41813. /*
  41814. * Licensed to the Apache Software Foundation (ASF) under one
  41815. * or more contributor license agreements. See the NOTICE file
  41816. * distributed with this work for additional information
  41817. * regarding copyright ownership. The ASF licenses this file
  41818. * to you under the Apache License, Version 2.0 (the
  41819. * "License"); you may not use this file except in compliance
  41820. * with the License. You may obtain a copy of the License at
  41821. *
  41822. * http://www.apache.org/licenses/LICENSE-2.0
  41823. *
  41824. * Unless required by applicable law or agreed to in writing,
  41825. * software distributed under the License is distributed on an
  41826. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41827. * KIND, either express or implied. See the License for the
  41828. * specific language governing permissions and limitations
  41829. * under the License.
  41830. */
  41831. // CartesianAxisPointer is not supposed to be required here. But consider
  41832. // echarts.simple.js and online build tooltip, which only require gridSimple,
  41833. // CartesianAxisPointer should be able to required somewhere.
  41834. registerPreprocessor(function (option) {
  41835. // Always has a global axisPointerModel for default setting.
  41836. if (option) {
  41837. (!option.axisPointer || option.axisPointer.length === 0)
  41838. && (option.axisPointer = {});
  41839. var link = option.axisPointer.link;
  41840. // Normalize to array to avoid object mergin. But if link
  41841. // is not set, remain null/undefined, otherwise it will
  41842. // override existent link setting.
  41843. if (link && !isArray(link)) {
  41844. option.axisPointer.link = [link];
  41845. }
  41846. }
  41847. });
  41848. // This process should proformed after coordinate systems created
  41849. // and series data processed. So put it on statistic processing stage.
  41850. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  41851. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  41852. // allAxesInfo should be updated when setOption performed.
  41853. ecModel.getComponent('axisPointer').coordSysAxesInfo =
  41854. collect(ecModel, api);
  41855. });
  41856. // Broadcast to all views.
  41857. registerAction({
  41858. type: 'updateAxisPointer',
  41859. event: 'updateAxisPointer',
  41860. update: ':updateAxisPointer'
  41861. }, axisTrigger);
  41862. /*
  41863. * Licensed to the Apache Software Foundation (ASF) under one
  41864. * or more contributor license agreements. See the NOTICE file
  41865. * distributed with this work for additional information
  41866. * regarding copyright ownership. The ASF licenses this file
  41867. * to you under the Apache License, Version 2.0 (the
  41868. * "License"); you may not use this file except in compliance
  41869. * with the License. You may obtain a copy of the License at
  41870. *
  41871. * http://www.apache.org/licenses/LICENSE-2.0
  41872. *
  41873. * Unless required by applicable law or agreed to in writing,
  41874. * software distributed under the License is distributed on an
  41875. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41876. * KIND, either express or implied. See the License for the
  41877. * specific language governing permissions and limitations
  41878. * under the License.
  41879. */
  41880. extendComponentModel({
  41881. type: 'tooltip',
  41882. dependencies: ['axisPointer'],
  41883. defaultOption: {
  41884. zlevel: 0,
  41885. z: 60,
  41886. show: true,
  41887. // tooltip主体内容
  41888. showContent: true,
  41889. // 'trigger' only works on coordinate system.
  41890. // 'item' | 'axis' | 'none'
  41891. trigger: 'item',
  41892. // 'click' | 'mousemove' | 'none'
  41893. triggerOn: 'mousemove|click',
  41894. alwaysShowContent: false,
  41895. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  41896. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  41897. // 'auto': use html by default, and use non-html if `document` is not defined
  41898. // 'html': use html for tooltip
  41899. // 'richText': use canvas, svg, and etc. for tooltip
  41900. // 位置 {Array} | {Function}
  41901. // position: null
  41902. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  41903. // align: null,
  41904. // verticalAlign: null,
  41905. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  41906. confine: false,
  41907. // 内容格式器:{string}(Template) ¦ {Function}
  41908. // formatter: null
  41909. showDelay: 0,
  41910. // 隐藏延迟,单位ms
  41911. hideDelay: 100,
  41912. // 动画变换时间,单位s
  41913. transitionDuration: 0.4,
  41914. enterable: false,
  41915. // 提示背景颜色,默认为透明度为0.7的黑色
  41916. backgroundColor: 'rgba(50,50,50,0.7)',
  41917. // 提示边框颜色
  41918. borderColor: '#333',
  41919. // 提示边框圆角,单位px,默认为4
  41920. borderRadius: 4,
  41921. // 提示边框线宽,单位px,默认为0(无边框)
  41922. borderWidth: 0,
  41923. // 提示内边距,单位px,默认各方向内边距为5,
  41924. // 接受数组分别设定上右下左边距,同css
  41925. padding: 5,
  41926. // Extra css text
  41927. extraCssText: '',
  41928. // 坐标轴指示器,坐标轴触发有效
  41929. axisPointer: {
  41930. // 默认为直线
  41931. // 可选为:'line' | 'shadow' | 'cross'
  41932. type: 'line',
  41933. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  41934. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  41935. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  41936. // 极坐标系会默认选择 angle 轴
  41937. axis: 'auto',
  41938. animation: 'auto',
  41939. animationDurationUpdate: 200,
  41940. animationEasingUpdate: 'exponentialOut',
  41941. crossStyle: {
  41942. color: '#999',
  41943. width: 1,
  41944. type: 'dashed',
  41945. // TODO formatter
  41946. textStyle: {}
  41947. }
  41948. // lineStyle and shadowStyle should not be specified here,
  41949. // otherwise it will always override those styles on option.axisPointer.
  41950. },
  41951. textStyle: {
  41952. color: '#fff',
  41953. fontSize: 14
  41954. }
  41955. }
  41956. });
  41957. /*
  41958. * Licensed to the Apache Software Foundation (ASF) under one
  41959. * or more contributor license agreements. See the NOTICE file
  41960. * distributed with this work for additional information
  41961. * regarding copyright ownership. The ASF licenses this file
  41962. * to you under the Apache License, Version 2.0 (the
  41963. * "License"); you may not use this file except in compliance
  41964. * with the License. You may obtain a copy of the License at
  41965. *
  41966. * http://www.apache.org/licenses/LICENSE-2.0
  41967. *
  41968. * Unless required by applicable law or agreed to in writing,
  41969. * software distributed under the License is distributed on an
  41970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41971. * KIND, either express or implied. See the License for the
  41972. * specific language governing permissions and limitations
  41973. * under the License.
  41974. */
  41975. var each$10 = each$1;
  41976. var toCamelCase$1 = toCamelCase;
  41977. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  41978. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  41979. /**
  41980. * @param {number} duration
  41981. * @return {string}
  41982. * @inner
  41983. */
  41984. function assembleTransition(duration) {
  41985. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  41986. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  41987. + 'top ' + duration + 's ' + transitionCurve;
  41988. return map(vendors, function (vendorPrefix) {
  41989. return vendorPrefix + 'transition:' + transitionText;
  41990. }).join(';');
  41991. }
  41992. /**
  41993. * @param {Object} textStyle
  41994. * @return {string}
  41995. * @inner
  41996. */
  41997. function assembleFont(textStyleModel) {
  41998. var cssText = [];
  41999. var fontSize = textStyleModel.get('fontSize');
  42000. var color = textStyleModel.getTextColor();
  42001. color && cssText.push('color:' + color);
  42002. cssText.push('font:' + textStyleModel.getFont());
  42003. fontSize
  42004. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  42005. each$10(['decoration', 'align'], function (name) {
  42006. var val = textStyleModel.get(name);
  42007. val && cssText.push('text-' + name + ':' + val);
  42008. });
  42009. return cssText.join(';');
  42010. }
  42011. /**
  42012. * @param {Object} tooltipModel
  42013. * @return {string}
  42014. * @inner
  42015. */
  42016. function assembleCssText(tooltipModel) {
  42017. var cssText = [];
  42018. var transitionDuration = tooltipModel.get('transitionDuration');
  42019. var backgroundColor = tooltipModel.get('backgroundColor');
  42020. var textStyleModel = tooltipModel.getModel('textStyle');
  42021. var padding = tooltipModel.get('padding');
  42022. // Animation transition. Do not animate when transitionDuration is 0.
  42023. transitionDuration
  42024. && cssText.push(assembleTransition(transitionDuration));
  42025. if (backgroundColor) {
  42026. if (env$1.canvasSupported) {
  42027. cssText.push('background-Color:' + backgroundColor);
  42028. }
  42029. else {
  42030. // for ie
  42031. cssText.push(
  42032. 'background-Color:#' + toHex(backgroundColor)
  42033. );
  42034. cssText.push('filter:alpha(opacity=70)');
  42035. }
  42036. }
  42037. // Border style
  42038. each$10(['width', 'color', 'radius'], function (name) {
  42039. var borderName = 'border-' + name;
  42040. var camelCase = toCamelCase$1(borderName);
  42041. var val = tooltipModel.get(camelCase);
  42042. val != null
  42043. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  42044. });
  42045. // Text style
  42046. cssText.push(assembleFont(textStyleModel));
  42047. // Padding
  42048. if (padding != null) {
  42049. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  42050. }
  42051. return cssText.join(';') + ';';
  42052. }
  42053. /**
  42054. * @alias module:echarts/component/tooltip/TooltipContent
  42055. * @constructor
  42056. */
  42057. function TooltipContent(container, api) {
  42058. if (env$1.wxa) {
  42059. return null;
  42060. }
  42061. var el = document.createElement('div');
  42062. var zr = this._zr = api.getZr();
  42063. this.el = el;
  42064. this._x = api.getWidth() / 2;
  42065. this._y = api.getHeight() / 2;
  42066. container.appendChild(el);
  42067. this._container = container;
  42068. this._show = false;
  42069. /**
  42070. * @private
  42071. */
  42072. this._hideTimeout;
  42073. // FIXME
  42074. // Is it needed to trigger zr event manually if
  42075. // the browser do not support `pointer-events: none`.
  42076. var self = this;
  42077. el.onmouseenter = function () {
  42078. // clear the timeout in hideLater and keep showing tooltip
  42079. if (self._enterable) {
  42080. clearTimeout(self._hideTimeout);
  42081. self._show = true;
  42082. }
  42083. self._inContent = true;
  42084. };
  42085. el.onmousemove = function (e) {
  42086. e = e || window.event;
  42087. if (!self._enterable) {
  42088. // `pointer-events: none` is set to tooltip content div
  42089. // if `enterable` is set as `false`, and `el.onmousemove`
  42090. // can not be triggered. But in browser that do not
  42091. // support `pointer-events`, we need to do this:
  42092. // Try trigger zrender event to avoid mouse
  42093. // in and out shape too frequently
  42094. var handler = zr.handler;
  42095. normalizeEvent(container, e, true);
  42096. handler.dispatch('mousemove', e);
  42097. }
  42098. };
  42099. el.onmouseleave = function () {
  42100. if (self._enterable) {
  42101. if (self._show) {
  42102. self.hideLater(self._hideDelay);
  42103. }
  42104. }
  42105. self._inContent = false;
  42106. };
  42107. }
  42108. TooltipContent.prototype = {
  42109. constructor: TooltipContent,
  42110. /**
  42111. * @private
  42112. * @type {boolean}
  42113. */
  42114. _enterable: true,
  42115. /**
  42116. * Update when tooltip is rendered
  42117. */
  42118. update: function () {
  42119. // FIXME
  42120. // Move this logic to ec main?
  42121. var container = this._container;
  42122. var stl = container.currentStyle
  42123. || document.defaultView.getComputedStyle(container);
  42124. var domStyle = container.style;
  42125. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  42126. domStyle.position = 'relative';
  42127. }
  42128. // Hide the tooltip
  42129. // PENDING
  42130. // this.hide();
  42131. },
  42132. show: function (tooltipModel) {
  42133. clearTimeout(this._hideTimeout);
  42134. var el = this.el;
  42135. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  42136. // Because of the reason described in:
  42137. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  42138. // we should set initial value to `left` and `top`.
  42139. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  42140. + (tooltipModel.get('extraCssText') || '');
  42141. el.style.display = el.innerHTML ? 'block' : 'none';
  42142. // If mouse occsionally move over the tooltip, a mouseout event will be
  42143. // triggered by canvas, and cuase some unexpectable result like dragging
  42144. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  42145. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  42146. // scenario.
  42147. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  42148. this._show = true;
  42149. },
  42150. setContent: function (content) {
  42151. this.el.innerHTML = content == null ? '' : content;
  42152. },
  42153. setEnterable: function (enterable) {
  42154. this._enterable = enterable;
  42155. },
  42156. getSize: function () {
  42157. var el = this.el;
  42158. return [el.clientWidth, el.clientHeight];
  42159. },
  42160. moveTo: function (x, y) {
  42161. // xy should be based on canvas root. But tooltipContent is
  42162. // the sibling of canvas root. So padding of ec container
  42163. // should be considered here.
  42164. var zr = this._zr;
  42165. var viewportRootOffset;
  42166. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  42167. x += viewportRootOffset.offsetLeft;
  42168. y += viewportRootOffset.offsetTop;
  42169. }
  42170. var style = this.el.style;
  42171. style.left = x + 'px';
  42172. style.top = y + 'px';
  42173. this._x = x;
  42174. this._y = y;
  42175. },
  42176. hide: function () {
  42177. this.el.style.display = 'none';
  42178. this._show = false;
  42179. },
  42180. hideLater: function (time) {
  42181. if (this._show && !(this._inContent && this._enterable)) {
  42182. if (time) {
  42183. this._hideDelay = time;
  42184. // Set show false to avoid invoke hideLater mutiple times
  42185. this._show = false;
  42186. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  42187. }
  42188. else {
  42189. this.hide();
  42190. }
  42191. }
  42192. },
  42193. isShow: function () {
  42194. return this._show;
  42195. },
  42196. getOuterSize: function () {
  42197. var width = this.el.clientWidth;
  42198. var height = this.el.clientHeight;
  42199. // Consider browser compatibility.
  42200. // IE8 does not support getComputedStyle.
  42201. if (document.defaultView && document.defaultView.getComputedStyle) {
  42202. var stl = document.defaultView.getComputedStyle(this.el);
  42203. if (stl) {
  42204. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  42205. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  42206. }
  42207. }
  42208. return {width: width, height: height};
  42209. }
  42210. };
  42211. /*
  42212. * Licensed to the Apache Software Foundation (ASF) under one
  42213. * or more contributor license agreements. See the NOTICE file
  42214. * distributed with this work for additional information
  42215. * regarding copyright ownership. The ASF licenses this file
  42216. * to you under the Apache License, Version 2.0 (the
  42217. * "License"); you may not use this file except in compliance
  42218. * with the License. You may obtain a copy of the License at
  42219. *
  42220. * http://www.apache.org/licenses/LICENSE-2.0
  42221. *
  42222. * Unless required by applicable law or agreed to in writing,
  42223. * software distributed under the License is distributed on an
  42224. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42225. * KIND, either express or implied. See the License for the
  42226. * specific language governing permissions and limitations
  42227. * under the License.
  42228. */
  42229. // import Group from 'zrender/src/container/Group';
  42230. /**
  42231. * @alias module:echarts/component/tooltip/TooltipRichContent
  42232. * @constructor
  42233. */
  42234. function TooltipRichContent(api) {
  42235. this._zr = api.getZr();
  42236. this._show = false;
  42237. /**
  42238. * @private
  42239. */
  42240. this._hideTimeout;
  42241. }
  42242. TooltipRichContent.prototype = {
  42243. constructor: TooltipRichContent,
  42244. /**
  42245. * @private
  42246. * @type {boolean}
  42247. */
  42248. _enterable: true,
  42249. /**
  42250. * Update when tooltip is rendered
  42251. */
  42252. update: function () {
  42253. // noop
  42254. },
  42255. show: function (tooltipModel) {
  42256. if (this._hideTimeout) {
  42257. clearTimeout(this._hideTimeout);
  42258. }
  42259. this.el.attr('show', true);
  42260. this._show = true;
  42261. },
  42262. /**
  42263. * Set tooltip content
  42264. *
  42265. * @param {string} content rich text string of content
  42266. * @param {Object} markerRich rich text style
  42267. * @param {Object} tooltipModel tooltip model
  42268. */
  42269. setContent: function (content, markerRich, tooltipModel) {
  42270. if (this.el) {
  42271. this._zr.remove(this.el);
  42272. }
  42273. var markers = {};
  42274. var text = content;
  42275. var prefix = '{marker';
  42276. var suffix = '|}';
  42277. var startId = text.indexOf(prefix);
  42278. while (startId >= 0) {
  42279. var endId = text.indexOf(suffix);
  42280. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  42281. if (name.indexOf('sub') > -1) {
  42282. markers['marker' + name] = {
  42283. textWidth: 4,
  42284. textHeight: 4,
  42285. textBorderRadius: 2,
  42286. textBackgroundColor: markerRich[name],
  42287. // TODO: textOffset is not implemented for rich text
  42288. textOffset: [3, 0]
  42289. };
  42290. }
  42291. else {
  42292. markers['marker' + name] = {
  42293. textWidth: 10,
  42294. textHeight: 10,
  42295. textBorderRadius: 5,
  42296. textBackgroundColor: markerRich[name]
  42297. };
  42298. }
  42299. text = text.substr(endId + 1);
  42300. startId = text.indexOf('{marker');
  42301. }
  42302. this.el = new Text({
  42303. style: {
  42304. rich: markers,
  42305. text: content,
  42306. textLineHeight: 20,
  42307. textBackgroundColor: tooltipModel.get('backgroundColor'),
  42308. textBorderRadius: tooltipModel.get('borderRadius'),
  42309. textFill: tooltipModel.get('textStyle.color'),
  42310. textPadding: tooltipModel.get('padding')
  42311. },
  42312. z: tooltipModel.get('z')
  42313. });
  42314. this._zr.add(this.el);
  42315. var self = this;
  42316. this.el.on('mouseover', function () {
  42317. // clear the timeout in hideLater and keep showing tooltip
  42318. if (self._enterable) {
  42319. clearTimeout(self._hideTimeout);
  42320. self._show = true;
  42321. }
  42322. self._inContent = true;
  42323. });
  42324. this.el.on('mouseout', function () {
  42325. if (self._enterable) {
  42326. if (self._show) {
  42327. self.hideLater(self._hideDelay);
  42328. }
  42329. }
  42330. self._inContent = false;
  42331. });
  42332. },
  42333. setEnterable: function (enterable) {
  42334. this._enterable = enterable;
  42335. },
  42336. getSize: function () {
  42337. var bounding = this.el.getBoundingRect();
  42338. return [bounding.width, bounding.height];
  42339. },
  42340. moveTo: function (x, y) {
  42341. if (this.el) {
  42342. this.el.attr('position', [x, y]);
  42343. }
  42344. },
  42345. hide: function () {
  42346. if (this.el) {
  42347. this.el.hide();
  42348. }
  42349. this._show = false;
  42350. },
  42351. hideLater: function (time) {
  42352. if (this._show && !(this._inContent && this._enterable)) {
  42353. if (time) {
  42354. this._hideDelay = time;
  42355. // Set show false to avoid invoke hideLater mutiple times
  42356. this._show = false;
  42357. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  42358. }
  42359. else {
  42360. this.hide();
  42361. }
  42362. }
  42363. },
  42364. isShow: function () {
  42365. return this._show;
  42366. },
  42367. getOuterSize: function () {
  42368. var size = this.getSize();
  42369. return {
  42370. width: size[0],
  42371. height: size[1]
  42372. };
  42373. }
  42374. };
  42375. /*
  42376. * Licensed to the Apache Software Foundation (ASF) under one
  42377. * or more contributor license agreements. See the NOTICE file
  42378. * distributed with this work for additional information
  42379. * regarding copyright ownership. The ASF licenses this file
  42380. * to you under the Apache License, Version 2.0 (the
  42381. * "License"); you may not use this file except in compliance
  42382. * with the License. You may obtain a copy of the License at
  42383. *
  42384. * http://www.apache.org/licenses/LICENSE-2.0
  42385. *
  42386. * Unless required by applicable law or agreed to in writing,
  42387. * software distributed under the License is distributed on an
  42388. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42389. * KIND, either express or implied. See the License for the
  42390. * specific language governing permissions and limitations
  42391. * under the License.
  42392. */
  42393. var bind$2 = bind;
  42394. var each$9 = each$1;
  42395. var parsePercent$2 = parsePercent$1;
  42396. var proxyRect = new Rect({
  42397. shape: {x: -1, y: -1, width: 2, height: 2}
  42398. });
  42399. extendComponentView({
  42400. type: 'tooltip',
  42401. init: function (ecModel, api) {
  42402. if (env$1.node) {
  42403. return;
  42404. }
  42405. var tooltipModel = ecModel.getComponent('tooltip');
  42406. var renderMode = tooltipModel.get('renderMode');
  42407. this._renderMode = getTooltipRenderMode(renderMode);
  42408. var tooltipContent;
  42409. if (this._renderMode === 'html') {
  42410. tooltipContent = new TooltipContent(api.getDom(), api);
  42411. this._newLine = '<br/>';
  42412. }
  42413. else {
  42414. tooltipContent = new TooltipRichContent(api);
  42415. this._newLine = '\n';
  42416. }
  42417. this._tooltipContent = tooltipContent;
  42418. },
  42419. render: function (tooltipModel, ecModel, api) {
  42420. if (env$1.node) {
  42421. return;
  42422. }
  42423. // Reset
  42424. this.group.removeAll();
  42425. /**
  42426. * @private
  42427. * @type {module:echarts/component/tooltip/TooltipModel}
  42428. */
  42429. this._tooltipModel = tooltipModel;
  42430. /**
  42431. * @private
  42432. * @type {module:echarts/model/Global}
  42433. */
  42434. this._ecModel = ecModel;
  42435. /**
  42436. * @private
  42437. * @type {module:echarts/ExtensionAPI}
  42438. */
  42439. this._api = api;
  42440. /**
  42441. * Should be cleaned when render.
  42442. * @private
  42443. * @type {Array.<Array.<Object>>}
  42444. */
  42445. this._lastDataByCoordSys = null;
  42446. /**
  42447. * @private
  42448. * @type {boolean}
  42449. */
  42450. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  42451. var tooltipContent = this._tooltipContent;
  42452. tooltipContent.update();
  42453. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  42454. this._initGlobalListener();
  42455. this._keepShow();
  42456. },
  42457. _initGlobalListener: function () {
  42458. var tooltipModel = this._tooltipModel;
  42459. var triggerOn = tooltipModel.get('triggerOn');
  42460. register(
  42461. 'itemTooltip',
  42462. this._api,
  42463. bind$2(function (currTrigger, e, dispatchAction) {
  42464. // If 'none', it is not controlled by mouse totally.
  42465. if (triggerOn !== 'none') {
  42466. if (triggerOn.indexOf(currTrigger) >= 0) {
  42467. this._tryShow(e, dispatchAction);
  42468. }
  42469. else if (currTrigger === 'leave') {
  42470. this._hide(dispatchAction);
  42471. }
  42472. }
  42473. }, this)
  42474. );
  42475. },
  42476. _keepShow: function () {
  42477. var tooltipModel = this._tooltipModel;
  42478. var ecModel = this._ecModel;
  42479. var api = this._api;
  42480. // Try to keep the tooltip show when refreshing
  42481. if (this._lastX != null
  42482. && this._lastY != null
  42483. // When user is willing to control tooltip totally using API,
  42484. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  42485. // which is not expected.
  42486. && tooltipModel.get('triggerOn') !== 'none'
  42487. ) {
  42488. var self = this;
  42489. clearTimeout(this._refreshUpdateTimeout);
  42490. this._refreshUpdateTimeout = setTimeout(function () {
  42491. // Show tip next tick after other charts are rendered
  42492. // In case highlight action has wrong result
  42493. // FIXME
  42494. !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
  42495. x: self._lastX,
  42496. y: self._lastY
  42497. });
  42498. });
  42499. }
  42500. },
  42501. /**
  42502. * Show tip manually by
  42503. * dispatchAction({
  42504. * type: 'showTip',
  42505. * x: 10,
  42506. * y: 10
  42507. * });
  42508. * Or
  42509. * dispatchAction({
  42510. * type: 'showTip',
  42511. * seriesIndex: 0,
  42512. * dataIndex or dataIndexInside or name
  42513. * });
  42514. *
  42515. * TODO Batch
  42516. */
  42517. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  42518. if (payload.from === this.uid || env$1.node) {
  42519. return;
  42520. }
  42521. var dispatchAction = makeDispatchAction$1(payload, api);
  42522. // Reset ticket
  42523. this._ticket = '';
  42524. // When triggered from axisPointer.
  42525. var dataByCoordSys = payload.dataByCoordSys;
  42526. if (payload.tooltip && payload.x != null && payload.y != null) {
  42527. var el = proxyRect;
  42528. el.position = [payload.x, payload.y];
  42529. el.update();
  42530. el.tooltip = payload.tooltip;
  42531. // Manually show tooltip while view is not using zrender elements.
  42532. this._tryShow({
  42533. offsetX: payload.x,
  42534. offsetY: payload.y,
  42535. target: el
  42536. }, dispatchAction);
  42537. }
  42538. else if (dataByCoordSys) {
  42539. this._tryShow({
  42540. offsetX: payload.x,
  42541. offsetY: payload.y,
  42542. position: payload.position,
  42543. event: {},
  42544. dataByCoordSys: payload.dataByCoordSys,
  42545. tooltipOption: payload.tooltipOption
  42546. }, dispatchAction);
  42547. }
  42548. else if (payload.seriesIndex != null) {
  42549. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  42550. return;
  42551. }
  42552. var pointInfo = findPointFromSeries(payload, ecModel);
  42553. var cx = pointInfo.point[0];
  42554. var cy = pointInfo.point[1];
  42555. if (cx != null && cy != null) {
  42556. this._tryShow({
  42557. offsetX: cx,
  42558. offsetY: cy,
  42559. position: payload.position,
  42560. target: pointInfo.el,
  42561. event: {}
  42562. }, dispatchAction);
  42563. }
  42564. }
  42565. else if (payload.x != null && payload.y != null) {
  42566. // FIXME
  42567. // should wrap dispatchAction like `axisPointer/globalListener` ?
  42568. api.dispatchAction({
  42569. type: 'updateAxisPointer',
  42570. x: payload.x,
  42571. y: payload.y
  42572. });
  42573. this._tryShow({
  42574. offsetX: payload.x,
  42575. offsetY: payload.y,
  42576. position: payload.position,
  42577. target: api.getZr().findHover(payload.x, payload.y).target,
  42578. event: {}
  42579. }, dispatchAction);
  42580. }
  42581. },
  42582. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  42583. var tooltipContent = this._tooltipContent;
  42584. if (!this._alwaysShowContent && this._tooltipModel) {
  42585. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  42586. }
  42587. this._lastX = this._lastY = null;
  42588. if (payload.from !== this.uid) {
  42589. this._hide(makeDispatchAction$1(payload, api));
  42590. }
  42591. },
  42592. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  42593. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  42594. // and tooltip.
  42595. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  42596. var seriesIndex = payload.seriesIndex;
  42597. var dataIndex = payload.dataIndex;
  42598. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  42599. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  42600. return;
  42601. }
  42602. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  42603. if (!seriesModel) {
  42604. return;
  42605. }
  42606. var data = seriesModel.getData();
  42607. var tooltipModel = buildTooltipModel([
  42608. data.getItemModel(dataIndex),
  42609. seriesModel,
  42610. (seriesModel.coordinateSystem || {}).model,
  42611. tooltipModel
  42612. ]);
  42613. if (tooltipModel.get('trigger') !== 'axis') {
  42614. return;
  42615. }
  42616. api.dispatchAction({
  42617. type: 'updateAxisPointer',
  42618. seriesIndex: seriesIndex,
  42619. dataIndex: dataIndex,
  42620. position: payload.position
  42621. });
  42622. return true;
  42623. },
  42624. _tryShow: function (e, dispatchAction) {
  42625. var el = e.target;
  42626. var tooltipModel = this._tooltipModel;
  42627. if (!tooltipModel) {
  42628. return;
  42629. }
  42630. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  42631. this._lastX = e.offsetX;
  42632. this._lastY = e.offsetY;
  42633. var dataByCoordSys = e.dataByCoordSys;
  42634. if (dataByCoordSys && dataByCoordSys.length) {
  42635. this._showAxisTooltip(dataByCoordSys, e);
  42636. }
  42637. // Always show item tooltip if mouse is on the element with dataIndex
  42638. else if (el && el.dataIndex != null) {
  42639. this._lastDataByCoordSys = null;
  42640. this._showSeriesItemTooltip(e, el, dispatchAction);
  42641. }
  42642. // Tooltip provided directly. Like legend.
  42643. else if (el && el.tooltip) {
  42644. this._lastDataByCoordSys = null;
  42645. this._showComponentItemTooltip(e, el, dispatchAction);
  42646. }
  42647. else {
  42648. this._lastDataByCoordSys = null;
  42649. this._hide(dispatchAction);
  42650. }
  42651. },
  42652. _showOrMove: function (tooltipModel, cb) {
  42653. // showDelay is used in this case: tooltip.enterable is set
  42654. // as true. User intent to move mouse into tooltip and click
  42655. // something. `showDelay` makes it easyer to enter the content
  42656. // but tooltip do not move immediately.
  42657. var delay = tooltipModel.get('showDelay');
  42658. cb = bind(cb, this);
  42659. clearTimeout(this._showTimout);
  42660. delay > 0
  42661. ? (this._showTimout = setTimeout(cb, delay))
  42662. : cb();
  42663. },
  42664. _showAxisTooltip: function (dataByCoordSys, e) {
  42665. var ecModel = this._ecModel;
  42666. var globalTooltipModel = this._tooltipModel;
  42667. var point = [e.offsetX, e.offsetY];
  42668. var singleDefaultHTML = [];
  42669. var singleParamsList = [];
  42670. var singleTooltipModel = buildTooltipModel([
  42671. e.tooltipOption,
  42672. globalTooltipModel
  42673. ]);
  42674. var renderMode = this._renderMode;
  42675. var newLine = this._newLine;
  42676. var markers = {};
  42677. each$9(dataByCoordSys, function (itemCoordSys) {
  42678. // var coordParamList = [];
  42679. // var coordDefaultHTML = [];
  42680. // var coordTooltipModel = buildTooltipModel([
  42681. // e.tooltipOption,
  42682. // itemCoordSys.tooltipOption,
  42683. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  42684. // globalTooltipModel
  42685. // ]);
  42686. // var displayMode = coordTooltipModel.get('displayMode');
  42687. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  42688. each$9(itemCoordSys.dataByAxis, function (item) {
  42689. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  42690. var axisValue = item.value;
  42691. var seriesDefaultHTML = [];
  42692. if (!axisModel || axisValue == null) {
  42693. return;
  42694. }
  42695. var valueLabel = getValueLabel(
  42696. axisValue, axisModel.axis, ecModel,
  42697. item.seriesDataIndices,
  42698. item.valueLabelOpt
  42699. );
  42700. each$1(item.seriesDataIndices, function (idxItem) {
  42701. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  42702. var dataIndex = idxItem.dataIndexInside;
  42703. var dataParams = series && series.getDataParams(dataIndex);
  42704. dataParams.axisDim = item.axisDim;
  42705. dataParams.axisIndex = item.axisIndex;
  42706. dataParams.axisType = item.axisType;
  42707. dataParams.axisId = item.axisId;
  42708. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  42709. dataParams.axisValueLabel = valueLabel;
  42710. if (dataParams) {
  42711. singleParamsList.push(dataParams);
  42712. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  42713. var html;
  42714. if (isObject$1(seriesTooltip)) {
  42715. html = seriesTooltip.html;
  42716. var newMarkers = seriesTooltip.markers;
  42717. merge(markers, newMarkers);
  42718. }
  42719. else {
  42720. html = seriesTooltip;
  42721. }
  42722. seriesDefaultHTML.push(html);
  42723. }
  42724. });
  42725. // Default tooltip content
  42726. // FIXME
  42727. // (1) shold be the first data which has name?
  42728. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  42729. var firstLine = valueLabel;
  42730. if (renderMode !== 'html') {
  42731. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  42732. }
  42733. else {
  42734. singleDefaultHTML.push(
  42735. (firstLine ? encodeHTML(firstLine) + newLine : '')
  42736. + seriesDefaultHTML.join(newLine)
  42737. );
  42738. }
  42739. });
  42740. }, this);
  42741. // In most case, the second axis is shown upper than the first one.
  42742. singleDefaultHTML.reverse();
  42743. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  42744. var positionExpr = e.position;
  42745. this._showOrMove(singleTooltipModel, function () {
  42746. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  42747. this._updatePosition(
  42748. singleTooltipModel,
  42749. positionExpr,
  42750. point[0], point[1],
  42751. this._tooltipContent,
  42752. singleParamsList
  42753. );
  42754. }
  42755. else {
  42756. this._showTooltipContent(
  42757. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  42758. point[0], point[1], positionExpr, undefined, markers
  42759. );
  42760. }
  42761. });
  42762. // Do not trigger events here, because this branch only be entered
  42763. // from dispatchAction.
  42764. },
  42765. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  42766. var ecModel = this._ecModel;
  42767. // Use dataModel in element if possible
  42768. // Used when mouseover on a element like markPoint or edge
  42769. // In which case, the data is not main data in series.
  42770. var seriesIndex = el.seriesIndex;
  42771. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  42772. // For example, graph link.
  42773. var dataModel = el.dataModel || seriesModel;
  42774. var dataIndex = el.dataIndex;
  42775. var dataType = el.dataType;
  42776. var data = dataModel.getData();
  42777. var tooltipModel = buildTooltipModel([
  42778. data.getItemModel(dataIndex),
  42779. dataModel,
  42780. seriesModel && (seriesModel.coordinateSystem || {}).model,
  42781. this._tooltipModel
  42782. ]);
  42783. var tooltipTrigger = tooltipModel.get('trigger');
  42784. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  42785. return;
  42786. }
  42787. var params = dataModel.getDataParams(dataIndex, dataType);
  42788. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  42789. var defaultHtml;
  42790. var markers;
  42791. if (isObject$1(seriesTooltip)) {
  42792. defaultHtml = seriesTooltip.html;
  42793. markers = seriesTooltip.markers;
  42794. }
  42795. else {
  42796. defaultHtml = seriesTooltip;
  42797. markers = null;
  42798. }
  42799. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  42800. this._showOrMove(tooltipModel, function () {
  42801. this._showTooltipContent(
  42802. tooltipModel, defaultHtml, params, asyncTicket,
  42803. e.offsetX, e.offsetY, e.position, e.target, markers
  42804. );
  42805. });
  42806. // FIXME
  42807. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  42808. dispatchAction({
  42809. type: 'showTip',
  42810. dataIndexInside: dataIndex,
  42811. dataIndex: data.getRawIndex(dataIndex),
  42812. seriesIndex: seriesIndex,
  42813. from: this.uid
  42814. });
  42815. },
  42816. _showComponentItemTooltip: function (e, el, dispatchAction) {
  42817. var tooltipOpt = el.tooltip;
  42818. if (typeof tooltipOpt === 'string') {
  42819. var content = tooltipOpt;
  42820. tooltipOpt = {
  42821. content: content,
  42822. // Fixed formatter
  42823. formatter: content
  42824. };
  42825. }
  42826. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  42827. var defaultHtml = subTooltipModel.get('content');
  42828. var asyncTicket = Math.random();
  42829. // Do not check whether `trigger` is 'none' here, because `trigger`
  42830. // only works on cooridinate system. In fact, we have not found case
  42831. // that requires setting `trigger` nothing on component yet.
  42832. this._showOrMove(subTooltipModel, function () {
  42833. this._showTooltipContent(
  42834. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  42835. asyncTicket, e.offsetX, e.offsetY, e.position, el
  42836. );
  42837. });
  42838. // If not dispatch showTip, tip may be hide triggered by axis.
  42839. dispatchAction({
  42840. type: 'showTip',
  42841. from: this.uid
  42842. });
  42843. },
  42844. _showTooltipContent: function (
  42845. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  42846. ) {
  42847. // Reset ticket
  42848. this._ticket = '';
  42849. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  42850. return;
  42851. }
  42852. var tooltipContent = this._tooltipContent;
  42853. var formatter = tooltipModel.get('formatter');
  42854. positionExpr = positionExpr || tooltipModel.get('position');
  42855. var html = defaultHtml;
  42856. if (formatter && typeof formatter === 'string') {
  42857. html = formatTpl(formatter, params, true);
  42858. }
  42859. else if (typeof formatter === 'function') {
  42860. var callback = bind$2(function (cbTicket, html) {
  42861. if (cbTicket === this._ticket) {
  42862. tooltipContent.setContent(html, markers, tooltipModel);
  42863. this._updatePosition(
  42864. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  42865. );
  42866. }
  42867. }, this);
  42868. this._ticket = asyncTicket;
  42869. html = formatter(params, asyncTicket, callback);
  42870. }
  42871. tooltipContent.setContent(html, markers, tooltipModel);
  42872. tooltipContent.show(tooltipModel);
  42873. this._updatePosition(
  42874. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  42875. );
  42876. },
  42877. /**
  42878. * @param {string|Function|Array.<number>|Object} positionExpr
  42879. * @param {number} x Mouse x
  42880. * @param {number} y Mouse y
  42881. * @param {boolean} confine Whether confine tooltip content in view rect.
  42882. * @param {Object|<Array.<Object>} params
  42883. * @param {module:zrender/Element} el target element
  42884. * @param {module:echarts/ExtensionAPI} api
  42885. * @return {Array.<number>}
  42886. */
  42887. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  42888. var viewWidth = this._api.getWidth();
  42889. var viewHeight = this._api.getHeight();
  42890. positionExpr = positionExpr || tooltipModel.get('position');
  42891. var contentSize = content.getSize();
  42892. var align = tooltipModel.get('align');
  42893. var vAlign = tooltipModel.get('verticalAlign');
  42894. var rect = el && el.getBoundingRect().clone();
  42895. el && rect.applyTransform(el.transform);
  42896. if (typeof positionExpr === 'function') {
  42897. // Callback of position can be an array or a string specify the position
  42898. positionExpr = positionExpr([x, y], params, content.el, rect, {
  42899. viewSize: [viewWidth, viewHeight],
  42900. contentSize: contentSize.slice()
  42901. });
  42902. }
  42903. if (isArray(positionExpr)) {
  42904. x = parsePercent$2(positionExpr[0], viewWidth);
  42905. y = parsePercent$2(positionExpr[1], viewHeight);
  42906. }
  42907. else if (isObject$1(positionExpr)) {
  42908. positionExpr.width = contentSize[0];
  42909. positionExpr.height = contentSize[1];
  42910. var layoutRect = getLayoutRect(
  42911. positionExpr, {width: viewWidth, height: viewHeight}
  42912. );
  42913. x = layoutRect.x;
  42914. y = layoutRect.y;
  42915. align = null;
  42916. // When positionExpr is left/top/right/bottom,
  42917. // align and verticalAlign will not work.
  42918. vAlign = null;
  42919. }
  42920. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  42921. else if (typeof positionExpr === 'string' && el) {
  42922. var pos = calcTooltipPosition(
  42923. positionExpr, rect, contentSize
  42924. );
  42925. x = pos[0];
  42926. y = pos[1];
  42927. }
  42928. else {
  42929. var pos = refixTooltipPosition(
  42930. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  42931. );
  42932. x = pos[0];
  42933. y = pos[1];
  42934. }
  42935. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  42936. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  42937. if (tooltipModel.get('confine')) {
  42938. var pos = confineTooltipPosition(
  42939. x, y, content, viewWidth, viewHeight
  42940. );
  42941. x = pos[0];
  42942. y = pos[1];
  42943. }
  42944. content.moveTo(x, y);
  42945. },
  42946. // FIXME
  42947. // Should we remove this but leave this to user?
  42948. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  42949. var lastCoordSys = this._lastDataByCoordSys;
  42950. var contentNotChanged = !!lastCoordSys
  42951. && lastCoordSys.length === dataByCoordSys.length;
  42952. contentNotChanged && each$9(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  42953. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  42954. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  42955. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  42956. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  42957. contentNotChanged && each$9(lastDataByAxis, function (lastItem, indexAxis) {
  42958. var thisItem = thisDataByAxis[indexAxis] || {};
  42959. var lastIndices = lastItem.seriesDataIndices || [];
  42960. var newIndices = thisItem.seriesDataIndices || [];
  42961. contentNotChanged
  42962. &= lastItem.value === thisItem.value
  42963. && lastItem.axisType === thisItem.axisType
  42964. && lastItem.axisId === thisItem.axisId
  42965. && lastIndices.length === newIndices.length;
  42966. contentNotChanged && each$9(lastIndices, function (lastIdxItem, j) {
  42967. var newIdxItem = newIndices[j];
  42968. contentNotChanged
  42969. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  42970. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  42971. });
  42972. });
  42973. });
  42974. this._lastDataByCoordSys = dataByCoordSys;
  42975. return !!contentNotChanged;
  42976. },
  42977. _hide: function (dispatchAction) {
  42978. // Do not directly hideLater here, because this behavior may be prevented
  42979. // in dispatchAction when showTip is dispatched.
  42980. // FIXME
  42981. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  42982. this._lastDataByCoordSys = null;
  42983. dispatchAction({
  42984. type: 'hideTip',
  42985. from: this.uid
  42986. });
  42987. },
  42988. dispose: function (ecModel, api) {
  42989. if (env$1.node) {
  42990. return;
  42991. }
  42992. this._tooltipContent.hide();
  42993. unregister('itemTooltip', api);
  42994. }
  42995. });
  42996. /**
  42997. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  42998. * From top to bottom. (the last one should be globalTooltipModel);
  42999. */
  43000. function buildTooltipModel(modelCascade) {
  43001. var resultModel = modelCascade.pop();
  43002. while (modelCascade.length) {
  43003. var tooltipOpt = modelCascade.pop();
  43004. if (tooltipOpt) {
  43005. if (Model.isInstance(tooltipOpt)) {
  43006. tooltipOpt = tooltipOpt.get('tooltip', true);
  43007. }
  43008. // In each data item tooltip can be simply write:
  43009. // {
  43010. // value: 10,
  43011. // tooltip: 'Something you need to know'
  43012. // }
  43013. if (typeof tooltipOpt === 'string') {
  43014. tooltipOpt = {formatter: tooltipOpt};
  43015. }
  43016. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  43017. }
  43018. }
  43019. return resultModel;
  43020. }
  43021. function makeDispatchAction$1(payload, api) {
  43022. return payload.dispatchAction || bind(api.dispatchAction, api);
  43023. }
  43024. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  43025. var size = content.getOuterSize();
  43026. var width = size.width;
  43027. var height = size.height;
  43028. if (gapH != null) {
  43029. if (x + width + gapH > viewWidth) {
  43030. x -= width + gapH;
  43031. }
  43032. else {
  43033. x += gapH;
  43034. }
  43035. }
  43036. if (gapV != null) {
  43037. if (y + height + gapV > viewHeight) {
  43038. y -= height + gapV;
  43039. }
  43040. else {
  43041. y += gapV;
  43042. }
  43043. }
  43044. return [x, y];
  43045. }
  43046. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  43047. var size = content.getOuterSize();
  43048. var width = size.width;
  43049. var height = size.height;
  43050. x = Math.min(x + width, viewWidth) - width;
  43051. y = Math.min(y + height, viewHeight) - height;
  43052. x = Math.max(x, 0);
  43053. y = Math.max(y, 0);
  43054. return [x, y];
  43055. }
  43056. function calcTooltipPosition(position, rect, contentSize) {
  43057. var domWidth = contentSize[0];
  43058. var domHeight = contentSize[1];
  43059. var gap = 5;
  43060. var x = 0;
  43061. var y = 0;
  43062. var rectWidth = rect.width;
  43063. var rectHeight = rect.height;
  43064. switch (position) {
  43065. case 'inside':
  43066. x = rect.x + rectWidth / 2 - domWidth / 2;
  43067. y = rect.y + rectHeight / 2 - domHeight / 2;
  43068. break;
  43069. case 'top':
  43070. x = rect.x + rectWidth / 2 - domWidth / 2;
  43071. y = rect.y - domHeight - gap;
  43072. break;
  43073. case 'bottom':
  43074. x = rect.x + rectWidth / 2 - domWidth / 2;
  43075. y = rect.y + rectHeight + gap;
  43076. break;
  43077. case 'left':
  43078. x = rect.x - domWidth - gap;
  43079. y = rect.y + rectHeight / 2 - domHeight / 2;
  43080. break;
  43081. case 'right':
  43082. x = rect.x + rectWidth + gap;
  43083. y = rect.y + rectHeight / 2 - domHeight / 2;
  43084. }
  43085. return [x, y];
  43086. }
  43087. function isCenterAlign(align) {
  43088. return align === 'center' || align === 'middle';
  43089. }
  43090. /*
  43091. * Licensed to the Apache Software Foundation (ASF) under one
  43092. * or more contributor license agreements. See the NOTICE file
  43093. * distributed with this work for additional information
  43094. * regarding copyright ownership. The ASF licenses this file
  43095. * to you under the Apache License, Version 2.0 (the
  43096. * "License"); you may not use this file except in compliance
  43097. * with the License. You may obtain a copy of the License at
  43098. *
  43099. * http://www.apache.org/licenses/LICENSE-2.0
  43100. *
  43101. * Unless required by applicable law or agreed to in writing,
  43102. * software distributed under the License is distributed on an
  43103. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43104. * KIND, either express or implied. See the License for the
  43105. * specific language governing permissions and limitations
  43106. * under the License.
  43107. */
  43108. // FIXME Better way to pack data in graphic element
  43109. /**
  43110. * @action
  43111. * @property {string} type
  43112. * @property {number} seriesIndex
  43113. * @property {number} dataIndex
  43114. * @property {number} [x]
  43115. * @property {number} [y]
  43116. */
  43117. registerAction(
  43118. {
  43119. type: 'showTip',
  43120. event: 'showTip',
  43121. update: 'tooltip:manuallyShowTip'
  43122. },
  43123. // noop
  43124. function () {}
  43125. );
  43126. registerAction(
  43127. {
  43128. type: 'hideTip',
  43129. event: 'hideTip',
  43130. update: 'tooltip:manuallyHideTip'
  43131. },
  43132. // noop
  43133. function () {}
  43134. );
  43135. /*
  43136. * Licensed to the Apache Software Foundation (ASF) under one
  43137. * or more contributor license agreements. See the NOTICE file
  43138. * distributed with this work for additional information
  43139. * regarding copyright ownership. The ASF licenses this file
  43140. * to you under the Apache License, Version 2.0 (the
  43141. * "License"); you may not use this file except in compliance
  43142. * with the License. You may obtain a copy of the License at
  43143. *
  43144. * http://www.apache.org/licenses/LICENSE-2.0
  43145. *
  43146. * Unless required by applicable law or agreed to in writing,
  43147. * software distributed under the License is distributed on an
  43148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43149. * KIND, either express or implied. See the License for the
  43150. * specific language governing permissions and limitations
  43151. * under the License.
  43152. */
  43153. var langSelector = lang.legend.selector;
  43154. var defaultSelectorOption = {
  43155. all: {
  43156. type: 'all',
  43157. title: clone(langSelector.all)
  43158. },
  43159. inverse: {
  43160. type: 'inverse',
  43161. title: clone(langSelector.inverse)
  43162. }
  43163. };
  43164. var LegendModel = extendComponentModel({
  43165. type: 'legend.plain',
  43166. dependencies: ['series'],
  43167. layoutMode: {
  43168. type: 'box',
  43169. // legend.width/height are maxWidth/maxHeight actually,
  43170. // whereas realy width/height is calculated by its content.
  43171. // (Setting {left: 10, right: 10} does not make sense).
  43172. // So consider the case:
  43173. // `setOption({legend: {left: 10});`
  43174. // then `setOption({legend: {right: 10});`
  43175. // The previous `left` should be cleared by setting `ignoreSize`.
  43176. ignoreSize: true
  43177. },
  43178. init: function (option, parentModel, ecModel) {
  43179. this.mergeDefaultAndTheme(option, ecModel);
  43180. option.selected = option.selected || {};
  43181. this._updateSelector(option);
  43182. },
  43183. mergeOption: function (option) {
  43184. LegendModel.superCall(this, 'mergeOption', option);
  43185. this._updateSelector(option);
  43186. },
  43187. _updateSelector: function (option) {
  43188. var selector = option.selector;
  43189. if (selector === true) {
  43190. selector = option.selector = ['all', 'inverse'];
  43191. }
  43192. if (isArray(selector)) {
  43193. each$1(selector, function (item, index) {
  43194. isString(item) && (item = {type: item});
  43195. selector[index] = merge(item, defaultSelectorOption[item.type]);
  43196. });
  43197. }
  43198. },
  43199. optionUpdated: function () {
  43200. this._updateData(this.ecModel);
  43201. var legendData = this._data;
  43202. // If selectedMode is single, try to select one
  43203. if (legendData[0] && this.get('selectedMode') === 'single') {
  43204. var hasSelected = false;
  43205. // If has any selected in option.selected
  43206. for (var i = 0; i < legendData.length; i++) {
  43207. var name = legendData[i].get('name');
  43208. if (this.isSelected(name)) {
  43209. // Force to unselect others
  43210. this.select(name);
  43211. hasSelected = true;
  43212. break;
  43213. }
  43214. }
  43215. // Try select the first if selectedMode is single
  43216. !hasSelected && this.select(legendData[0].get('name'));
  43217. }
  43218. },
  43219. _updateData: function (ecModel) {
  43220. var potentialData = [];
  43221. var availableNames = [];
  43222. ecModel.eachRawSeries(function (seriesModel) {
  43223. var seriesName = seriesModel.name;
  43224. availableNames.push(seriesName);
  43225. var isPotential;
  43226. if (seriesModel.legendVisualProvider) {
  43227. var provider = seriesModel.legendVisualProvider;
  43228. var names = provider.getAllNames();
  43229. if (!ecModel.isSeriesFiltered(seriesModel)) {
  43230. availableNames = availableNames.concat(names);
  43231. }
  43232. if (names.length) {
  43233. potentialData = potentialData.concat(names);
  43234. }
  43235. else {
  43236. isPotential = true;
  43237. }
  43238. }
  43239. else {
  43240. isPotential = true;
  43241. }
  43242. if (isPotential && isNameSpecified(seriesModel)) {
  43243. potentialData.push(seriesModel.name);
  43244. }
  43245. });
  43246. /**
  43247. * @type {Array.<string>}
  43248. * @private
  43249. */
  43250. this._availableNames = availableNames;
  43251. // If legend.data not specified in option, use availableNames as data,
  43252. // which is convinient for user preparing option.
  43253. var rawData = this.get('data') || potentialData;
  43254. var legendData = map(rawData, function (dataItem) {
  43255. // Can be string or number
  43256. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  43257. dataItem = {
  43258. name: dataItem
  43259. };
  43260. }
  43261. return new Model(dataItem, this, this.ecModel);
  43262. }, this);
  43263. /**
  43264. * @type {Array.<module:echarts/model/Model>}
  43265. * @private
  43266. */
  43267. this._data = legendData;
  43268. },
  43269. /**
  43270. * @return {Array.<module:echarts/model/Model>}
  43271. */
  43272. getData: function () {
  43273. return this._data;
  43274. },
  43275. /**
  43276. * @param {string} name
  43277. */
  43278. select: function (name) {
  43279. var selected = this.option.selected;
  43280. var selectedMode = this.get('selectedMode');
  43281. if (selectedMode === 'single') {
  43282. var data = this._data;
  43283. each$1(data, function (dataItem) {
  43284. selected[dataItem.get('name')] = false;
  43285. });
  43286. }
  43287. selected[name] = true;
  43288. },
  43289. /**
  43290. * @param {string} name
  43291. */
  43292. unSelect: function (name) {
  43293. if (this.get('selectedMode') !== 'single') {
  43294. this.option.selected[name] = false;
  43295. }
  43296. },
  43297. /**
  43298. * @param {string} name
  43299. */
  43300. toggleSelected: function (name) {
  43301. var selected = this.option.selected;
  43302. // Default is true
  43303. if (!selected.hasOwnProperty(name)) {
  43304. selected[name] = true;
  43305. }
  43306. this[selected[name] ? 'unSelect' : 'select'](name);
  43307. },
  43308. allSelect: function () {
  43309. var data = this._data;
  43310. var selected = this.option.selected;
  43311. each$1(data, function (dataItem) {
  43312. selected[dataItem.get('name', true)] = true;
  43313. });
  43314. },
  43315. inverseSelect: function () {
  43316. var data = this._data;
  43317. var selected = this.option.selected;
  43318. each$1(data, function (dataItem) {
  43319. var name = dataItem.get('name', true);
  43320. // Initially, default value is true
  43321. if (!selected.hasOwnProperty(name)) {
  43322. selected[name] = true;
  43323. }
  43324. selected[name] = !selected[name];
  43325. });
  43326. },
  43327. /**
  43328. * @param {string} name
  43329. */
  43330. isSelected: function (name) {
  43331. var selected = this.option.selected;
  43332. return !(selected.hasOwnProperty(name) && !selected[name])
  43333. && indexOf(this._availableNames, name) >= 0;
  43334. },
  43335. getOrient: function () {
  43336. return this.get('orient') === 'vertical'
  43337. ? {index: 1, name: 'vertical'}
  43338. : {index: 0, name: 'horizontal'};
  43339. },
  43340. defaultOption: {
  43341. // 一级层叠
  43342. zlevel: 0,
  43343. // 二级层叠
  43344. z: 4,
  43345. show: true,
  43346. // 布局方式,默认为水平布局,可选为:
  43347. // 'horizontal' | 'vertical'
  43348. orient: 'horizontal',
  43349. left: 'center',
  43350. // right: 'center',
  43351. top: 0,
  43352. // bottom: null,
  43353. // 水平对齐
  43354. // 'auto' | 'left' | 'right'
  43355. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  43356. align: 'auto',
  43357. backgroundColor: 'rgba(0,0,0,0)',
  43358. // 图例边框颜色
  43359. borderColor: '#ccc',
  43360. borderRadius: 0,
  43361. // 图例边框线宽,单位px,默认为0(无边框)
  43362. borderWidth: 0,
  43363. // 图例内边距,单位px,默认各方向内边距为5,
  43364. // 接受数组分别设定上右下左边距,同css
  43365. padding: 5,
  43366. // 各个item之间的间隔,单位px,默认为10,
  43367. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  43368. itemGap: 10,
  43369. // the width of legend symbol
  43370. itemWidth: 25,
  43371. // the height of legend symbol
  43372. itemHeight: 14,
  43373. // the color of unselected legend symbol
  43374. inactiveColor: '#ccc',
  43375. // the borderColor of unselected legend symbol
  43376. inactiveBorderColor: '#ccc',
  43377. itemStyle: {
  43378. // the default borderWidth of legend symbol
  43379. borderWidth: 0
  43380. },
  43381. textStyle: {
  43382. // 图例文字颜色
  43383. color: '#333'
  43384. },
  43385. // formatter: '',
  43386. // 选择模式,默认开启图例开关
  43387. selectedMode: true,
  43388. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  43389. // selected: null,
  43390. // 图例内容(详见legend.data,数组中每一项代表一个item
  43391. // data: [],
  43392. // Usage:
  43393. // selector: [{type: 'all or inverse', title: xxx}]
  43394. // or
  43395. // selector: true
  43396. // or
  43397. // selector: ['all', 'inverse']
  43398. selector: false,
  43399. selectorLabel: {
  43400. show: true,
  43401. borderRadius: 10,
  43402. padding: [3, 5, 3, 5],
  43403. fontSize: 12,
  43404. fontFamily: ' sans-serif',
  43405. color: '#666',
  43406. borderWidth: 1,
  43407. borderColor: '#666'
  43408. },
  43409. emphasis: {
  43410. selectorLabel: {
  43411. show: true,
  43412. color: '#eee',
  43413. backgroundColor: '#666'
  43414. }
  43415. },
  43416. // Value can be 'start' or 'end'
  43417. selectorPosition: 'auto',
  43418. selectorItemGap: 7,
  43419. selectorButtonGap: 10,
  43420. // Tooltip 相关配置
  43421. tooltip: {
  43422. show: false
  43423. }
  43424. }
  43425. });
  43426. /*
  43427. * Licensed to the Apache Software Foundation (ASF) under one
  43428. * or more contributor license agreements. See the NOTICE file
  43429. * distributed with this work for additional information
  43430. * regarding copyright ownership. The ASF licenses this file
  43431. * to you under the Apache License, Version 2.0 (the
  43432. * "License"); you may not use this file except in compliance
  43433. * with the License. You may obtain a copy of the License at
  43434. *
  43435. * http://www.apache.org/licenses/LICENSE-2.0
  43436. *
  43437. * Unless required by applicable law or agreed to in writing,
  43438. * software distributed under the License is distributed on an
  43439. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43440. * KIND, either express or implied. See the License for the
  43441. * specific language governing permissions and limitations
  43442. * under the License.
  43443. */
  43444. function legendSelectActionHandler(methodName, payload, ecModel) {
  43445. var selectedMap = {};
  43446. var isToggleSelect = methodName === 'toggleSelected';
  43447. var isSelected;
  43448. // Update all legend components
  43449. ecModel.eachComponent('legend', function (legendModel) {
  43450. if (isToggleSelect && isSelected != null) {
  43451. // Force other legend has same selected status
  43452. // Or the first is toggled to true and other are toggled to false
  43453. // In the case one legend has some item unSelected in option. And if other legend
  43454. // doesn't has the item, they will assume it is selected.
  43455. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  43456. }
  43457. else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  43458. legendModel[methodName]();
  43459. }
  43460. else {
  43461. legendModel[methodName](payload.name);
  43462. isSelected = legendModel.isSelected(payload.name);
  43463. }
  43464. var legendData = legendModel.getData();
  43465. each$1(legendData, function (model) {
  43466. var name = model.get('name');
  43467. // Wrap element
  43468. if (name === '\n' || name === '') {
  43469. return;
  43470. }
  43471. var isItemSelected = legendModel.isSelected(name);
  43472. if (selectedMap.hasOwnProperty(name)) {
  43473. // Unselected if any legend is unselected
  43474. selectedMap[name] = selectedMap[name] && isItemSelected;
  43475. }
  43476. else {
  43477. selectedMap[name] = isItemSelected;
  43478. }
  43479. });
  43480. });
  43481. // Return the event explicitly
  43482. return (methodName === 'allSelect' || methodName === 'inverseSelect')
  43483. ? {
  43484. selected: selectedMap
  43485. }
  43486. : {
  43487. name: payload.name,
  43488. selected: selectedMap
  43489. };
  43490. }
  43491. /**
  43492. * @event legendToggleSelect
  43493. * @type {Object}
  43494. * @property {string} type 'legendToggleSelect'
  43495. * @property {string} [from]
  43496. * @property {string} name Series name or data item name
  43497. */
  43498. registerAction(
  43499. 'legendToggleSelect', 'legendselectchanged',
  43500. curry(legendSelectActionHandler, 'toggleSelected')
  43501. );
  43502. registerAction(
  43503. 'legendAllSelect', 'legendselectall',
  43504. curry(legendSelectActionHandler, 'allSelect')
  43505. );
  43506. registerAction(
  43507. 'legendInverseSelect', 'legendinverseselect',
  43508. curry(legendSelectActionHandler, 'inverseSelect')
  43509. );
  43510. /**
  43511. * @event legendSelect
  43512. * @type {Object}
  43513. * @property {string} type 'legendSelect'
  43514. * @property {string} name Series name or data item name
  43515. */
  43516. registerAction(
  43517. 'legendSelect', 'legendselected',
  43518. curry(legendSelectActionHandler, 'select')
  43519. );
  43520. /**
  43521. * @event legendUnSelect
  43522. * @type {Object}
  43523. * @property {string} type 'legendUnSelect'
  43524. * @property {string} name Series name or data item name
  43525. */
  43526. registerAction(
  43527. 'legendUnSelect', 'legendunselected',
  43528. curry(legendSelectActionHandler, 'unSelect')
  43529. );
  43530. /*
  43531. * Licensed to the Apache Software Foundation (ASF) under one
  43532. * or more contributor license agreements. See the NOTICE file
  43533. * distributed with this work for additional information
  43534. * regarding copyright ownership. The ASF licenses this file
  43535. * to you under the Apache License, Version 2.0 (the
  43536. * "License"); you may not use this file except in compliance
  43537. * with the License. You may obtain a copy of the License at
  43538. *
  43539. * http://www.apache.org/licenses/LICENSE-2.0
  43540. *
  43541. * Unless required by applicable law or agreed to in writing,
  43542. * software distributed under the License is distributed on an
  43543. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43544. * KIND, either express or implied. See the License for the
  43545. * specific language governing permissions and limitations
  43546. * under the License.
  43547. */
  43548. /**
  43549. * Layout list like component.
  43550. * It will box layout each items in group of component and then position the whole group in the viewport
  43551. * @param {module:zrender/group/Group} group
  43552. * @param {module:echarts/model/Component} componentModel
  43553. * @param {module:echarts/ExtensionAPI}
  43554. */
  43555. function layout$2(group, componentModel, api) {
  43556. var boxLayoutParams = componentModel.getBoxLayoutParams();
  43557. var padding = componentModel.get('padding');
  43558. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  43559. var rect = getLayoutRect(
  43560. boxLayoutParams,
  43561. viewportSize,
  43562. padding
  43563. );
  43564. box(
  43565. componentModel.get('orient'),
  43566. group,
  43567. componentModel.get('itemGap'),
  43568. rect.width,
  43569. rect.height
  43570. );
  43571. positionElement(
  43572. group,
  43573. boxLayoutParams,
  43574. viewportSize,
  43575. padding
  43576. );
  43577. }
  43578. function makeBackground(rect, componentModel) {
  43579. var padding = normalizeCssArray$1(
  43580. componentModel.get('padding')
  43581. );
  43582. var style = componentModel.getItemStyle(['color', 'opacity']);
  43583. style.fill = componentModel.get('backgroundColor');
  43584. var rect = new Rect({
  43585. shape: {
  43586. x: rect.x - padding[3],
  43587. y: rect.y - padding[0],
  43588. width: rect.width + padding[1] + padding[3],
  43589. height: rect.height + padding[0] + padding[2],
  43590. r: componentModel.get('borderRadius')
  43591. },
  43592. style: style,
  43593. silent: true,
  43594. z2: -1
  43595. });
  43596. // FIXME
  43597. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  43598. // and background rect when setting like `left: 0`, `top: 0`.
  43599. // graphic.subPixelOptimizeRect(rect);
  43600. return rect;
  43601. }
  43602. /*
  43603. * Licensed to the Apache Software Foundation (ASF) under one
  43604. * or more contributor license agreements. See the NOTICE file
  43605. * distributed with this work for additional information
  43606. * regarding copyright ownership. The ASF licenses this file
  43607. * to you under the Apache License, Version 2.0 (the
  43608. * "License"); you may not use this file except in compliance
  43609. * with the License. You may obtain a copy of the License at
  43610. *
  43611. * http://www.apache.org/licenses/LICENSE-2.0
  43612. *
  43613. * Unless required by applicable law or agreed to in writing,
  43614. * software distributed under the License is distributed on an
  43615. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43616. * KIND, either express or implied. See the License for the
  43617. * specific language governing permissions and limitations
  43618. * under the License.
  43619. */
  43620. var curry$3 = curry;
  43621. var each$11 = each$1;
  43622. var Group$2 = Group;
  43623. var LegendView = extendComponentView({
  43624. type: 'legend.plain',
  43625. newlineDisabled: false,
  43626. /**
  43627. * @override
  43628. */
  43629. init: function () {
  43630. /**
  43631. * @private
  43632. * @type {module:zrender/container/Group}
  43633. */
  43634. this.group.add(this._contentGroup = new Group$2());
  43635. /**
  43636. * @private
  43637. * @type {module:zrender/Element}
  43638. */
  43639. this._backgroundEl;
  43640. /**
  43641. * @private
  43642. * @type {module:zrender/container/Group}
  43643. */
  43644. this.group.add(this._selectorGroup = new Group$2());
  43645. /**
  43646. * If first rendering, `contentGroup.position` is [0, 0], which
  43647. * does not make sense and may cause unexepcted animation if adopted.
  43648. * @private
  43649. * @type {boolean}
  43650. */
  43651. this._isFirstRender = true;
  43652. },
  43653. /**
  43654. * @protected
  43655. */
  43656. getContentGroup: function () {
  43657. return this._contentGroup;
  43658. },
  43659. /**
  43660. * @protected
  43661. */
  43662. getSelectorGroup: function () {
  43663. return this._selectorGroup;
  43664. },
  43665. /**
  43666. * @override
  43667. */
  43668. render: function (legendModel, ecModel, api) {
  43669. var isFirstRender = this._isFirstRender;
  43670. this._isFirstRender = false;
  43671. this.resetInner();
  43672. if (!legendModel.get('show', true)) {
  43673. return;
  43674. }
  43675. var itemAlign = legendModel.get('align');
  43676. var orient = legendModel.get('orient');
  43677. if (!itemAlign || itemAlign === 'auto') {
  43678. itemAlign = (
  43679. legendModel.get('left') === 'right'
  43680. && orient === 'vertical'
  43681. ) ? 'right' : 'left';
  43682. }
  43683. var selector = legendModel.get('selector', true);
  43684. var selectorPosition = legendModel.get('selectorPosition', true);
  43685. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  43686. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  43687. }
  43688. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  43689. // Perform layout.
  43690. var positionInfo = legendModel.getBoxLayoutParams();
  43691. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  43692. var padding = legendModel.get('padding');
  43693. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  43694. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  43695. // Place mainGroup, based on the calculated `mainRect`.
  43696. var layoutRect = getLayoutRect(
  43697. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  43698. viewportSize,
  43699. padding
  43700. );
  43701. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  43702. // Render background after group is layout.
  43703. this.group.add(
  43704. this._backgroundEl = makeBackground(mainRect, legendModel)
  43705. );
  43706. },
  43707. /**
  43708. * @protected
  43709. */
  43710. resetInner: function () {
  43711. this.getContentGroup().removeAll();
  43712. this._backgroundEl && this.group.remove(this._backgroundEl);
  43713. this.getSelectorGroup().removeAll();
  43714. },
  43715. /**
  43716. * @protected
  43717. */
  43718. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  43719. var contentGroup = this.getContentGroup();
  43720. var legendDrawnMap = createHashMap();
  43721. var selectMode = legendModel.get('selectedMode');
  43722. var excludeSeriesId = [];
  43723. ecModel.eachRawSeries(function (seriesModel) {
  43724. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  43725. });
  43726. each$11(legendModel.getData(), function (itemModel, dataIndex) {
  43727. var name = itemModel.get('name');
  43728. // Use empty string or \n as a newline string
  43729. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  43730. contentGroup.add(new Group$2({
  43731. newline: true
  43732. }));
  43733. return;
  43734. }
  43735. // Representitive series.
  43736. var seriesModel = ecModel.getSeriesByName(name)[0];
  43737. if (legendDrawnMap.get(name)) {
  43738. // Have been drawed
  43739. return;
  43740. }
  43741. // Legend to control series.
  43742. if (seriesModel) {
  43743. var data = seriesModel.getData();
  43744. var color = data.getVisual('color');
  43745. var borderColor = data.getVisual('borderColor');
  43746. // If color is a callback function
  43747. if (typeof color === 'function') {
  43748. // Use the first data
  43749. color = color(seriesModel.getDataParams(0));
  43750. }
  43751. // If borderColor is a callback function
  43752. if (typeof borderColor === 'function') {
  43753. // Use the first data
  43754. borderColor = borderColor(seriesModel.getDataParams(0));
  43755. }
  43756. // Using rect symbol defaultly
  43757. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  43758. var symbolType = data.getVisual('symbol');
  43759. var itemGroup = this._createItem(
  43760. name, dataIndex, itemModel, legendModel,
  43761. legendSymbolType, symbolType,
  43762. itemAlign, color, borderColor,
  43763. selectMode
  43764. );
  43765. itemGroup.on('click', curry$3(dispatchSelectAction, name, null, api, excludeSeriesId))
  43766. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  43767. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  43768. legendDrawnMap.set(name, true);
  43769. }
  43770. else {
  43771. // Legend to control data. In pie and funnel.
  43772. ecModel.eachRawSeries(function (seriesModel) {
  43773. // In case multiple series has same data name
  43774. if (legendDrawnMap.get(name)) {
  43775. return;
  43776. }
  43777. if (seriesModel.legendVisualProvider) {
  43778. var provider = seriesModel.legendVisualProvider;
  43779. if (!provider.containName(name)) {
  43780. return;
  43781. }
  43782. var idx = provider.indexOfName(name);
  43783. var color = provider.getItemVisual(idx, 'color');
  43784. var borderColor = provider.getItemVisual(idx, 'borderColor');
  43785. var legendSymbolType = 'roundRect';
  43786. var itemGroup = this._createItem(
  43787. name, dataIndex, itemModel, legendModel,
  43788. legendSymbolType, null,
  43789. itemAlign, color, borderColor,
  43790. selectMode
  43791. );
  43792. // FIXME: consider different series has items with the same name.
  43793. itemGroup.on('click', curry$3(dispatchSelectAction, null, name, api, excludeSeriesId))
  43794. // Should not specify the series name, consider legend controls
  43795. // more than one pie series.
  43796. .on('mouseover', curry$3(dispatchHighlightAction, null, name, api, excludeSeriesId))
  43797. .on('mouseout', curry$3(dispatchDownplayAction, null, name, api, excludeSeriesId));
  43798. legendDrawnMap.set(name, true);
  43799. }
  43800. }, this);
  43801. }
  43802. if (__DEV__) {
  43803. if (!legendDrawnMap.get(name)) {
  43804. console.warn(
  43805. name + ' series not exists. Legend data should be same with series name or data name.'
  43806. );
  43807. }
  43808. }
  43809. }, this);
  43810. if (selector) {
  43811. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  43812. }
  43813. },
  43814. _createSelector: function (selector, legendModel, api, orient, selectorPosition) {
  43815. var selectorGroup = this.getSelectorGroup();
  43816. each$11(selector, function (selectorItem) {
  43817. createSelectorButton(selectorItem);
  43818. });
  43819. function createSelectorButton(selectorItem) {
  43820. var type = selectorItem.type;
  43821. var labelText = new Text({
  43822. style: {
  43823. x: 0,
  43824. y: 0,
  43825. align: 'center',
  43826. verticalAlign: 'middle'
  43827. },
  43828. onclick: function () {
  43829. api.dispatchAction({
  43830. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  43831. });
  43832. }
  43833. });
  43834. selectorGroup.add(labelText);
  43835. var labelModel = legendModel.getModel('selectorLabel');
  43836. var emphasisLabelModel = legendModel.getModel('emphasis.selectorLabel');
  43837. setLabelStyle(
  43838. labelText.style, labelText.hoverStyle = {}, labelModel, emphasisLabelModel,
  43839. {
  43840. defaultText: selectorItem.title,
  43841. isRectText: false
  43842. }
  43843. );
  43844. setHoverStyle(labelText);
  43845. }
  43846. },
  43847. _createItem: function (
  43848. name, dataIndex, itemModel, legendModel,
  43849. legendSymbolType, symbolType,
  43850. itemAlign, color, borderColor, selectMode
  43851. ) {
  43852. var itemWidth = legendModel.get('itemWidth');
  43853. var itemHeight = legendModel.get('itemHeight');
  43854. var inactiveColor = legendModel.get('inactiveColor');
  43855. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  43856. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  43857. var legendModelItemStyle = legendModel.getModel('itemStyle');
  43858. var isSelected = legendModel.isSelected(name);
  43859. var itemGroup = new Group$2();
  43860. var textStyleModel = itemModel.getModel('textStyle');
  43861. var itemIcon = itemModel.get('icon');
  43862. var tooltipModel = itemModel.getModel('tooltip');
  43863. var legendGlobalTooltipModel = tooltipModel.parentModel;
  43864. // Use user given icon first
  43865. legendSymbolType = itemIcon || legendSymbolType;
  43866. var legendSymbol = createSymbol(
  43867. legendSymbolType,
  43868. 0,
  43869. 0,
  43870. itemWidth,
  43871. itemHeight,
  43872. isSelected ? color : inactiveColor,
  43873. // symbolKeepAspect default true for legend
  43874. symbolKeepAspect == null ? true : symbolKeepAspect
  43875. );
  43876. itemGroup.add(
  43877. setSymbolStyle(
  43878. legendSymbol, legendSymbolType, legendModelItemStyle,
  43879. borderColor, inactiveBorderColor, isSelected
  43880. )
  43881. );
  43882. // Compose symbols
  43883. // PENDING
  43884. if (!itemIcon && symbolType
  43885. // At least show one symbol, can't be all none
  43886. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  43887. ) {
  43888. var size = itemHeight * 0.8;
  43889. if (symbolType === 'none') {
  43890. symbolType = 'circle';
  43891. }
  43892. var legendSymbolCenter = createSymbol(
  43893. symbolType,
  43894. (itemWidth - size) / 2,
  43895. (itemHeight - size) / 2,
  43896. size,
  43897. size,
  43898. isSelected ? color : inactiveColor,
  43899. // symbolKeepAspect default true for legend
  43900. symbolKeepAspect == null ? true : symbolKeepAspect
  43901. );
  43902. // Put symbol in the center
  43903. itemGroup.add(
  43904. setSymbolStyle(
  43905. legendSymbolCenter, symbolType, legendModelItemStyle,
  43906. borderColor, inactiveBorderColor, isSelected
  43907. )
  43908. );
  43909. }
  43910. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  43911. var textAlign = itemAlign;
  43912. var formatter = legendModel.get('formatter');
  43913. var content = name;
  43914. if (typeof formatter === 'string' && formatter) {
  43915. content = formatter.replace('{name}', name != null ? name : '');
  43916. }
  43917. else if (typeof formatter === 'function') {
  43918. content = formatter(name);
  43919. }
  43920. itemGroup.add(new Text({
  43921. style: setTextStyle({}, textStyleModel, {
  43922. text: content,
  43923. x: textX,
  43924. y: itemHeight / 2,
  43925. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  43926. textAlign: textAlign,
  43927. textVerticalAlign: 'middle'
  43928. })
  43929. }));
  43930. // Add a invisible rect to increase the area of mouse hover
  43931. var hitRect = new Rect({
  43932. shape: itemGroup.getBoundingRect(),
  43933. invisible: true,
  43934. tooltip: tooltipModel.get('show') ? extend({
  43935. content: name,
  43936. // Defaul formatter
  43937. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  43938. return name;
  43939. },
  43940. formatterParams: {
  43941. componentType: 'legend',
  43942. legendIndex: legendModel.componentIndex,
  43943. name: name,
  43944. $vars: ['name']
  43945. }
  43946. }, tooltipModel.option) : null
  43947. });
  43948. itemGroup.add(hitRect);
  43949. itemGroup.eachChild(function (child) {
  43950. child.silent = true;
  43951. });
  43952. hitRect.silent = !selectMode;
  43953. this.getContentGroup().add(itemGroup);
  43954. setHoverStyle(itemGroup);
  43955. itemGroup.__legendDataIndex = dataIndex;
  43956. return itemGroup;
  43957. },
  43958. /**
  43959. * @protected
  43960. */
  43961. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  43962. var contentGroup = this.getContentGroup();
  43963. var selectorGroup = this.getSelectorGroup();
  43964. // Place items in contentGroup.
  43965. box(
  43966. legendModel.get('orient'),
  43967. contentGroup,
  43968. legendModel.get('itemGap'),
  43969. maxSize.width,
  43970. maxSize.height
  43971. );
  43972. var contentRect = contentGroup.getBoundingRect();
  43973. var contentPos = [-contentRect.x, -contentRect.y];
  43974. if (selector) {
  43975. // Place buttons in selectorGroup
  43976. box(
  43977. // Buttons in selectorGroup always layout horizontally
  43978. 'horizontal',
  43979. selectorGroup,
  43980. legendModel.get('selectorItemGap', true)
  43981. );
  43982. var selectorRect = selectorGroup.getBoundingRect();
  43983. var selectorPos = [-selectorRect.x, -selectorRect.y];
  43984. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  43985. var orientIdx = legendModel.getOrient().index;
  43986. var wh = orientIdx === 0 ? 'width' : 'height';
  43987. var hw = orientIdx === 0 ? 'height' : 'width';
  43988. var yx = orientIdx === 0 ? 'y' : 'x';
  43989. if (selectorPosition === 'end') {
  43990. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  43991. }
  43992. else {
  43993. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  43994. }
  43995. //Always align selector to content as 'middle'
  43996. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  43997. selectorGroup.attr('position', selectorPos);
  43998. contentGroup.attr('position', contentPos);
  43999. var mainRect = {x: 0, y: 0};
  44000. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  44001. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  44002. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  44003. return mainRect;
  44004. }
  44005. else {
  44006. contentGroup.attr('position', contentPos);
  44007. return this.group.getBoundingRect();
  44008. }
  44009. },
  44010. /**
  44011. * @protected
  44012. */
  44013. remove: function () {
  44014. this.getContentGroup().removeAll();
  44015. this._isFirstRender = true;
  44016. }
  44017. });
  44018. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected) {
  44019. var itemStyle;
  44020. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  44021. itemStyle = legendModelItemStyle.getItemStyle();
  44022. symbol.style.stroke = borderColor;
  44023. if (!isSelected) {
  44024. itemStyle.stroke = inactiveBorderColor;
  44025. }
  44026. }
  44027. else {
  44028. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  44029. }
  44030. return symbol.setStyle(itemStyle);
  44031. }
  44032. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  44033. // downplay before unselect
  44034. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  44035. api.dispatchAction({
  44036. type: 'legendToggleSelect',
  44037. name: seriesName != null ? seriesName : dataName
  44038. });
  44039. // highlight after select
  44040. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  44041. }
  44042. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  44043. // If element hover will move to a hoverLayer.
  44044. var el = api.getZr().storage.getDisplayList()[0];
  44045. if (!(el && el.useHoverLayer)) {
  44046. api.dispatchAction({
  44047. type: 'highlight',
  44048. seriesName: seriesName,
  44049. name: dataName,
  44050. excludeSeriesId: excludeSeriesId
  44051. });
  44052. }
  44053. }
  44054. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  44055. // If element hover will move to a hoverLayer.
  44056. var el = api.getZr().storage.getDisplayList()[0];
  44057. if (!(el && el.useHoverLayer)) {
  44058. api.dispatchAction({
  44059. type: 'downplay',
  44060. seriesName: seriesName,
  44061. name: dataName,
  44062. excludeSeriesId: excludeSeriesId
  44063. });
  44064. }
  44065. }
  44066. /*
  44067. * Licensed to the Apache Software Foundation (ASF) under one
  44068. * or more contributor license agreements. See the NOTICE file
  44069. * distributed with this work for additional information
  44070. * regarding copyright ownership. The ASF licenses this file
  44071. * to you under the Apache License, Version 2.0 (the
  44072. * "License"); you may not use this file except in compliance
  44073. * with the License. You may obtain a copy of the License at
  44074. *
  44075. * http://www.apache.org/licenses/LICENSE-2.0
  44076. *
  44077. * Unless required by applicable law or agreed to in writing,
  44078. * software distributed under the License is distributed on an
  44079. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44080. * KIND, either express or implied. See the License for the
  44081. * specific language governing permissions and limitations
  44082. * under the License.
  44083. */
  44084. var legendFilter = function (ecModel) {
  44085. var legendModels = ecModel.findComponents({
  44086. mainType: 'legend'
  44087. });
  44088. if (legendModels && legendModels.length) {
  44089. ecModel.filterSeries(function (series) {
  44090. // If in any legend component the status is not selected.
  44091. // Because in legend series is assumed selected when it is not in the legend data.
  44092. for (var i = 0; i < legendModels.length; i++) {
  44093. if (!legendModels[i].isSelected(series.name)) {
  44094. return false;
  44095. }
  44096. }
  44097. return true;
  44098. });
  44099. }
  44100. };
  44101. /*
  44102. * Licensed to the Apache Software Foundation (ASF) under one
  44103. * or more contributor license agreements. See the NOTICE file
  44104. * distributed with this work for additional information
  44105. * regarding copyright ownership. The ASF licenses this file
  44106. * to you under the Apache License, Version 2.0 (the
  44107. * "License"); you may not use this file except in compliance
  44108. * with the License. You may obtain a copy of the License at
  44109. *
  44110. * http://www.apache.org/licenses/LICENSE-2.0
  44111. *
  44112. * Unless required by applicable law or agreed to in writing,
  44113. * software distributed under the License is distributed on an
  44114. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44115. * KIND, either express or implied. See the License for the
  44116. * specific language governing permissions and limitations
  44117. * under the License.
  44118. */
  44119. // Do not contain scrollable legend, for sake of file size.
  44120. // Series Filter
  44121. registerProcessor(PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  44122. ComponentModel.registerSubTypeDefaulter('legend', function () {
  44123. // Default 'plain' when no type specified.
  44124. return 'plain';
  44125. });
  44126. /*
  44127. * Licensed to the Apache Software Foundation (ASF) under one
  44128. * or more contributor license agreements. See the NOTICE file
  44129. * distributed with this work for additional information
  44130. * regarding copyright ownership. The ASF licenses this file
  44131. * to you under the Apache License, Version 2.0 (the
  44132. * "License"); you may not use this file except in compliance
  44133. * with the License. You may obtain a copy of the License at
  44134. *
  44135. * http://www.apache.org/licenses/LICENSE-2.0
  44136. *
  44137. * Unless required by applicable law or agreed to in writing,
  44138. * software distributed under the License is distributed on an
  44139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44140. * KIND, either express or implied. See the License for the
  44141. * specific language governing permissions and limitations
  44142. * under the License.
  44143. */
  44144. var ScrollableLegendModel = LegendModel.extend({
  44145. type: 'legend.scroll',
  44146. /**
  44147. * @param {number} scrollDataIndex
  44148. */
  44149. setScrollDataIndex: function (scrollDataIndex) {
  44150. this.option.scrollDataIndex = scrollDataIndex;
  44151. },
  44152. defaultOption: {
  44153. scrollDataIndex: 0,
  44154. pageButtonItemGap: 5,
  44155. pageButtonGap: null,
  44156. pageButtonPosition: 'end', // 'start' or 'end'
  44157. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  44158. pageIcons: {
  44159. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  44160. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  44161. },
  44162. pageIconColor: '#2f4554',
  44163. pageIconInactiveColor: '#aaa',
  44164. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  44165. pageTextStyle: {
  44166. color: '#333'
  44167. },
  44168. animationDurationUpdate: 800
  44169. },
  44170. /**
  44171. * @override
  44172. */
  44173. init: function (option, parentModel, ecModel, extraOpt) {
  44174. var inputPositionParams = getLayoutParams(option);
  44175. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  44176. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  44177. },
  44178. /**
  44179. * @override
  44180. */
  44181. mergeOption: function (option, extraOpt) {
  44182. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  44183. mergeAndNormalizeLayoutParams(this, this.option, option);
  44184. }
  44185. });
  44186. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  44187. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  44188. var orient = legendModel.getOrient();
  44189. var ignoreSize = [1, 1];
  44190. ignoreSize[orient.index] = 0;
  44191. mergeLayoutParam(target, raw, {
  44192. type: 'box', ignoreSize: ignoreSize
  44193. });
  44194. }
  44195. /*
  44196. * Licensed to the Apache Software Foundation (ASF) under one
  44197. * or more contributor license agreements. See the NOTICE file
  44198. * distributed with this work for additional information
  44199. * regarding copyright ownership. The ASF licenses this file
  44200. * to you under the Apache License, Version 2.0 (the
  44201. * "License"); you may not use this file except in compliance
  44202. * with the License. You may obtain a copy of the License at
  44203. *
  44204. * http://www.apache.org/licenses/LICENSE-2.0
  44205. *
  44206. * Unless required by applicable law or agreed to in writing,
  44207. * software distributed under the License is distributed on an
  44208. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44209. * KIND, either express or implied. See the License for the
  44210. * specific language governing permissions and limitations
  44211. * under the License.
  44212. */
  44213. /**
  44214. * Separate legend and scrollable legend to reduce package size.
  44215. */
  44216. var Group$3 = Group;
  44217. var WH = ['width', 'height'];
  44218. var XY = ['x', 'y'];
  44219. var ScrollableLegendView = LegendView.extend({
  44220. type: 'legend.scroll',
  44221. newlineDisabled: true,
  44222. init: function () {
  44223. ScrollableLegendView.superCall(this, 'init');
  44224. /**
  44225. * @private
  44226. * @type {number} For `scroll`.
  44227. */
  44228. this._currentIndex = 0;
  44229. /**
  44230. * @private
  44231. * @type {module:zrender/container/Group}
  44232. */
  44233. this.group.add(this._containerGroup = new Group$3());
  44234. this._containerGroup.add(this.getContentGroup());
  44235. /**
  44236. * @private
  44237. * @type {module:zrender/container/Group}
  44238. */
  44239. this.group.add(this._controllerGroup = new Group$3());
  44240. /**
  44241. *
  44242. * @private
  44243. */
  44244. this._showController;
  44245. },
  44246. /**
  44247. * @override
  44248. */
  44249. resetInner: function () {
  44250. ScrollableLegendView.superCall(this, 'resetInner');
  44251. this._controllerGroup.removeAll();
  44252. this._containerGroup.removeClipPath();
  44253. this._containerGroup.__rectSize = null;
  44254. },
  44255. /**
  44256. * @override
  44257. */
  44258. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  44259. var me = this;
  44260. // Render content items.
  44261. ScrollableLegendView.superCall(this, 'renderInner', itemAlign,
  44262. legendModel, ecModel, api, selector, orient, selectorPosition);
  44263. var controllerGroup = this._controllerGroup;
  44264. // FIXME: support be 'auto' adapt to size number text length,
  44265. // e.g., '3/12345' should not overlap with the control arrow button.
  44266. var pageIconSize = legendModel.get('pageIconSize', true);
  44267. if (!isArray(pageIconSize)) {
  44268. pageIconSize = [pageIconSize, pageIconSize];
  44269. }
  44270. createPageButton('pagePrev', 0);
  44271. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  44272. controllerGroup.add(new Text({
  44273. name: 'pageText',
  44274. style: {
  44275. textFill: pageTextStyleModel.getTextColor(),
  44276. font: pageTextStyleModel.getFont(),
  44277. textVerticalAlign: 'middle',
  44278. textAlign: 'center'
  44279. },
  44280. silent: true
  44281. }));
  44282. createPageButton('pageNext', 1);
  44283. function createPageButton(name, iconIdx) {
  44284. var pageDataIndexName = name + 'DataIndex';
  44285. var icon = createIcon(
  44286. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  44287. {
  44288. // Buttons will be created in each render, so we do not need
  44289. // to worry about avoiding using legendModel kept in scope.
  44290. onclick: bind(
  44291. me._pageGo, me, pageDataIndexName, legendModel, api
  44292. )
  44293. },
  44294. {
  44295. x: -pageIconSize[0] / 2,
  44296. y: -pageIconSize[1] / 2,
  44297. width: pageIconSize[0],
  44298. height: pageIconSize[1]
  44299. }
  44300. );
  44301. icon.name = name;
  44302. controllerGroup.add(icon);
  44303. }
  44304. },
  44305. /**
  44306. * @override
  44307. */
  44308. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  44309. var selectorGroup = this.getSelectorGroup();
  44310. var orientIdx = legendModel.getOrient().index;
  44311. var wh = WH[orientIdx];
  44312. var xy = XY[orientIdx];
  44313. var hw = WH[1 - orientIdx];
  44314. var yx = XY[1 - orientIdx];
  44315. selector && box(
  44316. // Buttons in selectorGroup always layout horizontally
  44317. 'horizontal',
  44318. selectorGroup,
  44319. legendModel.get('selectorItemGap', true)
  44320. );
  44321. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  44322. var selectorRect = selectorGroup.getBoundingRect();
  44323. var selectorPos = [-selectorRect.x, -selectorRect.y];
  44324. var processMaxSize = clone(maxSize);
  44325. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  44326. var mainRect = this._layoutContentAndController(legendModel, isFirstRender,
  44327. processMaxSize, orientIdx, wh, hw, yx
  44328. );
  44329. if (selector) {
  44330. if (selectorPosition === 'end') {
  44331. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  44332. }
  44333. else {
  44334. var offset = selectorRect[wh] + selectorButtonGap;
  44335. selectorPos[orientIdx] -= offset;
  44336. mainRect[xy] -= offset;
  44337. }
  44338. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  44339. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  44340. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  44341. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  44342. selectorGroup.attr('position', selectorPos);
  44343. }
  44344. return mainRect;
  44345. },
  44346. _layoutContentAndController: function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx) {
  44347. var contentGroup = this.getContentGroup();
  44348. var containerGroup = this._containerGroup;
  44349. var controllerGroup = this._controllerGroup;
  44350. // Place items in contentGroup.
  44351. box(
  44352. legendModel.get('orient'),
  44353. contentGroup,
  44354. legendModel.get('itemGap'),
  44355. !orientIdx ? null : maxSize.width,
  44356. orientIdx ? null : maxSize.height
  44357. );
  44358. box(
  44359. // Buttons in controller are layout always horizontally.
  44360. 'horizontal',
  44361. controllerGroup,
  44362. legendModel.get('pageButtonItemGap', true)
  44363. );
  44364. var contentRect = contentGroup.getBoundingRect();
  44365. var controllerRect = controllerGroup.getBoundingRect();
  44366. var showController = this._showController = contentRect[wh] > maxSize[wh];
  44367. var contentPos = [-contentRect.x, -contentRect.y];
  44368. // Remain contentPos when scroll animation perfroming.
  44369. // If first rendering, `contentGroup.position` is [0, 0], which
  44370. // does not make sense and may cause unexepcted animation if adopted.
  44371. if (!isFirstRender) {
  44372. contentPos[orientIdx] = contentGroup.position[orientIdx];
  44373. }
  44374. // Layout container group based on 0.
  44375. var containerPos = [0, 0];
  44376. var controllerPos = [-controllerRect.x, -controllerRect.y];
  44377. var pageButtonGap = retrieve2(
  44378. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  44379. );
  44380. // Place containerGroup and controllerGroup and contentGroup.
  44381. if (showController) {
  44382. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  44383. // controller is on the right / bottom.
  44384. if (pageButtonPosition === 'end') {
  44385. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  44386. }
  44387. // controller is on the left / top.
  44388. else {
  44389. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  44390. }
  44391. }
  44392. // Always align controller to content as 'middle'.
  44393. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  44394. contentGroup.attr('position', contentPos);
  44395. containerGroup.attr('position', containerPos);
  44396. controllerGroup.attr('position', controllerPos);
  44397. // Calculate `mainRect` and set `clipPath`.
  44398. // mainRect should not be calculated by `this.group.getBoundingRect()`
  44399. // for sake of the overflow.
  44400. var mainRect = {x: 0, y: 0};
  44401. // Consider content may be overflow (should be clipped).
  44402. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  44403. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  44404. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  44405. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  44406. containerGroup.__rectSize = maxSize[wh];
  44407. if (showController) {
  44408. var clipShape = {x: 0, y: 0};
  44409. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  44410. clipShape[hw] = mainRect[hw];
  44411. containerGroup.setClipPath(new Rect({shape: clipShape}));
  44412. // Consider content may be larger than container, container rect
  44413. // can not be obtained from `containerGroup.getBoundingRect()`.
  44414. containerGroup.__rectSize = clipShape[wh];
  44415. }
  44416. else {
  44417. // Do not remove or ignore controller. Keep them set as placeholders.
  44418. controllerGroup.eachChild(function (child) {
  44419. child.attr({invisible: true, silent: true});
  44420. });
  44421. }
  44422. // Content translate animation.
  44423. var pageInfo = this._getPageInfo(legendModel);
  44424. pageInfo.pageIndex != null && updateProps(
  44425. contentGroup,
  44426. {position: pageInfo.contentPosition},
  44427. // When switch from "show controller" to "not show controller", view should be
  44428. // updated immediately without animation, otherwise causes weird effect.
  44429. showController ? legendModel : false
  44430. );
  44431. this._updatePageInfoView(legendModel, pageInfo);
  44432. return mainRect;
  44433. },
  44434. _pageGo: function (to, legendModel, api) {
  44435. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  44436. scrollDataIndex != null && api.dispatchAction({
  44437. type: 'legendScroll',
  44438. scrollDataIndex: scrollDataIndex,
  44439. legendId: legendModel.id
  44440. });
  44441. },
  44442. _updatePageInfoView: function (legendModel, pageInfo) {
  44443. var controllerGroup = this._controllerGroup;
  44444. each$1(['pagePrev', 'pageNext'], function (name) {
  44445. var canJump = pageInfo[name + 'DataIndex'] != null;
  44446. var icon = controllerGroup.childOfName(name);
  44447. if (icon) {
  44448. icon.setStyle(
  44449. 'fill',
  44450. canJump
  44451. ? legendModel.get('pageIconColor', true)
  44452. : legendModel.get('pageIconInactiveColor', true)
  44453. );
  44454. icon.cursor = canJump ? 'pointer' : 'default';
  44455. }
  44456. });
  44457. var pageText = controllerGroup.childOfName('pageText');
  44458. var pageFormatter = legendModel.get('pageFormatter');
  44459. var pageIndex = pageInfo.pageIndex;
  44460. var current = pageIndex != null ? pageIndex + 1 : 0;
  44461. var total = pageInfo.pageCount;
  44462. pageText && pageFormatter && pageText.setStyle(
  44463. 'text',
  44464. isString(pageFormatter)
  44465. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  44466. : pageFormatter({current: current, total: total})
  44467. );
  44468. },
  44469. /**
  44470. * @param {module:echarts/model/Model} legendModel
  44471. * @return {Object} {
  44472. * contentPosition: Array.<number>, null when data item not found.
  44473. * pageIndex: number, null when data item not found.
  44474. * pageCount: number, always be a number, can be 0.
  44475. * pagePrevDataIndex: number, null when no previous page.
  44476. * pageNextDataIndex: number, null when no next page.
  44477. * }
  44478. */
  44479. _getPageInfo: function (legendModel) {
  44480. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  44481. var contentGroup = this.getContentGroup();
  44482. var containerRectSize = this._containerGroup.__rectSize;
  44483. var orientIdx = legendModel.getOrient().index;
  44484. var wh = WH[orientIdx];
  44485. var xy = XY[orientIdx];
  44486. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  44487. var children = contentGroup.children();
  44488. var targetItem = children[targetItemIndex];
  44489. var itemCount = children.length;
  44490. var pCount = !itemCount ? 0 : 1;
  44491. var result = {
  44492. contentPosition: contentGroup.position.slice(),
  44493. pageCount: pCount,
  44494. pageIndex: pCount - 1,
  44495. pagePrevDataIndex: null,
  44496. pageNextDataIndex: null
  44497. };
  44498. if (!targetItem) {
  44499. return result;
  44500. }
  44501. var targetItemInfo = getItemInfo(targetItem);
  44502. result.contentPosition[orientIdx] = -targetItemInfo.s;
  44503. // Strategy:
  44504. // (1) Always align based on the left/top most item.
  44505. // (2) It is user-friendly that the last item shown in the
  44506. // current window is shown at the begining of next window.
  44507. // Otherwise if half of the last item is cut by the window,
  44508. // it will have no chance to display entirely.
  44509. // (3) Consider that item size probably be different, we
  44510. // have calculate pageIndex by size rather than item index,
  44511. // and we can not get page index directly by division.
  44512. // (4) The window is to narrow to contain more than
  44513. // one item, we should make sure that the page can be fliped.
  44514. for (var i = targetItemIndex + 1,
  44515. winStartItemInfo = targetItemInfo,
  44516. winEndItemInfo = targetItemInfo,
  44517. currItemInfo = null;
  44518. i <= itemCount;
  44519. ++i
  44520. ) {
  44521. currItemInfo = getItemInfo(children[i]);
  44522. if (
  44523. // Half of the last item is out of the window.
  44524. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  44525. // If the current item does not intersect with the window, the new page
  44526. // can be started at the current item or the last item.
  44527. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  44528. ) {
  44529. if (winEndItemInfo.i > winStartItemInfo.i) {
  44530. winStartItemInfo = winEndItemInfo;
  44531. }
  44532. else { // e.g., when page size is smaller than item size.
  44533. winStartItemInfo = currItemInfo;
  44534. }
  44535. if (winStartItemInfo) {
  44536. if (result.pageNextDataIndex == null) {
  44537. result.pageNextDataIndex = winStartItemInfo.i;
  44538. }
  44539. ++result.pageCount;
  44540. }
  44541. }
  44542. winEndItemInfo = currItemInfo;
  44543. }
  44544. for (var i = targetItemIndex - 1,
  44545. winStartItemInfo = targetItemInfo,
  44546. winEndItemInfo = targetItemInfo,
  44547. currItemInfo = null;
  44548. i >= -1;
  44549. --i
  44550. ) {
  44551. currItemInfo = getItemInfo(children[i]);
  44552. if (
  44553. // If the the end item does not intersect with the window started
  44554. // from the current item, a page can be settled.
  44555. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  44556. // e.g., when page size is smaller than item size.
  44557. && winStartItemInfo.i < winEndItemInfo.i
  44558. ) {
  44559. winEndItemInfo = winStartItemInfo;
  44560. if (result.pagePrevDataIndex == null) {
  44561. result.pagePrevDataIndex = winStartItemInfo.i;
  44562. }
  44563. ++result.pageCount;
  44564. ++result.pageIndex;
  44565. }
  44566. winStartItemInfo = currItemInfo;
  44567. }
  44568. return result;
  44569. function getItemInfo(el) {
  44570. if (el) {
  44571. var itemRect = el.getBoundingRect();
  44572. var start = itemRect[xy] + el.position[orientIdx];
  44573. return {
  44574. s: start,
  44575. e: start + itemRect[wh],
  44576. i: el.__legendDataIndex
  44577. };
  44578. }
  44579. }
  44580. function intersect(itemInfo, winStart) {
  44581. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  44582. }
  44583. },
  44584. _findTargetItemIndex: function (targetDataIndex) {
  44585. var index;
  44586. var contentGroup = this.getContentGroup();
  44587. var defaultIndex;
  44588. if (this._showController) {
  44589. contentGroup.eachChild(function (child, idx) {
  44590. var legendDataIdx = child.__legendDataIndex;
  44591. // FIXME
  44592. // If the given targetDataIndex (from model) is illegal,
  44593. // we use defualtIndex. But the index on the legend model and
  44594. // action payload is still illegal. That case will not be
  44595. // changed until some scenario requires.
  44596. if (defaultIndex == null && legendDataIdx != null) {
  44597. defaultIndex = idx;
  44598. }
  44599. if (legendDataIdx === targetDataIndex) {
  44600. index = idx;
  44601. }
  44602. });
  44603. }
  44604. return index != null ? index : defaultIndex;
  44605. }
  44606. });
  44607. /*
  44608. * Licensed to the Apache Software Foundation (ASF) under one
  44609. * or more contributor license agreements. See the NOTICE file
  44610. * distributed with this work for additional information
  44611. * regarding copyright ownership. The ASF licenses this file
  44612. * to you under the Apache License, Version 2.0 (the
  44613. * "License"); you may not use this file except in compliance
  44614. * with the License. You may obtain a copy of the License at
  44615. *
  44616. * http://www.apache.org/licenses/LICENSE-2.0
  44617. *
  44618. * Unless required by applicable law or agreed to in writing,
  44619. * software distributed under the License is distributed on an
  44620. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44621. * KIND, either express or implied. See the License for the
  44622. * specific language governing permissions and limitations
  44623. * under the License.
  44624. */
  44625. /**
  44626. * @event legendScroll
  44627. * @type {Object}
  44628. * @property {string} type 'legendScroll'
  44629. * @property {string} scrollDataIndex
  44630. */
  44631. registerAction(
  44632. 'legendScroll', 'legendscroll',
  44633. function (payload, ecModel) {
  44634. var scrollDataIndex = payload.scrollDataIndex;
  44635. scrollDataIndex != null && ecModel.eachComponent(
  44636. {mainType: 'legend', subType: 'scroll', query: payload},
  44637. function (legendModel) {
  44638. legendModel.setScrollDataIndex(scrollDataIndex);
  44639. }
  44640. );
  44641. }
  44642. );
  44643. /*
  44644. * Licensed to the Apache Software Foundation (ASF) under one
  44645. * or more contributor license agreements. See the NOTICE file
  44646. * distributed with this work for additional information
  44647. * regarding copyright ownership. The ASF licenses this file
  44648. * to you under the Apache License, Version 2.0 (the
  44649. * "License"); you may not use this file except in compliance
  44650. * with the License. You may obtain a copy of the License at
  44651. *
  44652. * http://www.apache.org/licenses/LICENSE-2.0
  44653. *
  44654. * Unless required by applicable law or agreed to in writing,
  44655. * software distributed under the License is distributed on an
  44656. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44657. * KIND, either express or implied. See the License for the
  44658. * specific language governing permissions and limitations
  44659. * under the License.
  44660. */
  44661. /**
  44662. * Legend component entry file8
  44663. */
  44664. /*
  44665. * Licensed to the Apache Software Foundation (ASF) under one
  44666. * or more contributor license agreements. See the NOTICE file
  44667. * distributed with this work for additional information
  44668. * regarding copyright ownership. The ASF licenses this file
  44669. * to you under the Apache License, Version 2.0 (the
  44670. * "License"); you may not use this file except in compliance
  44671. * with the License. You may obtain a copy of the License at
  44672. *
  44673. * http://www.apache.org/licenses/LICENSE-2.0
  44674. *
  44675. * Unless required by applicable law or agreed to in writing,
  44676. * software distributed under the License is distributed on an
  44677. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44678. * KIND, either express or implied. See the License for the
  44679. * specific language governing permissions and limitations
  44680. * under the License.
  44681. */
  44682. /*
  44683. * Licensed to the Apache Software Foundation (ASF) under one
  44684. * or more contributor license agreements. See the NOTICE file
  44685. * distributed with this work for additional information
  44686. * regarding copyright ownership. The ASF licenses this file
  44687. * to you under the Apache License, Version 2.0 (the
  44688. * "License"); you may not use this file except in compliance
  44689. * with the License. You may obtain a copy of the License at
  44690. *
  44691. * http://www.apache.org/licenses/LICENSE-2.0
  44692. *
  44693. * Unless required by applicable law or agreed to in writing,
  44694. * software distributed under the License is distributed on an
  44695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44696. * KIND, either express or implied. See the License for the
  44697. * specific language governing permissions and limitations
  44698. * under the License.
  44699. */
  44700. // Model
  44701. extendComponentModel({
  44702. type: 'title',
  44703. layoutMode: {type: 'box', ignoreSize: true},
  44704. defaultOption: {
  44705. // 一级层叠
  44706. zlevel: 0,
  44707. // 二级层叠
  44708. z: 6,
  44709. show: true,
  44710. text: '',
  44711. // 超链接跳转
  44712. // link: null,
  44713. // 仅支持self | blank
  44714. target: 'blank',
  44715. subtext: '',
  44716. // 超链接跳转
  44717. // sublink: null,
  44718. // 仅支持self | blank
  44719. subtarget: 'blank',
  44720. // 'center' ¦ 'left' ¦ 'right'
  44721. // ¦ {number}(x坐标,单位px)
  44722. left: 0,
  44723. // 'top' ¦ 'bottom' ¦ 'center'
  44724. // ¦ {number}(y坐标,单位px)
  44725. top: 0,
  44726. // 水平对齐
  44727. // 'auto' | 'left' | 'right' | 'center'
  44728. // 默认根据 left 的位置判断是左对齐还是右对齐
  44729. // textAlign: null
  44730. //
  44731. // 垂直对齐
  44732. // 'auto' | 'top' | 'bottom' | 'middle'
  44733. // 默认根据 top 位置判断是上对齐还是下对齐
  44734. // textVerticalAlign: null
  44735. // textBaseline: null // The same as textVerticalAlign.
  44736. backgroundColor: 'rgba(0,0,0,0)',
  44737. // 标题边框颜色
  44738. borderColor: '#ccc',
  44739. // 标题边框线宽,单位px,默认为0(无边框)
  44740. borderWidth: 0,
  44741. // 标题内边距,单位px,默认各方向内边距为5,
  44742. // 接受数组分别设定上右下左边距,同css
  44743. padding: 5,
  44744. // 主副标题纵向间隔,单位px,默认为10,
  44745. itemGap: 10,
  44746. textStyle: {
  44747. fontSize: 18,
  44748. fontWeight: 'bolder',
  44749. color: '#333'
  44750. },
  44751. subtextStyle: {
  44752. color: '#aaa'
  44753. }
  44754. }
  44755. });
  44756. // View
  44757. extendComponentView({
  44758. type: 'title',
  44759. render: function (titleModel, ecModel, api) {
  44760. this.group.removeAll();
  44761. if (!titleModel.get('show')) {
  44762. return;
  44763. }
  44764. var group = this.group;
  44765. var textStyleModel = titleModel.getModel('textStyle');
  44766. var subtextStyleModel = titleModel.getModel('subtextStyle');
  44767. var textAlign = titleModel.get('textAlign');
  44768. var textVerticalAlign = retrieve2(
  44769. titleModel.get('textBaseline'), titleModel.get('textVerticalAlign')
  44770. );
  44771. var textEl = new Text({
  44772. style: setTextStyle({}, textStyleModel, {
  44773. text: titleModel.get('text'),
  44774. textFill: textStyleModel.getTextColor()
  44775. }, {disableBox: true}),
  44776. z2: 10
  44777. });
  44778. var textRect = textEl.getBoundingRect();
  44779. var subText = titleModel.get('subtext');
  44780. var subTextEl = new Text({
  44781. style: setTextStyle({}, subtextStyleModel, {
  44782. text: subText,
  44783. textFill: subtextStyleModel.getTextColor(),
  44784. y: textRect.height + titleModel.get('itemGap'),
  44785. textVerticalAlign: 'top'
  44786. }, {disableBox: true}),
  44787. z2: 10
  44788. });
  44789. var link = titleModel.get('link');
  44790. var sublink = titleModel.get('sublink');
  44791. var triggerEvent = titleModel.get('triggerEvent', true);
  44792. textEl.silent = !link && !triggerEvent;
  44793. subTextEl.silent = !sublink && !triggerEvent;
  44794. if (link) {
  44795. textEl.on('click', function () {
  44796. window.open(link, '_' + titleModel.get('target'));
  44797. });
  44798. }
  44799. if (sublink) {
  44800. subTextEl.on('click', function () {
  44801. window.open(sublink, '_' + titleModel.get('subtarget'));
  44802. });
  44803. }
  44804. textEl.eventData = subTextEl.eventData = triggerEvent
  44805. ? {
  44806. componentType: 'title',
  44807. componentIndex: titleModel.componentIndex
  44808. }
  44809. : null;
  44810. group.add(textEl);
  44811. subText && group.add(subTextEl);
  44812. // If no subText, but add subTextEl, there will be an empty line.
  44813. var groupRect = group.getBoundingRect();
  44814. var layoutOption = titleModel.getBoxLayoutParams();
  44815. layoutOption.width = groupRect.width;
  44816. layoutOption.height = groupRect.height;
  44817. var layoutRect = getLayoutRect(
  44818. layoutOption, {
  44819. width: api.getWidth(),
  44820. height: api.getHeight()
  44821. }, titleModel.get('padding')
  44822. );
  44823. // Adjust text align based on position
  44824. if (!textAlign) {
  44825. // Align left if title is on the left. center and right is same
  44826. textAlign = titleModel.get('left') || titleModel.get('right');
  44827. if (textAlign === 'middle') {
  44828. textAlign = 'center';
  44829. }
  44830. // Adjust layout by text align
  44831. if (textAlign === 'right') {
  44832. layoutRect.x += layoutRect.width;
  44833. }
  44834. else if (textAlign === 'center') {
  44835. layoutRect.x += layoutRect.width / 2;
  44836. }
  44837. }
  44838. if (!textVerticalAlign) {
  44839. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  44840. if (textVerticalAlign === 'center') {
  44841. textVerticalAlign = 'middle';
  44842. }
  44843. if (textVerticalAlign === 'bottom') {
  44844. layoutRect.y += layoutRect.height;
  44845. }
  44846. else if (textVerticalAlign === 'middle') {
  44847. layoutRect.y += layoutRect.height / 2;
  44848. }
  44849. textVerticalAlign = textVerticalAlign || 'top';
  44850. }
  44851. group.attr('position', [layoutRect.x, layoutRect.y]);
  44852. var alignStyle = {
  44853. textAlign: textAlign,
  44854. textVerticalAlign: textVerticalAlign
  44855. };
  44856. textEl.setStyle(alignStyle);
  44857. subTextEl.setStyle(alignStyle);
  44858. // Render background
  44859. // Get groupRect again because textAlign has been changed
  44860. groupRect = group.getBoundingRect();
  44861. var padding = layoutRect.margin;
  44862. var style = titleModel.getItemStyle(['color', 'opacity']);
  44863. style.fill = titleModel.get('backgroundColor');
  44864. var rect = new Rect({
  44865. shape: {
  44866. x: groupRect.x - padding[3],
  44867. y: groupRect.y - padding[0],
  44868. width: groupRect.width + padding[1] + padding[3],
  44869. height: groupRect.height + padding[0] + padding[2],
  44870. r: titleModel.get('borderRadius')
  44871. },
  44872. style: style,
  44873. subPixelOptimize: true,
  44874. silent: true
  44875. });
  44876. group.add(rect);
  44877. }
  44878. });
  44879. /*
  44880. * Licensed to the Apache Software Foundation (ASF) under one
  44881. * or more contributor license agreements. See the NOTICE file
  44882. * distributed with this work for additional information
  44883. * regarding copyright ownership. The ASF licenses this file
  44884. * to you under the Apache License, Version 2.0 (the
  44885. * "License"); you may not use this file except in compliance
  44886. * with the License. You may obtain a copy of the License at
  44887. *
  44888. * http://www.apache.org/licenses/LICENSE-2.0
  44889. *
  44890. * Unless required by applicable law or agreed to in writing,
  44891. * software distributed under the License is distributed on an
  44892. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44893. * KIND, either express or implied. See the License for the
  44894. * specific language governing permissions and limitations
  44895. * under the License.
  44896. */
  44897. var addCommas$1 = addCommas;
  44898. var encodeHTML$1 = encodeHTML;
  44899. function fillLabel(opt) {
  44900. defaultEmphasis(opt, 'label', ['show']);
  44901. }
  44902. var MarkerModel = extendComponentModel({
  44903. type: 'marker',
  44904. dependencies: ['series', 'grid', 'polar', 'geo'],
  44905. /**
  44906. * @overrite
  44907. */
  44908. init: function (option, parentModel, ecModel) {
  44909. if (__DEV__) {
  44910. if (this.type === 'marker') {
  44911. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  44912. }
  44913. }
  44914. this.mergeDefaultAndTheme(option, ecModel);
  44915. this._mergeOption(option, ecModel, false, true);
  44916. },
  44917. /**
  44918. * @return {boolean}
  44919. */
  44920. isAnimationEnabled: function () {
  44921. if (env$1.node) {
  44922. return false;
  44923. }
  44924. var hostSeries = this.__hostSeries;
  44925. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  44926. },
  44927. /**
  44928. * @overrite
  44929. */
  44930. mergeOption: function (newOpt, ecModel) {
  44931. this._mergeOption(newOpt, ecModel, false, false);
  44932. },
  44933. _mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  44934. var MarkerModel = this.constructor;
  44935. var modelPropName = this.mainType + 'Model';
  44936. if (!createdBySelf) {
  44937. ecModel.eachSeries(function (seriesModel) {
  44938. var markerOpt = seriesModel.get(this.mainType, true);
  44939. var markerModel = seriesModel[modelPropName];
  44940. if (!markerOpt || !markerOpt.data) {
  44941. seriesModel[modelPropName] = null;
  44942. return;
  44943. }
  44944. if (!markerModel) {
  44945. if (isInit) {
  44946. // Default label emphasis `position` and `show`
  44947. fillLabel(markerOpt);
  44948. }
  44949. each$1(markerOpt.data, function (item) {
  44950. // FIXME Overwrite fillLabel method ?
  44951. if (item instanceof Array) {
  44952. fillLabel(item[0]);
  44953. fillLabel(item[1]);
  44954. }
  44955. else {
  44956. fillLabel(item);
  44957. }
  44958. });
  44959. markerModel = new MarkerModel(
  44960. markerOpt, this, ecModel
  44961. );
  44962. extend(markerModel, {
  44963. mainType: this.mainType,
  44964. // Use the same series index and name
  44965. seriesIndex: seriesModel.seriesIndex,
  44966. name: seriesModel.name,
  44967. createdBySelf: true
  44968. });
  44969. markerModel.__hostSeries = seriesModel;
  44970. }
  44971. else {
  44972. markerModel._mergeOption(markerOpt, ecModel, true);
  44973. }
  44974. seriesModel[modelPropName] = markerModel;
  44975. }, this);
  44976. }
  44977. },
  44978. formatTooltip: function (dataIndex) {
  44979. var data = this.getData();
  44980. var value = this.getRawValue(dataIndex);
  44981. var formattedValue = isArray(value)
  44982. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  44983. var name = data.getName(dataIndex);
  44984. var html = encodeHTML$1(this.name);
  44985. if (value != null || name) {
  44986. html += '<br />';
  44987. }
  44988. if (name) {
  44989. html += encodeHTML$1(name);
  44990. if (value != null) {
  44991. html += ' : ';
  44992. }
  44993. }
  44994. if (value != null) {
  44995. html += encodeHTML$1(formattedValue);
  44996. }
  44997. return html;
  44998. },
  44999. getData: function () {
  45000. return this._data;
  45001. },
  45002. setData: function (data) {
  45003. this._data = data;
  45004. }
  45005. });
  45006. mixin(MarkerModel, dataFormatMixin);
  45007. /*
  45008. * Licensed to the Apache Software Foundation (ASF) under one
  45009. * or more contributor license agreements. See the NOTICE file
  45010. * distributed with this work for additional information
  45011. * regarding copyright ownership. The ASF licenses this file
  45012. * to you under the Apache License, Version 2.0 (the
  45013. * "License"); you may not use this file except in compliance
  45014. * with the License. You may obtain a copy of the License at
  45015. *
  45016. * http://www.apache.org/licenses/LICENSE-2.0
  45017. *
  45018. * Unless required by applicable law or agreed to in writing,
  45019. * software distributed under the License is distributed on an
  45020. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45021. * KIND, either express or implied. See the License for the
  45022. * specific language governing permissions and limitations
  45023. * under the License.
  45024. */
  45025. MarkerModel.extend({
  45026. type: 'markPoint',
  45027. defaultOption: {
  45028. zlevel: 0,
  45029. z: 5,
  45030. symbol: 'pin',
  45031. symbolSize: 50,
  45032. //symbolRotate: 0,
  45033. //symbolOffset: [0, 0]
  45034. tooltip: {
  45035. trigger: 'item'
  45036. },
  45037. label: {
  45038. show: true,
  45039. position: 'inside'
  45040. },
  45041. itemStyle: {
  45042. borderWidth: 2
  45043. },
  45044. emphasis: {
  45045. label: {
  45046. show: true
  45047. }
  45048. }
  45049. }
  45050. });
  45051. /*
  45052. * Licensed to the Apache Software Foundation (ASF) under one
  45053. * or more contributor license agreements. See the NOTICE file
  45054. * distributed with this work for additional information
  45055. * regarding copyright ownership. The ASF licenses this file
  45056. * to you under the Apache License, Version 2.0 (the
  45057. * "License"); you may not use this file except in compliance
  45058. * with the License. You may obtain a copy of the License at
  45059. *
  45060. * http://www.apache.org/licenses/LICENSE-2.0
  45061. *
  45062. * Unless required by applicable law or agreed to in writing,
  45063. * software distributed under the License is distributed on an
  45064. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45065. * KIND, either express or implied. See the License for the
  45066. * specific language governing permissions and limitations
  45067. * under the License.
  45068. */
  45069. var indexOf$1 = indexOf;
  45070. function hasXOrY(item) {
  45071. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  45072. }
  45073. function hasXAndY(item) {
  45074. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  45075. }
  45076. // Make it simple, do not visit all stacked value to count precision.
  45077. // function getPrecision(data, valueAxisDim, dataIndex) {
  45078. // var precision = -1;
  45079. // var stackedDim = data.mapDimension(valueAxisDim);
  45080. // do {
  45081. // precision = Math.max(
  45082. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  45083. // precision
  45084. // );
  45085. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  45086. // if (stackedOnSeries) {
  45087. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  45088. // data = stackedOnSeries.getData();
  45089. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  45090. // stackedDim = data.getCalculationInfo('stackedDimension');
  45091. // }
  45092. // else {
  45093. // data = null;
  45094. // }
  45095. // } while (data);
  45096. // return precision;
  45097. // }
  45098. function markerTypeCalculatorWithExtent(
  45099. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  45100. ) {
  45101. var coordArr = [];
  45102. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  45103. var calcDataDim = stacked
  45104. ? data.getCalculationInfo('stackResultDimension')
  45105. : targetDataDim;
  45106. var value = numCalculate(data, calcDataDim, mlType);
  45107. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  45108. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  45109. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  45110. // Make it simple, do not visit all stacked value to count precision.
  45111. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  45112. precision = Math.min(precision, 20);
  45113. if (precision >= 0) {
  45114. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  45115. }
  45116. return coordArr;
  45117. }
  45118. var curry$4 = curry;
  45119. // TODO Specified percent
  45120. var markerTypeCalculator = {
  45121. /**
  45122. * @method
  45123. * @param {module:echarts/data/List} data
  45124. * @param {string} baseAxisDim
  45125. * @param {string} valueAxisDim
  45126. */
  45127. min: curry$4(markerTypeCalculatorWithExtent, 'min'),
  45128. /**
  45129. * @method
  45130. * @param {module:echarts/data/List} data
  45131. * @param {string} baseAxisDim
  45132. * @param {string} valueAxisDim
  45133. */
  45134. max: curry$4(markerTypeCalculatorWithExtent, 'max'),
  45135. /**
  45136. * @method
  45137. * @param {module:echarts/data/List} data
  45138. * @param {string} baseAxisDim
  45139. * @param {string} valueAxisDim
  45140. */
  45141. average: curry$4(markerTypeCalculatorWithExtent, 'average')
  45142. };
  45143. /**
  45144. * Transform markPoint data item to format used in List by do the following
  45145. * 1. Calculate statistic like `max`, `min`, `average`
  45146. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  45147. * @param {module:echarts/model/Series} seriesModel
  45148. * @param {module:echarts/coord/*} [coordSys]
  45149. * @param {Object} item
  45150. * @return {Object}
  45151. */
  45152. function dataTransform(seriesModel, item) {
  45153. var data = seriesModel.getData();
  45154. var coordSys = seriesModel.coordinateSystem;
  45155. // 1. If not specify the position with pixel directly
  45156. // 2. If `coord` is not a data array. Which uses `xAxis`,
  45157. // `yAxis` to specify the coord on each dimension
  45158. // parseFloat first because item.x and item.y can be percent string like '20%'
  45159. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  45160. var dims = coordSys.dimensions;
  45161. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  45162. // Clone the option
  45163. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  45164. item = clone(item);
  45165. if (item.type
  45166. && markerTypeCalculator[item.type]
  45167. && axisInfo.baseAxis && axisInfo.valueAxis
  45168. ) {
  45169. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  45170. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  45171. item.coord = markerTypeCalculator[item.type](
  45172. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  45173. otherCoordIndex, targetCoordIndex
  45174. );
  45175. // Force to use the value of calculated value.
  45176. item.value = item.coord[targetCoordIndex];
  45177. }
  45178. else {
  45179. // FIXME Only has one of xAxis and yAxis.
  45180. var coord = [
  45181. item.xAxis != null ? item.xAxis : item.radiusAxis,
  45182. item.yAxis != null ? item.yAxis : item.angleAxis
  45183. ];
  45184. // Each coord support max, min, average
  45185. for (var i = 0; i < 2; i++) {
  45186. if (markerTypeCalculator[coord[i]]) {
  45187. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  45188. }
  45189. }
  45190. item.coord = coord;
  45191. }
  45192. }
  45193. return item;
  45194. }
  45195. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  45196. var ret = {};
  45197. if (item.valueIndex != null || item.valueDim != null) {
  45198. ret.valueDataDim = item.valueIndex != null
  45199. ? data.getDimension(item.valueIndex) : item.valueDim;
  45200. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  45201. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  45202. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  45203. }
  45204. else {
  45205. ret.baseAxis = seriesModel.getBaseAxis();
  45206. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  45207. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  45208. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  45209. }
  45210. return ret;
  45211. }
  45212. function dataDimToCoordDim(seriesModel, dataDim) {
  45213. var data = seriesModel.getData();
  45214. var dimensions = data.dimensions;
  45215. dataDim = data.getDimension(dataDim);
  45216. for (var i = 0; i < dimensions.length; i++) {
  45217. var dimItem = data.getDimensionInfo(dimensions[i]);
  45218. if (dimItem.name === dataDim) {
  45219. return dimItem.coordDim;
  45220. }
  45221. }
  45222. }
  45223. /**
  45224. * Filter data which is out of coordinateSystem range
  45225. * [dataFilter description]
  45226. * @param {module:echarts/coord/*} [coordSys]
  45227. * @param {Object} item
  45228. * @return {boolean}
  45229. */
  45230. function dataFilter$1(coordSys, item) {
  45231. // Alwalys return true if there is no coordSys
  45232. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  45233. ? coordSys.containData(item.coord) : true;
  45234. }
  45235. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  45236. // x, y, radius, angle
  45237. if (dimIndex < 2) {
  45238. return item.coord && item.coord[dimIndex];
  45239. }
  45240. return item.value;
  45241. }
  45242. function numCalculate(data, valueDataDim, type) {
  45243. if (type === 'average') {
  45244. var sum = 0;
  45245. var count = 0;
  45246. data.each(valueDataDim, function (val, idx) {
  45247. if (!isNaN(val)) {
  45248. sum += val;
  45249. count++;
  45250. }
  45251. });
  45252. return sum / count;
  45253. }
  45254. else if (type === 'median') {
  45255. return data.getMedian(valueDataDim);
  45256. }
  45257. else {
  45258. // max & min
  45259. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  45260. }
  45261. }
  45262. /*
  45263. * Licensed to the Apache Software Foundation (ASF) under one
  45264. * or more contributor license agreements. See the NOTICE file
  45265. * distributed with this work for additional information
  45266. * regarding copyright ownership. The ASF licenses this file
  45267. * to you under the Apache License, Version 2.0 (the
  45268. * "License"); you may not use this file except in compliance
  45269. * with the License. You may obtain a copy of the License at
  45270. *
  45271. * http://www.apache.org/licenses/LICENSE-2.0
  45272. *
  45273. * Unless required by applicable law or agreed to in writing,
  45274. * software distributed under the License is distributed on an
  45275. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45276. * KIND, either express or implied. See the License for the
  45277. * specific language governing permissions and limitations
  45278. * under the License.
  45279. */
  45280. var MarkerView = extendComponentView({
  45281. type: 'marker',
  45282. init: function () {
  45283. /**
  45284. * Markline grouped by series
  45285. * @private
  45286. * @type {module:zrender/core/util.HashMap}
  45287. */
  45288. this.markerGroupMap = createHashMap();
  45289. },
  45290. render: function (markerModel, ecModel, api) {
  45291. var markerGroupMap = this.markerGroupMap;
  45292. markerGroupMap.each(function (item) {
  45293. item.__keep = false;
  45294. });
  45295. var markerModelKey = this.type + 'Model';
  45296. ecModel.eachSeries(function (seriesModel) {
  45297. var markerModel = seriesModel[markerModelKey];
  45298. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  45299. }, this);
  45300. markerGroupMap.each(function (item) {
  45301. !item.__keep && this.group.remove(item.group);
  45302. }, this);
  45303. },
  45304. renderSeries: function () {}
  45305. });
  45306. /*
  45307. * Licensed to the Apache Software Foundation (ASF) under one
  45308. * or more contributor license agreements. See the NOTICE file
  45309. * distributed with this work for additional information
  45310. * regarding copyright ownership. The ASF licenses this file
  45311. * to you under the Apache License, Version 2.0 (the
  45312. * "License"); you may not use this file except in compliance
  45313. * with the License. You may obtain a copy of the License at
  45314. *
  45315. * http://www.apache.org/licenses/LICENSE-2.0
  45316. *
  45317. * Unless required by applicable law or agreed to in writing,
  45318. * software distributed under the License is distributed on an
  45319. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45320. * KIND, either express or implied. See the License for the
  45321. * specific language governing permissions and limitations
  45322. * under the License.
  45323. */
  45324. function updateMarkerLayout(mpData, seriesModel, api) {
  45325. var coordSys = seriesModel.coordinateSystem;
  45326. mpData.each(function (idx) {
  45327. var itemModel = mpData.getItemModel(idx);
  45328. var point;
  45329. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  45330. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  45331. if (!isNaN(xPx) && !isNaN(yPx)) {
  45332. point = [xPx, yPx];
  45333. }
  45334. // Chart like bar may have there own marker positioning logic
  45335. else if (seriesModel.getMarkerPosition) {
  45336. // Use the getMarkerPoisition
  45337. point = seriesModel.getMarkerPosition(
  45338. mpData.getValues(mpData.dimensions, idx)
  45339. );
  45340. }
  45341. else if (coordSys) {
  45342. var x = mpData.get(coordSys.dimensions[0], idx);
  45343. var y = mpData.get(coordSys.dimensions[1], idx);
  45344. point = coordSys.dataToPoint([x, y]);
  45345. }
  45346. // Use x, y if has any
  45347. if (!isNaN(xPx)) {
  45348. point[0] = xPx;
  45349. }
  45350. if (!isNaN(yPx)) {
  45351. point[1] = yPx;
  45352. }
  45353. mpData.setItemLayout(idx, point);
  45354. });
  45355. }
  45356. MarkerView.extend({
  45357. type: 'markPoint',
  45358. // updateLayout: function (markPointModel, ecModel, api) {
  45359. // ecModel.eachSeries(function (seriesModel) {
  45360. // var mpModel = seriesModel.markPointModel;
  45361. // if (mpModel) {
  45362. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45363. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  45364. // }
  45365. // }, this);
  45366. // },
  45367. updateTransform: function (markPointModel, ecModel, api) {
  45368. ecModel.eachSeries(function (seriesModel) {
  45369. var mpModel = seriesModel.markPointModel;
  45370. if (mpModel) {
  45371. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45372. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  45373. }
  45374. }, this);
  45375. },
  45376. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  45377. var coordSys = seriesModel.coordinateSystem;
  45378. var seriesId = seriesModel.id;
  45379. var seriesData = seriesModel.getData();
  45380. var symbolDrawMap = this.markerGroupMap;
  45381. var symbolDraw = symbolDrawMap.get(seriesId)
  45382. || symbolDrawMap.set(seriesId, new SymbolDraw());
  45383. var mpData = createList$1(coordSys, seriesModel, mpModel);
  45384. // FIXME
  45385. mpModel.setData(mpData);
  45386. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45387. mpData.each(function (idx) {
  45388. var itemModel = mpData.getItemModel(idx);
  45389. var symbol = itemModel.getShallow('symbol');
  45390. var symbolSize = itemModel.getShallow('symbolSize');
  45391. var isFnSymbol = isFunction$1(symbol);
  45392. var isFnSymbolSize = isFunction$1(symbolSize);
  45393. if (isFnSymbol || isFnSymbolSize) {
  45394. var rawIdx = mpModel.getRawValue(idx);
  45395. var dataParams = mpModel.getDataParams(idx);
  45396. if (isFnSymbol) {
  45397. symbol = symbol(rawIdx, dataParams);
  45398. }
  45399. if (isFnSymbolSize) {
  45400. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  45401. symbolSize = symbolSize(rawIdx, dataParams);
  45402. }
  45403. }
  45404. mpData.setItemVisual(idx, {
  45405. symbol: symbol,
  45406. symbolSize: symbolSize,
  45407. color: itemModel.get('itemStyle.color')
  45408. || seriesData.getVisual('color')
  45409. });
  45410. });
  45411. // TODO Text are wrong
  45412. symbolDraw.updateData(mpData);
  45413. this.group.add(symbolDraw.group);
  45414. // Set host model for tooltip
  45415. // FIXME
  45416. mpData.eachItemGraphicEl(function (el) {
  45417. el.traverse(function (child) {
  45418. child.dataModel = mpModel;
  45419. });
  45420. });
  45421. symbolDraw.__keep = true;
  45422. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  45423. }
  45424. });
  45425. /**
  45426. * @inner
  45427. * @param {module:echarts/coord/*} [coordSys]
  45428. * @param {module:echarts/model/Series} seriesModel
  45429. * @param {module:echarts/model/Model} mpModel
  45430. */
  45431. function createList$1(coordSys, seriesModel, mpModel) {
  45432. var coordDimsInfos;
  45433. if (coordSys) {
  45434. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  45435. var info = seriesModel.getData().getDimensionInfo(
  45436. seriesModel.getData().mapDimension(coordDim)
  45437. ) || {};
  45438. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  45439. return defaults({name: coordDim}, info);
  45440. });
  45441. }
  45442. else {
  45443. coordDimsInfos = [{
  45444. name: 'value',
  45445. type: 'float'
  45446. }];
  45447. }
  45448. var mpData = new List(coordDimsInfos, mpModel);
  45449. var dataOpt = map(mpModel.get('data'), curry(
  45450. dataTransform, seriesModel
  45451. ));
  45452. if (coordSys) {
  45453. dataOpt = filter(
  45454. dataOpt, curry(dataFilter$1, coordSys)
  45455. );
  45456. }
  45457. mpData.initData(dataOpt, null,
  45458. coordSys ? dimValueGetter : function (item) {
  45459. return item.value;
  45460. }
  45461. );
  45462. return mpData;
  45463. }
  45464. /*
  45465. * Licensed to the Apache Software Foundation (ASF) under one
  45466. * or more contributor license agreements. See the NOTICE file
  45467. * distributed with this work for additional information
  45468. * regarding copyright ownership. The ASF licenses this file
  45469. * to you under the Apache License, Version 2.0 (the
  45470. * "License"); you may not use this file except in compliance
  45471. * with the License. You may obtain a copy of the License at
  45472. *
  45473. * http://www.apache.org/licenses/LICENSE-2.0
  45474. *
  45475. * Unless required by applicable law or agreed to in writing,
  45476. * software distributed under the License is distributed on an
  45477. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45478. * KIND, either express or implied. See the License for the
  45479. * specific language governing permissions and limitations
  45480. * under the License.
  45481. */
  45482. // HINT Markpoint can't be used too much
  45483. registerPreprocessor(function (opt) {
  45484. // Make sure markPoint component is enabled
  45485. opt.markPoint = opt.markPoint || {};
  45486. });
  45487. /*
  45488. * Licensed to the Apache Software Foundation (ASF) under one
  45489. * or more contributor license agreements. See the NOTICE file
  45490. * distributed with this work for additional information
  45491. * regarding copyright ownership. The ASF licenses this file
  45492. * to you under the Apache License, Version 2.0 (the
  45493. * "License"); you may not use this file except in compliance
  45494. * with the License. You may obtain a copy of the License at
  45495. *
  45496. * http://www.apache.org/licenses/LICENSE-2.0
  45497. *
  45498. * Unless required by applicable law or agreed to in writing,
  45499. * software distributed under the License is distributed on an
  45500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45501. * KIND, either express or implied. See the License for the
  45502. * specific language governing permissions and limitations
  45503. * under the License.
  45504. */
  45505. MarkerModel.extend({
  45506. type: 'markLine',
  45507. defaultOption: {
  45508. zlevel: 0,
  45509. z: 5,
  45510. symbol: ['circle', 'arrow'],
  45511. symbolSize: [8, 16],
  45512. //symbolRotate: 0,
  45513. precision: 2,
  45514. tooltip: {
  45515. trigger: 'item'
  45516. },
  45517. label: {
  45518. show: true,
  45519. position: 'end'
  45520. },
  45521. lineStyle: {
  45522. type: 'dashed'
  45523. },
  45524. emphasis: {
  45525. label: {
  45526. show: true
  45527. },
  45528. lineStyle: {
  45529. width: 3
  45530. }
  45531. },
  45532. animationEasing: 'linear'
  45533. }
  45534. });
  45535. /*
  45536. * Licensed to the Apache Software Foundation (ASF) under one
  45537. * or more contributor license agreements. See the NOTICE file
  45538. * distributed with this work for additional information
  45539. * regarding copyright ownership. The ASF licenses this file
  45540. * to you under the Apache License, Version 2.0 (the
  45541. * "License"); you may not use this file except in compliance
  45542. * with the License. You may obtain a copy of the License at
  45543. *
  45544. * http://www.apache.org/licenses/LICENSE-2.0
  45545. *
  45546. * Unless required by applicable law or agreed to in writing,
  45547. * software distributed under the License is distributed on an
  45548. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45549. * KIND, either express or implied. See the License for the
  45550. * specific language governing permissions and limitations
  45551. * under the License.
  45552. */
  45553. /**
  45554. * Line path for bezier and straight line draw
  45555. */
  45556. var straightLineProto = Line.prototype;
  45557. var bezierCurveProto = BezierCurve.prototype;
  45558. function isLine(shape) {
  45559. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  45560. }
  45561. var LinePath = extendShape({
  45562. type: 'ec-line',
  45563. style: {
  45564. stroke: '#000',
  45565. fill: null
  45566. },
  45567. shape: {
  45568. x1: 0,
  45569. y1: 0,
  45570. x2: 0,
  45571. y2: 0,
  45572. percent: 1,
  45573. cpx1: null,
  45574. cpy1: null
  45575. },
  45576. buildPath: function (ctx, shape) {
  45577. this[isLine(shape) ? '_buildPathLine' : '_buildPathCurve'](ctx, shape);
  45578. },
  45579. _buildPathLine: straightLineProto.buildPath,
  45580. _buildPathCurve: bezierCurveProto.buildPath,
  45581. pointAt: function (t) {
  45582. return this[isLine(this.shape) ? '_pointAtLine' : '_pointAtCurve'](t);
  45583. },
  45584. _pointAtLine: straightLineProto.pointAt,
  45585. _pointAtCurve: bezierCurveProto.pointAt,
  45586. tangentAt: function (t) {
  45587. var shape = this.shape;
  45588. var p = isLine(shape)
  45589. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  45590. : this._tangentAtCurve(t);
  45591. return normalize(p, p);
  45592. },
  45593. _tangentAtCurve: bezierCurveProto.tangentAt
  45594. });
  45595. /*
  45596. * Licensed to the Apache Software Foundation (ASF) under one
  45597. * or more contributor license agreements. See the NOTICE file
  45598. * distributed with this work for additional information
  45599. * regarding copyright ownership. The ASF licenses this file
  45600. * to you under the Apache License, Version 2.0 (the
  45601. * "License"); you may not use this file except in compliance
  45602. * with the License. You may obtain a copy of the License at
  45603. *
  45604. * http://www.apache.org/licenses/LICENSE-2.0
  45605. *
  45606. * Unless required by applicable law or agreed to in writing,
  45607. * software distributed under the License is distributed on an
  45608. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45609. * KIND, either express or implied. See the License for the
  45610. * specific language governing permissions and limitations
  45611. * under the License.
  45612. */
  45613. /**
  45614. * @module echarts/chart/helper/Line
  45615. */
  45616. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  45617. function makeSymbolTypeKey(symbolCategory) {
  45618. return '_' + symbolCategory + 'Type';
  45619. }
  45620. /**
  45621. * @inner
  45622. */
  45623. function createSymbol$1(name, lineData, idx) {
  45624. var color = lineData.getItemVisual(idx, 'color');
  45625. var symbolType = lineData.getItemVisual(idx, name);
  45626. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  45627. if (!symbolType || symbolType === 'none') {
  45628. return;
  45629. }
  45630. if (!isArray(symbolSize)) {
  45631. symbolSize = [symbolSize, symbolSize];
  45632. }
  45633. var symbolPath = createSymbol(
  45634. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  45635. symbolSize[0], symbolSize[1], color
  45636. );
  45637. symbolPath.name = name;
  45638. return symbolPath;
  45639. }
  45640. function createLine(points) {
  45641. var line = new LinePath({
  45642. name: 'line',
  45643. subPixelOptimize: true
  45644. });
  45645. setLinePoints(line.shape, points);
  45646. return line;
  45647. }
  45648. function setLinePoints(targetShape, points) {
  45649. targetShape.x1 = points[0][0];
  45650. targetShape.y1 = points[0][1];
  45651. targetShape.x2 = points[1][0];
  45652. targetShape.y2 = points[1][1];
  45653. targetShape.percent = 1;
  45654. var cp1 = points[2];
  45655. if (cp1) {
  45656. targetShape.cpx1 = cp1[0];
  45657. targetShape.cpy1 = cp1[1];
  45658. }
  45659. else {
  45660. targetShape.cpx1 = NaN;
  45661. targetShape.cpy1 = NaN;
  45662. }
  45663. }
  45664. function updateSymbolAndLabelBeforeLineUpdate() {
  45665. var lineGroup = this;
  45666. var symbolFrom = lineGroup.childOfName('fromSymbol');
  45667. var symbolTo = lineGroup.childOfName('toSymbol');
  45668. var label = lineGroup.childOfName('label');
  45669. // Quick reject
  45670. if (!symbolFrom && !symbolTo && label.ignore) {
  45671. return;
  45672. }
  45673. var invScale = 1;
  45674. var parentNode = this.parent;
  45675. while (parentNode) {
  45676. if (parentNode.scale) {
  45677. invScale /= parentNode.scale[0];
  45678. }
  45679. parentNode = parentNode.parent;
  45680. }
  45681. var line = lineGroup.childOfName('line');
  45682. // If line not changed
  45683. // FIXME Parent scale changed
  45684. if (!this.__dirty && !line.__dirty) {
  45685. return;
  45686. }
  45687. var percent = line.shape.percent;
  45688. var fromPos = line.pointAt(0);
  45689. var toPos = line.pointAt(percent);
  45690. var d = sub([], toPos, fromPos);
  45691. normalize(d, d);
  45692. if (symbolFrom) {
  45693. symbolFrom.attr('position', fromPos);
  45694. var tangent = line.tangentAt(0);
  45695. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  45696. tangent[1], tangent[0]
  45697. ));
  45698. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  45699. }
  45700. if (symbolTo) {
  45701. symbolTo.attr('position', toPos);
  45702. var tangent = line.tangentAt(1);
  45703. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  45704. tangent[1], tangent[0]
  45705. ));
  45706. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  45707. }
  45708. if (!label.ignore) {
  45709. label.attr('position', toPos);
  45710. var textPosition;
  45711. var textAlign;
  45712. var textVerticalAlign;
  45713. var distance$$1 = 5 * invScale;
  45714. // End
  45715. if (label.__position === 'end') {
  45716. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  45717. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  45718. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  45719. }
  45720. // Middle
  45721. else if (label.__position === 'middle') {
  45722. var halfPercent = percent / 2;
  45723. var tangent = line.tangentAt(halfPercent);
  45724. var n = [tangent[1], -tangent[0]];
  45725. var cp = line.pointAt(halfPercent);
  45726. if (n[1] > 0) {
  45727. n[0] = -n[0];
  45728. n[1] = -n[1];
  45729. }
  45730. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  45731. textAlign = 'center';
  45732. textVerticalAlign = 'bottom';
  45733. var rotation = -Math.atan2(tangent[1], tangent[0]);
  45734. if (toPos[0] < fromPos[0]) {
  45735. rotation = Math.PI + rotation;
  45736. }
  45737. label.attr('rotation', rotation);
  45738. }
  45739. // Start
  45740. else {
  45741. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  45742. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  45743. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  45744. }
  45745. label.attr({
  45746. style: {
  45747. // Use the user specified text align and baseline first
  45748. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  45749. textAlign: label.__textAlign || textAlign
  45750. },
  45751. position: textPosition,
  45752. scale: [invScale, invScale]
  45753. });
  45754. }
  45755. }
  45756. /**
  45757. * @constructor
  45758. * @extends {module:zrender/graphic/Group}
  45759. * @alias {module:echarts/chart/helper/Line}
  45760. */
  45761. function Line$1(lineData, idx, seriesScope) {
  45762. Group.call(this);
  45763. this._createLine(lineData, idx, seriesScope);
  45764. }
  45765. var lineProto = Line$1.prototype;
  45766. // Update symbol position and rotation
  45767. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  45768. lineProto._createLine = function (lineData, idx, seriesScope) {
  45769. var seriesModel = lineData.hostModel;
  45770. var linePoints = lineData.getItemLayout(idx);
  45771. var line = createLine(linePoints);
  45772. line.shape.percent = 0;
  45773. initProps(line, {
  45774. shape: {
  45775. percent: 1
  45776. }
  45777. }, seriesModel, idx);
  45778. this.add(line);
  45779. var label = new Text({
  45780. name: 'label',
  45781. // FIXME
  45782. // Temporary solution for `focusNodeAdjacency`.
  45783. // line label do not use the opacity of lineStyle.
  45784. lineLabelOriginalOpacity: 1
  45785. });
  45786. this.add(label);
  45787. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  45788. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  45789. // symbols must added after line to make sure
  45790. // it will be updated after line#update.
  45791. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  45792. this.add(symbol);
  45793. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  45794. }, this);
  45795. this._updateCommonStl(lineData, idx, seriesScope);
  45796. };
  45797. lineProto.updateData = function (lineData, idx, seriesScope) {
  45798. var seriesModel = lineData.hostModel;
  45799. var line = this.childOfName('line');
  45800. var linePoints = lineData.getItemLayout(idx);
  45801. var target = {
  45802. shape: {}
  45803. };
  45804. setLinePoints(target.shape, linePoints);
  45805. updateProps(line, target, seriesModel, idx);
  45806. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  45807. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  45808. var key = makeSymbolTypeKey(symbolCategory);
  45809. // Symbol changed
  45810. if (this[key] !== symbolType) {
  45811. this.remove(this.childOfName(symbolCategory));
  45812. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  45813. this.add(symbol);
  45814. }
  45815. this[key] = symbolType;
  45816. }, this);
  45817. this._updateCommonStl(lineData, idx, seriesScope);
  45818. };
  45819. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  45820. var seriesModel = lineData.hostModel;
  45821. var line = this.childOfName('line');
  45822. var lineStyle = seriesScope && seriesScope.lineStyle;
  45823. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  45824. var labelModel = seriesScope && seriesScope.labelModel;
  45825. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  45826. // Optimization for large dataset
  45827. if (!seriesScope || lineData.hasItemOption) {
  45828. var itemModel = lineData.getItemModel(idx);
  45829. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  45830. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  45831. labelModel = itemModel.getModel('label');
  45832. hoverLabelModel = itemModel.getModel('emphasis.label');
  45833. }
  45834. var visualColor = lineData.getItemVisual(idx, 'color');
  45835. var visualOpacity = retrieve3(
  45836. lineData.getItemVisual(idx, 'opacity'),
  45837. lineStyle.opacity,
  45838. 1
  45839. );
  45840. line.useStyle(defaults(
  45841. {
  45842. strokeNoScale: true,
  45843. fill: 'none',
  45844. stroke: visualColor,
  45845. opacity: visualOpacity
  45846. },
  45847. lineStyle
  45848. ));
  45849. line.hoverStyle = hoverLineStyle;
  45850. // Update symbol
  45851. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  45852. var symbol = this.childOfName(symbolCategory);
  45853. if (symbol) {
  45854. symbol.setColor(visualColor);
  45855. symbol.setStyle({
  45856. opacity: visualOpacity
  45857. });
  45858. }
  45859. }, this);
  45860. var showLabel = labelModel.getShallow('show');
  45861. var hoverShowLabel = hoverLabelModel.getShallow('show');
  45862. var label = this.childOfName('label');
  45863. var defaultLabelColor;
  45864. var baseText;
  45865. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  45866. if (showLabel || hoverShowLabel) {
  45867. defaultLabelColor = visualColor || '#000';
  45868. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  45869. if (baseText == null) {
  45870. var rawVal = seriesModel.getRawValue(idx);
  45871. baseText = rawVal == null
  45872. ? lineData.getName(idx)
  45873. : isFinite(rawVal)
  45874. ? round$1(rawVal)
  45875. : rawVal;
  45876. }
  45877. }
  45878. var normalText = showLabel ? baseText : null;
  45879. var emphasisText = hoverShowLabel
  45880. ? retrieve2(
  45881. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  45882. baseText
  45883. )
  45884. : null;
  45885. var labelStyle = label.style;
  45886. // Always set `textStyle` even if `normalStyle.text` is null, because default
  45887. // values have to be set on `normalStyle`.
  45888. if (normalText != null || emphasisText != null) {
  45889. setTextStyle(label.style, labelModel, {
  45890. text: normalText
  45891. }, {
  45892. autoColor: defaultLabelColor
  45893. });
  45894. label.__textAlign = labelStyle.textAlign;
  45895. label.__verticalAlign = labelStyle.textVerticalAlign;
  45896. // 'start', 'middle', 'end'
  45897. label.__position = labelModel.get('position') || 'middle';
  45898. }
  45899. if (emphasisText != null) {
  45900. // Only these properties supported in this emphasis style here.
  45901. label.hoverStyle = {
  45902. text: emphasisText,
  45903. textFill: hoverLabelModel.getTextColor(true),
  45904. // For merging hover style to normal style, do not use
  45905. // `hoverLabelModel.getFont()` here.
  45906. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  45907. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  45908. fontSize: hoverLabelModel.getShallow('fontSize'),
  45909. fontFamily: hoverLabelModel.getShallow('fontFamily')
  45910. };
  45911. }
  45912. else {
  45913. label.hoverStyle = {
  45914. text: null
  45915. };
  45916. }
  45917. label.ignore = !showLabel && !hoverShowLabel;
  45918. setHoverStyle(this);
  45919. };
  45920. lineProto.highlight = function () {
  45921. this.trigger('emphasis');
  45922. };
  45923. lineProto.downplay = function () {
  45924. this.trigger('normal');
  45925. };
  45926. lineProto.updateLayout = function (lineData, idx) {
  45927. this.setLinePoints(lineData.getItemLayout(idx));
  45928. };
  45929. lineProto.setLinePoints = function (points) {
  45930. var linePath = this.childOfName('line');
  45931. setLinePoints(linePath.shape, points);
  45932. linePath.dirty();
  45933. };
  45934. inherits(Line$1, Group);
  45935. /*
  45936. * Licensed to the Apache Software Foundation (ASF) under one
  45937. * or more contributor license agreements. See the NOTICE file
  45938. * distributed with this work for additional information
  45939. * regarding copyright ownership. The ASF licenses this file
  45940. * to you under the Apache License, Version 2.0 (the
  45941. * "License"); you may not use this file except in compliance
  45942. * with the License. You may obtain a copy of the License at
  45943. *
  45944. * http://www.apache.org/licenses/LICENSE-2.0
  45945. *
  45946. * Unless required by applicable law or agreed to in writing,
  45947. * software distributed under the License is distributed on an
  45948. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45949. * KIND, either express or implied. See the License for the
  45950. * specific language governing permissions and limitations
  45951. * under the License.
  45952. */
  45953. /**
  45954. * @module echarts/chart/helper/LineDraw
  45955. */
  45956. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  45957. /**
  45958. * @alias module:echarts/component/marker/LineDraw
  45959. * @constructor
  45960. */
  45961. function LineDraw(ctor) {
  45962. this._ctor = ctor || Line$1;
  45963. this.group = new Group();
  45964. }
  45965. var lineDrawProto = LineDraw.prototype;
  45966. lineDrawProto.isPersistent = function () {
  45967. return true;
  45968. };
  45969. /**
  45970. * @param {module:echarts/data/List} lineData
  45971. */
  45972. lineDrawProto.updateData = function (lineData) {
  45973. var lineDraw = this;
  45974. var group = lineDraw.group;
  45975. var oldLineData = lineDraw._lineData;
  45976. lineDraw._lineData = lineData;
  45977. // There is no oldLineData only when first rendering or switching from
  45978. // stream mode to normal mode, where previous elements should be removed.
  45979. if (!oldLineData) {
  45980. group.removeAll();
  45981. }
  45982. var seriesScope = makeSeriesScope$1(lineData);
  45983. lineData.diff(oldLineData)
  45984. .add(function (idx) {
  45985. doAdd(lineDraw, lineData, idx, seriesScope);
  45986. })
  45987. .update(function (newIdx, oldIdx) {
  45988. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  45989. })
  45990. .remove(function (idx) {
  45991. group.remove(oldLineData.getItemGraphicEl(idx));
  45992. })
  45993. .execute();
  45994. };
  45995. function doAdd(lineDraw, lineData, idx, seriesScope) {
  45996. var itemLayout = lineData.getItemLayout(idx);
  45997. if (!lineNeedsDraw(itemLayout)) {
  45998. return;
  45999. }
  46000. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  46001. lineData.setItemGraphicEl(idx, el);
  46002. lineDraw.group.add(el);
  46003. }
  46004. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  46005. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  46006. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  46007. lineDraw.group.remove(itemEl);
  46008. return;
  46009. }
  46010. if (!itemEl) {
  46011. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  46012. }
  46013. else {
  46014. itemEl.updateData(newLineData, newIdx, seriesScope);
  46015. }
  46016. newLineData.setItemGraphicEl(newIdx, itemEl);
  46017. lineDraw.group.add(itemEl);
  46018. }
  46019. lineDrawProto.updateLayout = function () {
  46020. var lineData = this._lineData;
  46021. // Do not support update layout in incremental mode.
  46022. if (!lineData) {
  46023. return;
  46024. }
  46025. lineData.eachItemGraphicEl(function (el, idx) {
  46026. el.updateLayout(lineData, idx);
  46027. }, this);
  46028. };
  46029. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  46030. this._seriesScope = makeSeriesScope$1(lineData);
  46031. this._lineData = null;
  46032. this.group.removeAll();
  46033. };
  46034. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  46035. function updateIncrementalAndHover(el) {
  46036. if (!el.isGroup) {
  46037. el.incremental = el.useHoverLayer = true;
  46038. }
  46039. }
  46040. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  46041. var itemLayout = lineData.getItemLayout(idx);
  46042. if (lineNeedsDraw(itemLayout)) {
  46043. var el = new this._ctor(lineData, idx, this._seriesScope);
  46044. el.traverse(updateIncrementalAndHover);
  46045. this.group.add(el);
  46046. lineData.setItemGraphicEl(idx, el);
  46047. }
  46048. }
  46049. };
  46050. function makeSeriesScope$1(lineData) {
  46051. var hostModel = lineData.hostModel;
  46052. return {
  46053. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  46054. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  46055. labelModel: hostModel.getModel('label'),
  46056. hoverLabelModel: hostModel.getModel('emphasis.label')
  46057. };
  46058. }
  46059. lineDrawProto.remove = function () {
  46060. this._clearIncremental();
  46061. this._incremental = null;
  46062. this.group.removeAll();
  46063. };
  46064. lineDrawProto._clearIncremental = function () {
  46065. var incremental = this._incremental;
  46066. if (incremental) {
  46067. incremental.clearDisplaybles();
  46068. }
  46069. };
  46070. function isPointNaN(pt) {
  46071. return isNaN(pt[0]) || isNaN(pt[1]);
  46072. }
  46073. function lineNeedsDraw(pts) {
  46074. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  46075. }
  46076. /*
  46077. * Licensed to the Apache Software Foundation (ASF) under one
  46078. * or more contributor license agreements. See the NOTICE file
  46079. * distributed with this work for additional information
  46080. * regarding copyright ownership. The ASF licenses this file
  46081. * to you under the Apache License, Version 2.0 (the
  46082. * "License"); you may not use this file except in compliance
  46083. * with the License. You may obtain a copy of the License at
  46084. *
  46085. * http://www.apache.org/licenses/LICENSE-2.0
  46086. *
  46087. * Unless required by applicable law or agreed to in writing,
  46088. * software distributed under the License is distributed on an
  46089. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46090. * KIND, either express or implied. See the License for the
  46091. * specific language governing permissions and limitations
  46092. * under the License.
  46093. */
  46094. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  46095. var data = seriesModel.getData();
  46096. // Special type markLine like 'min', 'max', 'average', 'median'
  46097. var mlType = item.type;
  46098. if (!isArray(item)
  46099. && (
  46100. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  46101. // In case
  46102. // data: [{
  46103. // yAxis: 10
  46104. // }]
  46105. || (item.xAxis != null || item.yAxis != null)
  46106. )
  46107. ) {
  46108. var valueAxis;
  46109. var value;
  46110. if (item.yAxis != null || item.xAxis != null) {
  46111. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  46112. value = retrieve(item.yAxis, item.xAxis);
  46113. }
  46114. else {
  46115. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  46116. valueAxis = axisInfo.valueAxis;
  46117. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  46118. value = numCalculate(data, valueDataDim, mlType);
  46119. }
  46120. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  46121. var baseIndex = 1 - valueIndex;
  46122. var mlFrom = clone(item);
  46123. var mlTo = {};
  46124. mlFrom.type = null;
  46125. mlFrom.coord = [];
  46126. mlTo.coord = [];
  46127. mlFrom.coord[baseIndex] = -Infinity;
  46128. mlTo.coord[baseIndex] = Infinity;
  46129. var precision = mlModel.get('precision');
  46130. if (precision >= 0 && typeof value === 'number') {
  46131. value = +value.toFixed(Math.min(precision, 20));
  46132. }
  46133. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  46134. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  46135. type: mlType,
  46136. valueIndex: item.valueIndex,
  46137. // Force to use the value of calculated value.
  46138. value: value
  46139. }];
  46140. }
  46141. item = [
  46142. dataTransform(seriesModel, item[0]),
  46143. dataTransform(seriesModel, item[1]),
  46144. extend({}, item[2])
  46145. ];
  46146. // Avoid line data type is extended by from(to) data type
  46147. item[2].type = item[2].type || '';
  46148. // Merge from option and to option into line option
  46149. merge(item[2], item[0]);
  46150. merge(item[2], item[1]);
  46151. return item;
  46152. };
  46153. function isInifinity(val) {
  46154. return !isNaN(val) && !isFinite(val);
  46155. }
  46156. // If a markLine has one dim
  46157. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  46158. var otherDimIndex = 1 - dimIndex;
  46159. var dimName = coordSys.dimensions[dimIndex];
  46160. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  46161. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  46162. }
  46163. function markLineFilter(coordSys, item) {
  46164. if (coordSys.type === 'cartesian2d') {
  46165. var fromCoord = item[0].coord;
  46166. var toCoord = item[1].coord;
  46167. // In case
  46168. // {
  46169. // markLine: {
  46170. // data: [{ yAxis: 2 }]
  46171. // }
  46172. // }
  46173. if (
  46174. fromCoord && toCoord
  46175. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  46176. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  46177. ) {
  46178. return true;
  46179. }
  46180. }
  46181. return dataFilter$1(coordSys, item[0])
  46182. && dataFilter$1(coordSys, item[1]);
  46183. }
  46184. function updateSingleMarkerEndLayout(
  46185. data, idx, isFrom, seriesModel, api
  46186. ) {
  46187. var coordSys = seriesModel.coordinateSystem;
  46188. var itemModel = data.getItemModel(idx);
  46189. var point;
  46190. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  46191. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  46192. if (!isNaN(xPx) && !isNaN(yPx)) {
  46193. point = [xPx, yPx];
  46194. }
  46195. else {
  46196. // Chart like bar may have there own marker positioning logic
  46197. if (seriesModel.getMarkerPosition) {
  46198. // Use the getMarkerPoisition
  46199. point = seriesModel.getMarkerPosition(
  46200. data.getValues(data.dimensions, idx)
  46201. );
  46202. }
  46203. else {
  46204. var dims = coordSys.dimensions;
  46205. var x = data.get(dims[0], idx);
  46206. var y = data.get(dims[1], idx);
  46207. point = coordSys.dataToPoint([x, y]);
  46208. }
  46209. // Expand line to the edge of grid if value on one axis is Inifnity
  46210. // In case
  46211. // markLine: {
  46212. // data: [{
  46213. // yAxis: 2
  46214. // // or
  46215. // type: 'average'
  46216. // }]
  46217. // }
  46218. if (coordSys.type === 'cartesian2d') {
  46219. var xAxis = coordSys.getAxis('x');
  46220. var yAxis = coordSys.getAxis('y');
  46221. var dims = coordSys.dimensions;
  46222. if (isInifinity(data.get(dims[0], idx))) {
  46223. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  46224. }
  46225. else if (isInifinity(data.get(dims[1], idx))) {
  46226. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  46227. }
  46228. }
  46229. // Use x, y if has any
  46230. if (!isNaN(xPx)) {
  46231. point[0] = xPx;
  46232. }
  46233. if (!isNaN(yPx)) {
  46234. point[1] = yPx;
  46235. }
  46236. }
  46237. data.setItemLayout(idx, point);
  46238. }
  46239. MarkerView.extend({
  46240. type: 'markLine',
  46241. // updateLayout: function (markLineModel, ecModel, api) {
  46242. // ecModel.eachSeries(function (seriesModel) {
  46243. // var mlModel = seriesModel.markLineModel;
  46244. // if (mlModel) {
  46245. // var mlData = mlModel.getData();
  46246. // var fromData = mlModel.__from;
  46247. // var toData = mlModel.__to;
  46248. // // Update visual and layout of from symbol and to symbol
  46249. // fromData.each(function (idx) {
  46250. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  46251. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  46252. // });
  46253. // // Update layout of line
  46254. // mlData.each(function (idx) {
  46255. // mlData.setItemLayout(idx, [
  46256. // fromData.getItemLayout(idx),
  46257. // toData.getItemLayout(idx)
  46258. // ]);
  46259. // });
  46260. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  46261. // }
  46262. // }, this);
  46263. // },
  46264. updateTransform: function (markLineModel, ecModel, api) {
  46265. ecModel.eachSeries(function (seriesModel) {
  46266. var mlModel = seriesModel.markLineModel;
  46267. if (mlModel) {
  46268. var mlData = mlModel.getData();
  46269. var fromData = mlModel.__from;
  46270. var toData = mlModel.__to;
  46271. // Update visual and layout of from symbol and to symbol
  46272. fromData.each(function (idx) {
  46273. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  46274. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  46275. });
  46276. // Update layout of line
  46277. mlData.each(function (idx) {
  46278. mlData.setItemLayout(idx, [
  46279. fromData.getItemLayout(idx),
  46280. toData.getItemLayout(idx)
  46281. ]);
  46282. });
  46283. this.markerGroupMap.get(seriesModel.id).updateLayout();
  46284. }
  46285. }, this);
  46286. },
  46287. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  46288. var coordSys = seriesModel.coordinateSystem;
  46289. var seriesId = seriesModel.id;
  46290. var seriesData = seriesModel.getData();
  46291. var lineDrawMap = this.markerGroupMap;
  46292. var lineDraw = lineDrawMap.get(seriesId)
  46293. || lineDrawMap.set(seriesId, new LineDraw());
  46294. this.group.add(lineDraw.group);
  46295. var mlData = createList$2(coordSys, seriesModel, mlModel);
  46296. var fromData = mlData.from;
  46297. var toData = mlData.to;
  46298. var lineData = mlData.line;
  46299. mlModel.__from = fromData;
  46300. mlModel.__to = toData;
  46301. // Line data for tooltip and formatter
  46302. mlModel.setData(lineData);
  46303. var symbolType = mlModel.get('symbol');
  46304. var symbolSize = mlModel.get('symbolSize');
  46305. if (!isArray(symbolType)) {
  46306. symbolType = [symbolType, symbolType];
  46307. }
  46308. if (typeof symbolSize === 'number') {
  46309. symbolSize = [symbolSize, symbolSize];
  46310. }
  46311. // Update visual and layout of from symbol and to symbol
  46312. mlData.from.each(function (idx) {
  46313. updateDataVisualAndLayout(fromData, idx, true);
  46314. updateDataVisualAndLayout(toData, idx, false);
  46315. });
  46316. // Update visual and layout of line
  46317. lineData.each(function (idx) {
  46318. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  46319. lineData.setItemVisual(idx, {
  46320. color: lineColor || fromData.getItemVisual(idx, 'color')
  46321. });
  46322. lineData.setItemLayout(idx, [
  46323. fromData.getItemLayout(idx),
  46324. toData.getItemLayout(idx)
  46325. ]);
  46326. lineData.setItemVisual(idx, {
  46327. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  46328. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  46329. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  46330. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  46331. });
  46332. });
  46333. lineDraw.updateData(lineData);
  46334. // Set host model for tooltip
  46335. // FIXME
  46336. mlData.line.eachItemGraphicEl(function (el, idx) {
  46337. el.traverse(function (child) {
  46338. child.dataModel = mlModel;
  46339. });
  46340. });
  46341. function updateDataVisualAndLayout(data, idx, isFrom) {
  46342. var itemModel = data.getItemModel(idx);
  46343. updateSingleMarkerEndLayout(
  46344. data, idx, isFrom, seriesModel, api
  46345. );
  46346. data.setItemVisual(idx, {
  46347. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  46348. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  46349. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  46350. });
  46351. }
  46352. lineDraw.__keep = true;
  46353. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  46354. }
  46355. });
  46356. /**
  46357. * @inner
  46358. * @param {module:echarts/coord/*} coordSys
  46359. * @param {module:echarts/model/Series} seriesModel
  46360. * @param {module:echarts/model/Model} mpModel
  46361. */
  46362. function createList$2(coordSys, seriesModel, mlModel) {
  46363. var coordDimsInfos;
  46364. if (coordSys) {
  46365. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  46366. var info = seriesModel.getData().getDimensionInfo(
  46367. seriesModel.getData().mapDimension(coordDim)
  46368. ) || {};
  46369. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  46370. return defaults({name: coordDim}, info);
  46371. });
  46372. }
  46373. else {
  46374. coordDimsInfos = [{
  46375. name: 'value',
  46376. type: 'float'
  46377. }];
  46378. }
  46379. var fromData = new List(coordDimsInfos, mlModel);
  46380. var toData = new List(coordDimsInfos, mlModel);
  46381. // No dimensions
  46382. var lineData = new List([], mlModel);
  46383. var optData = map(mlModel.get('data'), curry(
  46384. markLineTransform, seriesModel, coordSys, mlModel
  46385. ));
  46386. if (coordSys) {
  46387. optData = filter(
  46388. optData, curry(markLineFilter, coordSys)
  46389. );
  46390. }
  46391. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  46392. return item.value;
  46393. };
  46394. fromData.initData(
  46395. map(optData, function (item) {
  46396. return item[0];
  46397. }),
  46398. null,
  46399. dimValueGetter$$1
  46400. );
  46401. toData.initData(
  46402. map(optData, function (item) {
  46403. return item[1];
  46404. }),
  46405. null,
  46406. dimValueGetter$$1
  46407. );
  46408. lineData.initData(
  46409. map(optData, function (item) {
  46410. return item[2];
  46411. })
  46412. );
  46413. lineData.hasItemOption = true;
  46414. return {
  46415. from: fromData,
  46416. to: toData,
  46417. line: lineData
  46418. };
  46419. }
  46420. /*
  46421. * Licensed to the Apache Software Foundation (ASF) under one
  46422. * or more contributor license agreements. See the NOTICE file
  46423. * distributed with this work for additional information
  46424. * regarding copyright ownership. The ASF licenses this file
  46425. * to you under the Apache License, Version 2.0 (the
  46426. * "License"); you may not use this file except in compliance
  46427. * with the License. You may obtain a copy of the License at
  46428. *
  46429. * http://www.apache.org/licenses/LICENSE-2.0
  46430. *
  46431. * Unless required by applicable law or agreed to in writing,
  46432. * software distributed under the License is distributed on an
  46433. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46434. * KIND, either express or implied. See the License for the
  46435. * specific language governing permissions and limitations
  46436. * under the License.
  46437. */
  46438. registerPreprocessor(function (opt) {
  46439. // Make sure markLine component is enabled
  46440. opt.markLine = opt.markLine || {};
  46441. });
  46442. /*
  46443. * Licensed to the Apache Software Foundation (ASF) under one
  46444. * or more contributor license agreements. See the NOTICE file
  46445. * distributed with this work for additional information
  46446. * regarding copyright ownership. The ASF licenses this file
  46447. * to you under the Apache License, Version 2.0 (the
  46448. * "License"); you may not use this file except in compliance
  46449. * with the License. You may obtain a copy of the License at
  46450. *
  46451. * http://www.apache.org/licenses/LICENSE-2.0
  46452. *
  46453. * Unless required by applicable law or agreed to in writing,
  46454. * software distributed under the License is distributed on an
  46455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46456. * KIND, either express or implied. See the License for the
  46457. * specific language governing permissions and limitations
  46458. * under the License.
  46459. */
  46460. MarkerModel.extend({
  46461. type: 'markArea',
  46462. defaultOption: {
  46463. zlevel: 0,
  46464. // PENDING
  46465. z: 1,
  46466. tooltip: {
  46467. trigger: 'item'
  46468. },
  46469. // markArea should fixed on the coordinate system
  46470. animation: false,
  46471. label: {
  46472. show: true,
  46473. position: 'top'
  46474. },
  46475. itemStyle: {
  46476. // color and borderColor default to use color from series
  46477. // color: 'auto'
  46478. // borderColor: 'auto'
  46479. borderWidth: 0
  46480. },
  46481. emphasis: {
  46482. label: {
  46483. show: true,
  46484. position: 'top'
  46485. }
  46486. }
  46487. }
  46488. });
  46489. /*
  46490. * Licensed to the Apache Software Foundation (ASF) under one
  46491. * or more contributor license agreements. See the NOTICE file
  46492. * distributed with this work for additional information
  46493. * regarding copyright ownership. The ASF licenses this file
  46494. * to you under the Apache License, Version 2.0 (the
  46495. * "License"); you may not use this file except in compliance
  46496. * with the License. You may obtain a copy of the License at
  46497. *
  46498. * http://www.apache.org/licenses/LICENSE-2.0
  46499. *
  46500. * Unless required by applicable law or agreed to in writing,
  46501. * software distributed under the License is distributed on an
  46502. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46503. * KIND, either express or implied. See the License for the
  46504. * specific language governing permissions and limitations
  46505. * under the License.
  46506. */
  46507. // TODO Better on polar
  46508. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  46509. var lt = dataTransform(seriesModel, item[0]);
  46510. var rb = dataTransform(seriesModel, item[1]);
  46511. var retrieve$$1 = retrieve;
  46512. // FIXME make sure lt is less than rb
  46513. var ltCoord = lt.coord;
  46514. var rbCoord = rb.coord;
  46515. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  46516. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  46517. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  46518. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  46519. // Merge option into one
  46520. var result = mergeAll([{}, lt, rb]);
  46521. result.coord = [
  46522. lt.coord, rb.coord
  46523. ];
  46524. result.x0 = lt.x;
  46525. result.y0 = lt.y;
  46526. result.x1 = rb.x;
  46527. result.y1 = rb.y;
  46528. return result;
  46529. };
  46530. function isInifinity$1(val) {
  46531. return !isNaN(val) && !isFinite(val);
  46532. }
  46533. // If a markArea has one dim
  46534. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  46535. var otherDimIndex = 1 - dimIndex;
  46536. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  46537. }
  46538. function markAreaFilter(coordSys, item) {
  46539. var fromCoord = item.coord[0];
  46540. var toCoord = item.coord[1];
  46541. if (coordSys.type === 'cartesian2d') {
  46542. // In case
  46543. // {
  46544. // markArea: {
  46545. // data: [{ yAxis: 2 }]
  46546. // }
  46547. // }
  46548. if (
  46549. fromCoord && toCoord
  46550. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  46551. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  46552. ) {
  46553. return true;
  46554. }
  46555. }
  46556. return dataFilter$1(coordSys, {
  46557. coord: fromCoord,
  46558. x: item.x0,
  46559. y: item.y0
  46560. })
  46561. || dataFilter$1(coordSys, {
  46562. coord: toCoord,
  46563. x: item.x1,
  46564. y: item.y1
  46565. });
  46566. }
  46567. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  46568. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  46569. var coordSys = seriesModel.coordinateSystem;
  46570. var itemModel = data.getItemModel(idx);
  46571. var point;
  46572. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  46573. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  46574. if (!isNaN(xPx) && !isNaN(yPx)) {
  46575. point = [xPx, yPx];
  46576. }
  46577. else {
  46578. // Chart like bar may have there own marker positioning logic
  46579. if (seriesModel.getMarkerPosition) {
  46580. // Use the getMarkerPoisition
  46581. point = seriesModel.getMarkerPosition(
  46582. data.getValues(dims, idx)
  46583. );
  46584. }
  46585. else {
  46586. var x = data.get(dims[0], idx);
  46587. var y = data.get(dims[1], idx);
  46588. var pt = [x, y];
  46589. coordSys.clampData && coordSys.clampData(pt, pt);
  46590. point = coordSys.dataToPoint(pt, true);
  46591. }
  46592. if (coordSys.type === 'cartesian2d') {
  46593. var xAxis = coordSys.getAxis('x');
  46594. var yAxis = coordSys.getAxis('y');
  46595. var x = data.get(dims[0], idx);
  46596. var y = data.get(dims[1], idx);
  46597. if (isInifinity$1(x)) {
  46598. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  46599. }
  46600. else if (isInifinity$1(y)) {
  46601. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  46602. }
  46603. }
  46604. // Use x, y if has any
  46605. if (!isNaN(xPx)) {
  46606. point[0] = xPx;
  46607. }
  46608. if (!isNaN(yPx)) {
  46609. point[1] = yPx;
  46610. }
  46611. }
  46612. return point;
  46613. }
  46614. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  46615. MarkerView.extend({
  46616. type: 'markArea',
  46617. // updateLayout: function (markAreaModel, ecModel, api) {
  46618. // ecModel.eachSeries(function (seriesModel) {
  46619. // var maModel = seriesModel.markAreaModel;
  46620. // if (maModel) {
  46621. // var areaData = maModel.getData();
  46622. // areaData.each(function (idx) {
  46623. // var points = zrUtil.map(dimPermutations, function (dim) {
  46624. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  46625. // });
  46626. // // Layout
  46627. // areaData.setItemLayout(idx, points);
  46628. // var el = areaData.getItemGraphicEl(idx);
  46629. // el.setShape('points', points);
  46630. // });
  46631. // }
  46632. // }, this);
  46633. // },
  46634. updateTransform: function (markAreaModel, ecModel, api) {
  46635. ecModel.eachSeries(function (seriesModel) {
  46636. var maModel = seriesModel.markAreaModel;
  46637. if (maModel) {
  46638. var areaData = maModel.getData();
  46639. areaData.each(function (idx) {
  46640. var points = map(dimPermutations, function (dim) {
  46641. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  46642. });
  46643. // Layout
  46644. areaData.setItemLayout(idx, points);
  46645. var el = areaData.getItemGraphicEl(idx);
  46646. el.setShape('points', points);
  46647. });
  46648. }
  46649. }, this);
  46650. },
  46651. renderSeries: function (seriesModel, maModel, ecModel, api) {
  46652. var coordSys = seriesModel.coordinateSystem;
  46653. var seriesId = seriesModel.id;
  46654. var seriesData = seriesModel.getData();
  46655. var areaGroupMap = this.markerGroupMap;
  46656. var polygonGroup = areaGroupMap.get(seriesId)
  46657. || areaGroupMap.set(seriesId, {group: new Group()});
  46658. this.group.add(polygonGroup.group);
  46659. polygonGroup.__keep = true;
  46660. var areaData = createList$3(coordSys, seriesModel, maModel);
  46661. // Line data for tooltip and formatter
  46662. maModel.setData(areaData);
  46663. // Update visual and layout of line
  46664. areaData.each(function (idx) {
  46665. // Layout
  46666. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  46667. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  46668. }));
  46669. // Visual
  46670. areaData.setItemVisual(idx, {
  46671. color: seriesData.getVisual('color')
  46672. });
  46673. });
  46674. areaData.diff(polygonGroup.__data)
  46675. .add(function (idx) {
  46676. var polygon = new Polygon({
  46677. shape: {
  46678. points: areaData.getItemLayout(idx)
  46679. }
  46680. });
  46681. areaData.setItemGraphicEl(idx, polygon);
  46682. polygonGroup.group.add(polygon);
  46683. })
  46684. .update(function (newIdx, oldIdx) {
  46685. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  46686. updateProps(polygon, {
  46687. shape: {
  46688. points: areaData.getItemLayout(newIdx)
  46689. }
  46690. }, maModel, newIdx);
  46691. polygonGroup.group.add(polygon);
  46692. areaData.setItemGraphicEl(newIdx, polygon);
  46693. })
  46694. .remove(function (idx) {
  46695. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  46696. polygonGroup.group.remove(polygon);
  46697. })
  46698. .execute();
  46699. areaData.eachItemGraphicEl(function (polygon, idx) {
  46700. var itemModel = areaData.getItemModel(idx);
  46701. var labelModel = itemModel.getModel('label');
  46702. var labelHoverModel = itemModel.getModel('emphasis.label');
  46703. var color = areaData.getItemVisual(idx, 'color');
  46704. polygon.useStyle(
  46705. defaults(
  46706. itemModel.getModel('itemStyle').getItemStyle(),
  46707. {
  46708. fill: modifyAlpha(color, 0.4),
  46709. stroke: color
  46710. }
  46711. )
  46712. );
  46713. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  46714. setLabelStyle(
  46715. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  46716. {
  46717. labelFetcher: maModel,
  46718. labelDataIndex: idx,
  46719. defaultText: areaData.getName(idx) || '',
  46720. isRectText: true,
  46721. autoColor: color
  46722. }
  46723. );
  46724. setHoverStyle(polygon, {});
  46725. polygon.dataModel = maModel;
  46726. });
  46727. polygonGroup.__data = areaData;
  46728. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  46729. }
  46730. });
  46731. /**
  46732. * @inner
  46733. * @param {module:echarts/coord/*} coordSys
  46734. * @param {module:echarts/model/Series} seriesModel
  46735. * @param {module:echarts/model/Model} mpModel
  46736. */
  46737. function createList$3(coordSys, seriesModel, maModel) {
  46738. var coordDimsInfos;
  46739. var areaData;
  46740. var dims = ['x0', 'y0', 'x1', 'y1'];
  46741. if (coordSys) {
  46742. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  46743. var data = seriesModel.getData();
  46744. var info = data.getDimensionInfo(
  46745. data.mapDimension(coordDim)
  46746. ) || {};
  46747. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  46748. return defaults({name: coordDim}, info);
  46749. });
  46750. areaData = new List(map(dims, function (dim, idx) {
  46751. return {
  46752. name: dim,
  46753. type: coordDimsInfos[idx % 2].type
  46754. };
  46755. }), maModel);
  46756. }
  46757. else {
  46758. coordDimsInfos = [{
  46759. name: 'value',
  46760. type: 'float'
  46761. }];
  46762. areaData = new List(coordDimsInfos, maModel);
  46763. }
  46764. var optData = map(maModel.get('data'), curry(
  46765. markAreaTransform, seriesModel, coordSys, maModel
  46766. ));
  46767. if (coordSys) {
  46768. optData = filter(
  46769. optData, curry(markAreaFilter, coordSys)
  46770. );
  46771. }
  46772. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  46773. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  46774. } : function (item) {
  46775. return item.value;
  46776. };
  46777. areaData.initData(optData, null, dimValueGetter$$1);
  46778. areaData.hasItemOption = true;
  46779. return areaData;
  46780. }
  46781. /*
  46782. * Licensed to the Apache Software Foundation (ASF) under one
  46783. * or more contributor license agreements. See the NOTICE file
  46784. * distributed with this work for additional information
  46785. * regarding copyright ownership. The ASF licenses this file
  46786. * to you under the Apache License, Version 2.0 (the
  46787. * "License"); you may not use this file except in compliance
  46788. * with the License. You may obtain a copy of the License at
  46789. *
  46790. * http://www.apache.org/licenses/LICENSE-2.0
  46791. *
  46792. * Unless required by applicable law or agreed to in writing,
  46793. * software distributed under the License is distributed on an
  46794. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46795. * KIND, either express or implied. See the License for the
  46796. * specific language governing permissions and limitations
  46797. * under the License.
  46798. */
  46799. registerPreprocessor(function (opt) {
  46800. // Make sure markArea component is enabled
  46801. opt.markArea = opt.markArea || {};
  46802. });
  46803. /*
  46804. * Licensed to the Apache Software Foundation (ASF) under one
  46805. * or more contributor license agreements. See the NOTICE file
  46806. * distributed with this work for additional information
  46807. * regarding copyright ownership. The ASF licenses this file
  46808. * to you under the Apache License, Version 2.0 (the
  46809. * "License"); you may not use this file except in compliance
  46810. * with the License. You may obtain a copy of the License at
  46811. *
  46812. * http://www.apache.org/licenses/LICENSE-2.0
  46813. *
  46814. * Unless required by applicable law or agreed to in writing,
  46815. * software distributed under the License is distributed on an
  46816. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46817. * KIND, either express or implied. See the License for the
  46818. * specific language governing permissions and limitations
  46819. * under the License.
  46820. */
  46821. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  46822. // Default 'slider' when no type specified.
  46823. return 'slider';
  46824. });
  46825. /*
  46826. * Licensed to the Apache Software Foundation (ASF) under one
  46827. * or more contributor license agreements. See the NOTICE file
  46828. * distributed with this work for additional information
  46829. * regarding copyright ownership. The ASF licenses this file
  46830. * to you under the Apache License, Version 2.0 (the
  46831. * "License"); you may not use this file except in compliance
  46832. * with the License. You may obtain a copy of the License at
  46833. *
  46834. * http://www.apache.org/licenses/LICENSE-2.0
  46835. *
  46836. * Unless required by applicable law or agreed to in writing,
  46837. * software distributed under the License is distributed on an
  46838. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46839. * KIND, either express or implied. See the License for the
  46840. * specific language governing permissions and limitations
  46841. * under the License.
  46842. */
  46843. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  46844. // Supported coords.
  46845. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  46846. /**
  46847. * @param {string} coordType
  46848. * @return {boolean}
  46849. */
  46850. function isCoordSupported(coordType) {
  46851. return indexOf(COORDS, coordType) >= 0;
  46852. }
  46853. /**
  46854. * Create "each" method to iterate names.
  46855. *
  46856. * @pubilc
  46857. * @param {Array.<string>} names
  46858. * @param {Array.<string>=} attrs
  46859. * @return {Function}
  46860. */
  46861. function createNameEach(names, attrs) {
  46862. names = names.slice();
  46863. var capitalNames = map(names, capitalFirst);
  46864. attrs = (attrs || []).slice();
  46865. var capitalAttrs = map(attrs, capitalFirst);
  46866. return function (callback, context) {
  46867. each$1(names, function (name, index) {
  46868. var nameObj = {name: name, capital: capitalNames[index]};
  46869. for (var j = 0; j < attrs.length; j++) {
  46870. nameObj[attrs[j]] = name + capitalAttrs[j];
  46871. }
  46872. callback.call(context, nameObj);
  46873. });
  46874. };
  46875. }
  46876. /**
  46877. * Iterate each dimension name.
  46878. *
  46879. * @public
  46880. * @param {Function} callback The parameter is like:
  46881. * {
  46882. * name: 'angle',
  46883. * capital: 'Angle',
  46884. * axis: 'angleAxis',
  46885. * axisIndex: 'angleAixs',
  46886. * index: 'angleIndex'
  46887. * }
  46888. * @param {Object} context
  46889. */
  46890. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  46891. /**
  46892. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  46893. * dataZoomModels and 'links' make up one or more graphics.
  46894. * This function finds the graphic where the source dataZoomModel is in.
  46895. *
  46896. * @public
  46897. * @param {Function} forEachNode Node iterator.
  46898. * @param {Function} forEachEdgeType edgeType iterator
  46899. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  46900. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  46901. */
  46902. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  46903. return function (sourceNode) {
  46904. var result = {
  46905. nodes: [],
  46906. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  46907. };
  46908. forEachEdgeType(function (edgeType) {
  46909. result.records[edgeType.name] = {};
  46910. });
  46911. if (!sourceNode) {
  46912. return result;
  46913. }
  46914. absorb(sourceNode, result);
  46915. var existsLink;
  46916. do {
  46917. existsLink = false;
  46918. forEachNode(processSingleNode);
  46919. }
  46920. while (existsLink);
  46921. function processSingleNode(node) {
  46922. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  46923. absorb(node, result);
  46924. existsLink = true;
  46925. }
  46926. }
  46927. return result;
  46928. };
  46929. function isNodeAbsorded(node, result) {
  46930. return indexOf(result.nodes, node) >= 0;
  46931. }
  46932. function isLinked(node, result) {
  46933. var hasLink = false;
  46934. forEachEdgeType(function (edgeType) {
  46935. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  46936. result.records[edgeType.name][edgeId] && (hasLink = true);
  46937. });
  46938. });
  46939. return hasLink;
  46940. }
  46941. function absorb(node, result) {
  46942. result.nodes.push(node);
  46943. forEachEdgeType(function (edgeType) {
  46944. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  46945. result.records[edgeType.name][edgeId] = true;
  46946. });
  46947. });
  46948. }
  46949. }
  46950. /*
  46951. * Licensed to the Apache Software Foundation (ASF) under one
  46952. * or more contributor license agreements. See the NOTICE file
  46953. * distributed with this work for additional information
  46954. * regarding copyright ownership. The ASF licenses this file
  46955. * to you under the Apache License, Version 2.0 (the
  46956. * "License"); you may not use this file except in compliance
  46957. * with the License. You may obtain a copy of the License at
  46958. *
  46959. * http://www.apache.org/licenses/LICENSE-2.0
  46960. *
  46961. * Unless required by applicable law or agreed to in writing,
  46962. * software distributed under the License is distributed on an
  46963. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46964. * KIND, either express or implied. See the License for the
  46965. * specific language governing permissions and limitations
  46966. * under the License.
  46967. */
  46968. /**
  46969. * Calculate slider move result.
  46970. * Usage:
  46971. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  46972. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  46973. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  46974. *
  46975. * @param {number} delta Move length.
  46976. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  46977. * handleEnds will be modified in this method.
  46978. * @param {Array.<number>} extent handleEnds is restricted by extent.
  46979. * extent[0] should less or equals than extent[1].
  46980. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds.
  46981. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  46982. * If not set, handle0 and cross handle1. If set as a non-negative
  46983. * number (including `0`), handles will push each other when reaching
  46984. * the minSpan.
  46985. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  46986. * @return {Array.<number>} The input handleEnds.
  46987. */
  46988. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  46989. delta = delta || 0;
  46990. var extentSpan = extent[1] - extent[0];
  46991. // Notice maxSpan and minSpan can be null/undefined.
  46992. if (minSpan != null) {
  46993. minSpan = restrict(minSpan, [0, extentSpan]);
  46994. }
  46995. if (maxSpan != null) {
  46996. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  46997. }
  46998. if (handleIndex === 'all') {
  46999. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  47000. handleSpan = restrict(handleSpan, [0, extentSpan]);
  47001. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  47002. handleIndex = 0;
  47003. }
  47004. handleEnds[0] = restrict(handleEnds[0], extent);
  47005. handleEnds[1] = restrict(handleEnds[1], extent);
  47006. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  47007. handleEnds[handleIndex] += delta;
  47008. // Restrict in extent.
  47009. var extentMinSpan = minSpan || 0;
  47010. var realExtent = extent.slice();
  47011. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  47012. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  47013. // Expand span.
  47014. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47015. if (minSpan != null && (
  47016. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  47017. )) {
  47018. // If minSpan exists, 'cross' is forbidden.
  47019. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  47020. }
  47021. // Shrink span.
  47022. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47023. if (maxSpan != null && currDistSign.span > maxSpan) {
  47024. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  47025. }
  47026. return handleEnds;
  47027. };
  47028. function getSpanSign(handleEnds, handleIndex) {
  47029. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  47030. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  47031. // is at left of handleEnds[1] for non-cross case.
  47032. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  47033. }
  47034. function restrict(value, extend) {
  47035. return Math.min(
  47036. extend[1] != null ? extend[1] : Infinity,
  47037. Math.max(extend[0] != null ? extend[0] : -Infinity, value)
  47038. );
  47039. }
  47040. /*
  47041. * Licensed to the Apache Software Foundation (ASF) under one
  47042. * or more contributor license agreements. See the NOTICE file
  47043. * distributed with this work for additional information
  47044. * regarding copyright ownership. The ASF licenses this file
  47045. * to you under the Apache License, Version 2.0 (the
  47046. * "License"); you may not use this file except in compliance
  47047. * with the License. You may obtain a copy of the License at
  47048. *
  47049. * http://www.apache.org/licenses/LICENSE-2.0
  47050. *
  47051. * Unless required by applicable law or agreed to in writing,
  47052. * software distributed under the License is distributed on an
  47053. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47054. * KIND, either express or implied. See the License for the
  47055. * specific language governing permissions and limitations
  47056. * under the License.
  47057. */
  47058. var each$13 = each$1;
  47059. var asc$1 = asc;
  47060. /**
  47061. * Operate single axis.
  47062. * One axis can only operated by one axis operator.
  47063. * Different dataZoomModels may be defined to operate the same axis.
  47064. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  47065. * So dataZoomModels share one axisProxy in that case.
  47066. *
  47067. * @class
  47068. */
  47069. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  47070. /**
  47071. * @private
  47072. * @type {string}
  47073. */
  47074. this._dimName = dimName;
  47075. /**
  47076. * @private
  47077. */
  47078. this._axisIndex = axisIndex;
  47079. /**
  47080. * @private
  47081. * @type {Array.<number>}
  47082. */
  47083. this._valueWindow;
  47084. /**
  47085. * @private
  47086. * @type {Array.<number>}
  47087. */
  47088. this._percentWindow;
  47089. /**
  47090. * @private
  47091. * @type {Array.<number>}
  47092. */
  47093. this._dataExtent;
  47094. /**
  47095. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  47096. * @private
  47097. * @type {Object}
  47098. */
  47099. this._minMaxSpan;
  47100. /**
  47101. * @readOnly
  47102. * @type {module: echarts/model/Global}
  47103. */
  47104. this.ecModel = ecModel;
  47105. /**
  47106. * @private
  47107. * @type {module: echarts/component/dataZoom/DataZoomModel}
  47108. */
  47109. this._dataZoomModel = dataZoomModel;
  47110. // /**
  47111. // * @readOnly
  47112. // * @private
  47113. // */
  47114. // this.hasSeriesStacked;
  47115. };
  47116. AxisProxy.prototype = {
  47117. constructor: AxisProxy,
  47118. /**
  47119. * Whether the axisProxy is hosted by dataZoomModel.
  47120. *
  47121. * @public
  47122. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47123. * @return {boolean}
  47124. */
  47125. hostedBy: function (dataZoomModel) {
  47126. return this._dataZoomModel === dataZoomModel;
  47127. },
  47128. /**
  47129. * @return {Array.<number>} Value can only be NaN or finite value.
  47130. */
  47131. getDataValueWindow: function () {
  47132. return this._valueWindow.slice();
  47133. },
  47134. /**
  47135. * @return {Array.<number>}
  47136. */
  47137. getDataPercentWindow: function () {
  47138. return this._percentWindow.slice();
  47139. },
  47140. /**
  47141. * @public
  47142. * @param {number} axisIndex
  47143. * @return {Array} seriesModels
  47144. */
  47145. getTargetSeriesModels: function () {
  47146. var seriesModels = [];
  47147. var ecModel = this.ecModel;
  47148. ecModel.eachSeries(function (seriesModel) {
  47149. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  47150. var dimName = this._dimName;
  47151. var axisModel = ecModel.queryComponents({
  47152. mainType: dimName + 'Axis',
  47153. index: seriesModel.get(dimName + 'AxisIndex'),
  47154. id: seriesModel.get(dimName + 'AxisId')
  47155. })[0];
  47156. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  47157. seriesModels.push(seriesModel);
  47158. }
  47159. }
  47160. }, this);
  47161. return seriesModels;
  47162. },
  47163. getAxisModel: function () {
  47164. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  47165. },
  47166. getOtherAxisModel: function () {
  47167. var axisDim = this._dimName;
  47168. var ecModel = this.ecModel;
  47169. var axisModel = this.getAxisModel();
  47170. var isCartesian = axisDim === 'x' || axisDim === 'y';
  47171. var otherAxisDim;
  47172. var coordSysIndexName;
  47173. if (isCartesian) {
  47174. coordSysIndexName = 'gridIndex';
  47175. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  47176. }
  47177. else {
  47178. coordSysIndexName = 'polarIndex';
  47179. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  47180. }
  47181. var foundOtherAxisModel;
  47182. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  47183. if ((otherAxisModel.get(coordSysIndexName) || 0)
  47184. === (axisModel.get(coordSysIndexName) || 0)
  47185. ) {
  47186. foundOtherAxisModel = otherAxisModel;
  47187. }
  47188. });
  47189. return foundOtherAxisModel;
  47190. },
  47191. getMinMaxSpan: function () {
  47192. return clone(this._minMaxSpan);
  47193. },
  47194. /**
  47195. * Only calculate by given range and this._dataExtent, do not change anything.
  47196. *
  47197. * @param {Object} opt
  47198. * @param {number} [opt.start]
  47199. * @param {number} [opt.end]
  47200. * @param {number} [opt.startValue]
  47201. * @param {number} [opt.endValue]
  47202. */
  47203. calculateDataWindow: function (opt) {
  47204. var dataExtent = this._dataExtent;
  47205. var axisModel = this.getAxisModel();
  47206. var scale = axisModel.axis.scale;
  47207. var rangePropMode = this._dataZoomModel.getRangePropMode();
  47208. var percentExtent = [0, 100];
  47209. var percentWindow = [];
  47210. var valueWindow = [];
  47211. var hasPropModeValue;
  47212. each$13(['start', 'end'], function (prop, idx) {
  47213. var boundPercent = opt[prop];
  47214. var boundValue = opt[prop + 'Value'];
  47215. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  47216. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  47217. // but not min/max of axis, which will be calculated by data window then).
  47218. // The former one is suitable for cases that a dataZoom component controls multiple
  47219. // axes with different unit or extent, and the latter one is suitable for accurate
  47220. // zoom by pixel (e.g., in dataZoomSelect).
  47221. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  47222. // only when setOption or dispatchAction, otherwise it remains its original value.
  47223. // (Why not only record `percentProp` and always map to `valueProp`? Because
  47224. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  47225. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  47226. // data extent. All of values that are overflow the `dataExtent` will be calculated
  47227. // to percent '100%').
  47228. if (rangePropMode[idx] === 'percent') {
  47229. boundPercent == null && (boundPercent = percentExtent[idx]);
  47230. // Use scale.parse to math round for category or time axis.
  47231. boundValue = scale.parse(linearMap(
  47232. boundPercent, percentExtent, dataExtent
  47233. ));
  47234. }
  47235. else {
  47236. hasPropModeValue = true;
  47237. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  47238. // Calculating `percent` from `value` may be not accurate, because
  47239. // This calculation can not be inversed, because all of values that
  47240. // are overflow the `dataExtent` will be calculated to percent '100%'
  47241. boundPercent = linearMap(
  47242. boundValue, dataExtent, percentExtent
  47243. );
  47244. }
  47245. // valueWindow[idx] = round(boundValue);
  47246. // percentWindow[idx] = round(boundPercent);
  47247. valueWindow[idx] = boundValue;
  47248. percentWindow[idx] = boundPercent;
  47249. });
  47250. asc$1(valueWindow);
  47251. asc$1(percentWindow);
  47252. // The windows from user calling of `dispatchAction` might be out of the extent,
  47253. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  47254. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  47255. // where API is able to initialize/modify the window size even though `zoomLock`
  47256. // specified.
  47257. var spans = this._minMaxSpan;
  47258. hasPropModeValue
  47259. ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false)
  47260. : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  47261. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  47262. var suffix = toValue ? 'Span' : 'ValueSpan';
  47263. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  47264. for (var i = 0; i < 2; i++) {
  47265. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  47266. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  47267. }
  47268. }
  47269. return {
  47270. valueWindow: valueWindow,
  47271. percentWindow: percentWindow
  47272. };
  47273. },
  47274. /**
  47275. * Notice: reset should not be called before series.restoreData() called,
  47276. * so it is recommanded to be called in "process stage" but not "model init
  47277. * stage".
  47278. *
  47279. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47280. */
  47281. reset: function (dataZoomModel) {
  47282. if (dataZoomModel !== this._dataZoomModel) {
  47283. return;
  47284. }
  47285. var targetSeries = this.getTargetSeriesModels();
  47286. // Culculate data window and data extent, and record them.
  47287. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  47288. // this.hasSeriesStacked = false;
  47289. // each(targetSeries, function (series) {
  47290. // var data = series.getData();
  47291. // var dataDim = data.mapDimension(this._dimName);
  47292. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  47293. // if (stackedDimension && stackedDimension === dataDim) {
  47294. // this.hasSeriesStacked = true;
  47295. // }
  47296. // }, this);
  47297. // `calculateDataWindow` uses min/maxSpan.
  47298. setMinMaxSpan(this);
  47299. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  47300. this._valueWindow = dataWindow.valueWindow;
  47301. this._percentWindow = dataWindow.percentWindow;
  47302. // Update axis setting then.
  47303. setAxisModel(this);
  47304. },
  47305. /**
  47306. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47307. */
  47308. restore: function (dataZoomModel) {
  47309. if (dataZoomModel !== this._dataZoomModel) {
  47310. return;
  47311. }
  47312. this._valueWindow = this._percentWindow = null;
  47313. setAxisModel(this, true);
  47314. },
  47315. /**
  47316. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47317. */
  47318. filterData: function (dataZoomModel, api) {
  47319. if (dataZoomModel !== this._dataZoomModel) {
  47320. return;
  47321. }
  47322. var axisDim = this._dimName;
  47323. var seriesModels = this.getTargetSeriesModels();
  47324. var filterMode = dataZoomModel.get('filterMode');
  47325. var valueWindow = this._valueWindow;
  47326. if (filterMode === 'none') {
  47327. return;
  47328. }
  47329. // FIXME
  47330. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  47331. // with NaN data, NaN will be filtered and stack will be wrong.
  47332. // So we need to force the mode to be set empty.
  47333. // In fect, it is not a big deal that do not support filterMode-'filter'
  47334. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  47335. // selection" some day, which might need "adapt to data extent on the
  47336. // otherAxis", which is disabled by filterMode-'empty'.
  47337. // But currently, stack has been fixed to based on value but not index,
  47338. // so this is not an issue any more.
  47339. // var otherAxisModel = this.getOtherAxisModel();
  47340. // if (dataZoomModel.get('$fromToolbox')
  47341. // && otherAxisModel
  47342. // && otherAxisModel.hasSeriesStacked
  47343. // ) {
  47344. // filterMode = 'empty';
  47345. // }
  47346. // TODO
  47347. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  47348. each$13(seriesModels, function (seriesModel) {
  47349. var seriesData = seriesModel.getData();
  47350. var dataDims = seriesData.mapDimension(axisDim, true);
  47351. if (!dataDims.length) {
  47352. return;
  47353. }
  47354. if (filterMode === 'weakFilter') {
  47355. seriesData.filterSelf(function (dataIndex) {
  47356. var leftOut;
  47357. var rightOut;
  47358. var hasValue;
  47359. for (var i = 0; i < dataDims.length; i++) {
  47360. var value = seriesData.get(dataDims[i], dataIndex);
  47361. var thisHasValue = !isNaN(value);
  47362. var thisLeftOut = value < valueWindow[0];
  47363. var thisRightOut = value > valueWindow[1];
  47364. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  47365. return true;
  47366. }
  47367. thisHasValue && (hasValue = true);
  47368. thisLeftOut && (leftOut = true);
  47369. thisRightOut && (rightOut = true);
  47370. }
  47371. // If both left out and right out, do not filter.
  47372. return hasValue && leftOut && rightOut;
  47373. });
  47374. }
  47375. else {
  47376. each$13(dataDims, function (dim) {
  47377. if (filterMode === 'empty') {
  47378. seriesModel.setData(
  47379. seriesData = seriesData.map(dim, function (value) {
  47380. return !isInWindow(value) ? NaN : value;
  47381. })
  47382. );
  47383. }
  47384. else {
  47385. var range = {};
  47386. range[dim] = valueWindow;
  47387. // console.time('select');
  47388. seriesData.selectRange(range);
  47389. // console.timeEnd('select');
  47390. }
  47391. });
  47392. }
  47393. each$13(dataDims, function (dim) {
  47394. seriesData.setApproximateExtent(valueWindow, dim);
  47395. });
  47396. });
  47397. function isInWindow(value) {
  47398. return value >= valueWindow[0] && value <= valueWindow[1];
  47399. }
  47400. }
  47401. };
  47402. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  47403. var dataExtent = [Infinity, -Infinity];
  47404. each$13(seriesModels, function (seriesModel) {
  47405. var seriesData = seriesModel.getData();
  47406. if (seriesData) {
  47407. each$13(seriesData.mapDimension(axisDim, true), function (dim) {
  47408. var seriesExtent = seriesData.getApproximateExtent(dim);
  47409. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  47410. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  47411. });
  47412. }
  47413. });
  47414. if (dataExtent[1] < dataExtent[0]) {
  47415. dataExtent = [NaN, NaN];
  47416. }
  47417. // It is important to get "consistent" extent when more then one axes is
  47418. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  47419. // when zooming. But it is difficult to know what is "consistent", considering
  47420. // axes have different type or even different meanings (For example, two
  47421. // time axes are used to compare data of the same date in different years).
  47422. // So basically dataZoom just obtains extent by series.data (in category axis
  47423. // extent can be obtained from axis.data).
  47424. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  47425. // consistent.
  47426. fixExtentByAxis(axisProxy, dataExtent);
  47427. return dataExtent;
  47428. }
  47429. function fixExtentByAxis(axisProxy, dataExtent) {
  47430. var axisModel = axisProxy.getAxisModel();
  47431. var min = axisModel.getMin(true);
  47432. // For category axis, if min/max/scale are not set, extent is determined
  47433. // by axis.data by default.
  47434. var isCategoryAxis = axisModel.get('type') === 'category';
  47435. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  47436. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  47437. dataExtent[0] = min;
  47438. }
  47439. else if (isCategoryAxis) {
  47440. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  47441. }
  47442. var max = axisModel.getMax(true);
  47443. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  47444. dataExtent[1] = max;
  47445. }
  47446. else if (isCategoryAxis) {
  47447. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  47448. }
  47449. if (!axisModel.get('scale', true)) {
  47450. dataExtent[0] > 0 && (dataExtent[0] = 0);
  47451. dataExtent[1] < 0 && (dataExtent[1] = 0);
  47452. }
  47453. // For value axis, if min/max/scale are not set, we just use the extent obtained
  47454. // by series data, which may be a little different from the extent calculated by
  47455. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  47456. // little when zooming. So it will not be fixed until some users require it strongly.
  47457. return dataExtent;
  47458. }
  47459. function setAxisModel(axisProxy, isRestore) {
  47460. var axisModel = axisProxy.getAxisModel();
  47461. var percentWindow = axisProxy._percentWindow;
  47462. var valueWindow = axisProxy._valueWindow;
  47463. if (!percentWindow) {
  47464. return;
  47465. }
  47466. // [0, 500]: arbitrary value, guess axis extent.
  47467. var precision = getPixelPrecision(valueWindow, [0, 500]);
  47468. precision = Math.min(precision, 20);
  47469. // isRestore or isFull
  47470. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  47471. axisModel.setRange(
  47472. useOrigin ? null : +valueWindow[0].toFixed(precision),
  47473. useOrigin ? null : +valueWindow[1].toFixed(precision)
  47474. );
  47475. }
  47476. function setMinMaxSpan(axisProxy) {
  47477. var minMaxSpan = axisProxy._minMaxSpan = {};
  47478. var dataZoomModel = axisProxy._dataZoomModel;
  47479. var dataExtent = axisProxy._dataExtent;
  47480. each$13(['min', 'max'], function (minMax) {
  47481. var percentSpan = dataZoomModel.get(minMax + 'Span');
  47482. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  47483. valueSpan != null && (valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan));
  47484. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  47485. if (valueSpan != null) {
  47486. percentSpan = linearMap(
  47487. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  47488. );
  47489. }
  47490. else if (percentSpan != null) {
  47491. valueSpan = linearMap(
  47492. percentSpan, [0, 100], dataExtent, true
  47493. ) - dataExtent[0];
  47494. }
  47495. minMaxSpan[minMax + 'Span'] = percentSpan;
  47496. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  47497. });
  47498. }
  47499. /*
  47500. * Licensed to the Apache Software Foundation (ASF) under one
  47501. * or more contributor license agreements. See the NOTICE file
  47502. * distributed with this work for additional information
  47503. * regarding copyright ownership. The ASF licenses this file
  47504. * to you under the Apache License, Version 2.0 (the
  47505. * "License"); you may not use this file except in compliance
  47506. * with the License. You may obtain a copy of the License at
  47507. *
  47508. * http://www.apache.org/licenses/LICENSE-2.0
  47509. *
  47510. * Unless required by applicable law or agreed to in writing,
  47511. * software distributed under the License is distributed on an
  47512. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47513. * KIND, either express or implied. See the License for the
  47514. * specific language governing permissions and limitations
  47515. * under the License.
  47516. */
  47517. var each$12 = each$1;
  47518. var eachAxisDim = eachAxisDim$1;
  47519. var DataZoomModel = extendComponentModel({
  47520. type: 'dataZoom',
  47521. dependencies: [
  47522. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  47523. ],
  47524. /**
  47525. * @protected
  47526. */
  47527. defaultOption: {
  47528. zlevel: 0,
  47529. z: 4, // Higher than normal component (z: 2).
  47530. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  47531. xAxisIndex: null, // Default the first horizontal category axis.
  47532. yAxisIndex: null, // Default the first vertical category axis.
  47533. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  47534. // 'filter': data items which are out of window will be removed. This option is
  47535. // applicable when filtering outliers. For each data item, it will be
  47536. // filtered if one of the relevant dimensions is out of the window.
  47537. // 'weakFilter': data items which are out of window will be removed. This option
  47538. // is applicable when filtering outliers. For each data item, it will be
  47539. // filtered only if all of the relevant dimensions are out of the same
  47540. // side of the window.
  47541. // 'empty': data items which are out of window will be set to empty.
  47542. // This option is applicable when user should not neglect
  47543. // that there are some data items out of window.
  47544. // 'none': Do not filter.
  47545. // Taking line chart as an example, line will be broken in
  47546. // the filtered points when filterModel is set to 'empty', but
  47547. // be connected when set to 'filter'.
  47548. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  47549. // default 100. Do not throttle when use null/undefined.
  47550. // If animation === true and animationDurationUpdate > 0,
  47551. // default value is 100, otherwise 20.
  47552. start: 0, // Start percent. 0 ~ 100
  47553. end: 100, // End percent. 0 ~ 100
  47554. startValue: null, // Start value. If startValue specified, start is ignored.
  47555. endValue: null, // End value. If endValue specified, end is ignored.
  47556. minSpan: null, // 0 ~ 100
  47557. maxSpan: null, // 0 ~ 100
  47558. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  47559. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  47560. rangeMode: null // Array, can be 'value' or 'percent'.
  47561. },
  47562. /**
  47563. * @override
  47564. */
  47565. init: function (option, parentModel, ecModel) {
  47566. /**
  47567. * key like x_0, y_1
  47568. * @private
  47569. * @type {Object}
  47570. */
  47571. this._dataIntervalByAxis = {};
  47572. /**
  47573. * @private
  47574. */
  47575. this._dataInfo = {};
  47576. /**
  47577. * key like x_0, y_1
  47578. * @private
  47579. */
  47580. this._axisProxies = {};
  47581. /**
  47582. * @readOnly
  47583. */
  47584. this.textStyleModel;
  47585. /**
  47586. * @private
  47587. */
  47588. this._autoThrottle = true;
  47589. /**
  47590. * It is `[rangeModeForMin, rangeModeForMax]`.
  47591. * The optional values for `rangeMode`:
  47592. * + `'value'` mode: the axis extent will always be determined by
  47593. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  47594. * how data like and how `axis.min` and `axis.max` are.
  47595. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  47596. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  47597. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  47598. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  47599. *
  47600. * For example, when users are using dynamic data (update data periodically via `setOption`),
  47601. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  47602. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  47603. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  47604. *
  47605. * @private
  47606. */
  47607. this._rangePropMode = ['percent', 'percent'];
  47608. var inputRawOption = retrieveRawOption(option);
  47609. /**
  47610. * Suppose a "main process" start at the point that model prepared (that is,
  47611. * model initialized or merged or method called in `action`).
  47612. * We should keep the `main process` idempotent, that is, given a set of values
  47613. * on `option`, we get the same result.
  47614. *
  47615. * But sometimes, values on `option` will be updated for providing users
  47616. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  47617. * should not be the base/input of the `main process`.
  47618. *
  47619. * So in that case we should save and keep the input of the `main process`
  47620. * separately, called `settledOption`.
  47621. *
  47622. * For example, consider the case:
  47623. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  47624. * where the original input `option.startValue`, `option.endValue` are earsed by
  47625. * calculated value.
  47626. * (Step)2) click the legend to hide and show a series,
  47627. * where the new range is calculated by the earsed `startValue` and `endValue`,
  47628. * which brings incorrect result.
  47629. *
  47630. * @readOnly
  47631. */
  47632. this.settledOption = inputRawOption;
  47633. this.mergeDefaultAndTheme(option, ecModel);
  47634. this.doInit(inputRawOption);
  47635. },
  47636. /**
  47637. * @override
  47638. */
  47639. mergeOption: function (newOption) {
  47640. var inputRawOption = retrieveRawOption(newOption);
  47641. //FIX #2591
  47642. merge(this.option, newOption, true);
  47643. merge(this.settledOption, inputRawOption, true);
  47644. this.doInit(inputRawOption);
  47645. },
  47646. /**
  47647. * @protected
  47648. */
  47649. doInit: function (inputRawOption) {
  47650. var thisOption = this.option;
  47651. // Disable realtime view update if canvas is not supported.
  47652. if (!env$1.canvasSupported) {
  47653. thisOption.realtime = false;
  47654. }
  47655. this._setDefaultThrottle(inputRawOption);
  47656. updateRangeUse(this, inputRawOption);
  47657. var settledOption = this.settledOption;
  47658. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  47659. // start/end has higher priority over startValue/endValue if they
  47660. // both set, but we should make chart.setOption({endValue: 1000})
  47661. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  47662. if (this._rangePropMode[index] === 'value') {
  47663. thisOption[names[0]] = settledOption[names[0]] = null;
  47664. }
  47665. // Otherwise do nothing and use the merge result.
  47666. }, this);
  47667. this.textStyleModel = this.getModel('textStyle');
  47668. this._resetTarget();
  47669. this._giveAxisProxies();
  47670. },
  47671. /**
  47672. * @private
  47673. */
  47674. _giveAxisProxies: function () {
  47675. var axisProxies = this._axisProxies;
  47676. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  47677. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  47678. // If exists, share axisProxy with other dataZoomModels.
  47679. var axisProxy = axisModel.__dzAxisProxy || (
  47680. // Use the first dataZoomModel as the main model of axisProxy.
  47681. axisModel.__dzAxisProxy = new AxisProxy(
  47682. dimNames.name, axisIndex, this, ecModel
  47683. )
  47684. );
  47685. // FIXME
  47686. // dispose __dzAxisProxy
  47687. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  47688. }, this);
  47689. },
  47690. /**
  47691. * @private
  47692. */
  47693. _resetTarget: function () {
  47694. var thisOption = this.option;
  47695. var autoMode = this._judgeAutoMode();
  47696. eachAxisDim(function (dimNames) {
  47697. var axisIndexName = dimNames.axisIndex;
  47698. thisOption[axisIndexName] = normalizeToArray(
  47699. thisOption[axisIndexName]
  47700. );
  47701. }, this);
  47702. if (autoMode === 'axisIndex') {
  47703. this._autoSetAxisIndex();
  47704. }
  47705. else if (autoMode === 'orient') {
  47706. this._autoSetOrient();
  47707. }
  47708. },
  47709. /**
  47710. * @private
  47711. */
  47712. _judgeAutoMode: function () {
  47713. // Auto set only works for setOption at the first time.
  47714. // The following is user's reponsibility. So using merged
  47715. // option is OK.
  47716. var thisOption = this.option;
  47717. var hasIndexSpecified = false;
  47718. eachAxisDim(function (dimNames) {
  47719. // When user set axisIndex as a empty array, we think that user specify axisIndex
  47720. // but do not want use auto mode. Because empty array may be encountered when
  47721. // some error occured.
  47722. if (thisOption[dimNames.axisIndex] != null) {
  47723. hasIndexSpecified = true;
  47724. }
  47725. }, this);
  47726. var orient = thisOption.orient;
  47727. if (orient == null && hasIndexSpecified) {
  47728. return 'orient';
  47729. }
  47730. else if (!hasIndexSpecified) {
  47731. if (orient == null) {
  47732. thisOption.orient = 'horizontal';
  47733. }
  47734. return 'axisIndex';
  47735. }
  47736. },
  47737. /**
  47738. * @private
  47739. */
  47740. _autoSetAxisIndex: function () {
  47741. var autoAxisIndex = true;
  47742. var orient = this.get('orient', true);
  47743. var thisOption = this.option;
  47744. var dependentModels = this.dependentModels;
  47745. if (autoAxisIndex) {
  47746. // Find axis that parallel to dataZoom as default.
  47747. var dimName = orient === 'vertical' ? 'y' : 'x';
  47748. if (dependentModels[dimName + 'Axis'].length) {
  47749. thisOption[dimName + 'AxisIndex'] = [0];
  47750. autoAxisIndex = false;
  47751. }
  47752. else {
  47753. each$12(dependentModels.singleAxis, function (singleAxisModel) {
  47754. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  47755. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  47756. autoAxisIndex = false;
  47757. }
  47758. });
  47759. }
  47760. }
  47761. if (autoAxisIndex) {
  47762. // Find the first category axis as default. (consider polar)
  47763. eachAxisDim(function (dimNames) {
  47764. if (!autoAxisIndex) {
  47765. return;
  47766. }
  47767. var axisIndices = [];
  47768. var axisModels = this.dependentModels[dimNames.axis];
  47769. if (axisModels.length && !axisIndices.length) {
  47770. for (var i = 0, len = axisModels.length; i < len; i++) {
  47771. if (axisModels[i].get('type') === 'category') {
  47772. axisIndices.push(i);
  47773. }
  47774. }
  47775. }
  47776. thisOption[dimNames.axisIndex] = axisIndices;
  47777. if (axisIndices.length) {
  47778. autoAxisIndex = false;
  47779. }
  47780. }, this);
  47781. }
  47782. if (autoAxisIndex) {
  47783. // FIXME
  47784. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  47785. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  47786. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  47787. // dataZoom component auto adopts series that reference to
  47788. // both xAxis and yAxis which type is 'value'.
  47789. this.ecModel.eachSeries(function (seriesModel) {
  47790. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  47791. eachAxisDim(function (dimNames) {
  47792. var axisIndices = thisOption[dimNames.axisIndex];
  47793. var axisIndex = seriesModel.get(dimNames.axisIndex);
  47794. var axisId = seriesModel.get(dimNames.axisId);
  47795. var axisModel = seriesModel.ecModel.queryComponents({
  47796. mainType: dimNames.axis,
  47797. index: axisIndex,
  47798. id: axisId
  47799. })[0];
  47800. if (__DEV__) {
  47801. if (!axisModel) {
  47802. throw new Error(
  47803. dimNames.axis + ' "' + retrieve(
  47804. axisIndex,
  47805. axisId,
  47806. 0
  47807. ) + '" not found'
  47808. );
  47809. }
  47810. }
  47811. axisIndex = axisModel.componentIndex;
  47812. if (indexOf(axisIndices, axisIndex) < 0) {
  47813. axisIndices.push(axisIndex);
  47814. }
  47815. });
  47816. }
  47817. }, this);
  47818. }
  47819. },
  47820. /**
  47821. * @private
  47822. */
  47823. _autoSetOrient: function () {
  47824. var dim;
  47825. // Find the first axis
  47826. this.eachTargetAxis(function (dimNames) {
  47827. !dim && (dim = dimNames.name);
  47828. }, this);
  47829. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  47830. },
  47831. /**
  47832. * @private
  47833. */
  47834. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  47835. // FIXME
  47836. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  47837. // 例如series.type === scatter时。
  47838. var is = true;
  47839. eachAxisDim(function (dimNames) {
  47840. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  47841. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  47842. if (!axisModel || axisModel.get('type') !== axisType) {
  47843. is = false;
  47844. }
  47845. }, this);
  47846. return is;
  47847. },
  47848. /**
  47849. * @private
  47850. */
  47851. _setDefaultThrottle: function (inputRawOption) {
  47852. // When first time user set throttle, auto throttle ends.
  47853. if (inputRawOption.hasOwnProperty('throttle')) {
  47854. this._autoThrottle = false;
  47855. }
  47856. if (this._autoThrottle) {
  47857. var globalOption = this.ecModel.option;
  47858. this.option.throttle = (
  47859. globalOption.animation && globalOption.animationDurationUpdate > 0
  47860. ) ? 100 : 20;
  47861. }
  47862. },
  47863. /**
  47864. * @public
  47865. */
  47866. getFirstTargetAxisModel: function () {
  47867. var firstAxisModel;
  47868. eachAxisDim(function (dimNames) {
  47869. if (firstAxisModel == null) {
  47870. var indices = this.get(dimNames.axisIndex);
  47871. if (indices.length) {
  47872. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  47873. }
  47874. }
  47875. }, this);
  47876. return firstAxisModel;
  47877. },
  47878. /**
  47879. * @public
  47880. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  47881. */
  47882. eachTargetAxis: function (callback, context) {
  47883. var ecModel = this.ecModel;
  47884. eachAxisDim(function (dimNames) {
  47885. each$12(
  47886. this.get(dimNames.axisIndex),
  47887. function (axisIndex) {
  47888. callback.call(context, dimNames, axisIndex, this, ecModel);
  47889. },
  47890. this
  47891. );
  47892. }, this);
  47893. },
  47894. /**
  47895. * @param {string} dimName
  47896. * @param {number} axisIndex
  47897. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  47898. */
  47899. getAxisProxy: function (dimName, axisIndex) {
  47900. return this._axisProxies[dimName + '_' + axisIndex];
  47901. },
  47902. /**
  47903. * @param {string} dimName
  47904. * @param {number} axisIndex
  47905. * @return {module:echarts/model/Model} If not found, return null/undefined.
  47906. */
  47907. getAxisModel: function (dimName, axisIndex) {
  47908. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  47909. return axisProxy && axisProxy.getAxisModel();
  47910. },
  47911. /**
  47912. * If not specified, set to undefined.
  47913. *
  47914. * @public
  47915. * @param {Object} opt
  47916. * @param {number} [opt.start]
  47917. * @param {number} [opt.end]
  47918. * @param {number} [opt.startValue]
  47919. * @param {number} [opt.endValue]
  47920. */
  47921. setRawRange: function (opt) {
  47922. var thisOption = this.option;
  47923. var settledOption = this.settledOption;
  47924. each$12([['start', 'startValue'], ['end', 'endValue']], function (names) {
  47925. // Consider the pair <start, startValue>:
  47926. // If one has value and the other one is `null/undefined`, we both set them
  47927. // to `settledOption`. This strategy enables the feature to clear the original
  47928. // value in `settledOption` to `null/undefined`.
  47929. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  47930. // and keep `settledOption` with the original value. This strategy enables users to
  47931. // only set <end or endValue> but not set <start or startValue> when calling
  47932. // `dispatchAction`.
  47933. // The pair <end, endValue> is treated in the same way.
  47934. if (opt[names[0]] != null || opt[names[1]] != null) {
  47935. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  47936. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  47937. }
  47938. }, this);
  47939. updateRangeUse(this, opt);
  47940. },
  47941. /**
  47942. * @public
  47943. * @param {Object} opt
  47944. * @param {number} [opt.start]
  47945. * @param {number} [opt.end]
  47946. * @param {number} [opt.startValue]
  47947. * @param {number} [opt.endValue]
  47948. */
  47949. setCalculatedRange: function (opt) {
  47950. var option = this.option;
  47951. each$12(['start', 'startValue', 'end', 'endValue'], function (name) {
  47952. option[name] = opt[name];
  47953. });
  47954. },
  47955. /**
  47956. * @public
  47957. * @return {Array.<number>} [startPercent, endPercent]
  47958. */
  47959. getPercentRange: function () {
  47960. var axisProxy = this.findRepresentativeAxisProxy();
  47961. if (axisProxy) {
  47962. return axisProxy.getDataPercentWindow();
  47963. }
  47964. },
  47965. /**
  47966. * @public
  47967. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  47968. *
  47969. * @param {string} [axisDimName]
  47970. * @param {number} [axisIndex]
  47971. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  47972. */
  47973. getValueRange: function (axisDimName, axisIndex) {
  47974. if (axisDimName == null && axisIndex == null) {
  47975. var axisProxy = this.findRepresentativeAxisProxy();
  47976. if (axisProxy) {
  47977. return axisProxy.getDataValueWindow();
  47978. }
  47979. }
  47980. else {
  47981. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  47982. }
  47983. },
  47984. /**
  47985. * @public
  47986. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  47987. * corresponding to the axisModel
  47988. * @return {module:echarts/component/dataZoom/AxisProxy}
  47989. */
  47990. findRepresentativeAxisProxy: function (axisModel) {
  47991. if (axisModel) {
  47992. return axisModel.__dzAxisProxy;
  47993. }
  47994. // Find the first hosted axisProxy
  47995. var axisProxies = this._axisProxies;
  47996. for (var key in axisProxies) {
  47997. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  47998. return axisProxies[key];
  47999. }
  48000. }
  48001. // If no hosted axis find not hosted axisProxy.
  48002. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  48003. // and the option.start or option.end settings are different. The percentRange
  48004. // should follow axisProxy.
  48005. // (We encounter this problem in toolbox data zoom.)
  48006. for (var key in axisProxies) {
  48007. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  48008. return axisProxies[key];
  48009. }
  48010. }
  48011. },
  48012. /**
  48013. * @return {Array.<string>}
  48014. */
  48015. getRangePropMode: function () {
  48016. return this._rangePropMode.slice();
  48017. }
  48018. });
  48019. /**
  48020. * Retrieve the those raw params from option, which will be cached separately.
  48021. * becasue they will be overwritten by normalized/calculated values in the main
  48022. * process.
  48023. */
  48024. function retrieveRawOption(option) {
  48025. var ret = {};
  48026. each$12(
  48027. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  48028. function (name) {
  48029. option.hasOwnProperty(name) && (ret[name] = option[name]);
  48030. }
  48031. );
  48032. return ret;
  48033. }
  48034. function updateRangeUse(dataZoomModel, inputRawOption) {
  48035. var rangePropMode = dataZoomModel._rangePropMode;
  48036. var rangeModeInOption = dataZoomModel.get('rangeMode');
  48037. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  48038. var percentSpecified = inputRawOption[names[0]] != null;
  48039. var valueSpecified = inputRawOption[names[1]] != null;
  48040. if (percentSpecified && !valueSpecified) {
  48041. rangePropMode[index] = 'percent';
  48042. }
  48043. else if (!percentSpecified && valueSpecified) {
  48044. rangePropMode[index] = 'value';
  48045. }
  48046. else if (rangeModeInOption) {
  48047. rangePropMode[index] = rangeModeInOption[index];
  48048. }
  48049. else if (percentSpecified) { // percentSpecified && valueSpecified
  48050. rangePropMode[index] = 'percent';
  48051. }
  48052. // else remain its original setting.
  48053. });
  48054. }
  48055. /*
  48056. * Licensed to the Apache Software Foundation (ASF) under one
  48057. * or more contributor license agreements. See the NOTICE file
  48058. * distributed with this work for additional information
  48059. * regarding copyright ownership. The ASF licenses this file
  48060. * to you under the Apache License, Version 2.0 (the
  48061. * "License"); you may not use this file except in compliance
  48062. * with the License. You may obtain a copy of the License at
  48063. *
  48064. * http://www.apache.org/licenses/LICENSE-2.0
  48065. *
  48066. * Unless required by applicable law or agreed to in writing,
  48067. * software distributed under the License is distributed on an
  48068. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48069. * KIND, either express or implied. See the License for the
  48070. * specific language governing permissions and limitations
  48071. * under the License.
  48072. */
  48073. var DataZoomView = Component$1.extend({
  48074. type: 'dataZoom',
  48075. render: function (dataZoomModel, ecModel, api, payload) {
  48076. this.dataZoomModel = dataZoomModel;
  48077. this.ecModel = ecModel;
  48078. this.api = api;
  48079. },
  48080. /**
  48081. * Find the first target coordinate system.
  48082. *
  48083. * @protected
  48084. * @return {Object} {
  48085. * grid: [
  48086. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  48087. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  48088. * ...
  48089. * ], // cartesians must not be null/undefined.
  48090. * polar: [
  48091. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  48092. * ...
  48093. * ], // polars must not be null/undefined.
  48094. * singleAxis: [
  48095. * {model: coord0, axisModels: [], coordIndex: 0}
  48096. * ]
  48097. */
  48098. getTargetCoordInfo: function () {
  48099. var dataZoomModel = this.dataZoomModel;
  48100. var ecModel = this.ecModel;
  48101. var coordSysLists = {};
  48102. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  48103. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  48104. if (axisModel) {
  48105. var coordModel = axisModel.getCoordSysModel();
  48106. coordModel && save(
  48107. coordModel,
  48108. axisModel,
  48109. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  48110. coordModel.componentIndex
  48111. );
  48112. }
  48113. }, this);
  48114. function save(coordModel, axisModel, store, coordIndex) {
  48115. var item;
  48116. for (var i = 0; i < store.length; i++) {
  48117. if (store[i].model === coordModel) {
  48118. item = store[i];
  48119. break;
  48120. }
  48121. }
  48122. if (!item) {
  48123. store.push(item = {
  48124. model: coordModel, axisModels: [], coordIndex: coordIndex
  48125. });
  48126. }
  48127. item.axisModels.push(axisModel);
  48128. }
  48129. return coordSysLists;
  48130. }
  48131. });
  48132. /*
  48133. * Licensed to the Apache Software Foundation (ASF) under one
  48134. * or more contributor license agreements. See the NOTICE file
  48135. * distributed with this work for additional information
  48136. * regarding copyright ownership. The ASF licenses this file
  48137. * to you under the Apache License, Version 2.0 (the
  48138. * "License"); you may not use this file except in compliance
  48139. * with the License. You may obtain a copy of the License at
  48140. *
  48141. * http://www.apache.org/licenses/LICENSE-2.0
  48142. *
  48143. * Unless required by applicable law or agreed to in writing,
  48144. * software distributed under the License is distributed on an
  48145. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48146. * KIND, either express or implied. See the License for the
  48147. * specific language governing permissions and limitations
  48148. * under the License.
  48149. */
  48150. var SliderZoomModel = DataZoomModel.extend({
  48151. type: 'dataZoom.slider',
  48152. layoutMode: 'box',
  48153. /**
  48154. * @protected
  48155. */
  48156. defaultOption: {
  48157. show: true,
  48158. // ph => placeholder. Using placehoder here because
  48159. // deault value can only be drived in view stage.
  48160. right: 'ph', // Default align to grid rect.
  48161. top: 'ph', // Default align to grid rect.
  48162. width: 'ph', // Default align to grid rect.
  48163. height: 'ph', // Default align to grid rect.
  48164. left: null, // Default align to grid rect.
  48165. bottom: null, // Default align to grid rect.
  48166. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  48167. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  48168. // highest priority, remain for compatibility of
  48169. // previous version, but not recommended any more.
  48170. dataBackground: {
  48171. lineStyle: {
  48172. color: '#2f4554',
  48173. width: 0.5,
  48174. opacity: 0.3
  48175. },
  48176. areaStyle: {
  48177. color: 'rgba(47,69,84,0.3)',
  48178. opacity: 0.3
  48179. }
  48180. },
  48181. borderColor: '#ddd', // border color of the box. For compatibility,
  48182. // if dataBackgroundColor is set, borderColor
  48183. // is ignored.
  48184. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  48185. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  48186. // 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',
  48187. /* eslint-disable */
  48188. 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',
  48189. /* eslint-enable */
  48190. // Percent of the slider height
  48191. handleSize: '100%',
  48192. handleStyle: {
  48193. color: '#a7b7cc'
  48194. },
  48195. labelPrecision: null,
  48196. labelFormatter: null,
  48197. showDetail: true,
  48198. showDataShadow: 'auto', // Default auto decision.
  48199. realtime: true,
  48200. zoomLock: false, // Whether disable zoom.
  48201. textStyle: {
  48202. color: '#333'
  48203. }
  48204. }
  48205. });
  48206. /*
  48207. * Licensed to the Apache Software Foundation (ASF) under one
  48208. * or more contributor license agreements. See the NOTICE file
  48209. * distributed with this work for additional information
  48210. * regarding copyright ownership. The ASF licenses this file
  48211. * to you under the Apache License, Version 2.0 (the
  48212. * "License"); you may not use this file except in compliance
  48213. * with the License. You may obtain a copy of the License at
  48214. *
  48215. * http://www.apache.org/licenses/LICENSE-2.0
  48216. *
  48217. * Unless required by applicable law or agreed to in writing,
  48218. * software distributed under the License is distributed on an
  48219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48220. * KIND, either express or implied. See the License for the
  48221. * specific language governing permissions and limitations
  48222. * under the License.
  48223. */
  48224. var Rect$1 = Rect;
  48225. var linearMap$1 = linearMap;
  48226. var asc$2 = asc;
  48227. var bind$3 = bind;
  48228. var each$14 = each$1;
  48229. // Constants
  48230. var DEFAULT_LOCATION_EDGE_GAP = 7;
  48231. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  48232. var DEFAULT_FILLER_SIZE = 30;
  48233. var HORIZONTAL = 'horizontal';
  48234. var VERTICAL = 'vertical';
  48235. var LABEL_GAP = 5;
  48236. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  48237. var SliderZoomView = DataZoomView.extend({
  48238. type: 'dataZoom.slider',
  48239. init: function (ecModel, api) {
  48240. /**
  48241. * @private
  48242. * @type {Object}
  48243. */
  48244. this._displayables = {};
  48245. /**
  48246. * @private
  48247. * @type {string}
  48248. */
  48249. this._orient;
  48250. /**
  48251. * [0, 100]
  48252. * @private
  48253. */
  48254. this._range;
  48255. /**
  48256. * [coord of the first handle, coord of the second handle]
  48257. * @private
  48258. */
  48259. this._handleEnds;
  48260. /**
  48261. * [length, thick]
  48262. * @private
  48263. * @type {Array.<number>}
  48264. */
  48265. this._size;
  48266. /**
  48267. * @private
  48268. * @type {number}
  48269. */
  48270. this._handleWidth;
  48271. /**
  48272. * @private
  48273. * @type {number}
  48274. */
  48275. this._handleHeight;
  48276. /**
  48277. * @private
  48278. */
  48279. this._location;
  48280. /**
  48281. * @private
  48282. */
  48283. this._dragging;
  48284. /**
  48285. * @private
  48286. */
  48287. this._dataShadowInfo;
  48288. this.api = api;
  48289. },
  48290. /**
  48291. * @override
  48292. */
  48293. render: function (dataZoomModel, ecModel, api, payload) {
  48294. SliderZoomView.superApply(this, 'render', arguments);
  48295. createOrUpdate(
  48296. this,
  48297. '_dispatchZoomAction',
  48298. this.dataZoomModel.get('throttle'),
  48299. 'fixRate'
  48300. );
  48301. this._orient = dataZoomModel.get('orient');
  48302. if (this.dataZoomModel.get('show') === false) {
  48303. this.group.removeAll();
  48304. return;
  48305. }
  48306. // Notice: this._resetInterval() should not be executed when payload.type
  48307. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  48308. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  48309. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  48310. this._buildView();
  48311. }
  48312. this._updateView();
  48313. },
  48314. /**
  48315. * @override
  48316. */
  48317. remove: function () {
  48318. SliderZoomView.superApply(this, 'remove', arguments);
  48319. clear(this, '_dispatchZoomAction');
  48320. },
  48321. /**
  48322. * @override
  48323. */
  48324. dispose: function () {
  48325. SliderZoomView.superApply(this, 'dispose', arguments);
  48326. clear(this, '_dispatchZoomAction');
  48327. },
  48328. _buildView: function () {
  48329. var thisGroup = this.group;
  48330. thisGroup.removeAll();
  48331. this._resetLocation();
  48332. this._resetInterval();
  48333. var barGroup = this._displayables.barGroup = new Group();
  48334. this._renderBackground();
  48335. this._renderHandle();
  48336. this._renderDataShadow();
  48337. thisGroup.add(barGroup);
  48338. this._positionGroup();
  48339. },
  48340. /**
  48341. * @private
  48342. */
  48343. _resetLocation: function () {
  48344. var dataZoomModel = this.dataZoomModel;
  48345. var api = this.api;
  48346. // If some of x/y/width/height are not specified,
  48347. // auto-adapt according to target grid.
  48348. var coordRect = this._findCoordRect();
  48349. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  48350. // Default align by coordinate system rect.
  48351. var positionInfo = this._orient === HORIZONTAL
  48352. ? {
  48353. // Why using 'right', because right should be used in vertical,
  48354. // and it is better to be consistent for dealing with position param merge.
  48355. right: ecSize.width - coordRect.x - coordRect.width,
  48356. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  48357. width: coordRect.width,
  48358. height: DEFAULT_FILLER_SIZE
  48359. }
  48360. : { // vertical
  48361. right: DEFAULT_LOCATION_EDGE_GAP,
  48362. top: coordRect.y,
  48363. width: DEFAULT_FILLER_SIZE,
  48364. height: coordRect.height
  48365. };
  48366. // Do not write back to option and replace value 'ph', because
  48367. // the 'ph' value should be recalculated when resize.
  48368. var layoutParams = getLayoutParams(dataZoomModel.option);
  48369. // Replace the placeholder value.
  48370. each$1(['right', 'top', 'width', 'height'], function (name) {
  48371. if (layoutParams[name] === 'ph') {
  48372. layoutParams[name] = positionInfo[name];
  48373. }
  48374. });
  48375. var layoutRect = getLayoutRect(
  48376. layoutParams,
  48377. ecSize,
  48378. dataZoomModel.padding
  48379. );
  48380. this._location = {x: layoutRect.x, y: layoutRect.y};
  48381. this._size = [layoutRect.width, layoutRect.height];
  48382. this._orient === VERTICAL && this._size.reverse();
  48383. },
  48384. /**
  48385. * @private
  48386. */
  48387. _positionGroup: function () {
  48388. var thisGroup = this.group;
  48389. var location = this._location;
  48390. var orient = this._orient;
  48391. // Just use the first axis to determine mapping.
  48392. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  48393. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  48394. var barGroup = this._displayables.barGroup;
  48395. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  48396. // Transform barGroup.
  48397. barGroup.attr(
  48398. (orient === HORIZONTAL && !inverse)
  48399. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  48400. : (orient === HORIZONTAL && inverse)
  48401. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  48402. : (orient === VERTICAL && !inverse)
  48403. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  48404. // Dont use Math.PI, considering shadow direction.
  48405. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  48406. );
  48407. // Position barGroup
  48408. var rect = thisGroup.getBoundingRect([barGroup]);
  48409. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  48410. },
  48411. /**
  48412. * @private
  48413. */
  48414. _getViewExtent: function () {
  48415. return [0, this._size[0]];
  48416. },
  48417. _renderBackground: function () {
  48418. var dataZoomModel = this.dataZoomModel;
  48419. var size = this._size;
  48420. var barGroup = this._displayables.barGroup;
  48421. barGroup.add(new Rect$1({
  48422. silent: true,
  48423. shape: {
  48424. x: 0, y: 0, width: size[0], height: size[1]
  48425. },
  48426. style: {
  48427. fill: dataZoomModel.get('backgroundColor')
  48428. },
  48429. z2: -40
  48430. }));
  48431. // Click panel, over shadow, below handles.
  48432. barGroup.add(new Rect$1({
  48433. shape: {
  48434. x: 0, y: 0, width: size[0], height: size[1]
  48435. },
  48436. style: {
  48437. fill: 'transparent'
  48438. },
  48439. z2: 0,
  48440. onclick: bind(this._onClickPanelClick, this)
  48441. }));
  48442. },
  48443. _renderDataShadow: function () {
  48444. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  48445. if (!info) {
  48446. return;
  48447. }
  48448. var size = this._size;
  48449. var seriesModel = info.series;
  48450. var data = seriesModel.getRawData();
  48451. var otherDim = seriesModel.getShadowDim
  48452. ? seriesModel.getShadowDim() // @see candlestick
  48453. : info.otherDim;
  48454. if (otherDim == null) {
  48455. return;
  48456. }
  48457. var otherDataExtent = data.getDataExtent(otherDim);
  48458. // Nice extent.
  48459. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  48460. otherDataExtent = [
  48461. otherDataExtent[0] - otherOffset,
  48462. otherDataExtent[1] + otherOffset
  48463. ];
  48464. var otherShadowExtent = [0, size[1]];
  48465. var thisShadowExtent = [0, size[0]];
  48466. var areaPoints = [[size[0], 0], [0, 0]];
  48467. var linePoints = [];
  48468. var step = thisShadowExtent[1] / (data.count() - 1);
  48469. var thisCoord = 0;
  48470. // Optimize for large data shadow
  48471. var stride = Math.round(data.count() / size[0]);
  48472. var lastIsEmpty;
  48473. data.each([otherDim], function (value, index) {
  48474. if (stride > 0 && (index % stride)) {
  48475. thisCoord += step;
  48476. return;
  48477. }
  48478. // FIXME
  48479. // Should consider axis.min/axis.max when drawing dataShadow.
  48480. // FIXME
  48481. // 应该使用统一的空判断?还是在list里进行空判断?
  48482. var isEmpty = value == null || isNaN(value) || value === '';
  48483. // See #4235.
  48484. var otherCoord = isEmpty
  48485. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  48486. // Attempt to draw data shadow precisely when there are empty value.
  48487. if (isEmpty && !lastIsEmpty && index) {
  48488. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  48489. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  48490. }
  48491. else if (!isEmpty && lastIsEmpty) {
  48492. areaPoints.push([thisCoord, 0]);
  48493. linePoints.push([thisCoord, 0]);
  48494. }
  48495. areaPoints.push([thisCoord, otherCoord]);
  48496. linePoints.push([thisCoord, otherCoord]);
  48497. thisCoord += step;
  48498. lastIsEmpty = isEmpty;
  48499. });
  48500. var dataZoomModel = this.dataZoomModel;
  48501. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  48502. this._displayables.barGroup.add(new Polygon({
  48503. shape: {points: areaPoints},
  48504. style: defaults(
  48505. {fill: dataZoomModel.get('dataBackgroundColor')},
  48506. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  48507. ),
  48508. silent: true,
  48509. z2: -20
  48510. }));
  48511. this._displayables.barGroup.add(new Polyline({
  48512. shape: {points: linePoints},
  48513. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  48514. silent: true,
  48515. z2: -19
  48516. }));
  48517. },
  48518. _prepareDataShadowInfo: function () {
  48519. var dataZoomModel = this.dataZoomModel;
  48520. var showDataShadow = dataZoomModel.get('showDataShadow');
  48521. if (showDataShadow === false) {
  48522. return;
  48523. }
  48524. // Find a representative series.
  48525. var result;
  48526. var ecModel = this.ecModel;
  48527. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  48528. var seriesModels = dataZoomModel
  48529. .getAxisProxy(dimNames.name, axisIndex)
  48530. .getTargetSeriesModels();
  48531. each$1(seriesModels, function (seriesModel) {
  48532. if (result) {
  48533. return;
  48534. }
  48535. if (showDataShadow !== true && indexOf(
  48536. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  48537. ) < 0
  48538. ) {
  48539. return;
  48540. }
  48541. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  48542. var otherDim = getOtherDim(dimNames.name);
  48543. var otherAxisInverse;
  48544. var coordSys = seriesModel.coordinateSystem;
  48545. if (otherDim != null && coordSys.getOtherAxis) {
  48546. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  48547. }
  48548. otherDim = seriesModel.getData().mapDimension(otherDim);
  48549. result = {
  48550. thisAxis: thisAxis,
  48551. series: seriesModel,
  48552. thisDim: dimNames.name,
  48553. otherDim: otherDim,
  48554. otherAxisInverse: otherAxisInverse
  48555. };
  48556. }, this);
  48557. }, this);
  48558. return result;
  48559. },
  48560. _renderHandle: function () {
  48561. var displaybles = this._displayables;
  48562. var handles = displaybles.handles = [];
  48563. var handleLabels = displaybles.handleLabels = [];
  48564. var barGroup = this._displayables.barGroup;
  48565. var size = this._size;
  48566. var dataZoomModel = this.dataZoomModel;
  48567. barGroup.add(displaybles.filler = new Rect$1({
  48568. draggable: true,
  48569. cursor: getCursor(this._orient),
  48570. drift: bind$3(this._onDragMove, this, 'all'),
  48571. ondragstart: bind$3(this._showDataInfo, this, true),
  48572. ondragend: bind$3(this._onDragEnd, this),
  48573. onmouseover: bind$3(this._showDataInfo, this, true),
  48574. onmouseout: bind$3(this._showDataInfo, this, false),
  48575. style: {
  48576. fill: dataZoomModel.get('fillerColor'),
  48577. textPosition: 'inside'
  48578. }
  48579. }));
  48580. // Frame border.
  48581. barGroup.add(new Rect$1({
  48582. silent: true,
  48583. subPixelOptimize: true,
  48584. shape: {
  48585. x: 0,
  48586. y: 0,
  48587. width: size[0],
  48588. height: size[1]
  48589. },
  48590. style: {
  48591. stroke: dataZoomModel.get('dataBackgroundColor')
  48592. || dataZoomModel.get('borderColor'),
  48593. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  48594. fill: 'rgba(0,0,0,0)'
  48595. }
  48596. }));
  48597. each$14([0, 1], function (handleIndex) {
  48598. var path = createIcon(
  48599. dataZoomModel.get('handleIcon'),
  48600. {
  48601. cursor: getCursor(this._orient),
  48602. draggable: true,
  48603. drift: bind$3(this._onDragMove, this, handleIndex),
  48604. ondragend: bind$3(this._onDragEnd, this),
  48605. onmouseover: bind$3(this._showDataInfo, this, true),
  48606. onmouseout: bind$3(this._showDataInfo, this, false)
  48607. },
  48608. {x: -1, y: 0, width: 2, height: 2}
  48609. );
  48610. var bRect = path.getBoundingRect();
  48611. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  48612. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  48613. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  48614. var handleColor = dataZoomModel.get('handleColor');
  48615. // Compatitable with previous version
  48616. if (handleColor != null) {
  48617. path.style.fill = handleColor;
  48618. }
  48619. barGroup.add(handles[handleIndex] = path);
  48620. var textStyleModel = dataZoomModel.textStyleModel;
  48621. this.group.add(
  48622. handleLabels[handleIndex] = new Text({
  48623. silent: true,
  48624. invisible: true,
  48625. style: {
  48626. x: 0, y: 0, text: '',
  48627. textVerticalAlign: 'middle',
  48628. textAlign: 'center',
  48629. textFill: textStyleModel.getTextColor(),
  48630. textFont: textStyleModel.getFont()
  48631. },
  48632. z2: 10
  48633. }));
  48634. }, this);
  48635. },
  48636. /**
  48637. * @private
  48638. */
  48639. _resetInterval: function () {
  48640. var range = this._range = this.dataZoomModel.getPercentRange();
  48641. var viewExtent = this._getViewExtent();
  48642. this._handleEnds = [
  48643. linearMap$1(range[0], [0, 100], viewExtent, true),
  48644. linearMap$1(range[1], [0, 100], viewExtent, true)
  48645. ];
  48646. },
  48647. /**
  48648. * @private
  48649. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  48650. * @param {number} delta
  48651. * @return {boolean} changed
  48652. */
  48653. _updateInterval: function (handleIndex, delta) {
  48654. var dataZoomModel = this.dataZoomModel;
  48655. var handleEnds = this._handleEnds;
  48656. var viewExtend = this._getViewExtent();
  48657. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  48658. var percentExtent = [0, 100];
  48659. sliderMove(
  48660. delta,
  48661. handleEnds,
  48662. viewExtend,
  48663. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  48664. minMaxSpan.minSpan != null
  48665. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  48666. minMaxSpan.maxSpan != null
  48667. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  48668. );
  48669. var lastRange = this._range;
  48670. var range = this._range = asc$2([
  48671. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  48672. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  48673. ]);
  48674. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  48675. },
  48676. /**
  48677. * @private
  48678. */
  48679. _updateView: function (nonRealtime) {
  48680. var displaybles = this._displayables;
  48681. var handleEnds = this._handleEnds;
  48682. var handleInterval = asc$2(handleEnds.slice());
  48683. var size = this._size;
  48684. each$14([0, 1], function (handleIndex) {
  48685. // Handles
  48686. var handle = displaybles.handles[handleIndex];
  48687. var handleHeight = this._handleHeight;
  48688. handle.attr({
  48689. scale: [handleHeight / 2, handleHeight / 2],
  48690. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  48691. });
  48692. }, this);
  48693. // Filler
  48694. displaybles.filler.setShape({
  48695. x: handleInterval[0],
  48696. y: 0,
  48697. width: handleInterval[1] - handleInterval[0],
  48698. height: size[1]
  48699. });
  48700. this._updateDataInfo(nonRealtime);
  48701. },
  48702. /**
  48703. * @private
  48704. */
  48705. _updateDataInfo: function (nonRealtime) {
  48706. var dataZoomModel = this.dataZoomModel;
  48707. var displaybles = this._displayables;
  48708. var handleLabels = displaybles.handleLabels;
  48709. var orient = this._orient;
  48710. var labelTexts = ['', ''];
  48711. // FIXME
  48712. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  48713. if (dataZoomModel.get('showDetail')) {
  48714. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  48715. if (axisProxy) {
  48716. var axis = axisProxy.getAxisModel().axis;
  48717. var range = this._range;
  48718. var dataInterval = nonRealtime
  48719. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  48720. ? axisProxy.calculateDataWindow({
  48721. start: range[0], end: range[1]
  48722. }).valueWindow
  48723. : axisProxy.getDataValueWindow();
  48724. labelTexts = [
  48725. this._formatLabel(dataInterval[0], axis),
  48726. this._formatLabel(dataInterval[1], axis)
  48727. ];
  48728. }
  48729. }
  48730. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  48731. setLabel.call(this, 0);
  48732. setLabel.call(this, 1);
  48733. function setLabel(handleIndex) {
  48734. // Label
  48735. // Text should not transform by barGroup.
  48736. // Ignore handlers transform
  48737. var barTransform = getTransform(
  48738. displaybles.handles[handleIndex].parent, this.group
  48739. );
  48740. var direction = transformDirection(
  48741. handleIndex === 0 ? 'right' : 'left', barTransform
  48742. );
  48743. var offset = this._handleWidth / 2 + LABEL_GAP;
  48744. var textPoint = applyTransform$1(
  48745. [
  48746. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  48747. this._size[1] / 2
  48748. ],
  48749. barTransform
  48750. );
  48751. handleLabels[handleIndex].setStyle({
  48752. x: textPoint[0],
  48753. y: textPoint[1],
  48754. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  48755. textAlign: orient === HORIZONTAL ? direction : 'center',
  48756. text: labelTexts[handleIndex]
  48757. });
  48758. }
  48759. },
  48760. /**
  48761. * @private
  48762. */
  48763. _formatLabel: function (value, axis) {
  48764. var dataZoomModel = this.dataZoomModel;
  48765. var labelFormatter = dataZoomModel.get('labelFormatter');
  48766. var labelPrecision = dataZoomModel.get('labelPrecision');
  48767. if (labelPrecision == null || labelPrecision === 'auto') {
  48768. labelPrecision = axis.getPixelPrecision();
  48769. }
  48770. var valueStr = (value == null || isNaN(value))
  48771. ? ''
  48772. // FIXME Glue code
  48773. : (axis.type === 'category' || axis.type === 'time')
  48774. ? axis.scale.getLabel(Math.round(value))
  48775. // param of toFixed should less then 20.
  48776. : value.toFixed(Math.min(labelPrecision, 20));
  48777. return isFunction$1(labelFormatter)
  48778. ? labelFormatter(value, valueStr)
  48779. : isString(labelFormatter)
  48780. ? labelFormatter.replace('{value}', valueStr)
  48781. : valueStr;
  48782. },
  48783. /**
  48784. * @private
  48785. * @param {boolean} showOrHide true: show, false: hide
  48786. */
  48787. _showDataInfo: function (showOrHide) {
  48788. // Always show when drgging.
  48789. showOrHide = this._dragging || showOrHide;
  48790. var handleLabels = this._displayables.handleLabels;
  48791. handleLabels[0].attr('invisible', !showOrHide);
  48792. handleLabels[1].attr('invisible', !showOrHide);
  48793. },
  48794. _onDragMove: function (handleIndex, dx, dy, event) {
  48795. this._dragging = true;
  48796. // For mobile device, prevent screen slider on the button.
  48797. stop(event.event);
  48798. // Transform dx, dy to bar coordination.
  48799. var barTransform = this._displayables.barGroup.getLocalTransform();
  48800. var vertex = applyTransform$1([dx, dy], barTransform, true);
  48801. var changed = this._updateInterval(handleIndex, vertex[0]);
  48802. var realtime = this.dataZoomModel.get('realtime');
  48803. this._updateView(!realtime);
  48804. // Avoid dispatch dataZoom repeatly but range not changed,
  48805. // which cause bad visual effect when progressive enabled.
  48806. changed && realtime && this._dispatchZoomAction();
  48807. },
  48808. _onDragEnd: function () {
  48809. this._dragging = false;
  48810. this._showDataInfo(false);
  48811. // While in realtime mode and stream mode, dispatch action when
  48812. // drag end will cause the whole view rerender, which is unnecessary.
  48813. var realtime = this.dataZoomModel.get('realtime');
  48814. !realtime && this._dispatchZoomAction();
  48815. },
  48816. _onClickPanelClick: function (e) {
  48817. var size = this._size;
  48818. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  48819. if (localPoint[0] < 0 || localPoint[0] > size[0]
  48820. || localPoint[1] < 0 || localPoint[1] > size[1]
  48821. ) {
  48822. return;
  48823. }
  48824. var handleEnds = this._handleEnds;
  48825. var center = (handleEnds[0] + handleEnds[1]) / 2;
  48826. var changed = this._updateInterval('all', localPoint[0] - center);
  48827. this._updateView();
  48828. changed && this._dispatchZoomAction();
  48829. },
  48830. /**
  48831. * This action will be throttled.
  48832. * @private
  48833. */
  48834. _dispatchZoomAction: function () {
  48835. var range = this._range;
  48836. this.api.dispatchAction({
  48837. type: 'dataZoom',
  48838. from: this.uid,
  48839. dataZoomId: this.dataZoomModel.id,
  48840. start: range[0],
  48841. end: range[1]
  48842. });
  48843. },
  48844. /**
  48845. * @private
  48846. */
  48847. _findCoordRect: function () {
  48848. // Find the grid coresponding to the first axis referred by dataZoom.
  48849. var rect;
  48850. each$14(this.getTargetCoordInfo(), function (coordInfoList) {
  48851. if (!rect && coordInfoList.length) {
  48852. var coordSys = coordInfoList[0].model.coordinateSystem;
  48853. rect = coordSys.getRect && coordSys.getRect();
  48854. }
  48855. });
  48856. if (!rect) {
  48857. var width = this.api.getWidth();
  48858. var height = this.api.getHeight();
  48859. rect = {
  48860. x: width * 0.2,
  48861. y: height * 0.2,
  48862. width: width * 0.6,
  48863. height: height * 0.6
  48864. };
  48865. }
  48866. return rect;
  48867. }
  48868. });
  48869. function getOtherDim(thisDim) {
  48870. // FIXME
  48871. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  48872. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  48873. return map$$1[thisDim];
  48874. }
  48875. function getCursor(orient) {
  48876. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  48877. }
  48878. /*
  48879. * Licensed to the Apache Software Foundation (ASF) under one
  48880. * or more contributor license agreements. See the NOTICE file
  48881. * distributed with this work for additional information
  48882. * regarding copyright ownership. The ASF licenses this file
  48883. * to you under the Apache License, Version 2.0 (the
  48884. * "License"); you may not use this file except in compliance
  48885. * with the License. You may obtain a copy of the License at
  48886. *
  48887. * http://www.apache.org/licenses/LICENSE-2.0
  48888. *
  48889. * Unless required by applicable law or agreed to in writing,
  48890. * software distributed under the License is distributed on an
  48891. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48892. * KIND, either express or implied. See the License for the
  48893. * specific language governing permissions and limitations
  48894. * under the License.
  48895. */
  48896. registerProcessor({
  48897. // `dataZoomProcessor` will only be performed in needed series. Consider if
  48898. // there is a line series and a pie series, it is better not to update the
  48899. // line series if only pie series is needed to be updated.
  48900. getTargetSeries: function (ecModel) {
  48901. var seriesModelMap = createHashMap();
  48902. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  48903. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  48904. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  48905. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  48906. seriesModelMap.set(seriesModel.uid, seriesModel);
  48907. });
  48908. });
  48909. });
  48910. return seriesModelMap;
  48911. },
  48912. modifyOutputEnd: true,
  48913. // Consider appendData, where filter should be performed. Because data process is
  48914. // in block mode currently, it is not need to worry about that the overallProgress
  48915. // execute every frame.
  48916. overallReset: function (ecModel, api) {
  48917. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  48918. // We calculate window and reset axis here but not in model
  48919. // init stage and not after action dispatch handler, because
  48920. // reset should be called after seriesData.restoreData.
  48921. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  48922. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  48923. });
  48924. // Caution: data zoom filtering is order sensitive when using
  48925. // percent range and no min/max/scale set on axis.
  48926. // For example, we have dataZoom definition:
  48927. // [
  48928. // {xAxisIndex: 0, start: 30, end: 70},
  48929. // {yAxisIndex: 0, start: 20, end: 80}
  48930. // ]
  48931. // In this case, [20, 80] of y-dataZoom should be based on data
  48932. // that have filtered by x-dataZoom using range of [30, 70],
  48933. // but should not be based on full raw data. Thus sliding
  48934. // x-dataZoom will change both ranges of xAxis and yAxis,
  48935. // while sliding y-dataZoom will only change the range of yAxis.
  48936. // So we should filter x-axis after reset x-axis immediately,
  48937. // and then reset y-axis and filter y-axis.
  48938. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  48939. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  48940. });
  48941. });
  48942. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  48943. // Fullfill all of the range props so that user
  48944. // is able to get them from chart.getOption().
  48945. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  48946. var percentRange = axisProxy.getDataPercentWindow();
  48947. var valueRange = axisProxy.getDataValueWindow();
  48948. dataZoomModel.setCalculatedRange({
  48949. start: percentRange[0],
  48950. end: percentRange[1],
  48951. startValue: valueRange[0],
  48952. endValue: valueRange[1]
  48953. });
  48954. });
  48955. }
  48956. });
  48957. /*
  48958. * Licensed to the Apache Software Foundation (ASF) under one
  48959. * or more contributor license agreements. See the NOTICE file
  48960. * distributed with this work for additional information
  48961. * regarding copyright ownership. The ASF licenses this file
  48962. * to you under the Apache License, Version 2.0 (the
  48963. * "License"); you may not use this file except in compliance
  48964. * with the License. You may obtain a copy of the License at
  48965. *
  48966. * http://www.apache.org/licenses/LICENSE-2.0
  48967. *
  48968. * Unless required by applicable law or agreed to in writing,
  48969. * software distributed under the License is distributed on an
  48970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48971. * KIND, either express or implied. See the License for the
  48972. * specific language governing permissions and limitations
  48973. * under the License.
  48974. */
  48975. registerAction('dataZoom', function (payload, ecModel) {
  48976. var linkedNodesFinder = createLinkedNodesFinder(
  48977. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  48978. eachAxisDim$1,
  48979. function (model, dimNames) {
  48980. return model.get(dimNames.axisIndex);
  48981. }
  48982. );
  48983. var effectedModels = [];
  48984. ecModel.eachComponent(
  48985. {mainType: 'dataZoom', query: payload},
  48986. function (model, index) {
  48987. effectedModels.push.apply(
  48988. effectedModels, linkedNodesFinder(model).nodes
  48989. );
  48990. }
  48991. );
  48992. each$1(effectedModels, function (dataZoomModel, index) {
  48993. dataZoomModel.setRawRange({
  48994. start: payload.start,
  48995. end: payload.end,
  48996. startValue: payload.startValue,
  48997. endValue: payload.endValue
  48998. });
  48999. });
  49000. });
  49001. /*
  49002. * Licensed to the Apache Software Foundation (ASF) under one
  49003. * or more contributor license agreements. See the NOTICE file
  49004. * distributed with this work for additional information
  49005. * regarding copyright ownership. The ASF licenses this file
  49006. * to you under the Apache License, Version 2.0 (the
  49007. * "License"); you may not use this file except in compliance
  49008. * with the License. You may obtain a copy of the License at
  49009. *
  49010. * http://www.apache.org/licenses/LICENSE-2.0
  49011. *
  49012. * Unless required by applicable law or agreed to in writing,
  49013. * software distributed under the License is distributed on an
  49014. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49015. * KIND, either express or implied. See the License for the
  49016. * specific language governing permissions and limitations
  49017. * under the License.
  49018. */
  49019. /*
  49020. * Licensed to the Apache Software Foundation (ASF) under one
  49021. * or more contributor license agreements. See the NOTICE file
  49022. * distributed with this work for additional information
  49023. * regarding copyright ownership. The ASF licenses this file
  49024. * to you under the Apache License, Version 2.0 (the
  49025. * "License"); you may not use this file except in compliance
  49026. * with the License. You may obtain a copy of the License at
  49027. *
  49028. * http://www.apache.org/licenses/LICENSE-2.0
  49029. *
  49030. * Unless required by applicable law or agreed to in writing,
  49031. * software distributed under the License is distributed on an
  49032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49033. * KIND, either express or implied. See the License for the
  49034. * specific language governing permissions and limitations
  49035. * under the License.
  49036. */
  49037. DataZoomModel.extend({
  49038. type: 'dataZoom.inside',
  49039. /**
  49040. * @protected
  49041. */
  49042. defaultOption: {
  49043. disabled: false, // Whether disable this inside zoom.
  49044. zoomLock: false, // Whether disable zoom but only pan.
  49045. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49046. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49047. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49048. preventDefaultMouseMove: true
  49049. }
  49050. });
  49051. /*
  49052. * Licensed to the Apache Software Foundation (ASF) under one
  49053. * or more contributor license agreements. See the NOTICE file
  49054. * distributed with this work for additional information
  49055. * regarding copyright ownership. The ASF licenses this file
  49056. * to you under the Apache License, Version 2.0 (the
  49057. * "License"); you may not use this file except in compliance
  49058. * with the License. You may obtain a copy of the License at
  49059. *
  49060. * http://www.apache.org/licenses/LICENSE-2.0
  49061. *
  49062. * Unless required by applicable law or agreed to in writing,
  49063. * software distributed under the License is distributed on an
  49064. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49065. * KIND, either express or implied. See the License for the
  49066. * specific language governing permissions and limitations
  49067. * under the License.
  49068. */
  49069. var ATTR$1 = '\0_ec_interaction_mutex';
  49070. function take(zr, resourceKey, userKey) {
  49071. var store = getStore(zr);
  49072. store[resourceKey] = userKey;
  49073. }
  49074. function release(zr, resourceKey, userKey) {
  49075. var store = getStore(zr);
  49076. var uKey = store[resourceKey];
  49077. if (uKey === userKey) {
  49078. store[resourceKey] = null;
  49079. }
  49080. }
  49081. function isTaken(zr, resourceKey) {
  49082. return !!getStore(zr)[resourceKey];
  49083. }
  49084. function getStore(zr) {
  49085. return zr[ATTR$1] || (zr[ATTR$1] = {});
  49086. }
  49087. /**
  49088. * payload: {
  49089. * type: 'takeGlobalCursor',
  49090. * key: 'dataZoomSelect', or 'brush', or ...,
  49091. * If no userKey, release global cursor.
  49092. * }
  49093. */
  49094. registerAction(
  49095. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  49096. function () {}
  49097. );
  49098. /*
  49099. * Licensed to the Apache Software Foundation (ASF) under one
  49100. * or more contributor license agreements. See the NOTICE file
  49101. * distributed with this work for additional information
  49102. * regarding copyright ownership. The ASF licenses this file
  49103. * to you under the Apache License, Version 2.0 (the
  49104. * "License"); you may not use this file except in compliance
  49105. * with the License. You may obtain a copy of the License at
  49106. *
  49107. * http://www.apache.org/licenses/LICENSE-2.0
  49108. *
  49109. * Unless required by applicable law or agreed to in writing,
  49110. * software distributed under the License is distributed on an
  49111. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49112. * KIND, either express or implied. See the License for the
  49113. * specific language governing permissions and limitations
  49114. * under the License.
  49115. */
  49116. /**
  49117. * @alias module:echarts/component/helper/RoamController
  49118. * @constructor
  49119. * @mixin {module:zrender/mixin/Eventful}
  49120. *
  49121. * @param {module:zrender/zrender~ZRender} zr
  49122. */
  49123. function RoamController(zr) {
  49124. /**
  49125. * @type {Function}
  49126. */
  49127. this.pointerChecker;
  49128. /**
  49129. * @type {module:zrender}
  49130. */
  49131. this._zr = zr;
  49132. /**
  49133. * @type {Object}
  49134. */
  49135. this._opt = {};
  49136. // Avoid two roamController bind the same handler
  49137. var bind$$1 = bind;
  49138. var mousedownHandler = bind$$1(mousedown, this);
  49139. var mousemoveHandler = bind$$1(mousemove, this);
  49140. var mouseupHandler = bind$$1(mouseup, this);
  49141. var mousewheelHandler = bind$$1(mousewheel, this);
  49142. var pinchHandler = bind$$1(pinch, this);
  49143. Eventful.call(this);
  49144. /**
  49145. * @param {Function} pointerChecker
  49146. * input: x, y
  49147. * output: boolean
  49148. */
  49149. this.setPointerChecker = function (pointerChecker) {
  49150. this.pointerChecker = pointerChecker;
  49151. };
  49152. /**
  49153. * Notice: only enable needed types. For example, if 'zoom'
  49154. * is not needed, 'zoom' should not be enabled, otherwise
  49155. * default mousewheel behaviour (scroll page) will be disabled.
  49156. *
  49157. * @param {boolean|string} [controlType=true] Specify the control type,
  49158. * which can be null/undefined or true/false
  49159. * or 'pan/move' or 'zoom'/'scale'
  49160. * @param {Object} [opt]
  49161. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49162. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49163. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49164. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  49165. */
  49166. this.enable = function (controlType, opt) {
  49167. // Disable previous first
  49168. this.disable();
  49169. this._opt = defaults(clone(opt) || {}, {
  49170. zoomOnMouseWheel: true,
  49171. moveOnMouseMove: true,
  49172. // By default, wheel do not trigger move.
  49173. moveOnMouseWheel: false,
  49174. preventDefaultMouseMove: true
  49175. });
  49176. if (controlType == null) {
  49177. controlType = true;
  49178. }
  49179. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  49180. zr.on('mousedown', mousedownHandler);
  49181. zr.on('mousemove', mousemoveHandler);
  49182. zr.on('mouseup', mouseupHandler);
  49183. }
  49184. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  49185. zr.on('mousewheel', mousewheelHandler);
  49186. zr.on('pinch', pinchHandler);
  49187. }
  49188. };
  49189. this.disable = function () {
  49190. zr.off('mousedown', mousedownHandler);
  49191. zr.off('mousemove', mousemoveHandler);
  49192. zr.off('mouseup', mouseupHandler);
  49193. zr.off('mousewheel', mousewheelHandler);
  49194. zr.off('pinch', pinchHandler);
  49195. };
  49196. this.dispose = this.disable;
  49197. this.isDragging = function () {
  49198. return this._dragging;
  49199. };
  49200. this.isPinching = function () {
  49201. return this._pinching;
  49202. };
  49203. }
  49204. mixin(RoamController, Eventful);
  49205. function mousedown(e) {
  49206. if (isMiddleOrRightButtonOnMouseUpDown(e)
  49207. || (e.target && e.target.draggable)
  49208. ) {
  49209. return;
  49210. }
  49211. var x = e.offsetX;
  49212. var y = e.offsetY;
  49213. // Only check on mosedown, but not mousemove.
  49214. // Mouse can be out of target when mouse moving.
  49215. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  49216. this._x = x;
  49217. this._y = y;
  49218. this._dragging = true;
  49219. }
  49220. }
  49221. function mousemove(e) {
  49222. if (!this._dragging
  49223. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  49224. || e.gestureEvent === 'pinch'
  49225. || isTaken(this._zr, 'globalPan')
  49226. ) {
  49227. return;
  49228. }
  49229. var x = e.offsetX;
  49230. var y = e.offsetY;
  49231. var oldX = this._x;
  49232. var oldY = this._y;
  49233. var dx = x - oldX;
  49234. var dy = y - oldY;
  49235. this._x = x;
  49236. this._y = y;
  49237. this._opt.preventDefaultMouseMove && stop(e.event);
  49238. trigger(this, 'pan', 'moveOnMouseMove', e, {
  49239. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  49240. });
  49241. }
  49242. function mouseup(e) {
  49243. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  49244. this._dragging = false;
  49245. }
  49246. }
  49247. function mousewheel(e) {
  49248. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  49249. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  49250. var wheelDelta = e.wheelDelta;
  49251. var absWheelDeltaDelta = Math.abs(wheelDelta);
  49252. var originX = e.offsetX;
  49253. var originY = e.offsetY;
  49254. // wheelDelta maybe -0 in chrome mac.
  49255. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  49256. return;
  49257. }
  49258. // If both `shouldZoom` and `shouldMove` is true, trigger
  49259. // their event both, and the final behavior is determined
  49260. // by event listener themselves.
  49261. if (shouldZoom) {
  49262. // Convenience:
  49263. // Mac and VM Windows on Mac: scroll up: zoom out.
  49264. // Windows: scroll up: zoom in.
  49265. // FIXME: Should do more test in different environment.
  49266. // wheelDelta is too complicated in difference nvironment
  49267. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  49268. // although it has been normallized by zrender.
  49269. // wheelDelta of mouse wheel is bigger than touch pad.
  49270. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  49271. var scale = wheelDelta > 0 ? factor : 1 / factor;
  49272. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  49273. scale: scale, originX: originX, originY: originY
  49274. });
  49275. }
  49276. if (shouldMove) {
  49277. // FIXME: Should do more test in different environment.
  49278. var absDelta = Math.abs(wheelDelta);
  49279. // wheelDelta of mouse wheel is bigger than touch pad.
  49280. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  49281. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  49282. scrollDelta: scrollDelta, originX: originX, originY: originY
  49283. });
  49284. }
  49285. }
  49286. function pinch(e) {
  49287. if (isTaken(this._zr, 'globalPan')) {
  49288. return;
  49289. }
  49290. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  49291. checkPointerAndTrigger(this, 'zoom', null, e, {
  49292. scale: scale, originX: e.pinchX, originY: e.pinchY
  49293. });
  49294. }
  49295. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  49296. if (controller.pointerChecker
  49297. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  49298. ) {
  49299. // When mouse is out of roamController rect,
  49300. // default befavoius should not be be disabled, otherwise
  49301. // page sliding is disabled, contrary to expectation.
  49302. stop(e.event);
  49303. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  49304. }
  49305. }
  49306. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  49307. // Also provide behavior checker for event listener, for some case that
  49308. // multiple components share one listener.
  49309. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  49310. controller.trigger(eventName, contollerEvent);
  49311. }
  49312. // settings: {
  49313. // zoomOnMouseWheel
  49314. // moveOnMouseMove
  49315. // moveOnMouseWheel
  49316. // }
  49317. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49318. function isAvailableBehavior(behaviorToCheck, e, settings) {
  49319. var setting = settings[behaviorToCheck];
  49320. return !behaviorToCheck || (
  49321. setting && (!isString(setting) || e.event[setting + 'Key'])
  49322. );
  49323. }
  49324. /*
  49325. * Licensed to the Apache Software Foundation (ASF) under one
  49326. * or more contributor license agreements. See the NOTICE file
  49327. * distributed with this work for additional information
  49328. * regarding copyright ownership. The ASF licenses this file
  49329. * to you under the Apache License, Version 2.0 (the
  49330. * "License"); you may not use this file except in compliance
  49331. * with the License. You may obtain a copy of the License at
  49332. *
  49333. * http://www.apache.org/licenses/LICENSE-2.0
  49334. *
  49335. * Unless required by applicable law or agreed to in writing,
  49336. * software distributed under the License is distributed on an
  49337. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49338. * KIND, either express or implied. See the License for the
  49339. * specific language governing permissions and limitations
  49340. * under the License.
  49341. */
  49342. // Only create one roam controller for each coordinate system.
  49343. // one roam controller might be refered by two inside data zoom
  49344. // components (for example, one for x and one for y). When user
  49345. // pan or zoom, only dispatch one action for those data zoom
  49346. // components.
  49347. var ATTR = '\0_ec_dataZoom_roams';
  49348. /**
  49349. * @public
  49350. * @param {module:echarts/ExtensionAPI} api
  49351. * @param {Object} dataZoomInfo
  49352. * @param {string} dataZoomInfo.coordId
  49353. * @param {Function} dataZoomInfo.containsPoint
  49354. * @param {Array.<string>} dataZoomInfo.allCoordIds
  49355. * @param {string} dataZoomInfo.dataZoomId
  49356. * @param {Object} dataZoomInfo.getRange
  49357. * @param {Function} dataZoomInfo.getRange.pan
  49358. * @param {Function} dataZoomInfo.getRange.zoom
  49359. * @param {Function} dataZoomInfo.getRange.scrollMove
  49360. * @param {boolean} dataZoomInfo.dataZoomModel
  49361. */
  49362. function register$1(api, dataZoomInfo) {
  49363. var store = giveStore(api);
  49364. var theDataZoomId = dataZoomInfo.dataZoomId;
  49365. var theCoordId = dataZoomInfo.coordId;
  49366. // Do clean when a dataZoom changes its target coordnate system.
  49367. // Avoid memory leak, dispose all not-used-registered.
  49368. each$1(store, function (record, coordId) {
  49369. var dataZoomInfos = record.dataZoomInfos;
  49370. if (dataZoomInfos[theDataZoomId]
  49371. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  49372. ) {
  49373. delete dataZoomInfos[theDataZoomId];
  49374. record.count--;
  49375. }
  49376. });
  49377. cleanStore(store);
  49378. var record = store[theCoordId];
  49379. // Create if needed.
  49380. if (!record) {
  49381. record = store[theCoordId] = {
  49382. coordId: theCoordId,
  49383. dataZoomInfos: {},
  49384. count: 0
  49385. };
  49386. record.controller = createController(api, record);
  49387. record.dispatchAction = curry(dispatchAction, api);
  49388. }
  49389. // Update reference of dataZoom.
  49390. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  49391. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  49392. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  49393. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  49394. // Consider resize, area should be always updated.
  49395. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  49396. // Update throttle.
  49397. createOrUpdate(
  49398. record,
  49399. 'dispatchAction',
  49400. dataZoomInfo.dataZoomModel.get('throttle', true),
  49401. 'fixRate'
  49402. );
  49403. }
  49404. /**
  49405. * @public
  49406. * @param {module:echarts/ExtensionAPI} api
  49407. * @param {string} dataZoomId
  49408. */
  49409. function unregister$1(api, dataZoomId) {
  49410. var store = giveStore(api);
  49411. each$1(store, function (record) {
  49412. record.controller.dispose();
  49413. var dataZoomInfos = record.dataZoomInfos;
  49414. if (dataZoomInfos[dataZoomId]) {
  49415. delete dataZoomInfos[dataZoomId];
  49416. record.count--;
  49417. }
  49418. });
  49419. cleanStore(store);
  49420. }
  49421. /**
  49422. * @public
  49423. */
  49424. function generateCoordId(coordModel) {
  49425. return coordModel.type + '\0_' + coordModel.id;
  49426. }
  49427. /**
  49428. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  49429. * @type {Array.<Object>}
  49430. */
  49431. function giveStore(api) {
  49432. // Mount store on zrender instance, so that we do not
  49433. // need to worry about dispose.
  49434. var zr = api.getZr();
  49435. return zr[ATTR] || (zr[ATTR] = {});
  49436. }
  49437. function createController(api, newRecord) {
  49438. var controller = new RoamController(api.getZr());
  49439. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  49440. controller.on(eventName, function (event) {
  49441. var batch = [];
  49442. each$1(newRecord.dataZoomInfos, function (info) {
  49443. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  49444. // moveOnMouseWheel, ...) enabled.
  49445. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  49446. return;
  49447. }
  49448. var method = (info.getRange || {})[eventName];
  49449. var range = method && method(newRecord.controller, event);
  49450. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  49451. dataZoomId: info.dataZoomId,
  49452. start: range[0],
  49453. end: range[1]
  49454. });
  49455. });
  49456. batch.length && newRecord.dispatchAction(batch);
  49457. });
  49458. });
  49459. return controller;
  49460. }
  49461. function cleanStore(store) {
  49462. each$1(store, function (record, coordId) {
  49463. if (!record.count) {
  49464. record.controller.dispose();
  49465. delete store[coordId];
  49466. }
  49467. });
  49468. }
  49469. /**
  49470. * This action will be throttled.
  49471. */
  49472. function dispatchAction(api, batch) {
  49473. api.dispatchAction({
  49474. type: 'dataZoom',
  49475. batch: batch
  49476. });
  49477. }
  49478. /**
  49479. * Merge roamController settings when multiple dataZooms share one roamController.
  49480. */
  49481. function mergeControllerParams(dataZoomInfos) {
  49482. var controlType;
  49483. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  49484. // as string, it is probably revert to reserved word by compress tool. See #7411.
  49485. var prefix = 'type_';
  49486. var typePriority = {
  49487. 'type_true': 2,
  49488. 'type_move': 1,
  49489. 'type_false': 0,
  49490. 'type_undefined': -1
  49491. };
  49492. var preventDefaultMouseMove = true;
  49493. each$1(dataZoomInfos, function (dataZoomInfo) {
  49494. var dataZoomModel = dataZoomInfo.dataZoomModel;
  49495. var oneType = dataZoomModel.get('disabled', true)
  49496. ? false
  49497. : dataZoomModel.get('zoomLock', true)
  49498. ? 'move'
  49499. : true;
  49500. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  49501. controlType = oneType;
  49502. }
  49503. // Prevent default move event by default. If one false, do not prevent. Otherwise
  49504. // users may be confused why it does not work when multiple insideZooms exist.
  49505. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  49506. });
  49507. return {
  49508. controlType: controlType,
  49509. opt: {
  49510. // RoamController will enable all of these functionalities,
  49511. // and the final behavior is determined by its event listener
  49512. // provided by each inside zoom.
  49513. zoomOnMouseWheel: true,
  49514. moveOnMouseMove: true,
  49515. moveOnMouseWheel: true,
  49516. preventDefaultMouseMove: !!preventDefaultMouseMove
  49517. }
  49518. };
  49519. }
  49520. /*
  49521. * Licensed to the Apache Software Foundation (ASF) under one
  49522. * or more contributor license agreements. See the NOTICE file
  49523. * distributed with this work for additional information
  49524. * regarding copyright ownership. The ASF licenses this file
  49525. * to you under the Apache License, Version 2.0 (the
  49526. * "License"); you may not use this file except in compliance
  49527. * with the License. You may obtain a copy of the License at
  49528. *
  49529. * http://www.apache.org/licenses/LICENSE-2.0
  49530. *
  49531. * Unless required by applicable law or agreed to in writing,
  49532. * software distributed under the License is distributed on an
  49533. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49534. * KIND, either express or implied. See the License for the
  49535. * specific language governing permissions and limitations
  49536. * under the License.
  49537. */
  49538. var bind$4 = bind;
  49539. var InsideZoomView = DataZoomView.extend({
  49540. type: 'dataZoom.inside',
  49541. /**
  49542. * @override
  49543. */
  49544. init: function (ecModel, api) {
  49545. /**
  49546. * 'throttle' is used in this.dispatchAction, so we save range
  49547. * to avoid missing some 'pan' info.
  49548. * @private
  49549. * @type {Array.<number>}
  49550. */
  49551. this._range;
  49552. },
  49553. /**
  49554. * @override
  49555. */
  49556. render: function (dataZoomModel, ecModel, api, payload) {
  49557. InsideZoomView.superApply(this, 'render', arguments);
  49558. // Hence the `throttle` util ensures to preserve command order,
  49559. // here simply updating range all the time will not cause missing
  49560. // any of the the roam change.
  49561. this._range = dataZoomModel.getPercentRange();
  49562. // Reset controllers.
  49563. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  49564. var allCoordIds = map(coordInfoList, function (coordInfo) {
  49565. return generateCoordId(coordInfo.model);
  49566. });
  49567. each$1(coordInfoList, function (coordInfo) {
  49568. var coordModel = coordInfo.model;
  49569. var getRange = {};
  49570. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  49571. getRange[eventName] = bind$4(roamHandlers[eventName], this, coordInfo, coordSysName);
  49572. }, this);
  49573. register$1(
  49574. api,
  49575. {
  49576. coordId: generateCoordId(coordModel),
  49577. allCoordIds: allCoordIds,
  49578. containsPoint: function (e, x, y) {
  49579. return coordModel.coordinateSystem.containPoint([x, y]);
  49580. },
  49581. dataZoomId: dataZoomModel.id,
  49582. dataZoomModel: dataZoomModel,
  49583. getRange: getRange
  49584. }
  49585. );
  49586. }, this);
  49587. }, this);
  49588. },
  49589. /**
  49590. * @override
  49591. */
  49592. dispose: function () {
  49593. unregister$1(this.api, this.dataZoomModel.id);
  49594. InsideZoomView.superApply(this, 'dispose', arguments);
  49595. this._range = null;
  49596. }
  49597. });
  49598. var roamHandlers = {
  49599. /**
  49600. * @this {module:echarts/component/dataZoom/InsideZoomView}
  49601. */
  49602. zoom: function (coordInfo, coordSysName, controller, e) {
  49603. var lastRange = this._range;
  49604. var range = lastRange.slice();
  49605. // Calculate transform by the first axis.
  49606. var axisModel = coordInfo.axisModels[0];
  49607. if (!axisModel) {
  49608. return;
  49609. }
  49610. var directionInfo = getDirectionInfo[coordSysName](
  49611. null, [e.originX, e.originY], axisModel, controller, coordInfo
  49612. );
  49613. var percentPoint = (
  49614. directionInfo.signal > 0
  49615. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  49616. : (directionInfo.pixel - directionInfo.pixelStart)
  49617. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  49618. var scale = Math.max(1 / e.scale, 0);
  49619. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  49620. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  49621. // Restrict range.
  49622. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  49623. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  49624. this._range = range;
  49625. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  49626. return range;
  49627. }
  49628. },
  49629. /**
  49630. * @this {module:echarts/component/dataZoom/InsideZoomView}
  49631. */
  49632. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  49633. var directionInfo = getDirectionInfo[coordSysName](
  49634. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  49635. );
  49636. return directionInfo.signal
  49637. * (range[1] - range[0])
  49638. * directionInfo.pixel / directionInfo.pixelLength;
  49639. }),
  49640. /**
  49641. * @this {module:echarts/component/dataZoom/InsideZoomView}
  49642. */
  49643. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  49644. var directionInfo = getDirectionInfo[coordSysName](
  49645. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  49646. );
  49647. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  49648. })
  49649. };
  49650. function makeMover(getPercentDelta) {
  49651. return function (coordInfo, coordSysName, controller, e) {
  49652. var lastRange = this._range;
  49653. var range = lastRange.slice();
  49654. // Calculate transform by the first axis.
  49655. var axisModel = coordInfo.axisModels[0];
  49656. if (!axisModel) {
  49657. return;
  49658. }
  49659. var percentDelta = getPercentDelta(
  49660. range, axisModel, coordInfo, coordSysName, controller, e
  49661. );
  49662. sliderMove(percentDelta, range, [0, 100], 'all');
  49663. this._range = range;
  49664. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  49665. return range;
  49666. }
  49667. };
  49668. }
  49669. var getDirectionInfo = {
  49670. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  49671. var axis = axisModel.axis;
  49672. var ret = {};
  49673. var rect = coordInfo.model.coordinateSystem.getRect();
  49674. oldPoint = oldPoint || [0, 0];
  49675. if (axis.dim === 'x') {
  49676. ret.pixel = newPoint[0] - oldPoint[0];
  49677. ret.pixelLength = rect.width;
  49678. ret.pixelStart = rect.x;
  49679. ret.signal = axis.inverse ? 1 : -1;
  49680. }
  49681. else { // axis.dim === 'y'
  49682. ret.pixel = newPoint[1] - oldPoint[1];
  49683. ret.pixelLength = rect.height;
  49684. ret.pixelStart = rect.y;
  49685. ret.signal = axis.inverse ? -1 : 1;
  49686. }
  49687. return ret;
  49688. },
  49689. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  49690. var axis = axisModel.axis;
  49691. var ret = {};
  49692. var polar = coordInfo.model.coordinateSystem;
  49693. var radiusExtent = polar.getRadiusAxis().getExtent();
  49694. var angleExtent = polar.getAngleAxis().getExtent();
  49695. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  49696. newPoint = polar.pointToCoord(newPoint);
  49697. if (axisModel.mainType === 'radiusAxis') {
  49698. ret.pixel = newPoint[0] - oldPoint[0];
  49699. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  49700. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  49701. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  49702. ret.pixelStart = radiusExtent[0];
  49703. ret.signal = axis.inverse ? 1 : -1;
  49704. }
  49705. else { // 'angleAxis'
  49706. ret.pixel = newPoint[1] - oldPoint[1];
  49707. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  49708. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  49709. ret.pixelLength = angleExtent[1] - angleExtent[0];
  49710. ret.pixelStart = angleExtent[0];
  49711. ret.signal = axis.inverse ? -1 : 1;
  49712. }
  49713. return ret;
  49714. },
  49715. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  49716. var axis = axisModel.axis;
  49717. var rect = coordInfo.model.coordinateSystem.getRect();
  49718. var ret = {};
  49719. oldPoint = oldPoint || [0, 0];
  49720. if (axis.orient === 'horizontal') {
  49721. ret.pixel = newPoint[0] - oldPoint[0];
  49722. ret.pixelLength = rect.width;
  49723. ret.pixelStart = rect.x;
  49724. ret.signal = axis.inverse ? 1 : -1;
  49725. }
  49726. else { // 'vertical'
  49727. ret.pixel = newPoint[1] - oldPoint[1];
  49728. ret.pixelLength = rect.height;
  49729. ret.pixelStart = rect.y;
  49730. ret.signal = axis.inverse ? -1 : 1;
  49731. }
  49732. return ret;
  49733. }
  49734. };
  49735. /*
  49736. * Licensed to the Apache Software Foundation (ASF) under one
  49737. * or more contributor license agreements. See the NOTICE file
  49738. * distributed with this work for additional information
  49739. * regarding copyright ownership. The ASF licenses this file
  49740. * to you under the Apache License, Version 2.0 (the
  49741. * "License"); you may not use this file except in compliance
  49742. * with the License. You may obtain a copy of the License at
  49743. *
  49744. * http://www.apache.org/licenses/LICENSE-2.0
  49745. *
  49746. * Unless required by applicable law or agreed to in writing,
  49747. * software distributed under the License is distributed on an
  49748. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49749. * KIND, either express or implied. See the License for the
  49750. * specific language governing permissions and limitations
  49751. * under the License.
  49752. */
  49753. /*
  49754. * Licensed to the Apache Software Foundation (ASF) under one
  49755. * or more contributor license agreements. See the NOTICE file
  49756. * distributed with this work for additional information
  49757. * regarding copyright ownership. The ASF licenses this file
  49758. * to you under the Apache License, Version 2.0 (the
  49759. * "License"); you may not use this file except in compliance
  49760. * with the License. You may obtain a copy of the License at
  49761. *
  49762. * http://www.apache.org/licenses/LICENSE-2.0
  49763. *
  49764. * Unless required by applicable law or agreed to in writing,
  49765. * software distributed under the License is distributed on an
  49766. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49767. * KIND, either express or implied. See the License for the
  49768. * specific language governing permissions and limitations
  49769. * under the License.
  49770. */
  49771. // Do not include './dataZoomSelect',
  49772. // since it only work for toolbox dataZoom.
  49773. /*
  49774. * Licensed to the Apache Software Foundation (ASF) under one
  49775. * or more contributor license agreements. See the NOTICE file
  49776. * distributed with this work for additional information
  49777. * regarding copyright ownership. The ASF licenses this file
  49778. * to you under the Apache License, Version 2.0 (the
  49779. * "License"); you may not use this file except in compliance
  49780. * with the License. You may obtain a copy of the License at
  49781. *
  49782. * http://www.apache.org/licenses/LICENSE-2.0
  49783. *
  49784. * Unless required by applicable law or agreed to in writing,
  49785. * software distributed under the License is distributed on an
  49786. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49787. * KIND, either express or implied. See the License for the
  49788. * specific language governing permissions and limitations
  49789. * under the License.
  49790. */
  49791. var features = {};
  49792. function register$2(name, ctor) {
  49793. features[name] = ctor;
  49794. }
  49795. function get$1(name) {
  49796. return features[name];
  49797. }
  49798. /*
  49799. * Licensed to the Apache Software Foundation (ASF) under one
  49800. * or more contributor license agreements. See the NOTICE file
  49801. * distributed with this work for additional information
  49802. * regarding copyright ownership. The ASF licenses this file
  49803. * to you under the Apache License, Version 2.0 (the
  49804. * "License"); you may not use this file except in compliance
  49805. * with the License. You may obtain a copy of the License at
  49806. *
  49807. * http://www.apache.org/licenses/LICENSE-2.0
  49808. *
  49809. * Unless required by applicable law or agreed to in writing,
  49810. * software distributed under the License is distributed on an
  49811. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49812. * KIND, either express or implied. See the License for the
  49813. * specific language governing permissions and limitations
  49814. * under the License.
  49815. */
  49816. var ToolboxModel = extendComponentModel({
  49817. type: 'toolbox',
  49818. layoutMode: {
  49819. type: 'box',
  49820. ignoreSize: true
  49821. },
  49822. optionUpdated: function () {
  49823. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  49824. each$1(this.option.feature, function (featureOpt, featureName) {
  49825. var Feature = get$1(featureName);
  49826. Feature && merge(featureOpt, Feature.defaultOption);
  49827. });
  49828. },
  49829. defaultOption: {
  49830. show: true,
  49831. z: 6,
  49832. zlevel: 0,
  49833. orient: 'horizontal',
  49834. left: 'right',
  49835. top: 'top',
  49836. // right
  49837. // bottom
  49838. backgroundColor: 'transparent',
  49839. borderColor: '#ccc',
  49840. borderRadius: 0,
  49841. borderWidth: 0,
  49842. padding: 5,
  49843. itemSize: 15,
  49844. itemGap: 8,
  49845. showTitle: true,
  49846. iconStyle: {
  49847. borderColor: '#666',
  49848. color: 'none'
  49849. },
  49850. emphasis: {
  49851. iconStyle: {
  49852. borderColor: '#3E98C5'
  49853. }
  49854. },
  49855. // textStyle: {},
  49856. // feature
  49857. tooltip: {
  49858. show: false
  49859. }
  49860. }
  49861. });
  49862. /*
  49863. * Licensed to the Apache Software Foundation (ASF) under one
  49864. * or more contributor license agreements. See the NOTICE file
  49865. * distributed with this work for additional information
  49866. * regarding copyright ownership. The ASF licenses this file
  49867. * to you under the Apache License, Version 2.0 (the
  49868. * "License"); you may not use this file except in compliance
  49869. * with the License. You may obtain a copy of the License at
  49870. *
  49871. * http://www.apache.org/licenses/LICENSE-2.0
  49872. *
  49873. * Unless required by applicable law or agreed to in writing,
  49874. * software distributed under the License is distributed on an
  49875. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49876. * KIND, either express or implied. See the License for the
  49877. * specific language governing permissions and limitations
  49878. * under the License.
  49879. */
  49880. extendComponentView({
  49881. type: 'toolbox',
  49882. render: function (toolboxModel, ecModel, api, payload) {
  49883. var group = this.group;
  49884. group.removeAll();
  49885. if (!toolboxModel.get('show')) {
  49886. return;
  49887. }
  49888. var itemSize = +toolboxModel.get('itemSize');
  49889. var featureOpts = toolboxModel.get('feature') || {};
  49890. var features = this._features || (this._features = {});
  49891. var featureNames = [];
  49892. each$1(featureOpts, function (opt, name) {
  49893. featureNames.push(name);
  49894. });
  49895. (new DataDiffer(this._featureNames || [], featureNames))
  49896. .add(processFeature)
  49897. .update(processFeature)
  49898. .remove(curry(processFeature, null))
  49899. .execute();
  49900. // Keep for diff.
  49901. this._featureNames = featureNames;
  49902. function processFeature(newIndex, oldIndex) {
  49903. var featureName = featureNames[newIndex];
  49904. var oldName = featureNames[oldIndex];
  49905. var featureOpt = featureOpts[featureName];
  49906. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  49907. var feature;
  49908. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  49909. if (payload && payload.newTitle != null) {
  49910. featureOpt.title = payload.newTitle;
  49911. }
  49912. if (featureName && !oldName) { // Create
  49913. if (isUserFeatureName(featureName)) {
  49914. feature = {
  49915. model: featureModel,
  49916. onclick: featureModel.option.onclick,
  49917. featureName: featureName
  49918. };
  49919. }
  49920. else {
  49921. var Feature = get$1(featureName);
  49922. if (!Feature) {
  49923. return;
  49924. }
  49925. feature = new Feature(featureModel, ecModel, api);
  49926. }
  49927. features[featureName] = feature;
  49928. }
  49929. else {
  49930. feature = features[oldName];
  49931. // If feature does not exsit.
  49932. if (!feature) {
  49933. return;
  49934. }
  49935. feature.model = featureModel;
  49936. feature.ecModel = ecModel;
  49937. feature.api = api;
  49938. }
  49939. if (!featureName && oldName) {
  49940. feature.dispose && feature.dispose(ecModel, api);
  49941. return;
  49942. }
  49943. if (!featureModel.get('show') || feature.unusable) {
  49944. feature.remove && feature.remove(ecModel, api);
  49945. return;
  49946. }
  49947. createIconPaths(featureModel, feature, featureName);
  49948. featureModel.setIconStatus = function (iconName, status) {
  49949. var option = this.option;
  49950. var iconPaths = this.iconPaths;
  49951. option.iconStatus = option.iconStatus || {};
  49952. option.iconStatus[iconName] = status;
  49953. // FIXME
  49954. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  49955. };
  49956. if (feature.render) {
  49957. feature.render(featureModel, ecModel, api, payload);
  49958. }
  49959. }
  49960. function createIconPaths(featureModel, feature, featureName) {
  49961. var iconStyleModel = featureModel.getModel('iconStyle');
  49962. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  49963. // If one feature has mutiple icon. they are orginaized as
  49964. // {
  49965. // icon: {
  49966. // foo: '',
  49967. // bar: ''
  49968. // },
  49969. // title: {
  49970. // foo: '',
  49971. // bar: ''
  49972. // }
  49973. // }
  49974. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  49975. var titles = featureModel.get('title') || {};
  49976. if (typeof icons === 'string') {
  49977. var icon = icons;
  49978. var title = titles;
  49979. icons = {};
  49980. titles = {};
  49981. icons[featureName] = icon;
  49982. titles[featureName] = title;
  49983. }
  49984. var iconPaths = featureModel.iconPaths = {};
  49985. each$1(icons, function (iconStr, iconName) {
  49986. var path = createIcon(
  49987. iconStr,
  49988. {},
  49989. {
  49990. x: -itemSize / 2,
  49991. y: -itemSize / 2,
  49992. width: itemSize,
  49993. height: itemSize
  49994. }
  49995. );
  49996. path.setStyle(iconStyleModel.getItemStyle());
  49997. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  49998. // Text position calculation
  49999. path.setStyle({
  50000. text: titles[iconName],
  50001. textAlign: iconStyleEmphasisModel.get('textAlign'),
  50002. textBorderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  50003. textPadding: iconStyleEmphasisModel.get('textPadding'),
  50004. textFill: null
  50005. });
  50006. var tooltipModel = toolboxModel.getModel('tooltip');
  50007. if (tooltipModel && tooltipModel.get('show')) {
  50008. path.attr('tooltip', extend({
  50009. content: titles[iconName],
  50010. formatter: tooltipModel.get('formatter', true)
  50011. || function () {
  50012. return titles[iconName];
  50013. },
  50014. formatterParams: {
  50015. componentType: 'toolbox',
  50016. name: iconName,
  50017. title: titles[iconName],
  50018. $vars: ['name', 'title']
  50019. },
  50020. position: tooltipModel.get('position', true) || 'bottom'
  50021. }, tooltipModel.option));
  50022. }
  50023. setHoverStyle(path);
  50024. if (toolboxModel.get('showTitle')) {
  50025. path.__title = titles[iconName];
  50026. path.on('mouseover', function () {
  50027. // Should not reuse above hoverStyle, which might be modified.
  50028. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  50029. var defaultTextPosition = toolboxModel.get('orient') === 'vertical'
  50030. ? (toolboxModel.get('right') == null ? 'right' : 'left')
  50031. : (toolboxModel.get('bottom') == null ? 'bottom' : 'top');
  50032. path.setStyle({
  50033. textFill: iconStyleEmphasisModel.get('textFill')
  50034. || hoverStyle.fill || hoverStyle.stroke || '#000',
  50035. textBackgroundColor: iconStyleEmphasisModel.get('textBackgroundColor'),
  50036. textPosition: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  50037. });
  50038. })
  50039. .on('mouseout', function () {
  50040. path.setStyle({
  50041. textFill: null,
  50042. textBackgroundColor: null
  50043. });
  50044. });
  50045. }
  50046. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  50047. group.add(path);
  50048. path.on('click', bind(
  50049. feature.onclick, feature, ecModel, api, iconName
  50050. ));
  50051. iconPaths[iconName] = path;
  50052. });
  50053. }
  50054. layout$2(group, toolboxModel, api);
  50055. // Render background after group is layout
  50056. // FIXME
  50057. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  50058. // Adjust icon title positions to avoid them out of screen
  50059. group.eachChild(function (icon) {
  50060. var titleText = icon.__title;
  50061. var hoverStyle = icon.hoverStyle;
  50062. // May be background element
  50063. if (hoverStyle && titleText) {
  50064. var rect = getBoundingRect(
  50065. titleText, makeFont(hoverStyle)
  50066. );
  50067. var offsetX = icon.position[0] + group.position[0];
  50068. var offsetY = icon.position[1] + group.position[1] + itemSize;
  50069. var needPutOnTop = false;
  50070. if (offsetY + rect.height > api.getHeight()) {
  50071. hoverStyle.textPosition = 'top';
  50072. needPutOnTop = true;
  50073. }
  50074. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  50075. if (offsetX + rect.width / 2 > api.getWidth()) {
  50076. hoverStyle.textPosition = ['100%', topOffset];
  50077. hoverStyle.textAlign = 'right';
  50078. }
  50079. else if (offsetX - rect.width / 2 < 0) {
  50080. hoverStyle.textPosition = [0, topOffset];
  50081. hoverStyle.textAlign = 'left';
  50082. }
  50083. }
  50084. });
  50085. },
  50086. updateView: function (toolboxModel, ecModel, api, payload) {
  50087. each$1(this._features, function (feature) {
  50088. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  50089. });
  50090. },
  50091. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  50092. // zrUtil.each(this._features, function (feature) {
  50093. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  50094. // });
  50095. // },
  50096. remove: function (ecModel, api) {
  50097. each$1(this._features, function (feature) {
  50098. feature.remove && feature.remove(ecModel, api);
  50099. });
  50100. this.group.removeAll();
  50101. },
  50102. dispose: function (ecModel, api) {
  50103. each$1(this._features, function (feature) {
  50104. feature.dispose && feature.dispose(ecModel, api);
  50105. });
  50106. }
  50107. });
  50108. function isUserFeatureName(featureName) {
  50109. return featureName.indexOf('my') === 0;
  50110. }
  50111. /*
  50112. * Licensed to the Apache Software Foundation (ASF) under one
  50113. * or more contributor license agreements. See the NOTICE file
  50114. * distributed with this work for additional information
  50115. * regarding copyright ownership. The ASF licenses this file
  50116. * to you under the Apache License, Version 2.0 (the
  50117. * "License"); you may not use this file except in compliance
  50118. * with the License. You may obtain a copy of the License at
  50119. *
  50120. * http://www.apache.org/licenses/LICENSE-2.0
  50121. *
  50122. * Unless required by applicable law or agreed to in writing,
  50123. * software distributed under the License is distributed on an
  50124. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50125. * KIND, either express or implied. See the License for the
  50126. * specific language governing permissions and limitations
  50127. * under the License.
  50128. */
  50129. /* global Uint8Array */
  50130. var saveAsImageLang = lang.toolbox.saveAsImage;
  50131. function SaveAsImage(model) {
  50132. this.model = model;
  50133. }
  50134. SaveAsImage.defaultOption = {
  50135. show: true,
  50136. 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',
  50137. title: saveAsImageLang.title,
  50138. type: 'png',
  50139. // Default use option.backgroundColor
  50140. // backgroundColor: '#fff',
  50141. connectedBackgroundColor: '#fff',
  50142. name: '',
  50143. excludeComponents: ['toolbox'],
  50144. pixelRatio: 1,
  50145. lang: saveAsImageLang.lang.slice()
  50146. };
  50147. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  50148. var proto$2 = SaveAsImage.prototype;
  50149. proto$2.onclick = function (ecModel, api) {
  50150. var model = this.model;
  50151. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  50152. var type = model.get('type', true) || 'png';
  50153. var url = api.getConnectedDataURL({
  50154. type: type,
  50155. backgroundColor: model.get('backgroundColor', true)
  50156. || ecModel.get('backgroundColor') || '#fff',
  50157. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  50158. excludeComponents: model.get('excludeComponents'),
  50159. pixelRatio: model.get('pixelRatio')
  50160. });
  50161. // Chrome and Firefox
  50162. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  50163. var $a = document.createElement('a');
  50164. $a.download = title + '.' + type;
  50165. $a.target = '_blank';
  50166. $a.href = url;
  50167. var evt = new MouseEvent('click', {
  50168. view: window,
  50169. bubbles: true,
  50170. cancelable: false
  50171. });
  50172. $a.dispatchEvent(evt);
  50173. }
  50174. // IE
  50175. else {
  50176. if (window.navigator.msSaveOrOpenBlob) {
  50177. var bstr = atob(url.split(',')[1]);
  50178. var n = bstr.length;
  50179. var u8arr = new Uint8Array(n);
  50180. while (n--) {
  50181. u8arr[n] = bstr.charCodeAt(n);
  50182. }
  50183. var blob = new Blob([u8arr]);
  50184. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  50185. }
  50186. else {
  50187. var lang$$1 = model.get('lang');
  50188. var html = ''
  50189. + '<body style="margin:0;">'
  50190. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  50191. + '</body>';
  50192. var tab = window.open();
  50193. tab.document.write(html);
  50194. }
  50195. }
  50196. };
  50197. register$2(
  50198. 'saveAsImage', SaveAsImage
  50199. );
  50200. /*
  50201. * Licensed to the Apache Software Foundation (ASF) under one
  50202. * or more contributor license agreements. See the NOTICE file
  50203. * distributed with this work for additional information
  50204. * regarding copyright ownership. The ASF licenses this file
  50205. * to you under the Apache License, Version 2.0 (the
  50206. * "License"); you may not use this file except in compliance
  50207. * with the License. You may obtain a copy of the License at
  50208. *
  50209. * http://www.apache.org/licenses/LICENSE-2.0
  50210. *
  50211. * Unless required by applicable law or agreed to in writing,
  50212. * software distributed under the License is distributed on an
  50213. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50214. * KIND, either express or implied. See the License for the
  50215. * specific language governing permissions and limitations
  50216. * under the License.
  50217. */
  50218. var magicTypeLang = lang.toolbox.magicType;
  50219. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  50220. function MagicType(model) {
  50221. this.model = model;
  50222. }
  50223. MagicType.defaultOption = {
  50224. show: true,
  50225. type: [],
  50226. // Icon group
  50227. icon: {
  50228. /* eslint-disable */
  50229. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  50230. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  50231. 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
  50232. /* eslint-enable */
  50233. },
  50234. // `line`, `bar`, `stack`, `tiled`
  50235. title: clone(magicTypeLang.title),
  50236. option: {},
  50237. seriesIndex: {}
  50238. };
  50239. var proto$3 = MagicType.prototype;
  50240. proto$3.getIcons = function () {
  50241. var model = this.model;
  50242. var availableIcons = model.get('icon');
  50243. var icons = {};
  50244. each$1(model.get('type'), function (type) {
  50245. if (availableIcons[type]) {
  50246. icons[type] = availableIcons[type];
  50247. }
  50248. });
  50249. return icons;
  50250. };
  50251. var seriesOptGenreator = {
  50252. 'line': function (seriesType, seriesId, seriesModel, model) {
  50253. if (seriesType === 'bar') {
  50254. return merge({
  50255. id: seriesId,
  50256. type: 'line',
  50257. // Preserve data related option
  50258. data: seriesModel.get('data'),
  50259. stack: seriesModel.get('stack'),
  50260. markPoint: seriesModel.get('markPoint'),
  50261. markLine: seriesModel.get('markLine')
  50262. }, model.get('option.line') || {}, true);
  50263. }
  50264. },
  50265. 'bar': function (seriesType, seriesId, seriesModel, model) {
  50266. if (seriesType === 'line') {
  50267. return merge({
  50268. id: seriesId,
  50269. type: 'bar',
  50270. // Preserve data related option
  50271. data: seriesModel.get('data'),
  50272. stack: seriesModel.get('stack'),
  50273. markPoint: seriesModel.get('markPoint'),
  50274. markLine: seriesModel.get('markLine')
  50275. }, model.get('option.bar') || {}, true);
  50276. }
  50277. },
  50278. 'stack': function (seriesType, seriesId, seriesModel, model) {
  50279. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  50280. if (seriesType === 'line' || seriesType === 'bar') {
  50281. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  50282. return merge({
  50283. id: seriesId,
  50284. stack: isStack ? '' : INNER_STACK_KEYWORD
  50285. }, model.get('option.stack') || {}, true);
  50286. }
  50287. }
  50288. };
  50289. var radioTypes = [
  50290. ['line', 'bar'],
  50291. ['stack']
  50292. ];
  50293. proto$3.onclick = function (ecModel, api, type) {
  50294. var model = this.model;
  50295. var seriesIndex = model.get('seriesIndex.' + type);
  50296. // Not supported magicType
  50297. if (!seriesOptGenreator[type]) {
  50298. return;
  50299. }
  50300. var newOption = {
  50301. series: []
  50302. };
  50303. var generateNewSeriesTypes = function (seriesModel) {
  50304. var seriesType = seriesModel.subType;
  50305. var seriesId = seriesModel.id;
  50306. var newSeriesOpt = seriesOptGenreator[type](
  50307. seriesType, seriesId, seriesModel, model
  50308. );
  50309. if (newSeriesOpt) {
  50310. // PENDING If merge original option?
  50311. defaults(newSeriesOpt, seriesModel.option);
  50312. newOption.series.push(newSeriesOpt);
  50313. }
  50314. // Modify boundaryGap
  50315. var coordSys = seriesModel.coordinateSystem;
  50316. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  50317. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  50318. if (categoryAxis) {
  50319. var axisDim = categoryAxis.dim;
  50320. var axisType = axisDim + 'Axis';
  50321. var axisModel = ecModel.queryComponents({
  50322. mainType: axisType,
  50323. index: seriesModel.get(name + 'Index'),
  50324. id: seriesModel.get(name + 'Id')
  50325. })[0];
  50326. var axisIndex = axisModel.componentIndex;
  50327. newOption[axisType] = newOption[axisType] || [];
  50328. for (var i = 0; i <= axisIndex; i++) {
  50329. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  50330. }
  50331. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  50332. }
  50333. }
  50334. };
  50335. each$1(radioTypes, function (radio) {
  50336. if (indexOf(radio, type) >= 0) {
  50337. each$1(radio, function (item) {
  50338. model.setIconStatus(item, 'normal');
  50339. });
  50340. }
  50341. });
  50342. model.setIconStatus(type, 'emphasis');
  50343. ecModel.eachComponent(
  50344. {
  50345. mainType: 'series',
  50346. query: seriesIndex == null ? null : {
  50347. seriesIndex: seriesIndex
  50348. }
  50349. }, generateNewSeriesTypes
  50350. );
  50351. var newTitle;
  50352. // Change title of stack
  50353. if (type === 'stack') {
  50354. var isStack = newOption.series && newOption.series[0] && newOption.series[0].stack === INNER_STACK_KEYWORD;
  50355. newTitle = isStack
  50356. ? merge({ stack: magicTypeLang.title.tiled }, magicTypeLang.title)
  50357. : clone(magicTypeLang.title);
  50358. }
  50359. api.dispatchAction({
  50360. type: 'changeMagicType',
  50361. currentType: type,
  50362. newOption: newOption,
  50363. newTitle: newTitle
  50364. });
  50365. };
  50366. registerAction({
  50367. type: 'changeMagicType',
  50368. event: 'magicTypeChanged',
  50369. update: 'prepareAndUpdate'
  50370. }, function (payload, ecModel) {
  50371. ecModel.mergeOption(payload.newOption);
  50372. });
  50373. register$2('magicType', MagicType);
  50374. /*
  50375. * Licensed to the Apache Software Foundation (ASF) under one
  50376. * or more contributor license agreements. See the NOTICE file
  50377. * distributed with this work for additional information
  50378. * regarding copyright ownership. The ASF licenses this file
  50379. * to you under the Apache License, Version 2.0 (the
  50380. * "License"); you may not use this file except in compliance
  50381. * with the License. You may obtain a copy of the License at
  50382. *
  50383. * http://www.apache.org/licenses/LICENSE-2.0
  50384. *
  50385. * Unless required by applicable law or agreed to in writing,
  50386. * software distributed under the License is distributed on an
  50387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50388. * KIND, either express or implied. See the License for the
  50389. * specific language governing permissions and limitations
  50390. * under the License.
  50391. */
  50392. var dataViewLang = lang.toolbox.dataView;
  50393. var BLOCK_SPLITER = new Array(60).join('-');
  50394. var ITEM_SPLITER = '\t';
  50395. /**
  50396. * Group series into two types
  50397. * 1. on category axis, like line, bar
  50398. * 2. others, like scatter, pie
  50399. * @param {module:echarts/model/Global} ecModel
  50400. * @return {Object}
  50401. * @inner
  50402. */
  50403. function groupSeries(ecModel) {
  50404. var seriesGroupByCategoryAxis = {};
  50405. var otherSeries = [];
  50406. var meta = [];
  50407. ecModel.eachRawSeries(function (seriesModel) {
  50408. var coordSys = seriesModel.coordinateSystem;
  50409. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  50410. var baseAxis = coordSys.getBaseAxis();
  50411. if (baseAxis.type === 'category') {
  50412. var key = baseAxis.dim + '_' + baseAxis.index;
  50413. if (!seriesGroupByCategoryAxis[key]) {
  50414. seriesGroupByCategoryAxis[key] = {
  50415. categoryAxis: baseAxis,
  50416. valueAxis: coordSys.getOtherAxis(baseAxis),
  50417. series: []
  50418. };
  50419. meta.push({
  50420. axisDim: baseAxis.dim,
  50421. axisIndex: baseAxis.index
  50422. });
  50423. }
  50424. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  50425. }
  50426. else {
  50427. otherSeries.push(seriesModel);
  50428. }
  50429. }
  50430. else {
  50431. otherSeries.push(seriesModel);
  50432. }
  50433. });
  50434. return {
  50435. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  50436. other: otherSeries,
  50437. meta: meta
  50438. };
  50439. }
  50440. /**
  50441. * Assemble content of series on cateogory axis
  50442. * @param {Array.<module:echarts/model/Series>} series
  50443. * @return {string}
  50444. * @inner
  50445. */
  50446. function assembleSeriesWithCategoryAxis(series) {
  50447. var tables = [];
  50448. each$1(series, function (group, key) {
  50449. var categoryAxis = group.categoryAxis;
  50450. var valueAxis = group.valueAxis;
  50451. var valueAxisDim = valueAxis.dim;
  50452. var headers = [' '].concat(map(group.series, function (series) {
  50453. return series.name;
  50454. }));
  50455. var columns = [categoryAxis.model.getCategories()];
  50456. each$1(group.series, function (series) {
  50457. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  50458. return val;
  50459. }));
  50460. });
  50461. // Assemble table content
  50462. var lines = [headers.join(ITEM_SPLITER)];
  50463. for (var i = 0; i < columns[0].length; i++) {
  50464. var items = [];
  50465. for (var j = 0; j < columns.length; j++) {
  50466. items.push(columns[j][i]);
  50467. }
  50468. lines.push(items.join(ITEM_SPLITER));
  50469. }
  50470. tables.push(lines.join('\n'));
  50471. });
  50472. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  50473. }
  50474. /**
  50475. * Assemble content of other series
  50476. * @param {Array.<module:echarts/model/Series>} series
  50477. * @return {string}
  50478. * @inner
  50479. */
  50480. function assembleOtherSeries(series) {
  50481. return map(series, function (series) {
  50482. var data = series.getRawData();
  50483. var lines = [series.name];
  50484. var vals = [];
  50485. data.each(data.dimensions, function () {
  50486. var argLen = arguments.length;
  50487. var dataIndex = arguments[argLen - 1];
  50488. var name = data.getName(dataIndex);
  50489. for (var i = 0; i < argLen - 1; i++) {
  50490. vals[i] = arguments[i];
  50491. }
  50492. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  50493. });
  50494. return lines.join('\n');
  50495. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  50496. }
  50497. /**
  50498. * @param {module:echarts/model/Global}
  50499. * @return {Object}
  50500. * @inner
  50501. */
  50502. function getContentFromModel(ecModel) {
  50503. var result = groupSeries(ecModel);
  50504. return {
  50505. value: filter([
  50506. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  50507. assembleOtherSeries(result.other)
  50508. ], function (str) {
  50509. return str.replace(/[\n\t\s]/g, '');
  50510. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  50511. meta: result.meta
  50512. };
  50513. }
  50514. function trim$1(str) {
  50515. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  50516. }
  50517. /**
  50518. * If a block is tsv format
  50519. */
  50520. function isTSVFormat(block) {
  50521. // Simple method to find out if a block is tsv format
  50522. var firstLine = block.slice(0, block.indexOf('\n'));
  50523. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  50524. return true;
  50525. }
  50526. }
  50527. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  50528. /**
  50529. * @param {string} tsv
  50530. * @return {Object}
  50531. */
  50532. function parseTSVContents(tsv) {
  50533. var tsvLines = tsv.split(/\n+/g);
  50534. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  50535. var categories = [];
  50536. var series = map(headers, function (header) {
  50537. return {
  50538. name: header,
  50539. data: []
  50540. };
  50541. });
  50542. for (var i = 0; i < tsvLines.length; i++) {
  50543. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  50544. categories.push(items.shift());
  50545. for (var j = 0; j < items.length; j++) {
  50546. series[j] && (series[j].data[i] = items[j]);
  50547. }
  50548. }
  50549. return {
  50550. series: series,
  50551. categories: categories
  50552. };
  50553. }
  50554. /**
  50555. * @param {string} str
  50556. * @return {Array.<Object>}
  50557. * @inner
  50558. */
  50559. function parseListContents(str) {
  50560. var lines = str.split(/\n+/g);
  50561. var seriesName = trim$1(lines.shift());
  50562. var data = [];
  50563. for (var i = 0; i < lines.length; i++) {
  50564. var items = trim$1(lines[i]).split(itemSplitRegex);
  50565. var name = '';
  50566. var value;
  50567. var hasName = false;
  50568. if (isNaN(items[0])) { // First item is name
  50569. hasName = true;
  50570. name = items[0];
  50571. items = items.slice(1);
  50572. data[i] = {
  50573. name: name,
  50574. value: []
  50575. };
  50576. value = data[i].value;
  50577. }
  50578. else {
  50579. value = data[i] = [];
  50580. }
  50581. for (var j = 0; j < items.length; j++) {
  50582. value.push(+items[j]);
  50583. }
  50584. if (value.length === 1) {
  50585. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  50586. }
  50587. }
  50588. return {
  50589. name: seriesName,
  50590. data: data
  50591. };
  50592. }
  50593. /**
  50594. * @param {string} str
  50595. * @param {Array.<Object>} blockMetaList
  50596. * @return {Object}
  50597. * @inner
  50598. */
  50599. function parseContents(str, blockMetaList) {
  50600. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  50601. var newOption = {
  50602. series: []
  50603. };
  50604. each$1(blocks, function (block, idx) {
  50605. if (isTSVFormat(block)) {
  50606. var result = parseTSVContents(block);
  50607. var blockMeta = blockMetaList[idx];
  50608. var axisKey = blockMeta.axisDim + 'Axis';
  50609. if (blockMeta) {
  50610. newOption[axisKey] = newOption[axisKey] || [];
  50611. newOption[axisKey][blockMeta.axisIndex] = {
  50612. data: result.categories
  50613. };
  50614. newOption.series = newOption.series.concat(result.series);
  50615. }
  50616. }
  50617. else {
  50618. var result = parseListContents(block);
  50619. newOption.series.push(result);
  50620. }
  50621. });
  50622. return newOption;
  50623. }
  50624. /**
  50625. * @alias {module:echarts/component/toolbox/feature/DataView}
  50626. * @constructor
  50627. * @param {module:echarts/model/Model} model
  50628. */
  50629. function DataView(model) {
  50630. this._dom = null;
  50631. this.model = model;
  50632. }
  50633. DataView.defaultOption = {
  50634. show: true,
  50635. readOnly: false,
  50636. optionToContent: null,
  50637. contentToOption: null,
  50638. 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',
  50639. title: clone(dataViewLang.title),
  50640. lang: clone(dataViewLang.lang),
  50641. backgroundColor: '#fff',
  50642. textColor: '#000',
  50643. textareaColor: '#fff',
  50644. textareaBorderColor: '#333',
  50645. buttonColor: '#c23531',
  50646. buttonTextColor: '#fff'
  50647. };
  50648. DataView.prototype.onclick = function (ecModel, api) {
  50649. var container = api.getDom();
  50650. var model = this.model;
  50651. if (this._dom) {
  50652. container.removeChild(this._dom);
  50653. }
  50654. var root = document.createElement('div');
  50655. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  50656. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  50657. // Create elements
  50658. var header = document.createElement('h4');
  50659. var lang$$1 = model.get('lang') || [];
  50660. header.innerHTML = lang$$1[0] || model.get('title');
  50661. header.style.cssText = 'margin: 10px 20px;';
  50662. header.style.color = model.get('textColor');
  50663. var viewMain = document.createElement('div');
  50664. var textarea = document.createElement('textarea');
  50665. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  50666. var optionToContent = model.get('optionToContent');
  50667. var contentToOption = model.get('contentToOption');
  50668. var result = getContentFromModel(ecModel);
  50669. if (typeof optionToContent === 'function') {
  50670. var htmlOrDom = optionToContent(api.getOption());
  50671. if (typeof htmlOrDom === 'string') {
  50672. viewMain.innerHTML = htmlOrDom;
  50673. }
  50674. else if (isDom(htmlOrDom)) {
  50675. viewMain.appendChild(htmlOrDom);
  50676. }
  50677. }
  50678. else {
  50679. // Use default textarea
  50680. viewMain.appendChild(textarea);
  50681. textarea.readOnly = model.get('readOnly');
  50682. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  50683. textarea.style.color = model.get('textColor');
  50684. textarea.style.borderColor = model.get('textareaBorderColor');
  50685. textarea.style.backgroundColor = model.get('textareaColor');
  50686. textarea.value = result.value;
  50687. }
  50688. var blockMetaList = result.meta;
  50689. var buttonContainer = document.createElement('div');
  50690. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  50691. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  50692. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  50693. var closeButton = document.createElement('div');
  50694. var refreshButton = document.createElement('div');
  50695. buttonStyle += ';background-color:' + model.get('buttonColor');
  50696. buttonStyle += ';color:' + model.get('buttonTextColor');
  50697. var self = this;
  50698. function close() {
  50699. container.removeChild(root);
  50700. self._dom = null;
  50701. }
  50702. addEventListener(closeButton, 'click', close);
  50703. addEventListener(refreshButton, 'click', function () {
  50704. var newOption;
  50705. try {
  50706. if (typeof contentToOption === 'function') {
  50707. newOption = contentToOption(viewMain, api.getOption());
  50708. }
  50709. else {
  50710. newOption = parseContents(textarea.value, blockMetaList);
  50711. }
  50712. }
  50713. catch (e) {
  50714. close();
  50715. throw new Error('Data view format error ' + e);
  50716. }
  50717. if (newOption) {
  50718. api.dispatchAction({
  50719. type: 'changeDataView',
  50720. newOption: newOption
  50721. });
  50722. }
  50723. close();
  50724. });
  50725. closeButton.innerHTML = lang$$1[1];
  50726. refreshButton.innerHTML = lang$$1[2];
  50727. refreshButton.style.cssText = buttonStyle;
  50728. closeButton.style.cssText = buttonStyle;
  50729. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  50730. buttonContainer.appendChild(closeButton);
  50731. root.appendChild(header);
  50732. root.appendChild(viewMain);
  50733. root.appendChild(buttonContainer);
  50734. viewMain.style.height = (container.clientHeight - 80) + 'px';
  50735. container.appendChild(root);
  50736. this._dom = root;
  50737. };
  50738. DataView.prototype.remove = function (ecModel, api) {
  50739. this._dom && api.getDom().removeChild(this._dom);
  50740. };
  50741. DataView.prototype.dispose = function (ecModel, api) {
  50742. this.remove(ecModel, api);
  50743. };
  50744. /**
  50745. * @inner
  50746. */
  50747. function tryMergeDataOption(newData, originalData) {
  50748. return map(newData, function (newVal, idx) {
  50749. var original = originalData && originalData[idx];
  50750. if (isObject$1(original) && !isArray(original)) {
  50751. if (isObject$1(newVal) && !isArray(newVal)) {
  50752. newVal = newVal.value;
  50753. }
  50754. // Original data has option
  50755. return defaults({
  50756. value: newVal
  50757. }, original);
  50758. }
  50759. else {
  50760. return newVal;
  50761. }
  50762. });
  50763. }
  50764. register$2('dataView', DataView);
  50765. registerAction({
  50766. type: 'changeDataView',
  50767. event: 'dataViewChanged',
  50768. update: 'prepareAndUpdate'
  50769. }, function (payload, ecModel) {
  50770. var newSeriesOptList = [];
  50771. each$1(payload.newOption.series, function (seriesOpt) {
  50772. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  50773. if (!seriesModel) {
  50774. // New created series
  50775. // Geuss the series type
  50776. newSeriesOptList.push(extend({
  50777. // Default is scatter
  50778. type: 'scatter'
  50779. }, seriesOpt));
  50780. }
  50781. else {
  50782. var originalData = seriesModel.get('data');
  50783. newSeriesOptList.push({
  50784. name: seriesOpt.name,
  50785. data: tryMergeDataOption(seriesOpt.data, originalData)
  50786. });
  50787. }
  50788. });
  50789. ecModel.mergeOption(defaults({
  50790. series: newSeriesOptList
  50791. }, payload.newOption));
  50792. });
  50793. /*
  50794. * Licensed to the Apache Software Foundation (ASF) under one
  50795. * or more contributor license agreements. See the NOTICE file
  50796. * distributed with this work for additional information
  50797. * regarding copyright ownership. The ASF licenses this file
  50798. * to you under the Apache License, Version 2.0 (the
  50799. * "License"); you may not use this file except in compliance
  50800. * with the License. You may obtain a copy of the License at
  50801. *
  50802. * http://www.apache.org/licenses/LICENSE-2.0
  50803. *
  50804. * Unless required by applicable law or agreed to in writing,
  50805. * software distributed under the License is distributed on an
  50806. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50807. * KIND, either express or implied. See the License for the
  50808. * specific language governing permissions and limitations
  50809. * under the License.
  50810. */
  50811. var curry$5 = curry;
  50812. var each$16 = each$1;
  50813. var map$2 = map;
  50814. var mathMin$5 = Math.min;
  50815. var mathMax$5 = Math.max;
  50816. var mathPow$2 = Math.pow;
  50817. var COVER_Z = 10000;
  50818. var UNSELECT_THRESHOLD = 6;
  50819. var MIN_RESIZE_LINE_WIDTH = 6;
  50820. var MUTEX_RESOURCE_KEY = 'globalPan';
  50821. var DIRECTION_MAP = {
  50822. w: [0, 0],
  50823. e: [0, 1],
  50824. n: [1, 0],
  50825. s: [1, 1]
  50826. };
  50827. var CURSOR_MAP = {
  50828. w: 'ew',
  50829. e: 'ew',
  50830. n: 'ns',
  50831. s: 'ns',
  50832. ne: 'nesw',
  50833. sw: 'nesw',
  50834. nw: 'nwse',
  50835. se: 'nwse'
  50836. };
  50837. var DEFAULT_BRUSH_OPT = {
  50838. brushStyle: {
  50839. lineWidth: 2,
  50840. stroke: 'rgba(0,0,0,0.3)',
  50841. fill: 'rgba(0,0,0,0.1)'
  50842. },
  50843. transformable: true,
  50844. brushMode: 'single',
  50845. removeOnClick: false
  50846. };
  50847. var baseUID = 0;
  50848. /**
  50849. * @alias module:echarts/component/helper/BrushController
  50850. * @constructor
  50851. * @mixin {module:zrender/mixin/Eventful}
  50852. * @event module:echarts/component/helper/BrushController#brush
  50853. * params:
  50854. * areas: Array.<Array>, coord relates to container group,
  50855. * If no container specified, to global.
  50856. * opt {
  50857. * isEnd: boolean,
  50858. * removeOnClick: boolean
  50859. * }
  50860. *
  50861. * @param {module:zrender/zrender~ZRender} zr
  50862. */
  50863. function BrushController(zr) {
  50864. if (__DEV__) {
  50865. assert$1(zr);
  50866. }
  50867. Eventful.call(this);
  50868. /**
  50869. * @type {module:zrender/zrender~ZRender}
  50870. * @private
  50871. */
  50872. this._zr = zr;
  50873. /**
  50874. * @type {module:zrender/container/Group}
  50875. * @readOnly
  50876. */
  50877. this.group = new Group();
  50878. /**
  50879. * Only for drawing (after enabledBrush).
  50880. * 'line', 'rect', 'polygon' or false
  50881. * If passing false/null/undefined, disable brush.
  50882. * If passing 'auto', determined by panel.defaultBrushType
  50883. * @private
  50884. * @type {string}
  50885. */
  50886. this._brushType;
  50887. /**
  50888. * Only for drawing (after enabledBrush).
  50889. *
  50890. * @private
  50891. * @type {Object}
  50892. */
  50893. this._brushOption;
  50894. /**
  50895. * @private
  50896. * @type {Object}
  50897. */
  50898. this._panels;
  50899. /**
  50900. * @private
  50901. * @type {Array.<nubmer>}
  50902. */
  50903. this._track = [];
  50904. /**
  50905. * @private
  50906. * @type {boolean}
  50907. */
  50908. this._dragging;
  50909. /**
  50910. * @private
  50911. * @type {Array}
  50912. */
  50913. this._covers = [];
  50914. /**
  50915. * @private
  50916. * @type {moudule:zrender/container/Group}
  50917. */
  50918. this._creatingCover;
  50919. /**
  50920. * `true` means global panel
  50921. * @private
  50922. * @type {module:zrender/container/Group|boolean}
  50923. */
  50924. this._creatingPanel;
  50925. /**
  50926. * @private
  50927. * @type {boolean}
  50928. */
  50929. this._enableGlobalPan;
  50930. /**
  50931. * @private
  50932. * @type {boolean}
  50933. */
  50934. if (__DEV__) {
  50935. this._mounted;
  50936. }
  50937. /**
  50938. * @private
  50939. * @type {string}
  50940. */
  50941. this._uid = 'brushController_' + baseUID++;
  50942. /**
  50943. * @private
  50944. * @type {Object}
  50945. */
  50946. this._handlers = {};
  50947. each$16(pointerHandlers, function (handler, eventName) {
  50948. this._handlers[eventName] = bind(handler, this);
  50949. }, this);
  50950. }
  50951. BrushController.prototype = {
  50952. constructor: BrushController,
  50953. /**
  50954. * If set to null/undefined/false, select disabled.
  50955. * @param {Object} brushOption
  50956. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  50957. * If passing false/null/undefined, disable brush.
  50958. * If passing 'auto', determined by panel.defaultBrushType.
  50959. * ('auto' can not be used in global panel)
  50960. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  50961. * @param {boolean} [brushOption.transformable=true]
  50962. * @param {boolean} [brushOption.removeOnClick=false]
  50963. * @param {Object} [brushOption.brushStyle]
  50964. * @param {number} [brushOption.brushStyle.width]
  50965. * @param {number} [brushOption.brushStyle.lineWidth]
  50966. * @param {string} [brushOption.brushStyle.stroke]
  50967. * @param {string} [brushOption.brushStyle.fill]
  50968. * @param {number} [brushOption.z]
  50969. */
  50970. enableBrush: function (brushOption) {
  50971. if (__DEV__) {
  50972. assert$1(this._mounted);
  50973. }
  50974. this._brushType && doDisableBrush(this);
  50975. brushOption.brushType && doEnableBrush(this, brushOption);
  50976. return this;
  50977. },
  50978. /**
  50979. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  50980. * Each items: {
  50981. * panelId, // mandatory.
  50982. * clipPath, // mandatory. function.
  50983. * isTargetByCursor, // mandatory. function.
  50984. * defaultBrushType, // optional, only used when brushType is 'auto'.
  50985. * getLinearBrushOtherExtent, // optional. function.
  50986. * }
  50987. */
  50988. setPanels: function (panelOpts) {
  50989. if (panelOpts && panelOpts.length) {
  50990. var panels = this._panels = {};
  50991. each$1(panelOpts, function (panelOpts) {
  50992. panels[panelOpts.panelId] = clone(panelOpts);
  50993. });
  50994. }
  50995. else {
  50996. this._panels = null;
  50997. }
  50998. return this;
  50999. },
  51000. /**
  51001. * @param {Object} [opt]
  51002. * @return {boolean} [opt.enableGlobalPan=false]
  51003. */
  51004. mount: function (opt) {
  51005. opt = opt || {};
  51006. if (__DEV__) {
  51007. this._mounted = true; // should be at first.
  51008. }
  51009. this._enableGlobalPan = opt.enableGlobalPan;
  51010. var thisGroup = this.group;
  51011. this._zr.add(thisGroup);
  51012. thisGroup.attr({
  51013. position: opt.position || [0, 0],
  51014. rotation: opt.rotation || 0,
  51015. scale: opt.scale || [1, 1]
  51016. });
  51017. this._transform = thisGroup.getLocalTransform();
  51018. return this;
  51019. },
  51020. eachCover: function (cb, context) {
  51021. each$16(this._covers, cb, context);
  51022. },
  51023. /**
  51024. * Update covers.
  51025. * @param {Array.<Object>} brushOptionList Like:
  51026. * [
  51027. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  51028. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  51029. * ...
  51030. * ]
  51031. * `brushType` is required in each cover info. (can not be 'auto')
  51032. * `id` is not mandatory.
  51033. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  51034. * If brushOptionList is null/undefined, all covers removed.
  51035. */
  51036. updateCovers: function (brushOptionList) {
  51037. if (__DEV__) {
  51038. assert$1(this._mounted);
  51039. }
  51040. brushOptionList = map(brushOptionList, function (brushOption) {
  51041. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  51042. });
  51043. var tmpIdPrefix = '\0-brush-index-';
  51044. var oldCovers = this._covers;
  51045. var newCovers = this._covers = [];
  51046. var controller = this;
  51047. var creatingCover = this._creatingCover;
  51048. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  51049. .add(addOrUpdate)
  51050. .update(addOrUpdate)
  51051. .remove(remove)
  51052. .execute();
  51053. return this;
  51054. function getKey(brushOption, index) {
  51055. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  51056. + '-' + brushOption.brushType;
  51057. }
  51058. function oldGetKey(cover, index) {
  51059. return getKey(cover.__brushOption, index);
  51060. }
  51061. function addOrUpdate(newIndex, oldIndex) {
  51062. var newBrushOption = brushOptionList[newIndex];
  51063. // Consider setOption in event listener of brushSelect,
  51064. // where updating cover when creating should be forbiden.
  51065. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  51066. newCovers[newIndex] = oldCovers[oldIndex];
  51067. }
  51068. else {
  51069. var cover = newCovers[newIndex] = oldIndex != null
  51070. ? (
  51071. oldCovers[oldIndex].__brushOption = newBrushOption,
  51072. oldCovers[oldIndex]
  51073. )
  51074. : endCreating(controller, createCover(controller, newBrushOption));
  51075. updateCoverAfterCreation(controller, cover);
  51076. }
  51077. }
  51078. function remove(oldIndex) {
  51079. if (oldCovers[oldIndex] !== creatingCover) {
  51080. controller.group.remove(oldCovers[oldIndex]);
  51081. }
  51082. }
  51083. },
  51084. unmount: function () {
  51085. if (__DEV__) {
  51086. if (!this._mounted) {
  51087. return;
  51088. }
  51089. }
  51090. this.enableBrush(false);
  51091. // container may 'removeAll' outside.
  51092. clearCovers(this);
  51093. this._zr.remove(this.group);
  51094. if (__DEV__) {
  51095. this._mounted = false; // should be at last.
  51096. }
  51097. return this;
  51098. },
  51099. dispose: function () {
  51100. this.unmount();
  51101. this.off();
  51102. }
  51103. };
  51104. mixin(BrushController, Eventful);
  51105. function doEnableBrush(controller, brushOption) {
  51106. var zr = controller._zr;
  51107. // Consider roam, which takes globalPan too.
  51108. if (!controller._enableGlobalPan) {
  51109. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  51110. }
  51111. mountHandlers(zr, controller._handlers);
  51112. controller._brushType = brushOption.brushType;
  51113. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  51114. }
  51115. function doDisableBrush(controller) {
  51116. var zr = controller._zr;
  51117. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  51118. unmountHandlers(zr, controller._handlers);
  51119. controller._brushType = controller._brushOption = null;
  51120. }
  51121. function mountHandlers(zr, handlers) {
  51122. each$16(handlers, function (handler, eventName) {
  51123. zr.on(eventName, handler);
  51124. });
  51125. }
  51126. function unmountHandlers(zr, handlers) {
  51127. each$16(handlers, function (handler, eventName) {
  51128. zr.off(eventName, handler);
  51129. });
  51130. }
  51131. function createCover(controller, brushOption) {
  51132. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  51133. cover.__brushOption = brushOption;
  51134. updateZ$1(cover, brushOption);
  51135. controller.group.add(cover);
  51136. return cover;
  51137. }
  51138. function endCreating(controller, creatingCover) {
  51139. var coverRenderer = getCoverRenderer(creatingCover);
  51140. if (coverRenderer.endCreating) {
  51141. coverRenderer.endCreating(controller, creatingCover);
  51142. updateZ$1(creatingCover, creatingCover.__brushOption);
  51143. }
  51144. return creatingCover;
  51145. }
  51146. function updateCoverShape(controller, cover) {
  51147. var brushOption = cover.__brushOption;
  51148. getCoverRenderer(cover).updateCoverShape(
  51149. controller, cover, brushOption.range, brushOption
  51150. );
  51151. }
  51152. function updateZ$1(cover, brushOption) {
  51153. var z = brushOption.z;
  51154. z == null && (z = COVER_Z);
  51155. cover.traverse(function (el) {
  51156. el.z = z;
  51157. el.z2 = z; // Consider in given container.
  51158. });
  51159. }
  51160. function updateCoverAfterCreation(controller, cover) {
  51161. getCoverRenderer(cover).updateCommon(controller, cover);
  51162. updateCoverShape(controller, cover);
  51163. }
  51164. function getCoverRenderer(cover) {
  51165. return coverRenderers[cover.__brushOption.brushType];
  51166. }
  51167. // return target panel or `true` (means global panel)
  51168. function getPanelByPoint(controller, e, localCursorPoint) {
  51169. var panels = controller._panels;
  51170. if (!panels) {
  51171. return true; // Global panel
  51172. }
  51173. var panel;
  51174. var transform = controller._transform;
  51175. each$16(panels, function (pn) {
  51176. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  51177. });
  51178. return panel;
  51179. }
  51180. // Return a panel or true
  51181. function getPanelByCover(controller, cover) {
  51182. var panels = controller._panels;
  51183. if (!panels) {
  51184. return true; // Global panel
  51185. }
  51186. var panelId = cover.__brushOption.panelId;
  51187. // User may give cover without coord sys info,
  51188. // which is then treated as global panel.
  51189. return panelId != null ? panels[panelId] : true;
  51190. }
  51191. function clearCovers(controller) {
  51192. var covers = controller._covers;
  51193. var originalLength = covers.length;
  51194. each$16(covers, function (cover) {
  51195. controller.group.remove(cover);
  51196. }, controller);
  51197. covers.length = 0;
  51198. return !!originalLength;
  51199. }
  51200. function trigger$1(controller, opt) {
  51201. var areas = map$2(controller._covers, function (cover) {
  51202. var brushOption = cover.__brushOption;
  51203. var range = clone(brushOption.range);
  51204. return {
  51205. brushType: brushOption.brushType,
  51206. panelId: brushOption.panelId,
  51207. range: range
  51208. };
  51209. });
  51210. controller.trigger('brush', areas, {
  51211. isEnd: !!opt.isEnd,
  51212. removeOnClick: !!opt.removeOnClick
  51213. });
  51214. }
  51215. function shouldShowCover(controller) {
  51216. var track = controller._track;
  51217. if (!track.length) {
  51218. return false;
  51219. }
  51220. var p2 = track[track.length - 1];
  51221. var p1 = track[0];
  51222. var dx = p2[0] - p1[0];
  51223. var dy = p2[1] - p1[1];
  51224. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  51225. return dist > UNSELECT_THRESHOLD;
  51226. }
  51227. function getTrackEnds(track) {
  51228. var tail = track.length - 1;
  51229. tail < 0 && (tail = 0);
  51230. return [track[0], track[tail]];
  51231. }
  51232. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  51233. var cover = new Group();
  51234. cover.add(new Rect({
  51235. name: 'main',
  51236. style: makeStyle(brushOption),
  51237. silent: true,
  51238. draggable: true,
  51239. cursor: 'move',
  51240. drift: curry$5(doDrift, controller, cover, 'nswe'),
  51241. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51242. }));
  51243. each$16(
  51244. edgeNames,
  51245. function (name) {
  51246. cover.add(new Rect({
  51247. name: name,
  51248. style: {opacity: 0},
  51249. draggable: true,
  51250. silent: true,
  51251. invisible: true,
  51252. drift: curry$5(doDrift, controller, cover, name),
  51253. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51254. }));
  51255. }
  51256. );
  51257. return cover;
  51258. }
  51259. function updateBaseRect(controller, cover, localRange, brushOption) {
  51260. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  51261. var handleSize = mathMax$5(lineWidth, MIN_RESIZE_LINE_WIDTH);
  51262. var x = localRange[0][0];
  51263. var y = localRange[1][0];
  51264. var xa = x - lineWidth / 2;
  51265. var ya = y - lineWidth / 2;
  51266. var x2 = localRange[0][1];
  51267. var y2 = localRange[1][1];
  51268. var x2a = x2 - handleSize + lineWidth / 2;
  51269. var y2a = y2 - handleSize + lineWidth / 2;
  51270. var width = x2 - x;
  51271. var height = y2 - y;
  51272. var widtha = width + lineWidth;
  51273. var heighta = height + lineWidth;
  51274. updateRectShape(controller, cover, 'main', x, y, width, height);
  51275. if (brushOption.transformable) {
  51276. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  51277. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  51278. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  51279. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  51280. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  51281. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  51282. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  51283. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  51284. }
  51285. }
  51286. function updateCommon(controller, cover) {
  51287. var brushOption = cover.__brushOption;
  51288. var transformable = brushOption.transformable;
  51289. var mainEl = cover.childAt(0);
  51290. mainEl.useStyle(makeStyle(brushOption));
  51291. mainEl.attr({
  51292. silent: !transformable,
  51293. cursor: transformable ? 'move' : 'default'
  51294. });
  51295. each$16(
  51296. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  51297. function (name) {
  51298. var el = cover.childOfName(name);
  51299. var globalDir = getGlobalDirection(controller, name);
  51300. el && el.attr({
  51301. silent: !transformable,
  51302. invisible: !transformable,
  51303. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  51304. });
  51305. }
  51306. );
  51307. }
  51308. function updateRectShape(controller, cover, name, x, y, w, h) {
  51309. var el = cover.childOfName(name);
  51310. el && el.setShape(pointsToRect(
  51311. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  51312. ));
  51313. }
  51314. function makeStyle(brushOption) {
  51315. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  51316. }
  51317. function formatRectRange(x, y, x2, y2) {
  51318. var min = [mathMin$5(x, x2), mathMin$5(y, y2)];
  51319. var max = [mathMax$5(x, x2), mathMax$5(y, y2)];
  51320. return [
  51321. [min[0], max[0]], // x range
  51322. [min[1], max[1]] // y range
  51323. ];
  51324. }
  51325. function getTransform$1(controller) {
  51326. return getTransform(controller.group);
  51327. }
  51328. function getGlobalDirection(controller, localDirection) {
  51329. if (localDirection.length > 1) {
  51330. localDirection = localDirection.split('');
  51331. var globalDir = [
  51332. getGlobalDirection(controller, localDirection[0]),
  51333. getGlobalDirection(controller, localDirection[1])
  51334. ];
  51335. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  51336. return globalDir.join('');
  51337. }
  51338. else {
  51339. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  51340. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  51341. var globalDir = transformDirection(
  51342. map$$1[localDirection], getTransform$1(controller)
  51343. );
  51344. return inverseMap[globalDir];
  51345. }
  51346. }
  51347. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  51348. var brushOption = cover.__brushOption;
  51349. var rectRange = toRectRange(brushOption.range);
  51350. var localDelta = toLocalDelta(controller, dx, dy);
  51351. each$16(name.split(''), function (namePart) {
  51352. var ind = DIRECTION_MAP[namePart];
  51353. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  51354. });
  51355. brushOption.range = fromRectRange(formatRectRange(
  51356. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  51357. ));
  51358. updateCoverAfterCreation(controller, cover);
  51359. trigger$1(controller, {isEnd: false});
  51360. }
  51361. function driftPolygon(controller, cover, dx, dy, e) {
  51362. var range = cover.__brushOption.range;
  51363. var localDelta = toLocalDelta(controller, dx, dy);
  51364. each$16(range, function (point) {
  51365. point[0] += localDelta[0];
  51366. point[1] += localDelta[1];
  51367. });
  51368. updateCoverAfterCreation(controller, cover);
  51369. trigger$1(controller, {isEnd: false});
  51370. }
  51371. function toLocalDelta(controller, dx, dy) {
  51372. var thisGroup = controller.group;
  51373. var localD = thisGroup.transformCoordToLocal(dx, dy);
  51374. var localZero = thisGroup.transformCoordToLocal(0, 0);
  51375. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  51376. }
  51377. function clipByPanel(controller, cover, data) {
  51378. var panel = getPanelByCover(controller, cover);
  51379. return (panel && panel !== true)
  51380. ? panel.clipPath(data, controller._transform)
  51381. : clone(data);
  51382. }
  51383. function pointsToRect(points) {
  51384. var xmin = mathMin$5(points[0][0], points[1][0]);
  51385. var ymin = mathMin$5(points[0][1], points[1][1]);
  51386. var xmax = mathMax$5(points[0][0], points[1][0]);
  51387. var ymax = mathMax$5(points[0][1], points[1][1]);
  51388. return {
  51389. x: xmin,
  51390. y: ymin,
  51391. width: xmax - xmin,
  51392. height: ymax - ymin
  51393. };
  51394. }
  51395. function resetCursor(controller, e, localCursorPoint) {
  51396. if (
  51397. // Check active
  51398. !controller._brushType
  51399. // resetCursor should be always called when mouse is in zr area,
  51400. // but not called when mouse is out of zr area to avoid bad influence
  51401. // if `mousemove`, `mouseup` are triggered from `document` event.
  51402. || isOutsideZrArea(controller, e)
  51403. ) {
  51404. return;
  51405. }
  51406. var zr = controller._zr;
  51407. var covers = controller._covers;
  51408. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  51409. // Check whether in covers.
  51410. if (!controller._dragging) {
  51411. for (var i = 0; i < covers.length; i++) {
  51412. var brushOption = covers[i].__brushOption;
  51413. if (currPanel
  51414. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  51415. && coverRenderers[brushOption.brushType].contain(
  51416. covers[i], localCursorPoint[0], localCursorPoint[1]
  51417. )
  51418. ) {
  51419. // Use cursor style set on cover.
  51420. return;
  51421. }
  51422. }
  51423. }
  51424. currPanel && zr.setCursorStyle('crosshair');
  51425. }
  51426. function preventDefault(e) {
  51427. var rawE = e.event;
  51428. rawE.preventDefault && rawE.preventDefault();
  51429. }
  51430. function mainShapeContain(cover, x, y) {
  51431. return cover.childOfName('main').contain(x, y);
  51432. }
  51433. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  51434. var creatingCover = controller._creatingCover;
  51435. var panel = controller._creatingPanel;
  51436. var thisBrushOption = controller._brushOption;
  51437. var eventParams;
  51438. controller._track.push(localCursorPoint.slice());
  51439. if (shouldShowCover(controller) || creatingCover) {
  51440. if (panel && !creatingCover) {
  51441. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  51442. var brushOption = clone(thisBrushOption);
  51443. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  51444. brushOption.panelId = panel === true ? null : panel.panelId;
  51445. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  51446. controller._covers.push(creatingCover);
  51447. }
  51448. if (creatingCover) {
  51449. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  51450. var coverBrushOption = creatingCover.__brushOption;
  51451. coverBrushOption.range = coverRenderer.getCreatingRange(
  51452. clipByPanel(controller, creatingCover, controller._track)
  51453. );
  51454. if (isEnd) {
  51455. endCreating(controller, creatingCover);
  51456. coverRenderer.updateCommon(controller, creatingCover);
  51457. }
  51458. updateCoverShape(controller, creatingCover);
  51459. eventParams = {isEnd: isEnd};
  51460. }
  51461. }
  51462. else if (
  51463. isEnd
  51464. && thisBrushOption.brushMode === 'single'
  51465. && thisBrushOption.removeOnClick
  51466. ) {
  51467. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  51468. // But a single click do not clear covers, because user may have casual
  51469. // clicks (for example, click on other component and do not expect covers
  51470. // disappear).
  51471. // Only some cover removed, trigger action, but not every click trigger action.
  51472. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  51473. eventParams = {isEnd: isEnd, removeOnClick: true};
  51474. }
  51475. }
  51476. return eventParams;
  51477. }
  51478. function determineBrushType(brushType, panel) {
  51479. if (brushType === 'auto') {
  51480. if (__DEV__) {
  51481. assert$1(
  51482. panel && panel.defaultBrushType,
  51483. 'MUST have defaultBrushType when brushType is "atuo"'
  51484. );
  51485. }
  51486. return panel.defaultBrushType;
  51487. }
  51488. return brushType;
  51489. }
  51490. var pointerHandlers = {
  51491. mousedown: function (e) {
  51492. if (this._dragging) {
  51493. // In case some browser do not support globalOut,
  51494. // and release mose out side the browser.
  51495. handleDragEnd(this, e);
  51496. }
  51497. else if (!e.target || !e.target.draggable) {
  51498. preventDefault(e);
  51499. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  51500. this._creatingCover = null;
  51501. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  51502. if (panel) {
  51503. this._dragging = true;
  51504. this._track = [localCursorPoint.slice()];
  51505. }
  51506. }
  51507. },
  51508. mousemove: function (e) {
  51509. var x = e.offsetX;
  51510. var y = e.offsetY;
  51511. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  51512. resetCursor(this, e, localCursorPoint);
  51513. if (this._dragging) {
  51514. preventDefault(e);
  51515. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  51516. eventParams && trigger$1(this, eventParams);
  51517. }
  51518. },
  51519. mouseup: function (e) {
  51520. handleDragEnd(this, e);
  51521. }
  51522. };
  51523. function handleDragEnd(controller, e) {
  51524. if (controller._dragging) {
  51525. preventDefault(e);
  51526. var x = e.offsetX;
  51527. var y = e.offsetY;
  51528. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  51529. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  51530. controller._dragging = false;
  51531. controller._track = [];
  51532. controller._creatingCover = null;
  51533. // trigger event shoule be at final, after procedure will be nested.
  51534. eventParams && trigger$1(controller, eventParams);
  51535. }
  51536. }
  51537. function isOutsideZrArea(controller, x, y) {
  51538. var zr = controller._zr;
  51539. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  51540. }
  51541. /**
  51542. * key: brushType
  51543. * @type {Object}
  51544. */
  51545. var coverRenderers = {
  51546. lineX: getLineRenderer(0),
  51547. lineY: getLineRenderer(1),
  51548. rect: {
  51549. createCover: function (controller, brushOption) {
  51550. return createBaseRectCover(
  51551. curry$5(
  51552. driftRect,
  51553. function (range) {
  51554. return range;
  51555. },
  51556. function (range) {
  51557. return range;
  51558. }
  51559. ),
  51560. controller,
  51561. brushOption,
  51562. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  51563. );
  51564. },
  51565. getCreatingRange: function (localTrack) {
  51566. var ends = getTrackEnds(localTrack);
  51567. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  51568. },
  51569. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51570. updateBaseRect(controller, cover, localRange, brushOption);
  51571. },
  51572. updateCommon: updateCommon,
  51573. contain: mainShapeContain
  51574. },
  51575. polygon: {
  51576. createCover: function (controller, brushOption) {
  51577. var cover = new Group();
  51578. // Do not use graphic.Polygon because graphic.Polyline do not close the
  51579. // border of the shape when drawing, which is a better experience for user.
  51580. cover.add(new Polyline({
  51581. name: 'main',
  51582. style: makeStyle(brushOption),
  51583. silent: true
  51584. }));
  51585. return cover;
  51586. },
  51587. getCreatingRange: function (localTrack) {
  51588. return localTrack;
  51589. },
  51590. endCreating: function (controller, cover) {
  51591. cover.remove(cover.childAt(0));
  51592. // Use graphic.Polygon close the shape.
  51593. cover.add(new Polygon({
  51594. name: 'main',
  51595. draggable: true,
  51596. drift: curry$5(driftPolygon, controller, cover),
  51597. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51598. }));
  51599. },
  51600. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51601. cover.childAt(0).setShape({
  51602. points: clipByPanel(controller, cover, localRange)
  51603. });
  51604. },
  51605. updateCommon: updateCommon,
  51606. contain: mainShapeContain
  51607. }
  51608. };
  51609. function getLineRenderer(xyIndex) {
  51610. return {
  51611. createCover: function (controller, brushOption) {
  51612. return createBaseRectCover(
  51613. curry$5(
  51614. driftRect,
  51615. function (range) {
  51616. var rectRange = [range, [0, 100]];
  51617. xyIndex && rectRange.reverse();
  51618. return rectRange;
  51619. },
  51620. function (rectRange) {
  51621. return rectRange[xyIndex];
  51622. }
  51623. ),
  51624. controller,
  51625. brushOption,
  51626. [['w', 'e'], ['n', 's']][xyIndex]
  51627. );
  51628. },
  51629. getCreatingRange: function (localTrack) {
  51630. var ends = getTrackEnds(localTrack);
  51631. var min = mathMin$5(ends[0][xyIndex], ends[1][xyIndex]);
  51632. var max = mathMax$5(ends[0][xyIndex], ends[1][xyIndex]);
  51633. return [min, max];
  51634. },
  51635. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51636. var otherExtent;
  51637. // If brushWidth not specified, fit the panel.
  51638. var panel = getPanelByCover(controller, cover);
  51639. if (panel !== true && panel.getLinearBrushOtherExtent) {
  51640. otherExtent = panel.getLinearBrushOtherExtent(
  51641. xyIndex, controller._transform
  51642. );
  51643. }
  51644. else {
  51645. var zr = controller._zr;
  51646. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  51647. }
  51648. var rectRange = [localRange, otherExtent];
  51649. xyIndex && rectRange.reverse();
  51650. updateBaseRect(controller, cover, rectRange, brushOption);
  51651. },
  51652. updateCommon: updateCommon,
  51653. contain: mainShapeContain
  51654. };
  51655. }
  51656. /*
  51657. * Licensed to the Apache Software Foundation (ASF) under one
  51658. * or more contributor license agreements. See the NOTICE file
  51659. * distributed with this work for additional information
  51660. * regarding copyright ownership. The ASF licenses this file
  51661. * to you under the Apache License, Version 2.0 (the
  51662. * "License"); you may not use this file except in compliance
  51663. * with the License. You may obtain a copy of the License at
  51664. *
  51665. * http://www.apache.org/licenses/LICENSE-2.0
  51666. *
  51667. * Unless required by applicable law or agreed to in writing,
  51668. * software distributed under the License is distributed on an
  51669. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51670. * KIND, either express or implied. See the License for the
  51671. * specific language governing permissions and limitations
  51672. * under the License.
  51673. */
  51674. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  51675. /**
  51676. * Avoid that: mouse click on a elements that is over geo or graph,
  51677. * but roam is triggered.
  51678. */
  51679. function onIrrelevantElement(e, api, targetCoordSysModel) {
  51680. var model = api.getComponentByElement(e.topTarget);
  51681. // If model is axisModel, it works only if it is injected with coordinateSystem.
  51682. var coordSys = model && model.coordinateSystem;
  51683. return model
  51684. && model !== targetCoordSysModel
  51685. && !IRRELEVANT_EXCLUDES[model.mainType]
  51686. && (coordSys && coordSys.model !== targetCoordSysModel);
  51687. }
  51688. /*
  51689. * Licensed to the Apache Software Foundation (ASF) under one
  51690. * or more contributor license agreements. See the NOTICE file
  51691. * distributed with this work for additional information
  51692. * regarding copyright ownership. The ASF licenses this file
  51693. * to you under the Apache License, Version 2.0 (the
  51694. * "License"); you may not use this file except in compliance
  51695. * with the License. You may obtain a copy of the License at
  51696. *
  51697. * http://www.apache.org/licenses/LICENSE-2.0
  51698. *
  51699. * Unless required by applicable law or agreed to in writing,
  51700. * software distributed under the License is distributed on an
  51701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51702. * KIND, either express or implied. See the License for the
  51703. * specific language governing permissions and limitations
  51704. * under the License.
  51705. */
  51706. function makeRectPanelClipPath(rect) {
  51707. rect = normalizeRect(rect);
  51708. return function (localPoints, transform) {
  51709. return clipPointsByRect(localPoints, rect);
  51710. };
  51711. }
  51712. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  51713. rect = normalizeRect(rect);
  51714. return function (xyIndex) {
  51715. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  51716. var brushWidth = idx ? rect.width : rect.height;
  51717. var base = idx ? rect.x : rect.y;
  51718. return [base, base + (brushWidth || 0)];
  51719. };
  51720. }
  51721. function makeRectIsTargetByCursor(rect, api, targetModel) {
  51722. rect = normalizeRect(rect);
  51723. return function (e, localCursorPoint, transform) {
  51724. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  51725. && !onIrrelevantElement(e, api, targetModel);
  51726. };
  51727. }
  51728. // Consider width/height is negative.
  51729. function normalizeRect(rect) {
  51730. return BoundingRect.create(rect);
  51731. }
  51732. /*
  51733. * Licensed to the Apache Software Foundation (ASF) under one
  51734. * or more contributor license agreements. See the NOTICE file
  51735. * distributed with this work for additional information
  51736. * regarding copyright ownership. The ASF licenses this file
  51737. * to you under the Apache License, Version 2.0 (the
  51738. * "License"); you may not use this file except in compliance
  51739. * with the License. You may obtain a copy of the License at
  51740. *
  51741. * http://www.apache.org/licenses/LICENSE-2.0
  51742. *
  51743. * Unless required by applicable law or agreed to in writing,
  51744. * software distributed under the License is distributed on an
  51745. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51746. * KIND, either express or implied. See the License for the
  51747. * specific language governing permissions and limitations
  51748. * under the License.
  51749. */
  51750. var each$17 = each$1;
  51751. var indexOf$2 = indexOf;
  51752. var curry$6 = curry;
  51753. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  51754. // FIXME
  51755. // how to genarialize to more coordinate systems.
  51756. var INCLUDE_FINDER_MAIN_TYPES = [
  51757. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  51758. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  51759. ];
  51760. /**
  51761. * [option in constructor]:
  51762. * {
  51763. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  51764. * }
  51765. *
  51766. *
  51767. * [targetInfo]:
  51768. *
  51769. * There can be multiple axes in a single targetInfo. Consider the case
  51770. * of `grid` component, a targetInfo represents a grid which contains one or more
  51771. * cartesian and one or more axes. And consider the case of parallel system,
  51772. * which has multiple axes in a coordinate system.
  51773. * Can be {
  51774. * panelId: ...,
  51775. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  51776. * coordSyses: all cartesians.
  51777. * gridModel: <grid component>
  51778. * xAxes: correspond to coordSyses on index
  51779. * yAxes: correspond to coordSyses on index
  51780. * }
  51781. * or {
  51782. * panelId: ...,
  51783. * coordSys: <geo coord sys>
  51784. * coordSyses: [<geo coord sys>]
  51785. * geoModel: <geo component>
  51786. * }
  51787. *
  51788. *
  51789. * [panelOpt]:
  51790. *
  51791. * Make from targetInfo. Input to BrushController.
  51792. * {
  51793. * panelId: ...,
  51794. * rect: ...
  51795. * }
  51796. *
  51797. *
  51798. * [area]:
  51799. *
  51800. * Generated by BrushController or user input.
  51801. * {
  51802. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  51803. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  51804. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  51805. * range: pixel range.
  51806. * coordRange: representitive coord range (the first one of coordRanges).
  51807. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  51808. * }
  51809. */
  51810. /**
  51811. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  51812. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  51813. * @param {module:echarts/model/Global} ecModel
  51814. * @param {Object} [opt]
  51815. * @param {Array.<string>} [opt.include] include coordinate system types.
  51816. */
  51817. function BrushTargetManager(option, ecModel, opt) {
  51818. /**
  51819. * @private
  51820. * @type {Array.<Object>}
  51821. */
  51822. var targetInfoList = this._targetInfoList = [];
  51823. var info = {};
  51824. var foundCpts = parseFinder$1(ecModel, option);
  51825. each$17(targetInfoBuilders, function (builder, type) {
  51826. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  51827. builder(foundCpts, targetInfoList, info);
  51828. }
  51829. });
  51830. }
  51831. var proto$5 = BrushTargetManager.prototype;
  51832. proto$5.setOutputRanges = function (areas, ecModel) {
  51833. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  51834. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  51835. // area.coordRange is the first of area.coordRanges
  51836. if (!area.coordRange) {
  51837. area.coordRange = coordRange;
  51838. // In 'category' axis, coord to pixel is not reversible, so we can not
  51839. // rebuild range by coordRange accrately, which may bring trouble when
  51840. // brushing only one item. So we use __rangeOffset to rebuilding range
  51841. // by coordRange. And this it only used in brush component so it is no
  51842. // need to be adapted to coordRanges.
  51843. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  51844. area.__rangeOffset = {
  51845. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  51846. xyMinMax: result.xyMinMax
  51847. };
  51848. }
  51849. });
  51850. };
  51851. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  51852. each$17(areas, function (area) {
  51853. var targetInfo = this.findTargetInfo(area, ecModel);
  51854. if (targetInfo && targetInfo !== true) {
  51855. each$1(
  51856. targetInfo.coordSyses,
  51857. function (coordSys) {
  51858. var result = coordConvert[area.brushType](1, coordSys, area.range);
  51859. cb(area, result.values, coordSys, ecModel);
  51860. }
  51861. );
  51862. }
  51863. }, this);
  51864. };
  51865. proto$5.setInputRanges = function (areas, ecModel) {
  51866. each$17(areas, function (area) {
  51867. var targetInfo = this.findTargetInfo(area, ecModel);
  51868. if (__DEV__) {
  51869. assert$1(
  51870. !targetInfo || targetInfo === true || area.coordRange,
  51871. 'coordRange must be specified when coord index specified.'
  51872. );
  51873. assert$1(
  51874. !targetInfo || targetInfo !== true || area.range,
  51875. 'range must be specified in global brush.'
  51876. );
  51877. }
  51878. area.range = area.range || [];
  51879. // convert coordRange to global range and set panelId.
  51880. if (targetInfo && targetInfo !== true) {
  51881. area.panelId = targetInfo.panelId;
  51882. // (1) area.range shoule always be calculate from coordRange but does
  51883. // not keep its original value, for the sake of the dataZoom scenario,
  51884. // where area.coordRange remains unchanged but area.range may be changed.
  51885. // (2) Only support converting one coordRange to pixel range in brush
  51886. // component. So do not consider `coordRanges`.
  51887. // (3) About __rangeOffset, see comment above.
  51888. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  51889. var rangeOffset = area.__rangeOffset;
  51890. area.range = rangeOffset
  51891. ? diffProcessor[area.brushType](
  51892. result.values,
  51893. rangeOffset.offset,
  51894. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  51895. )
  51896. : result.values;
  51897. }
  51898. }, this);
  51899. };
  51900. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  51901. return map(this._targetInfoList, function (targetInfo) {
  51902. var rect = targetInfo.getPanelRect();
  51903. return {
  51904. panelId: targetInfo.panelId,
  51905. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  51906. clipPath: makeRectPanelClipPath(rect),
  51907. isTargetByCursor: makeRectIsTargetByCursor(
  51908. rect, api, targetInfo.coordSysModel
  51909. ),
  51910. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  51911. };
  51912. });
  51913. };
  51914. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  51915. // Check whether area is bound in coord, and series do not belong to that coord.
  51916. // If do not do this check, some brush (like lineX) will controll all axes.
  51917. var targetInfo = this.findTargetInfo(area, ecModel);
  51918. return targetInfo === true || (
  51919. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  51920. );
  51921. };
  51922. /**
  51923. * If return Object, a coord found.
  51924. * If reutrn true, global found.
  51925. * Otherwise nothing found.
  51926. *
  51927. * @param {Object} area
  51928. * @param {Array} targetInfoList
  51929. * @return {Object|boolean}
  51930. */
  51931. proto$5.findTargetInfo = function (area, ecModel) {
  51932. var targetInfoList = this._targetInfoList;
  51933. var foundCpts = parseFinder$1(ecModel, area);
  51934. for (var i = 0; i < targetInfoList.length; i++) {
  51935. var targetInfo = targetInfoList[i];
  51936. var areaPanelId = area.panelId;
  51937. if (areaPanelId) {
  51938. if (targetInfo.panelId === areaPanelId) {
  51939. return targetInfo;
  51940. }
  51941. }
  51942. else {
  51943. for (var i = 0; i < targetInfoMatchers.length; i++) {
  51944. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  51945. return targetInfo;
  51946. }
  51947. }
  51948. }
  51949. }
  51950. return true;
  51951. };
  51952. function formatMinMax(minMax) {
  51953. minMax[0] > minMax[1] && minMax.reverse();
  51954. return minMax;
  51955. }
  51956. function parseFinder$1(ecModel, option) {
  51957. return parseFinder(
  51958. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  51959. );
  51960. }
  51961. var targetInfoBuilders = {
  51962. grid: function (foundCpts, targetInfoList) {
  51963. var xAxisModels = foundCpts.xAxisModels;
  51964. var yAxisModels = foundCpts.yAxisModels;
  51965. var gridModels = foundCpts.gridModels;
  51966. // Remove duplicated.
  51967. var gridModelMap = createHashMap();
  51968. var xAxesHas = {};
  51969. var yAxesHas = {};
  51970. if (!xAxisModels && !yAxisModels && !gridModels) {
  51971. return;
  51972. }
  51973. each$17(xAxisModels, function (axisModel) {
  51974. var gridModel = axisModel.axis.grid.model;
  51975. gridModelMap.set(gridModel.id, gridModel);
  51976. xAxesHas[gridModel.id] = true;
  51977. });
  51978. each$17(yAxisModels, function (axisModel) {
  51979. var gridModel = axisModel.axis.grid.model;
  51980. gridModelMap.set(gridModel.id, gridModel);
  51981. yAxesHas[gridModel.id] = true;
  51982. });
  51983. each$17(gridModels, function (gridModel) {
  51984. gridModelMap.set(gridModel.id, gridModel);
  51985. xAxesHas[gridModel.id] = true;
  51986. yAxesHas[gridModel.id] = true;
  51987. });
  51988. gridModelMap.each(function (gridModel) {
  51989. var grid = gridModel.coordinateSystem;
  51990. var cartesians = [];
  51991. each$17(grid.getCartesians(), function (cartesian, index) {
  51992. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  51993. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  51994. ) {
  51995. cartesians.push(cartesian);
  51996. }
  51997. });
  51998. targetInfoList.push({
  51999. panelId: 'grid--' + gridModel.id,
  52000. gridModel: gridModel,
  52001. coordSysModel: gridModel,
  52002. // Use the first one as the representitive coordSys.
  52003. coordSys: cartesians[0],
  52004. coordSyses: cartesians,
  52005. getPanelRect: panelRectBuilder.grid,
  52006. xAxisDeclared: xAxesHas[gridModel.id],
  52007. yAxisDeclared: yAxesHas[gridModel.id]
  52008. });
  52009. });
  52010. },
  52011. geo: function (foundCpts, targetInfoList) {
  52012. each$17(foundCpts.geoModels, function (geoModel) {
  52013. var coordSys = geoModel.coordinateSystem;
  52014. targetInfoList.push({
  52015. panelId: 'geo--' + geoModel.id,
  52016. geoModel: geoModel,
  52017. coordSysModel: geoModel,
  52018. coordSys: coordSys,
  52019. coordSyses: [coordSys],
  52020. getPanelRect: panelRectBuilder.geo
  52021. });
  52022. });
  52023. }
  52024. };
  52025. var targetInfoMatchers = [
  52026. // grid
  52027. function (foundCpts, targetInfo) {
  52028. var xAxisModel = foundCpts.xAxisModel;
  52029. var yAxisModel = foundCpts.yAxisModel;
  52030. var gridModel = foundCpts.gridModel;
  52031. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  52032. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  52033. return gridModel && gridModel === targetInfo.gridModel;
  52034. },
  52035. // geo
  52036. function (foundCpts, targetInfo) {
  52037. var geoModel = foundCpts.geoModel;
  52038. return geoModel && geoModel === targetInfo.geoModel;
  52039. }
  52040. ];
  52041. var panelRectBuilder = {
  52042. grid: function () {
  52043. // grid is not Transformable.
  52044. return this.coordSys.grid.getRect().clone();
  52045. },
  52046. geo: function () {
  52047. var coordSys = this.coordSys;
  52048. var rect = coordSys.getBoundingRect().clone();
  52049. // geo roam and zoom transform
  52050. rect.applyTransform(getTransform(coordSys));
  52051. return rect;
  52052. }
  52053. };
  52054. var coordConvert = {
  52055. lineX: curry$6(axisConvert, 0),
  52056. lineY: curry$6(axisConvert, 1),
  52057. rect: function (to, coordSys, rangeOrCoordRange) {
  52058. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  52059. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  52060. var values = [
  52061. formatMinMax([xminymin[0], xmaxymax[0]]),
  52062. formatMinMax([xminymin[1], xmaxymax[1]])
  52063. ];
  52064. return {values: values, xyMinMax: values};
  52065. },
  52066. polygon: function (to, coordSys, rangeOrCoordRange) {
  52067. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  52068. var values = map(rangeOrCoordRange, function (item) {
  52069. var p = coordSys[COORD_CONVERTS[to]](item);
  52070. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  52071. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  52072. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  52073. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  52074. return p;
  52075. });
  52076. return {values: values, xyMinMax: xyMinMax};
  52077. }
  52078. };
  52079. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  52080. if (__DEV__) {
  52081. assert$1(
  52082. coordSys.type === 'cartesian2d',
  52083. 'lineX/lineY brush is available only in cartesian2d.'
  52084. );
  52085. }
  52086. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  52087. var values = formatMinMax(map([0, 1], function (i) {
  52088. return to
  52089. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  52090. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  52091. }));
  52092. var xyMinMax = [];
  52093. xyMinMax[axisNameIndex] = values;
  52094. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  52095. return {values: values, xyMinMax: xyMinMax};
  52096. }
  52097. var diffProcessor = {
  52098. lineX: curry$6(axisDiffProcessor, 0),
  52099. lineY: curry$6(axisDiffProcessor, 1),
  52100. rect: function (values, refer, scales) {
  52101. return [
  52102. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  52103. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  52104. ];
  52105. },
  52106. polygon: function (values, refer, scales) {
  52107. return map(values, function (item, idx) {
  52108. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  52109. });
  52110. }
  52111. };
  52112. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  52113. return [
  52114. values[0] - scales[axisNameIndex] * refer[0],
  52115. values[1] - scales[axisNameIndex] * refer[1]
  52116. ];
  52117. }
  52118. // We have to process scale caused by dataZoom manually,
  52119. // although it might be not accurate.
  52120. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  52121. var sizeCurr = getSize(xyMinMaxCurr);
  52122. var sizeOrigin = getSize(xyMinMaxOrigin);
  52123. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  52124. isNaN(scales[0]) && (scales[0] = 1);
  52125. isNaN(scales[1]) && (scales[1] = 1);
  52126. return scales;
  52127. }
  52128. function getSize(xyMinMax) {
  52129. return xyMinMax
  52130. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  52131. : [NaN, NaN];
  52132. }
  52133. /*
  52134. * Licensed to the Apache Software Foundation (ASF) under one
  52135. * or more contributor license agreements. See the NOTICE file
  52136. * distributed with this work for additional information
  52137. * regarding copyright ownership. The ASF licenses this file
  52138. * to you under the Apache License, Version 2.0 (the
  52139. * "License"); you may not use this file except in compliance
  52140. * with the License. You may obtain a copy of the License at
  52141. *
  52142. * http://www.apache.org/licenses/LICENSE-2.0
  52143. *
  52144. * Unless required by applicable law or agreed to in writing,
  52145. * software distributed under the License is distributed on an
  52146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52147. * KIND, either express or implied. See the License for the
  52148. * specific language governing permissions and limitations
  52149. * under the License.
  52150. */
  52151. var each$18 = each$1;
  52152. var ATTR$2 = '\0_ec_hist_store';
  52153. /**
  52154. * @param {module:echarts/model/Global} ecModel
  52155. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  52156. */
  52157. function push(ecModel, newSnapshot) {
  52158. var store = giveStore$1(ecModel);
  52159. // If previous dataZoom can not be found,
  52160. // complete an range with current range.
  52161. each$18(newSnapshot, function (batchItem, dataZoomId) {
  52162. var i = store.length - 1;
  52163. for (; i >= 0; i--) {
  52164. var snapshot = store[i];
  52165. if (snapshot[dataZoomId]) {
  52166. break;
  52167. }
  52168. }
  52169. if (i < 0) {
  52170. // No origin range set, create one by current range.
  52171. var dataZoomModel = ecModel.queryComponents(
  52172. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  52173. )[0];
  52174. if (dataZoomModel) {
  52175. var percentRange = dataZoomModel.getPercentRange();
  52176. store[0][dataZoomId] = {
  52177. dataZoomId: dataZoomId,
  52178. start: percentRange[0],
  52179. end: percentRange[1]
  52180. };
  52181. }
  52182. }
  52183. });
  52184. store.push(newSnapshot);
  52185. }
  52186. /**
  52187. * @param {module:echarts/model/Global} ecModel
  52188. * @return {Object} snapshot
  52189. */
  52190. function pop(ecModel) {
  52191. var store = giveStore$1(ecModel);
  52192. var head = store[store.length - 1];
  52193. store.length > 1 && store.pop();
  52194. // Find top for all dataZoom.
  52195. var snapshot = {};
  52196. each$18(head, function (batchItem, dataZoomId) {
  52197. for (var i = store.length - 1; i >= 0; i--) {
  52198. var batchItem = store[i][dataZoomId];
  52199. if (batchItem) {
  52200. snapshot[dataZoomId] = batchItem;
  52201. break;
  52202. }
  52203. }
  52204. });
  52205. return snapshot;
  52206. }
  52207. /**
  52208. * @param {module:echarts/model/Global} ecModel
  52209. */
  52210. function clear$1(ecModel) {
  52211. ecModel[ATTR$2] = null;
  52212. }
  52213. /**
  52214. * @param {module:echarts/model/Global} ecModel
  52215. * @return {number} records. always >= 1.
  52216. */
  52217. function count(ecModel) {
  52218. return giveStore$1(ecModel).length;
  52219. }
  52220. /**
  52221. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  52222. * History length of each dataZoom may be different.
  52223. * this._history[0] is used to store origin range.
  52224. * @type {Array.<Object>}
  52225. */
  52226. function giveStore$1(ecModel) {
  52227. var store = ecModel[ATTR$2];
  52228. if (!store) {
  52229. store = ecModel[ATTR$2] = [{}];
  52230. }
  52231. return store;
  52232. }
  52233. /*
  52234. * Licensed to the Apache Software Foundation (ASF) under one
  52235. * or more contributor license agreements. See the NOTICE file
  52236. * distributed with this work for additional information
  52237. * regarding copyright ownership. The ASF licenses this file
  52238. * to you under the Apache License, Version 2.0 (the
  52239. * "License"); you may not use this file except in compliance
  52240. * with the License. You may obtain a copy of the License at
  52241. *
  52242. * http://www.apache.org/licenses/LICENSE-2.0
  52243. *
  52244. * Unless required by applicable law or agreed to in writing,
  52245. * software distributed under the License is distributed on an
  52246. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52247. * KIND, either express or implied. See the License for the
  52248. * specific language governing permissions and limitations
  52249. * under the License.
  52250. */
  52251. DataZoomModel.extend({
  52252. type: 'dataZoom.select'
  52253. });
  52254. /*
  52255. * Licensed to the Apache Software Foundation (ASF) under one
  52256. * or more contributor license agreements. See the NOTICE file
  52257. * distributed with this work for additional information
  52258. * regarding copyright ownership. The ASF licenses this file
  52259. * to you under the Apache License, Version 2.0 (the
  52260. * "License"); you may not use this file except in compliance
  52261. * with the License. You may obtain a copy of the License at
  52262. *
  52263. * http://www.apache.org/licenses/LICENSE-2.0
  52264. *
  52265. * Unless required by applicable law or agreed to in writing,
  52266. * software distributed under the License is distributed on an
  52267. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52268. * KIND, either express or implied. See the License for the
  52269. * specific language governing permissions and limitations
  52270. * under the License.
  52271. */
  52272. DataZoomView.extend({
  52273. type: 'dataZoom.select'
  52274. });
  52275. /*
  52276. * Licensed to the Apache Software Foundation (ASF) under one
  52277. * or more contributor license agreements. See the NOTICE file
  52278. * distributed with this work for additional information
  52279. * regarding copyright ownership. The ASF licenses this file
  52280. * to you under the Apache License, Version 2.0 (the
  52281. * "License"); you may not use this file except in compliance
  52282. * with the License. You may obtain a copy of the License at
  52283. *
  52284. * http://www.apache.org/licenses/LICENSE-2.0
  52285. *
  52286. * Unless required by applicable law or agreed to in writing,
  52287. * software distributed under the License is distributed on an
  52288. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52289. * KIND, either express or implied. See the License for the
  52290. * specific language governing permissions and limitations
  52291. * under the License.
  52292. */
  52293. /**
  52294. * Only work for toolbox dataZoom. User
  52295. * MUST NOT import this module directly.
  52296. */
  52297. /*
  52298. * Licensed to the Apache Software Foundation (ASF) under one
  52299. * or more contributor license agreements. See the NOTICE file
  52300. * distributed with this work for additional information
  52301. * regarding copyright ownership. The ASF licenses this file
  52302. * to you under the Apache License, Version 2.0 (the
  52303. * "License"); you may not use this file except in compliance
  52304. * with the License. You may obtain a copy of the License at
  52305. *
  52306. * http://www.apache.org/licenses/LICENSE-2.0
  52307. *
  52308. * Unless required by applicable law or agreed to in writing,
  52309. * software distributed under the License is distributed on an
  52310. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52311. * KIND, either express or implied. See the License for the
  52312. * specific language governing permissions and limitations
  52313. * under the License.
  52314. */
  52315. // Use dataZoomSelect
  52316. var dataZoomLang = lang.toolbox.dataZoom;
  52317. var each$15 = each$1;
  52318. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  52319. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  52320. function DataZoom(model, ecModel, api) {
  52321. /**
  52322. * @private
  52323. * @type {module:echarts/component/helper/BrushController}
  52324. */
  52325. (this._brushController = new BrushController(api.getZr()))
  52326. .on('brush', bind(this._onBrush, this))
  52327. .mount();
  52328. /**
  52329. * @private
  52330. * @type {boolean}
  52331. */
  52332. this._isZoomActive;
  52333. }
  52334. DataZoom.defaultOption = {
  52335. show: true,
  52336. filterMode: 'filter',
  52337. // Icon group
  52338. icon: {
  52339. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  52340. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  52341. },
  52342. // `zoom`, `back`
  52343. title: clone(dataZoomLang.title)
  52344. };
  52345. var proto$4 = DataZoom.prototype;
  52346. proto$4.render = function (featureModel, ecModel, api, payload) {
  52347. this.model = featureModel;
  52348. this.ecModel = ecModel;
  52349. this.api = api;
  52350. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  52351. updateBackBtnStatus(featureModel, ecModel);
  52352. };
  52353. proto$4.onclick = function (ecModel, api, type) {
  52354. handlers[type].call(this);
  52355. };
  52356. proto$4.remove = function (ecModel, api) {
  52357. this._brushController.unmount();
  52358. };
  52359. proto$4.dispose = function (ecModel, api) {
  52360. this._brushController.dispose();
  52361. };
  52362. /**
  52363. * @private
  52364. */
  52365. var handlers = {
  52366. zoom: function () {
  52367. var nextActive = !this._isZoomActive;
  52368. this.api.dispatchAction({
  52369. type: 'takeGlobalCursor',
  52370. key: 'dataZoomSelect',
  52371. dataZoomSelectActive: nextActive
  52372. });
  52373. },
  52374. back: function () {
  52375. this._dispatchZoomAction(pop(this.ecModel));
  52376. }
  52377. };
  52378. /**
  52379. * @private
  52380. */
  52381. proto$4._onBrush = function (areas, opt) {
  52382. if (!opt.isEnd || !areas.length) {
  52383. return;
  52384. }
  52385. var snapshot = {};
  52386. var ecModel = this.ecModel;
  52387. this._brushController.updateCovers([]); // remove cover
  52388. var brushTargetManager = new BrushTargetManager(
  52389. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  52390. );
  52391. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  52392. if (coordSys.type !== 'cartesian2d') {
  52393. return;
  52394. }
  52395. var brushType = area.brushType;
  52396. if (brushType === 'rect') {
  52397. setBatch('x', coordSys, coordRange[0]);
  52398. setBatch('y', coordSys, coordRange[1]);
  52399. }
  52400. else {
  52401. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  52402. }
  52403. });
  52404. push(ecModel, snapshot);
  52405. this._dispatchZoomAction(snapshot);
  52406. function setBatch(dimName, coordSys, minMax) {
  52407. var axis = coordSys.getAxis(dimName);
  52408. var axisModel = axis.model;
  52409. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  52410. // Restrict range.
  52411. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  52412. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  52413. minMax = sliderMove(
  52414. 0, minMax.slice(), axis.scale.getExtent(), 0,
  52415. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  52416. );
  52417. }
  52418. dataZoomModel && (snapshot[dataZoomModel.id] = {
  52419. dataZoomId: dataZoomModel.id,
  52420. startValue: minMax[0],
  52421. endValue: minMax[1]
  52422. });
  52423. }
  52424. function findDataZoom(dimName, axisModel, ecModel) {
  52425. var found;
  52426. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  52427. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  52428. has && (found = dzModel);
  52429. });
  52430. return found;
  52431. }
  52432. };
  52433. /**
  52434. * @private
  52435. */
  52436. proto$4._dispatchZoomAction = function (snapshot) {
  52437. var batch = [];
  52438. // Convert from hash map to array.
  52439. each$15(snapshot, function (batchItem, dataZoomId) {
  52440. batch.push(clone(batchItem));
  52441. });
  52442. batch.length && this.api.dispatchAction({
  52443. type: 'dataZoom',
  52444. from: this.uid,
  52445. batch: batch
  52446. });
  52447. };
  52448. function retrieveAxisSetting(option) {
  52449. var setting = {};
  52450. // Compatible with previous setting: null => all axis, false => no axis.
  52451. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  52452. setting[name] = option[name];
  52453. setting[name] == null && (setting[name] = 'all');
  52454. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  52455. });
  52456. return setting;
  52457. }
  52458. function updateBackBtnStatus(featureModel, ecModel) {
  52459. featureModel.setIconStatus(
  52460. 'back',
  52461. count(ecModel) > 1 ? 'emphasis' : 'normal'
  52462. );
  52463. }
  52464. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  52465. var zoomActive = view._isZoomActive;
  52466. if (payload && payload.type === 'takeGlobalCursor') {
  52467. zoomActive = payload.key === 'dataZoomSelect'
  52468. ? payload.dataZoomSelectActive : false;
  52469. }
  52470. view._isZoomActive = zoomActive;
  52471. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  52472. var brushTargetManager = new BrushTargetManager(
  52473. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  52474. );
  52475. view._brushController
  52476. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  52477. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  52478. ? 'lineX'
  52479. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  52480. ? 'lineY'
  52481. : 'rect';
  52482. }))
  52483. .enableBrush(
  52484. zoomActive
  52485. ? {
  52486. brushType: 'auto',
  52487. brushStyle: {
  52488. // FIXME user customized?
  52489. lineWidth: 0,
  52490. fill: 'rgba(0,0,0,0.2)'
  52491. }
  52492. }
  52493. : false
  52494. );
  52495. }
  52496. register$2('dataZoom', DataZoom);
  52497. // Create special dataZoom option for select
  52498. // FIXME consider the case of merge option, where axes options are not exists.
  52499. registerPreprocessor(function (option) {
  52500. if (!option) {
  52501. return;
  52502. }
  52503. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  52504. if (!isArray(dataZoomOpts)) {
  52505. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  52506. }
  52507. var toolboxOpt = option.toolbox;
  52508. if (toolboxOpt) {
  52509. // Assume there is only one toolbox
  52510. if (isArray(toolboxOpt)) {
  52511. toolboxOpt = toolboxOpt[0];
  52512. }
  52513. if (toolboxOpt && toolboxOpt.feature) {
  52514. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  52515. // FIXME: If add dataZoom when setOption in merge mode,
  52516. // no axis info to be added. See `test/dataZoom-extreme.html`
  52517. addForAxis('xAxis', dataZoomOpt);
  52518. addForAxis('yAxis', dataZoomOpt);
  52519. }
  52520. }
  52521. function addForAxis(axisName, dataZoomOpt) {
  52522. if (!dataZoomOpt) {
  52523. return;
  52524. }
  52525. // Try not to modify model, because it is not merged yet.
  52526. var axisIndicesName = axisName + 'Index';
  52527. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  52528. if (givenAxisIndices != null
  52529. && givenAxisIndices !== 'all'
  52530. && !isArray(givenAxisIndices)
  52531. ) {
  52532. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  52533. }
  52534. forEachComponent(axisName, function (axisOpt, axisIndex) {
  52535. if (givenAxisIndices != null
  52536. && givenAxisIndices !== 'all'
  52537. && indexOf(givenAxisIndices, axisIndex) === -1
  52538. ) {
  52539. return;
  52540. }
  52541. var newOpt = {
  52542. type: 'select',
  52543. $fromToolbox: true,
  52544. // Default to be filter
  52545. filterMode: dataZoomOpt.filterMode || 'filter',
  52546. // Id for merge mapping.
  52547. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  52548. };
  52549. // FIXME
  52550. // Only support one axis now.
  52551. newOpt[axisIndicesName] = axisIndex;
  52552. dataZoomOpts.push(newOpt);
  52553. });
  52554. }
  52555. function forEachComponent(mainType, cb) {
  52556. var opts = option[mainType];
  52557. if (!isArray(opts)) {
  52558. opts = opts ? [opts] : [];
  52559. }
  52560. each$15(opts, cb);
  52561. }
  52562. });
  52563. /*
  52564. * Licensed to the Apache Software Foundation (ASF) under one
  52565. * or more contributor license agreements. See the NOTICE file
  52566. * distributed with this work for additional information
  52567. * regarding copyright ownership. The ASF licenses this file
  52568. * to you under the Apache License, Version 2.0 (the
  52569. * "License"); you may not use this file except in compliance
  52570. * with the License. You may obtain a copy of the License at
  52571. *
  52572. * http://www.apache.org/licenses/LICENSE-2.0
  52573. *
  52574. * Unless required by applicable law or agreed to in writing,
  52575. * software distributed under the License is distributed on an
  52576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52577. * KIND, either express or implied. See the License for the
  52578. * specific language governing permissions and limitations
  52579. * under the License.
  52580. */
  52581. var restoreLang = lang.toolbox.restore;
  52582. function Restore(model) {
  52583. this.model = model;
  52584. }
  52585. Restore.defaultOption = {
  52586. show: true,
  52587. /* eslint-disable */
  52588. 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',
  52589. /* eslint-enable */
  52590. title: restoreLang.title
  52591. };
  52592. var proto$6 = Restore.prototype;
  52593. proto$6.onclick = function (ecModel, api, type) {
  52594. clear$1(ecModel);
  52595. api.dispatchAction({
  52596. type: 'restore',
  52597. from: this.uid
  52598. });
  52599. };
  52600. register$2('restore', Restore);
  52601. registerAction(
  52602. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  52603. function (payload, ecModel) {
  52604. ecModel.resetOption('recreate');
  52605. }
  52606. );
  52607. /*
  52608. * Licensed to the Apache Software Foundation (ASF) under one
  52609. * or more contributor license agreements. See the NOTICE file
  52610. * distributed with this work for additional information
  52611. * regarding copyright ownership. The ASF licenses this file
  52612. * to you under the Apache License, Version 2.0 (the
  52613. * "License"); you may not use this file except in compliance
  52614. * with the License. You may obtain a copy of the License at
  52615. *
  52616. * http://www.apache.org/licenses/LICENSE-2.0
  52617. *
  52618. * Unless required by applicable law or agreed to in writing,
  52619. * software distributed under the License is distributed on an
  52620. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52621. * KIND, either express or implied. See the License for the
  52622. * specific language governing permissions and limitations
  52623. * under the License.
  52624. */
  52625. var urn = 'urn:schemas-microsoft-com:vml';
  52626. var win = typeof window === 'undefined' ? null : window;
  52627. var vmlInited = false;
  52628. var doc = win && win.document;
  52629. function createNode(tagName) {
  52630. return doCreateNode(tagName);
  52631. }
  52632. // Avoid assign to an exported variable, for transforming to cjs.
  52633. var doCreateNode;
  52634. if (doc && !env$1.canvasSupported) {
  52635. try {
  52636. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  52637. doCreateNode = function (tagName) {
  52638. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  52639. };
  52640. }
  52641. catch (e) {
  52642. doCreateNode = function (tagName) {
  52643. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  52644. };
  52645. }
  52646. }
  52647. // From raphael
  52648. function initVML() {
  52649. if (vmlInited || !doc) {
  52650. return;
  52651. }
  52652. vmlInited = true;
  52653. var styleSheets = doc.styleSheets;
  52654. if (styleSheets.length < 31) {
  52655. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  52656. }
  52657. else {
  52658. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  52659. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  52660. }
  52661. }
  52662. // http://www.w3.org/TR/NOTE-VML
  52663. // TODO Use proxy like svg instead of overwrite brush methods
  52664. var CMD$3 = PathProxy.CMD;
  52665. var round$2 = Math.round;
  52666. var sqrt = Math.sqrt;
  52667. var abs$1 = Math.abs;
  52668. var cos = Math.cos;
  52669. var sin = Math.sin;
  52670. var mathMax$6 = Math.max;
  52671. if (!env$1.canvasSupported) {
  52672. var comma = ',';
  52673. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  52674. var Z = 21600;
  52675. var Z2 = Z / 2;
  52676. var ZLEVEL_BASE = 100000;
  52677. var Z_BASE = 1000;
  52678. var initRootElStyle = function (el) {
  52679. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  52680. el.coordsize = Z + ',' + Z;
  52681. el.coordorigin = '0,0';
  52682. };
  52683. var encodeHtmlAttribute = function (s) {
  52684. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  52685. };
  52686. var rgb2Str = function (r, g, b) {
  52687. return 'rgb(' + [r, g, b].join(',') + ')';
  52688. };
  52689. var append = function (parent, child) {
  52690. if (child && parent && child.parentNode !== parent) {
  52691. parent.appendChild(child);
  52692. }
  52693. };
  52694. var remove = function (parent, child) {
  52695. if (child && parent && child.parentNode === parent) {
  52696. parent.removeChild(child);
  52697. }
  52698. };
  52699. var getZIndex = function (zlevel, z, z2) {
  52700. // z 的取值范围为 [0, 1000]
  52701. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  52702. };
  52703. var parsePercent$3 = parsePercent;
  52704. /***************************************************
  52705. * PATH
  52706. **************************************************/
  52707. var setColorAndOpacity = function (el, color, opacity) {
  52708. var colorArr = parse(color);
  52709. opacity = +opacity;
  52710. if (isNaN(opacity)) {
  52711. opacity = 1;
  52712. }
  52713. if (colorArr) {
  52714. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  52715. el.opacity = opacity * colorArr[3];
  52716. }
  52717. };
  52718. var getColorAndAlpha = function (color) {
  52719. var colorArr = parse(color);
  52720. return [
  52721. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  52722. colorArr[3]
  52723. ];
  52724. };
  52725. var updateFillNode = function (el, style, zrEl) {
  52726. // TODO pattern
  52727. var fill = style.fill;
  52728. if (fill != null) {
  52729. // Modified from excanvas
  52730. if (fill instanceof Gradient) {
  52731. var gradientType;
  52732. var angle = 0;
  52733. var focus = [0, 0];
  52734. // additional offset
  52735. var shift = 0;
  52736. // scale factor for offset
  52737. var expansion = 1;
  52738. var rect = zrEl.getBoundingRect();
  52739. var rectWidth = rect.width;
  52740. var rectHeight = rect.height;
  52741. if (fill.type === 'linear') {
  52742. gradientType = 'gradient';
  52743. var transform = zrEl.transform;
  52744. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  52745. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  52746. if (transform) {
  52747. applyTransform(p0, p0, transform);
  52748. applyTransform(p1, p1, transform);
  52749. }
  52750. var dx = p1[0] - p0[0];
  52751. var dy = p1[1] - p0[1];
  52752. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  52753. // The angle should be a non-negative number.
  52754. if (angle < 0) {
  52755. angle += 360;
  52756. }
  52757. // Very small angles produce an unexpected result because they are
  52758. // converted to a scientific notation string.
  52759. if (angle < 1e-6) {
  52760. angle = 0;
  52761. }
  52762. }
  52763. else {
  52764. gradientType = 'gradientradial';
  52765. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  52766. var transform = zrEl.transform;
  52767. var scale$$1 = zrEl.scale;
  52768. var width = rectWidth;
  52769. var height = rectHeight;
  52770. focus = [
  52771. // Percent in bounding rect
  52772. (p0[0] - rect.x) / width,
  52773. (p0[1] - rect.y) / height
  52774. ];
  52775. if (transform) {
  52776. applyTransform(p0, p0, transform);
  52777. }
  52778. width /= scale$$1[0] * Z;
  52779. height /= scale$$1[1] * Z;
  52780. var dimension = mathMax$6(width, height);
  52781. shift = 2 * 0 / dimension;
  52782. expansion = 2 * fill.r / dimension - shift;
  52783. }
  52784. // We need to sort the color stops in ascending order by offset,
  52785. // otherwise IE won't interpret it correctly.
  52786. var stops = fill.colorStops.slice();
  52787. stops.sort(function (cs1, cs2) {
  52788. return cs1.offset - cs2.offset;
  52789. });
  52790. var length$$1 = stops.length;
  52791. // Color and alpha list of first and last stop
  52792. var colorAndAlphaList = [];
  52793. var colors = [];
  52794. for (var i = 0; i < length$$1; i++) {
  52795. var stop = stops[i];
  52796. var colorAndAlpha = getColorAndAlpha(stop.color);
  52797. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  52798. if (i === 0 || i === length$$1 - 1) {
  52799. colorAndAlphaList.push(colorAndAlpha);
  52800. }
  52801. }
  52802. if (length$$1 >= 2) {
  52803. var color1 = colorAndAlphaList[0][0];
  52804. var color2 = colorAndAlphaList[1][0];
  52805. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  52806. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  52807. el.type = gradientType;
  52808. el.method = 'none';
  52809. el.focus = '100%';
  52810. el.angle = angle;
  52811. el.color = color1;
  52812. el.color2 = color2;
  52813. el.colors = colors.join(',');
  52814. // When colors attribute is used, the meanings of opacity and o:opacity2
  52815. // are reversed.
  52816. el.opacity = opacity2;
  52817. // FIXME g_o_:opacity ?
  52818. el.opacity2 = opacity1;
  52819. }
  52820. if (gradientType === 'radial') {
  52821. el.focusposition = focus.join(',');
  52822. }
  52823. }
  52824. else {
  52825. // FIXME Change from Gradient fill to color fill
  52826. setColorAndOpacity(el, fill, style.opacity);
  52827. }
  52828. }
  52829. };
  52830. var updateStrokeNode = function (el, style) {
  52831. // if (style.lineJoin != null) {
  52832. // el.joinstyle = style.lineJoin;
  52833. // }
  52834. // if (style.miterLimit != null) {
  52835. // el.miterlimit = style.miterLimit * Z;
  52836. // }
  52837. // if (style.lineCap != null) {
  52838. // el.endcap = style.lineCap;
  52839. // }
  52840. if (style.lineDash) {
  52841. el.dashstyle = style.lineDash.join(' ');
  52842. }
  52843. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  52844. setColorAndOpacity(el, style.stroke, style.opacity);
  52845. }
  52846. };
  52847. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  52848. var isFill = type === 'fill';
  52849. var el = vmlEl.getElementsByTagName(type)[0];
  52850. // Stroke must have lineWidth
  52851. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  52852. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  52853. // FIXME Remove before updating, or set `colors` will throw error
  52854. if (style[type] instanceof Gradient) {
  52855. remove(vmlEl, el);
  52856. }
  52857. if (!el) {
  52858. el = createNode(type);
  52859. }
  52860. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  52861. append(vmlEl, el);
  52862. }
  52863. else {
  52864. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  52865. remove(vmlEl, el);
  52866. }
  52867. };
  52868. var points$1 = [[], [], []];
  52869. var pathDataToString = function (path, m) {
  52870. var M = CMD$3.M;
  52871. var C = CMD$3.C;
  52872. var L = CMD$3.L;
  52873. var A = CMD$3.A;
  52874. var Q = CMD$3.Q;
  52875. var str = [];
  52876. var nPoint;
  52877. var cmdStr;
  52878. var cmd;
  52879. var i;
  52880. var xi;
  52881. var yi;
  52882. var data = path.data;
  52883. var dataLength = path.len();
  52884. for (i = 0; i < dataLength;) {
  52885. cmd = data[i++];
  52886. cmdStr = '';
  52887. nPoint = 0;
  52888. switch (cmd) {
  52889. case M:
  52890. cmdStr = ' m ';
  52891. nPoint = 1;
  52892. xi = data[i++];
  52893. yi = data[i++];
  52894. points$1[0][0] = xi;
  52895. points$1[0][1] = yi;
  52896. break;
  52897. case L:
  52898. cmdStr = ' l ';
  52899. nPoint = 1;
  52900. xi = data[i++];
  52901. yi = data[i++];
  52902. points$1[0][0] = xi;
  52903. points$1[0][1] = yi;
  52904. break;
  52905. case Q:
  52906. case C:
  52907. cmdStr = ' c ';
  52908. nPoint = 3;
  52909. var x1 = data[i++];
  52910. var y1 = data[i++];
  52911. var x2 = data[i++];
  52912. var y2 = data[i++];
  52913. var x3;
  52914. var y3;
  52915. if (cmd === Q) {
  52916. // Convert quadratic to cubic using degree elevation
  52917. x3 = x2;
  52918. y3 = y2;
  52919. x2 = (x2 + 2 * x1) / 3;
  52920. y2 = (y2 + 2 * y1) / 3;
  52921. x1 = (xi + 2 * x1) / 3;
  52922. y1 = (yi + 2 * y1) / 3;
  52923. }
  52924. else {
  52925. x3 = data[i++];
  52926. y3 = data[i++];
  52927. }
  52928. points$1[0][0] = x1;
  52929. points$1[0][1] = y1;
  52930. points$1[1][0] = x2;
  52931. points$1[1][1] = y2;
  52932. points$1[2][0] = x3;
  52933. points$1[2][1] = y3;
  52934. xi = x3;
  52935. yi = y3;
  52936. break;
  52937. case A:
  52938. var x = 0;
  52939. var y = 0;
  52940. var sx = 1;
  52941. var sy = 1;
  52942. var angle = 0;
  52943. if (m) {
  52944. // Extract SRT from matrix
  52945. x = m[4];
  52946. y = m[5];
  52947. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  52948. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  52949. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  52950. }
  52951. var cx = data[i++];
  52952. var cy = data[i++];
  52953. var rx = data[i++];
  52954. var ry = data[i++];
  52955. var startAngle = data[i++] + angle;
  52956. var endAngle = data[i++] + startAngle + angle;
  52957. // FIXME
  52958. // var psi = data[i++];
  52959. i++;
  52960. var clockwise = data[i++];
  52961. var x0 = cx + cos(startAngle) * rx;
  52962. var y0 = cy + sin(startAngle) * ry;
  52963. var x1 = cx + cos(endAngle) * rx;
  52964. var y1 = cy + sin(endAngle) * ry;
  52965. var type = clockwise ? ' wa ' : ' at ';
  52966. if (Math.abs(x0 - x1) < 1e-4) {
  52967. // IE won't render arches drawn counter clockwise if x0 == x1.
  52968. if (Math.abs(endAngle - startAngle) > 1e-2) {
  52969. // Offset x0 by 1/80 of a pixel. Use something
  52970. // that can be represented in binary
  52971. if (clockwise) {
  52972. x0 += 270 / Z;
  52973. }
  52974. }
  52975. else {
  52976. // Avoid case draw full circle
  52977. if (Math.abs(y0 - cy) < 1e-4) {
  52978. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  52979. y1 -= 270 / Z;
  52980. }
  52981. else {
  52982. y1 += 270 / Z;
  52983. }
  52984. }
  52985. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  52986. x1 += 270 / Z;
  52987. }
  52988. else {
  52989. x1 -= 270 / Z;
  52990. }
  52991. }
  52992. }
  52993. str.push(
  52994. type,
  52995. round$2(((cx - rx) * sx + x) * Z - Z2), comma,
  52996. round$2(((cy - ry) * sy + y) * Z - Z2), comma,
  52997. round$2(((cx + rx) * sx + x) * Z - Z2), comma,
  52998. round$2(((cy + ry) * sy + y) * Z - Z2), comma,
  52999. round$2((x0 * sx + x) * Z - Z2), comma,
  53000. round$2((y0 * sy + y) * Z - Z2), comma,
  53001. round$2((x1 * sx + x) * Z - Z2), comma,
  53002. round$2((y1 * sy + y) * Z - Z2)
  53003. );
  53004. xi = x1;
  53005. yi = y1;
  53006. break;
  53007. case CMD$3.R:
  53008. var p0 = points$1[0];
  53009. var p1 = points$1[1];
  53010. // x0, y0
  53011. p0[0] = data[i++];
  53012. p0[1] = data[i++];
  53013. // x1, y1
  53014. p1[0] = p0[0] + data[i++];
  53015. p1[1] = p0[1] + data[i++];
  53016. if (m) {
  53017. applyTransform(p0, p0, m);
  53018. applyTransform(p1, p1, m);
  53019. }
  53020. p0[0] = round$2(p0[0] * Z - Z2);
  53021. p1[0] = round$2(p1[0] * Z - Z2);
  53022. p0[1] = round$2(p0[1] * Z - Z2);
  53023. p1[1] = round$2(p1[1] * Z - Z2);
  53024. str.push(
  53025. // x0, y0
  53026. ' m ', p0[0], comma, p0[1],
  53027. // x1, y0
  53028. ' l ', p1[0], comma, p0[1],
  53029. // x1, y1
  53030. ' l ', p1[0], comma, p1[1],
  53031. // x0, y1
  53032. ' l ', p0[0], comma, p1[1]
  53033. );
  53034. break;
  53035. case CMD$3.Z:
  53036. // FIXME Update xi, yi
  53037. str.push(' x ');
  53038. }
  53039. if (nPoint > 0) {
  53040. str.push(cmdStr);
  53041. for (var k = 0; k < nPoint; k++) {
  53042. var p = points$1[k];
  53043. m && applyTransform(p, p, m);
  53044. // 不 round 会非常慢
  53045. str.push(
  53046. round$2(p[0] * Z - Z2), comma, round$2(p[1] * Z - Z2),
  53047. k < nPoint - 1 ? comma : ''
  53048. );
  53049. }
  53050. }
  53051. }
  53052. return str.join('');
  53053. };
  53054. // Rewrite the original path method
  53055. Path.prototype.brushVML = function (vmlRoot) {
  53056. var style = this.style;
  53057. var vmlEl = this._vmlEl;
  53058. if (!vmlEl) {
  53059. vmlEl = createNode('shape');
  53060. initRootElStyle(vmlEl);
  53061. this._vmlEl = vmlEl;
  53062. }
  53063. updateFillAndStroke(vmlEl, 'fill', style, this);
  53064. updateFillAndStroke(vmlEl, 'stroke', style, this);
  53065. var m = this.transform;
  53066. var needTransform = m != null;
  53067. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  53068. if (strokeEl) {
  53069. var lineWidth = style.lineWidth;
  53070. // Get the line scale.
  53071. // Determinant of this.m_ means how much the area is enlarged by the
  53072. // transformation. So its square root can be used as a scale factor
  53073. // for width.
  53074. if (needTransform && !style.strokeNoScale) {
  53075. var det = m[0] * m[3] - m[1] * m[2];
  53076. lineWidth *= sqrt(abs$1(det));
  53077. }
  53078. strokeEl.weight = lineWidth + 'px';
  53079. }
  53080. var path = this.path || (this.path = new PathProxy());
  53081. if (this.__dirtyPath) {
  53082. path.beginPath();
  53083. path.subPixelOptimize = false;
  53084. this.buildPath(path, this.shape);
  53085. path.toStatic();
  53086. this.__dirtyPath = false;
  53087. }
  53088. vmlEl.path = pathDataToString(path, this.transform);
  53089. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53090. // Append to root
  53091. append(vmlRoot, vmlEl);
  53092. // Text
  53093. if (style.text != null) {
  53094. this.drawRectText(vmlRoot, this.getBoundingRect());
  53095. }
  53096. else {
  53097. this.removeRectText(vmlRoot);
  53098. }
  53099. };
  53100. Path.prototype.onRemove = function (vmlRoot) {
  53101. remove(vmlRoot, this._vmlEl);
  53102. this.removeRectText(vmlRoot);
  53103. };
  53104. Path.prototype.onAdd = function (vmlRoot) {
  53105. append(vmlRoot, this._vmlEl);
  53106. this.appendRectText(vmlRoot);
  53107. };
  53108. /***************************************************
  53109. * IMAGE
  53110. **************************************************/
  53111. var isImage = function (img) {
  53112. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  53113. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  53114. // return img instanceof Image;
  53115. };
  53116. // Rewrite the original path method
  53117. ZImage.prototype.brushVML = function (vmlRoot) {
  53118. var style = this.style;
  53119. var image = style.image;
  53120. // Image original width, height
  53121. var ow;
  53122. var oh;
  53123. if (isImage(image)) {
  53124. var src = image.src;
  53125. if (src === this._imageSrc) {
  53126. ow = this._imageWidth;
  53127. oh = this._imageHeight;
  53128. }
  53129. else {
  53130. var imageRuntimeStyle = image.runtimeStyle;
  53131. var oldRuntimeWidth = imageRuntimeStyle.width;
  53132. var oldRuntimeHeight = imageRuntimeStyle.height;
  53133. imageRuntimeStyle.width = 'auto';
  53134. imageRuntimeStyle.height = 'auto';
  53135. // get the original size
  53136. ow = image.width;
  53137. oh = image.height;
  53138. // and remove overides
  53139. imageRuntimeStyle.width = oldRuntimeWidth;
  53140. imageRuntimeStyle.height = oldRuntimeHeight;
  53141. // Caching image original width, height and src
  53142. this._imageSrc = src;
  53143. this._imageWidth = ow;
  53144. this._imageHeight = oh;
  53145. }
  53146. image = src;
  53147. }
  53148. else {
  53149. if (image === this._imageSrc) {
  53150. ow = this._imageWidth;
  53151. oh = this._imageHeight;
  53152. }
  53153. }
  53154. if (!image) {
  53155. return;
  53156. }
  53157. var x = style.x || 0;
  53158. var y = style.y || 0;
  53159. var dw = style.width;
  53160. var dh = style.height;
  53161. var sw = style.sWidth;
  53162. var sh = style.sHeight;
  53163. var sx = style.sx || 0;
  53164. var sy = style.sy || 0;
  53165. var hasCrop = sw && sh;
  53166. var vmlEl = this._vmlEl;
  53167. if (!vmlEl) {
  53168. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  53169. // vmlEl = vmlCore.createNode('group');
  53170. vmlEl = doc.createElement('div');
  53171. initRootElStyle(vmlEl);
  53172. this._vmlEl = vmlEl;
  53173. }
  53174. var vmlElStyle = vmlEl.style;
  53175. var hasRotation = false;
  53176. var m;
  53177. var scaleX = 1;
  53178. var scaleY = 1;
  53179. if (this.transform) {
  53180. m = this.transform;
  53181. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  53182. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  53183. hasRotation = m[1] || m[2];
  53184. }
  53185. if (hasRotation) {
  53186. // If filters are necessary (rotation exists), create them
  53187. // filters are bog-slow, so only create them if abbsolutely necessary
  53188. // The following check doesn't account for skews (which don't exist
  53189. // in the canvas spec (yet) anyway.
  53190. // From excanvas
  53191. var p0 = [x, y];
  53192. var p1 = [x + dw, y];
  53193. var p2 = [x, y + dh];
  53194. var p3 = [x + dw, y + dh];
  53195. applyTransform(p0, p0, m);
  53196. applyTransform(p1, p1, m);
  53197. applyTransform(p2, p2, m);
  53198. applyTransform(p3, p3, m);
  53199. var maxX = mathMax$6(p0[0], p1[0], p2[0], p3[0]);
  53200. var maxY = mathMax$6(p0[1], p1[1], p2[1], p3[1]);
  53201. var transformFilter = [];
  53202. transformFilter.push('M11=', m[0] / scaleX, comma,
  53203. 'M12=', m[2] / scaleY, comma,
  53204. 'M21=', m[1] / scaleX, comma,
  53205. 'M22=', m[3] / scaleY, comma,
  53206. 'Dx=', round$2(x * scaleX + m[4]), comma,
  53207. 'Dy=', round$2(y * scaleY + m[5]));
  53208. vmlElStyle.padding = '0 ' + round$2(maxX) + 'px ' + round$2(maxY) + 'px 0';
  53209. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  53210. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  53211. + transformFilter.join('') + ', SizingMethod=clip)';
  53212. }
  53213. else {
  53214. if (m) {
  53215. x = x * scaleX + m[4];
  53216. y = y * scaleY + m[5];
  53217. }
  53218. vmlElStyle.filter = '';
  53219. vmlElStyle.left = round$2(x) + 'px';
  53220. vmlElStyle.top = round$2(y) + 'px';
  53221. }
  53222. var imageEl = this._imageEl;
  53223. var cropEl = this._cropEl;
  53224. if (!imageEl) {
  53225. imageEl = doc.createElement('div');
  53226. this._imageEl = imageEl;
  53227. }
  53228. var imageELStyle = imageEl.style;
  53229. if (hasCrop) {
  53230. // Needs know image original width and height
  53231. if (!(ow && oh)) {
  53232. var tmpImage = new Image();
  53233. var self = this;
  53234. tmpImage.onload = function () {
  53235. tmpImage.onload = null;
  53236. ow = tmpImage.width;
  53237. oh = tmpImage.height;
  53238. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  53239. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  53240. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  53241. // Caching image original width, height and src
  53242. self._imageWidth = ow;
  53243. self._imageHeight = oh;
  53244. self._imageSrc = image;
  53245. };
  53246. tmpImage.src = image;
  53247. }
  53248. else {
  53249. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  53250. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  53251. }
  53252. if (!cropEl) {
  53253. cropEl = doc.createElement('div');
  53254. cropEl.style.overflow = 'hidden';
  53255. this._cropEl = cropEl;
  53256. }
  53257. var cropElStyle = cropEl.style;
  53258. cropElStyle.width = round$2((dw + sx * dw / sw) * scaleX);
  53259. cropElStyle.height = round$2((dh + sy * dh / sh) * scaleY);
  53260. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  53261. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  53262. if (!cropEl.parentNode) {
  53263. vmlEl.appendChild(cropEl);
  53264. }
  53265. if (imageEl.parentNode !== cropEl) {
  53266. cropEl.appendChild(imageEl);
  53267. }
  53268. }
  53269. else {
  53270. imageELStyle.width = round$2(scaleX * dw) + 'px';
  53271. imageELStyle.height = round$2(scaleY * dh) + 'px';
  53272. vmlEl.appendChild(imageEl);
  53273. if (cropEl && cropEl.parentNode) {
  53274. vmlEl.removeChild(cropEl);
  53275. this._cropEl = null;
  53276. }
  53277. }
  53278. var filterStr = '';
  53279. var alpha = style.opacity;
  53280. if (alpha < 1) {
  53281. filterStr += '.Alpha(opacity=' + round$2(alpha * 100) + ') ';
  53282. }
  53283. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  53284. imageELStyle.filter = filterStr;
  53285. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53286. // Append to root
  53287. append(vmlRoot, vmlEl);
  53288. // Text
  53289. if (style.text != null) {
  53290. this.drawRectText(vmlRoot, this.getBoundingRect());
  53291. }
  53292. };
  53293. ZImage.prototype.onRemove = function (vmlRoot) {
  53294. remove(vmlRoot, this._vmlEl);
  53295. this._vmlEl = null;
  53296. this._cropEl = null;
  53297. this._imageEl = null;
  53298. this.removeRectText(vmlRoot);
  53299. };
  53300. ZImage.prototype.onAdd = function (vmlRoot) {
  53301. append(vmlRoot, this._vmlEl);
  53302. this.appendRectText(vmlRoot);
  53303. };
  53304. /***************************************************
  53305. * TEXT
  53306. **************************************************/
  53307. var DEFAULT_STYLE_NORMAL = 'normal';
  53308. var fontStyleCache = {};
  53309. var fontStyleCacheCount = 0;
  53310. var MAX_FONT_CACHE_SIZE = 100;
  53311. var fontEl = document.createElement('div');
  53312. var getFontStyle = function (fontString) {
  53313. var fontStyle = fontStyleCache[fontString];
  53314. if (!fontStyle) {
  53315. // Clear cache
  53316. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  53317. fontStyleCacheCount = 0;
  53318. fontStyleCache = {};
  53319. }
  53320. var style = fontEl.style;
  53321. var fontFamily;
  53322. try {
  53323. style.font = fontString;
  53324. fontFamily = style.fontFamily.split(',')[0];
  53325. }
  53326. catch (e) {
  53327. }
  53328. fontStyle = {
  53329. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  53330. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  53331. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  53332. size: parseFloat(style.fontSize || 12) | 0,
  53333. family: fontFamily || 'Microsoft YaHei'
  53334. };
  53335. fontStyleCache[fontString] = fontStyle;
  53336. fontStyleCacheCount++;
  53337. }
  53338. return fontStyle;
  53339. };
  53340. var textMeasureEl;
  53341. // Overwrite measure text method
  53342. $override$1('measureText', function (text, textFont) {
  53343. var doc$$1 = doc;
  53344. if (!textMeasureEl) {
  53345. textMeasureEl = doc$$1.createElement('div');
  53346. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  53347. + 'padding:0;margin:0;border:none;white-space:pre;';
  53348. doc.body.appendChild(textMeasureEl);
  53349. }
  53350. try {
  53351. textMeasureEl.style.font = textFont;
  53352. }
  53353. catch (ex) {
  53354. // Ignore failures to set to invalid font.
  53355. }
  53356. textMeasureEl.innerHTML = '';
  53357. // Don't use innerHTML or innerText because they allow markup/whitespace.
  53358. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  53359. return {
  53360. width: textMeasureEl.offsetWidth
  53361. };
  53362. });
  53363. var tmpRect$2 = new BoundingRect();
  53364. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  53365. var style = this.style;
  53366. // Optimize, avoid normalize every time.
  53367. this.__dirty && normalizeTextStyle(style, true);
  53368. var text = style.text;
  53369. // Convert to string
  53370. text != null && (text += '');
  53371. if (!text) {
  53372. return;
  53373. }
  53374. // Convert rich text to plain text. Rich text is not supported in
  53375. // IE8-, but tags in rich text template will be removed.
  53376. if (style.rich) {
  53377. var contentBlock = parseRichText(text, style);
  53378. text = [];
  53379. for (var i = 0; i < contentBlock.lines.length; i++) {
  53380. var tokens = contentBlock.lines[i].tokens;
  53381. var textLine = [];
  53382. for (var j = 0; j < tokens.length; j++) {
  53383. textLine.push(tokens[j].text);
  53384. }
  53385. text.push(textLine.join(''));
  53386. }
  53387. text = text.join('\n');
  53388. }
  53389. var x;
  53390. var y;
  53391. var align = style.textAlign;
  53392. var verticalAlign = style.textVerticalAlign;
  53393. var fontStyle = getFontStyle(style.font);
  53394. // FIXME encodeHtmlAttribute ?
  53395. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  53396. + fontStyle.size + 'px "' + fontStyle.family + '"';
  53397. textRect = textRect || getBoundingRect(
  53398. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  53399. );
  53400. // Transform rect to view space
  53401. var m = this.transform;
  53402. // Ignore transform for text in other element
  53403. if (m && !fromTextEl) {
  53404. tmpRect$2.copy(rect);
  53405. tmpRect$2.applyTransform(m);
  53406. rect = tmpRect$2;
  53407. }
  53408. if (!fromTextEl) {
  53409. var textPosition = style.textPosition;
  53410. // Text position represented by coord
  53411. if (textPosition instanceof Array) {
  53412. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  53413. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  53414. align = align || 'left';
  53415. }
  53416. else {
  53417. var res = this.calculateTextPosition
  53418. ? this.calculateTextPosition({}, style, rect)
  53419. : calculateTextPosition({}, style, rect);
  53420. x = res.x;
  53421. y = res.y;
  53422. // Default align and baseline when has textPosition
  53423. align = align || res.textAlign;
  53424. verticalAlign = verticalAlign || res.textVerticalAlign;
  53425. }
  53426. }
  53427. else {
  53428. x = rect.x;
  53429. y = rect.y;
  53430. }
  53431. x = adjustTextX(x, textRect.width, align);
  53432. y = adjustTextY(y, textRect.height, verticalAlign);
  53433. // Force baseline 'middle'
  53434. y += textRect.height / 2;
  53435. // var fontSize = fontStyle.size;
  53436. // 1.75 is an arbitrary number, as there is no info about the text baseline
  53437. // switch (baseline) {
  53438. // case 'hanging':
  53439. // case 'top':
  53440. // y += fontSize / 1.75;
  53441. // break;
  53442. // case 'middle':
  53443. // break;
  53444. // default:
  53445. // // case null:
  53446. // // case 'alphabetic':
  53447. // // case 'ideographic':
  53448. // // case 'bottom':
  53449. // y -= fontSize / 2.25;
  53450. // break;
  53451. // }
  53452. // switch (align) {
  53453. // case 'left':
  53454. // break;
  53455. // case 'center':
  53456. // x -= textRect.width / 2;
  53457. // break;
  53458. // case 'right':
  53459. // x -= textRect.width;
  53460. // break;
  53461. // case 'end':
  53462. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  53463. // break;
  53464. // case 'start':
  53465. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  53466. // break;
  53467. // default:
  53468. // align = 'left';
  53469. // }
  53470. var createNode$$1 = createNode;
  53471. var textVmlEl = this._textVmlEl;
  53472. var pathEl;
  53473. var textPathEl;
  53474. var skewEl;
  53475. if (!textVmlEl) {
  53476. textVmlEl = createNode$$1('line');
  53477. pathEl = createNode$$1('path');
  53478. textPathEl = createNode$$1('textpath');
  53479. skewEl = createNode$$1('skew');
  53480. // FIXME Why here is not cammel case
  53481. // Align 'center' seems wrong
  53482. textPathEl.style['v-text-align'] = 'left';
  53483. initRootElStyle(textVmlEl);
  53484. pathEl.textpathok = true;
  53485. textPathEl.on = true;
  53486. textVmlEl.from = '0 0';
  53487. textVmlEl.to = '1000 0.05';
  53488. append(textVmlEl, skewEl);
  53489. append(textVmlEl, pathEl);
  53490. append(textVmlEl, textPathEl);
  53491. this._textVmlEl = textVmlEl;
  53492. }
  53493. else {
  53494. // 这里是在前面 appendChild 保证顺序的前提下
  53495. skewEl = textVmlEl.firstChild;
  53496. pathEl = skewEl.nextSibling;
  53497. textPathEl = pathEl.nextSibling;
  53498. }
  53499. var coords = [x, y];
  53500. var textVmlElStyle = textVmlEl.style;
  53501. // Ignore transform for text in other element
  53502. if (m && fromTextEl) {
  53503. applyTransform(coords, coords, m);
  53504. skewEl.on = true;
  53505. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  53506. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  53507. // Text position
  53508. skewEl.offset = (round$2(coords[0]) || 0) + ',' + (round$2(coords[1]) || 0);
  53509. // Left top point as origin
  53510. skewEl.origin = '0 0';
  53511. textVmlElStyle.left = '0px';
  53512. textVmlElStyle.top = '0px';
  53513. }
  53514. else {
  53515. skewEl.on = false;
  53516. textVmlElStyle.left = round$2(x) + 'px';
  53517. textVmlElStyle.top = round$2(y) + 'px';
  53518. }
  53519. textPathEl.string = encodeHtmlAttribute(text);
  53520. // TODO
  53521. try {
  53522. textPathEl.style.font = font;
  53523. }
  53524. // Error font format
  53525. catch (e) {}
  53526. updateFillAndStroke(textVmlEl, 'fill', {
  53527. fill: style.textFill,
  53528. opacity: style.opacity
  53529. }, this);
  53530. updateFillAndStroke(textVmlEl, 'stroke', {
  53531. stroke: style.textStroke,
  53532. opacity: style.opacity,
  53533. lineDash: style.lineDash || null // style.lineDash can be `false`.
  53534. }, this);
  53535. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53536. // Attached to root
  53537. append(vmlRoot, textVmlEl);
  53538. };
  53539. var removeRectText = function (vmlRoot) {
  53540. remove(vmlRoot, this._textVmlEl);
  53541. this._textVmlEl = null;
  53542. };
  53543. var appendRectText = function (vmlRoot) {
  53544. append(vmlRoot, this._textVmlEl);
  53545. };
  53546. var list = [RectText, Displayable, ZImage, Path, Text];
  53547. // In case Displayable has been mixed in RectText
  53548. for (var i$1 = 0; i$1 < list.length; i$1++) {
  53549. var proto$7 = list[i$1].prototype;
  53550. proto$7.drawRectText = drawRectText;
  53551. proto$7.removeRectText = removeRectText;
  53552. proto$7.appendRectText = appendRectText;
  53553. }
  53554. Text.prototype.brushVML = function (vmlRoot) {
  53555. var style = this.style;
  53556. if (style.text != null) {
  53557. this.drawRectText(vmlRoot, {
  53558. x: style.x || 0, y: style.y || 0,
  53559. width: 0, height: 0
  53560. }, this.getBoundingRect(), true);
  53561. }
  53562. else {
  53563. this.removeRectText(vmlRoot);
  53564. }
  53565. };
  53566. Text.prototype.onRemove = function (vmlRoot) {
  53567. this.removeRectText(vmlRoot);
  53568. };
  53569. Text.prototype.onAdd = function (vmlRoot) {
  53570. this.appendRectText(vmlRoot);
  53571. };
  53572. }
  53573. /**
  53574. * VML Painter.
  53575. *
  53576. * @module zrender/vml/Painter
  53577. */
  53578. function parseInt10$1(val) {
  53579. return parseInt(val, 10);
  53580. }
  53581. /**
  53582. * @alias module:zrender/vml/Painter
  53583. */
  53584. function VMLPainter(root, storage) {
  53585. initVML();
  53586. this.root = root;
  53587. this.storage = storage;
  53588. var vmlViewport = document.createElement('div');
  53589. var vmlRoot = document.createElement('div');
  53590. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  53591. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  53592. root.appendChild(vmlViewport);
  53593. this._vmlRoot = vmlRoot;
  53594. this._vmlViewport = vmlViewport;
  53595. this.resize();
  53596. // Modify storage
  53597. var oldDelFromStorage = storage.delFromStorage;
  53598. var oldAddToStorage = storage.addToStorage;
  53599. storage.delFromStorage = function (el) {
  53600. oldDelFromStorage.call(storage, el);
  53601. if (el) {
  53602. el.onRemove && el.onRemove(vmlRoot);
  53603. }
  53604. };
  53605. storage.addToStorage = function (el) {
  53606. // Displayable already has a vml node
  53607. el.onAdd && el.onAdd(vmlRoot);
  53608. oldAddToStorage.call(storage, el);
  53609. };
  53610. this._firstPaint = true;
  53611. }
  53612. VMLPainter.prototype = {
  53613. constructor: VMLPainter,
  53614. getType: function () {
  53615. return 'vml';
  53616. },
  53617. /**
  53618. * @return {HTMLDivElement}
  53619. */
  53620. getViewportRoot: function () {
  53621. return this._vmlViewport;
  53622. },
  53623. getViewportRootOffset: function () {
  53624. var viewportRoot = this.getViewportRoot();
  53625. if (viewportRoot) {
  53626. return {
  53627. offsetLeft: viewportRoot.offsetLeft || 0,
  53628. offsetTop: viewportRoot.offsetTop || 0
  53629. };
  53630. }
  53631. },
  53632. /**
  53633. * 刷新
  53634. */
  53635. refresh: function () {
  53636. var list = this.storage.getDisplayList(true, true);
  53637. this._paintList(list);
  53638. },
  53639. _paintList: function (list) {
  53640. var vmlRoot = this._vmlRoot;
  53641. for (var i = 0; i < list.length; i++) {
  53642. var el = list[i];
  53643. if (el.invisible || el.ignore) {
  53644. if (!el.__alreadyNotVisible) {
  53645. el.onRemove(vmlRoot);
  53646. }
  53647. // Set as already invisible
  53648. el.__alreadyNotVisible = true;
  53649. }
  53650. else {
  53651. if (el.__alreadyNotVisible) {
  53652. el.onAdd(vmlRoot);
  53653. }
  53654. el.__alreadyNotVisible = false;
  53655. if (el.__dirty) {
  53656. el.beforeBrush && el.beforeBrush();
  53657. (el.brushVML || el.brush).call(el, vmlRoot);
  53658. el.afterBrush && el.afterBrush();
  53659. }
  53660. }
  53661. el.__dirty = false;
  53662. }
  53663. if (this._firstPaint) {
  53664. // Detached from document at first time
  53665. // to avoid page refreshing too many times
  53666. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  53667. this._vmlViewport.appendChild(vmlRoot);
  53668. this._firstPaint = false;
  53669. }
  53670. },
  53671. resize: function (width, height) {
  53672. var width = width == null ? this._getWidth() : width;
  53673. var height = height == null ? this._getHeight() : height;
  53674. if (this._width !== width || this._height !== height) {
  53675. this._width = width;
  53676. this._height = height;
  53677. var vmlViewportStyle = this._vmlViewport.style;
  53678. vmlViewportStyle.width = width + 'px';
  53679. vmlViewportStyle.height = height + 'px';
  53680. }
  53681. },
  53682. dispose: function () {
  53683. this.root.innerHTML = '';
  53684. this._vmlRoot =
  53685. this._vmlViewport =
  53686. this.storage = null;
  53687. },
  53688. getWidth: function () {
  53689. return this._width;
  53690. },
  53691. getHeight: function () {
  53692. return this._height;
  53693. },
  53694. clear: function () {
  53695. if (this._vmlViewport) {
  53696. this.root.removeChild(this._vmlViewport);
  53697. }
  53698. },
  53699. _getWidth: function () {
  53700. var root = this.root;
  53701. var stl = root.currentStyle;
  53702. return ((root.clientWidth || parseInt10$1(stl.width))
  53703. - parseInt10$1(stl.paddingLeft)
  53704. - parseInt10$1(stl.paddingRight)) | 0;
  53705. },
  53706. _getHeight: function () {
  53707. var root = this.root;
  53708. var stl = root.currentStyle;
  53709. return ((root.clientHeight || parseInt10$1(stl.height))
  53710. - parseInt10$1(stl.paddingTop)
  53711. - parseInt10$1(stl.paddingBottom)) | 0;
  53712. }
  53713. };
  53714. // Not supported methods
  53715. function createMethodNotSupport(method) {
  53716. return function () {
  53717. logError$1('In IE8.0 VML mode painter not support method "' + method + '"');
  53718. };
  53719. }
  53720. // Unsupported methods
  53721. each$1([
  53722. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  53723. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  53724. ], function (name) {
  53725. VMLPainter.prototype[name] = createMethodNotSupport(name);
  53726. });
  53727. registerPainter('vml', VMLPainter);
  53728. var svgURI = 'http://www.w3.org/2000/svg';
  53729. function createElement(name) {
  53730. return document.createElementNS(svgURI, name);
  53731. }
  53732. // TODO
  53733. // 1. shadow
  53734. // 2. Image: sx, sy, sw, sh
  53735. var CMD$4 = PathProxy.CMD;
  53736. var arrayJoin = Array.prototype.join;
  53737. var NONE = 'none';
  53738. var mathRound = Math.round;
  53739. var mathSin$3 = Math.sin;
  53740. var mathCos$3 = Math.cos;
  53741. var PI$3 = Math.PI;
  53742. var PI2$5 = Math.PI * 2;
  53743. var degree = 180 / PI$3;
  53744. var EPSILON$4 = 1e-4;
  53745. function round4(val) {
  53746. return mathRound(val * 1e4) / 1e4;
  53747. }
  53748. function isAroundZero$1(val) {
  53749. return val < EPSILON$4 && val > -EPSILON$4;
  53750. }
  53751. function pathHasFill(style, isText) {
  53752. var fill = isText ? style.textFill : style.fill;
  53753. return fill != null && fill !== NONE;
  53754. }
  53755. function pathHasStroke(style, isText) {
  53756. var stroke = isText ? style.textStroke : style.stroke;
  53757. return stroke != null && stroke !== NONE;
  53758. }
  53759. function setTransform(svgEl, m) {
  53760. if (m) {
  53761. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  53762. }
  53763. }
  53764. function attr(el, key, val) {
  53765. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  53766. // Don't set attribute for gradient, since it need new dom nodes
  53767. el.setAttribute(key, val);
  53768. }
  53769. }
  53770. function attrXLink(el, key, val) {
  53771. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  53772. }
  53773. function bindStyle(svgEl, style, isText, el) {
  53774. if (pathHasFill(style, isText)) {
  53775. var fill = isText ? style.textFill : style.fill;
  53776. fill = fill === 'transparent' ? NONE : fill;
  53777. attr(svgEl, 'fill', fill);
  53778. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  53779. }
  53780. else {
  53781. attr(svgEl, 'fill', NONE);
  53782. }
  53783. if (pathHasStroke(style, isText)) {
  53784. var stroke = isText ? style.textStroke : style.stroke;
  53785. stroke = stroke === 'transparent' ? NONE : stroke;
  53786. attr(svgEl, 'stroke', stroke);
  53787. var strokeWidth = isText
  53788. ? style.textStrokeWidth
  53789. : style.lineWidth;
  53790. var strokeScale = !isText && style.strokeNoScale
  53791. ? el.getLineScale()
  53792. : 1;
  53793. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  53794. // stroke then fill for text; fill then stroke for others
  53795. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  53796. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  53797. var lineDash = style.lineDash;
  53798. if (lineDash) {
  53799. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  53800. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  53801. }
  53802. else {
  53803. attr(svgEl, 'stroke-dasharray', '');
  53804. }
  53805. // PENDING
  53806. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  53807. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  53808. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  53809. }
  53810. else {
  53811. attr(svgEl, 'stroke', NONE);
  53812. }
  53813. }
  53814. /***************************************************
  53815. * PATH
  53816. **************************************************/
  53817. function pathDataToString$1(path) {
  53818. var str = [];
  53819. var data = path.data;
  53820. var dataLength = path.len();
  53821. for (var i = 0; i < dataLength;) {
  53822. var cmd = data[i++];
  53823. var cmdStr = '';
  53824. var nData = 0;
  53825. switch (cmd) {
  53826. case CMD$4.M:
  53827. cmdStr = 'M';
  53828. nData = 2;
  53829. break;
  53830. case CMD$4.L:
  53831. cmdStr = 'L';
  53832. nData = 2;
  53833. break;
  53834. case CMD$4.Q:
  53835. cmdStr = 'Q';
  53836. nData = 4;
  53837. break;
  53838. case CMD$4.C:
  53839. cmdStr = 'C';
  53840. nData = 6;
  53841. break;
  53842. case CMD$4.A:
  53843. var cx = data[i++];
  53844. var cy = data[i++];
  53845. var rx = data[i++];
  53846. var ry = data[i++];
  53847. var theta = data[i++];
  53848. var dTheta = data[i++];
  53849. var psi = data[i++];
  53850. var clockwise = data[i++];
  53851. var dThetaPositive = Math.abs(dTheta);
  53852. var isCircle = isAroundZero$1(dThetaPositive - PI2$5)
  53853. || (clockwise ? dTheta >= PI2$5 : -dTheta >= PI2$5);
  53854. // Mapping to 0~2PI
  53855. var unifiedTheta = dTheta > 0 ? dTheta % PI2$5 : (dTheta % PI2$5 + PI2$5);
  53856. var large = false;
  53857. if (isCircle) {
  53858. large = true;
  53859. }
  53860. else if (isAroundZero$1(dThetaPositive)) {
  53861. large = false;
  53862. }
  53863. else {
  53864. large = (unifiedTheta >= PI$3) === !!clockwise;
  53865. }
  53866. var x0 = round4(cx + rx * mathCos$3(theta));
  53867. var y0 = round4(cy + ry * mathSin$3(theta));
  53868. // It will not draw if start point and end point are exactly the same
  53869. // We need to shift the end point with a small value
  53870. // FIXME A better way to draw circle ?
  53871. if (isCircle) {
  53872. if (clockwise) {
  53873. dTheta = PI2$5 - 1e-4;
  53874. }
  53875. else {
  53876. dTheta = -PI2$5 + 1e-4;
  53877. }
  53878. large = true;
  53879. if (i === 9) {
  53880. // Move to (x0, y0) only when CMD.A comes at the
  53881. // first position of a shape.
  53882. // For instance, when drawing a ring, CMD.A comes
  53883. // after CMD.M, so it's unnecessary to move to
  53884. // (x0, y0).
  53885. str.push('M', x0, y0);
  53886. }
  53887. }
  53888. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  53889. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  53890. // FIXME Ellipse
  53891. str.push('A', round4(rx), round4(ry),
  53892. mathRound(psi * degree), +large, +clockwise, x, y);
  53893. break;
  53894. case CMD$4.Z:
  53895. cmdStr = 'Z';
  53896. break;
  53897. case CMD$4.R:
  53898. var x = round4(data[i++]);
  53899. var y = round4(data[i++]);
  53900. var w = round4(data[i++]);
  53901. var h = round4(data[i++]);
  53902. str.push(
  53903. 'M', x, y,
  53904. 'L', x + w, y,
  53905. 'L', x + w, y + h,
  53906. 'L', x, y + h,
  53907. 'L', x, y
  53908. );
  53909. break;
  53910. }
  53911. cmdStr && str.push(cmdStr);
  53912. for (var j = 0; j < nData; j++) {
  53913. // PENDING With scale
  53914. str.push(round4(data[i++]));
  53915. }
  53916. }
  53917. return str.join(' ');
  53918. }
  53919. var svgPath = {};
  53920. svgPath.brush = function (el) {
  53921. var style = el.style;
  53922. var svgEl = el.__svgEl;
  53923. if (!svgEl) {
  53924. svgEl = createElement('path');
  53925. el.__svgEl = svgEl;
  53926. }
  53927. if (!el.path) {
  53928. el.createPathProxy();
  53929. }
  53930. var path = el.path;
  53931. if (el.__dirtyPath) {
  53932. path.beginPath();
  53933. path.subPixelOptimize = false;
  53934. el.buildPath(path, el.shape);
  53935. el.__dirtyPath = false;
  53936. var pathStr = pathDataToString$1(path);
  53937. if (pathStr.indexOf('NaN') < 0) {
  53938. // Ignore illegal path, which may happen such in out-of-range
  53939. // data in Calendar series.
  53940. attr(svgEl, 'd', pathStr);
  53941. }
  53942. }
  53943. bindStyle(svgEl, style, false, el);
  53944. setTransform(svgEl, el.transform);
  53945. if (style.text != null) {
  53946. svgTextDrawRectText(el, el.getBoundingRect());
  53947. }
  53948. else {
  53949. removeOldTextNode(el);
  53950. }
  53951. };
  53952. /***************************************************
  53953. * IMAGE
  53954. **************************************************/
  53955. var svgImage = {};
  53956. svgImage.brush = function (el) {
  53957. var style = el.style;
  53958. var image = style.image;
  53959. if (image instanceof HTMLImageElement) {
  53960. var src = image.src;
  53961. image = src;
  53962. }
  53963. if (!image) {
  53964. return;
  53965. }
  53966. var x = style.x || 0;
  53967. var y = style.y || 0;
  53968. var dw = style.width;
  53969. var dh = style.height;
  53970. var svgEl = el.__svgEl;
  53971. if (!svgEl) {
  53972. svgEl = createElement('image');
  53973. el.__svgEl = svgEl;
  53974. }
  53975. if (image !== el.__imageSrc) {
  53976. attrXLink(svgEl, 'href', image);
  53977. // Caching image src
  53978. el.__imageSrc = image;
  53979. }
  53980. attr(svgEl, 'width', dw);
  53981. attr(svgEl, 'height', dh);
  53982. attr(svgEl, 'x', x);
  53983. attr(svgEl, 'y', y);
  53984. setTransform(svgEl, el.transform);
  53985. if (style.text != null) {
  53986. svgTextDrawRectText(el, el.getBoundingRect());
  53987. }
  53988. else {
  53989. removeOldTextNode(el);
  53990. }
  53991. };
  53992. /***************************************************
  53993. * TEXT
  53994. **************************************************/
  53995. var svgText = {};
  53996. var _tmpTextHostRect = new BoundingRect();
  53997. var _tmpTextBoxPos = {};
  53998. var _tmpTextTransform = [];
  53999. var TEXT_ALIGN_TO_ANCHRO = {
  54000. left: 'start',
  54001. right: 'end',
  54002. center: 'middle',
  54003. middle: 'middle'
  54004. };
  54005. /**
  54006. * @param {module:zrender/Element} el
  54007. * @param {Object|boolean} [hostRect] {x, y, width, height}
  54008. * If set false, rect text is not used.
  54009. */
  54010. var svgTextDrawRectText = function (el, hostRect) {
  54011. var style = el.style;
  54012. var elTransform = el.transform;
  54013. var needTransformTextByHostEl = el instanceof Text || style.transformText;
  54014. el.__dirty && normalizeTextStyle(style, true);
  54015. var text = style.text;
  54016. // Convert to string
  54017. text != null && (text += '');
  54018. if (!needDrawText(text, style)) {
  54019. return;
  54020. }
  54021. // render empty text for svg if no text but need draw text.
  54022. text == null && (text = '');
  54023. // Follow the setting in the canvas renderer, if not transform the
  54024. // text, transform the hostRect, by which the text is located.
  54025. if (!needTransformTextByHostEl && elTransform) {
  54026. _tmpTextHostRect.copy(hostRect);
  54027. _tmpTextHostRect.applyTransform(elTransform);
  54028. hostRect = _tmpTextHostRect;
  54029. }
  54030. var textSvgEl = el.__textSvgEl;
  54031. if (!textSvgEl) {
  54032. textSvgEl = createElement('text');
  54033. el.__textSvgEl = textSvgEl;
  54034. }
  54035. // style.font has been normalized by `normalizeTextStyle`.
  54036. var textSvgElStyle = textSvgEl.style;
  54037. var font = style.font || DEFAULT_FONT$1;
  54038. var computedFont = textSvgEl.__computedFont;
  54039. if (font !== textSvgEl.__styleFont) {
  54040. textSvgElStyle.font = textSvgEl.__styleFont = font;
  54041. // The computedFont might not be the orginal font if it is illegal font.
  54042. computedFont = textSvgEl.__computedFont = textSvgElStyle.font;
  54043. }
  54044. var textPadding = style.textPadding;
  54045. var textLineHeight = style.textLineHeight;
  54046. var contentBlock = el.__textCotentBlock;
  54047. if (!contentBlock || el.__dirtyText) {
  54048. contentBlock = el.__textCotentBlock = parsePlainText(
  54049. text, computedFont, textPadding, textLineHeight, style.truncate
  54050. );
  54051. }
  54052. var outerHeight = contentBlock.outerHeight;
  54053. var lineHeight = contentBlock.lineHeight;
  54054. getBoxPosition(_tmpTextBoxPos, el, style, hostRect);
  54055. var baseX = _tmpTextBoxPos.baseX;
  54056. var baseY = _tmpTextBoxPos.baseY;
  54057. var textAlign = _tmpTextBoxPos.textAlign || 'left';
  54058. var textVerticalAlign = _tmpTextBoxPos.textVerticalAlign;
  54059. setTextTransform(
  54060. textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY
  54061. );
  54062. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  54063. var textX = baseX;
  54064. var textY = boxY;
  54065. // TODO needDrawBg
  54066. if (textPadding) {
  54067. textX = getTextXForPadding$1(baseX, textAlign, textPadding);
  54068. textY += textPadding[0];
  54069. }
  54070. // `textBaseline` is set as 'middle'.
  54071. textY += lineHeight / 2;
  54072. bindStyle(textSvgEl, style, true, el);
  54073. // FIXME
  54074. // Add a <style> to reset all of the text font as inherit?
  54075. // otherwise the outer <style> may set the unexpected style.
  54076. // Font may affect position of each tspan elements
  54077. var canCacheByTextString = contentBlock.canCacheByTextString;
  54078. var tspanList = el.__tspanList || (el.__tspanList = []);
  54079. var tspanOriginLen = tspanList.length;
  54080. // Optimize for most cases, just compare text string to determine change.
  54081. if (canCacheByTextString && el.__canCacheByTextString && el.__text === text) {
  54082. if (el.__dirtyText && tspanOriginLen) {
  54083. for (var idx = 0; idx < tspanOriginLen; ++idx) {
  54084. updateTextLocation(tspanList[idx], textAlign, textX, textY + idx * lineHeight);
  54085. }
  54086. }
  54087. }
  54088. else {
  54089. el.__text = text;
  54090. el.__canCacheByTextString = canCacheByTextString;
  54091. var textLines = contentBlock.lines;
  54092. var nTextLines = textLines.length;
  54093. var idx = 0;
  54094. for (; idx < nTextLines; idx++) {
  54095. // Using cached tspan elements
  54096. var tspan = tspanList[idx];
  54097. var singleLineText = textLines[idx];
  54098. if (!tspan) {
  54099. tspan = tspanList[idx] = createElement('tspan');
  54100. textSvgEl.appendChild(tspan);
  54101. tspan.appendChild(document.createTextNode(singleLineText));
  54102. }
  54103. else if (tspan.__zrText !== singleLineText) {
  54104. tspan.innerHTML = '';
  54105. tspan.appendChild(document.createTextNode(singleLineText));
  54106. }
  54107. updateTextLocation(tspan, textAlign, textX, textY + idx * lineHeight);
  54108. }
  54109. // Remove unused tspan elements
  54110. if (tspanOriginLen > nTextLines) {
  54111. for (; idx < tspanOriginLen; idx++) {
  54112. textSvgEl.removeChild(tspanList[idx]);
  54113. }
  54114. tspanList.length = nTextLines;
  54115. }
  54116. }
  54117. };
  54118. function setTextTransform(textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY) {
  54119. identity(_tmpTextTransform);
  54120. if (needTransformTextByHostEl && elTransform) {
  54121. copy$1(_tmpTextTransform, elTransform);
  54122. }
  54123. // textRotation only apply in RectText.
  54124. var textRotation = style.textRotation;
  54125. if (hostRect && textRotation) {
  54126. var origin = style.textOrigin;
  54127. if (origin === 'center') {
  54128. baseX = hostRect.width / 2 + hostRect.x;
  54129. baseY = hostRect.height / 2 + hostRect.y;
  54130. }
  54131. else if (origin) {
  54132. baseX = origin[0] + hostRect.x;
  54133. baseY = origin[1] + hostRect.y;
  54134. }
  54135. _tmpTextTransform[4] -= baseX;
  54136. _tmpTextTransform[5] -= baseY;
  54137. // Positive: anticlockwise
  54138. rotate(_tmpTextTransform, _tmpTextTransform, textRotation);
  54139. _tmpTextTransform[4] += baseX;
  54140. _tmpTextTransform[5] += baseY;
  54141. }
  54142. // See the definition in `Style.js#textOrigin`, the default
  54143. // origin is from the result of `getBoxPosition`.
  54144. setTransform(textSvgEl, _tmpTextTransform);
  54145. }
  54146. // FIXME merge the same code with `helper/text.js#getTextXForPadding`;
  54147. function getTextXForPadding$1(x, textAlign, textPadding) {
  54148. return textAlign === 'right'
  54149. ? (x - textPadding[1])
  54150. : textAlign === 'center'
  54151. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  54152. : (x + textPadding[3]);
  54153. }
  54154. function updateTextLocation(tspan, textAlign, x, y) {
  54155. // Consider different font display differently in vertial align, we always
  54156. // set vertialAlign as 'middle', and use 'y' to locate text vertically.
  54157. attr(tspan, 'dominant-baseline', 'middle');
  54158. attr(tspan, 'text-anchor', TEXT_ALIGN_TO_ANCHRO[textAlign]);
  54159. attr(tspan, 'x', x);
  54160. attr(tspan, 'y', y);
  54161. }
  54162. function removeOldTextNode(el) {
  54163. if (el && el.__textSvgEl) {
  54164. // textSvgEl may has no parentNode if el has been removed temporary.
  54165. if (el.__textSvgEl.parentNode) {
  54166. el.__textSvgEl.parentNode.removeChild(el.__textSvgEl);
  54167. }
  54168. el.__textSvgEl = null;
  54169. el.__tspanList = [];
  54170. el.__text = null;
  54171. }
  54172. }
  54173. svgText.drawRectText = svgTextDrawRectText;
  54174. svgText.brush = function (el) {
  54175. var style = el.style;
  54176. if (style.text != null) {
  54177. svgTextDrawRectText(el, false);
  54178. }
  54179. else {
  54180. removeOldTextNode(el);
  54181. }
  54182. };
  54183. // Myers' Diff Algorithm
  54184. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  54185. function Diff() {}
  54186. Diff.prototype = {
  54187. diff: function (oldArr, newArr, equals) {
  54188. if (!equals) {
  54189. equals = function (a, b) {
  54190. return a === b;
  54191. };
  54192. }
  54193. this.equals = equals;
  54194. var self = this;
  54195. oldArr = oldArr.slice();
  54196. newArr = newArr.slice();
  54197. // Allow subclasses to massage the input prior to running
  54198. var newLen = newArr.length;
  54199. var oldLen = oldArr.length;
  54200. var editLength = 1;
  54201. var maxEditLength = newLen + oldLen;
  54202. var bestPath = [{ newPos: -1, components: [] }];
  54203. // Seed editLength = 0, i.e. the content starts with the same values
  54204. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  54205. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  54206. var indices = [];
  54207. for (var i = 0; i < newArr.length; i++) {
  54208. indices.push(i);
  54209. }
  54210. // Identity per the equality and tokenizer
  54211. return [{
  54212. indices: indices, count: newArr.length
  54213. }];
  54214. }
  54215. // Main worker method. checks all permutations of a given edit length for acceptance.
  54216. function execEditLength() {
  54217. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  54218. var basePath;
  54219. var addPath = bestPath[diagonalPath - 1];
  54220. var removePath = bestPath[diagonalPath + 1];
  54221. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  54222. if (addPath) {
  54223. // No one else is going to attempt to use this value, clear it
  54224. bestPath[diagonalPath - 1] = undefined;
  54225. }
  54226. var canAdd = addPath && addPath.newPos + 1 < newLen;
  54227. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  54228. if (!canAdd && !canRemove) {
  54229. // If this path is a terminal then prune
  54230. bestPath[diagonalPath] = undefined;
  54231. continue;
  54232. }
  54233. // Select the diagonal that we want to branch from. We select the prior
  54234. // path whose position in the new string is the farthest from the origin
  54235. // and does not pass the bounds of the diff graph
  54236. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  54237. basePath = clonePath(removePath);
  54238. self.pushComponent(basePath.components, undefined, true);
  54239. }
  54240. else {
  54241. basePath = addPath; // No need to clone, we've pulled it from the list
  54242. basePath.newPos++;
  54243. self.pushComponent(basePath.components, true, undefined);
  54244. }
  54245. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  54246. // If we have hit the end of both strings, then we are done
  54247. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  54248. return buildValues(self, basePath.components, newArr, oldArr);
  54249. }
  54250. else {
  54251. // Otherwise track this path as a potential candidate and continue.
  54252. bestPath[diagonalPath] = basePath;
  54253. }
  54254. }
  54255. editLength++;
  54256. }
  54257. while (editLength <= maxEditLength) {
  54258. var ret = execEditLength();
  54259. if (ret) {
  54260. return ret;
  54261. }
  54262. }
  54263. },
  54264. pushComponent: function (components, added, removed) {
  54265. var last = components[components.length - 1];
  54266. if (last && last.added === added && last.removed === removed) {
  54267. // We need to clone here as the component clone operation is just
  54268. // as shallow array clone
  54269. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  54270. }
  54271. else {
  54272. components.push({count: 1, added: added, removed: removed });
  54273. }
  54274. },
  54275. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  54276. var newLen = newArr.length;
  54277. var oldLen = oldArr.length;
  54278. var newPos = basePath.newPos;
  54279. var oldPos = newPos - diagonalPath;
  54280. var commonCount = 0;
  54281. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  54282. newPos++;
  54283. oldPos++;
  54284. commonCount++;
  54285. }
  54286. if (commonCount) {
  54287. basePath.components.push({count: commonCount});
  54288. }
  54289. basePath.newPos = newPos;
  54290. return oldPos;
  54291. },
  54292. tokenize: function (value) {
  54293. return value.slice();
  54294. },
  54295. join: function (value) {
  54296. return value.slice();
  54297. }
  54298. };
  54299. function buildValues(diff, components, newArr, oldArr) {
  54300. var componentPos = 0;
  54301. var componentLen = components.length;
  54302. var newPos = 0;
  54303. var oldPos = 0;
  54304. for (; componentPos < componentLen; componentPos++) {
  54305. var component = components[componentPos];
  54306. if (!component.removed) {
  54307. var indices = [];
  54308. for (var i = newPos; i < newPos + component.count; i++) {
  54309. indices.push(i);
  54310. }
  54311. component.indices = indices;
  54312. newPos += component.count;
  54313. // Common case
  54314. if (!component.added) {
  54315. oldPos += component.count;
  54316. }
  54317. }
  54318. else {
  54319. var indices = [];
  54320. for (var i = oldPos; i < oldPos + component.count; i++) {
  54321. indices.push(i);
  54322. }
  54323. component.indices = indices;
  54324. oldPos += component.count;
  54325. }
  54326. }
  54327. return components;
  54328. }
  54329. function clonePath(path) {
  54330. return { newPos: path.newPos, components: path.components.slice(0) };
  54331. }
  54332. var arrayDiff = new Diff();
  54333. var arrayDiff$1 = function (oldArr, newArr, callback) {
  54334. return arrayDiff.diff(oldArr, newArr, callback);
  54335. };
  54336. /**
  54337. * @file Manages elements that can be defined in <defs> in SVG,
  54338. * e.g., gradients, clip path, etc.
  54339. * @author Zhang Wenli
  54340. */
  54341. var MARK_UNUSED = '0';
  54342. var MARK_USED = '1';
  54343. /**
  54344. * Manages elements that can be defined in <defs> in SVG,
  54345. * e.g., gradients, clip path, etc.
  54346. *
  54347. * @class
  54348. * @param {number} zrId zrender instance id
  54349. * @param {SVGElement} svgRoot root of SVG document
  54350. * @param {string|string[]} tagNames possible tag names
  54351. * @param {string} markLabel label name to make if the element
  54352. * is used
  54353. */
  54354. function Definable(
  54355. zrId,
  54356. svgRoot,
  54357. tagNames,
  54358. markLabel,
  54359. domName
  54360. ) {
  54361. this._zrId = zrId;
  54362. this._svgRoot = svgRoot;
  54363. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  54364. this._markLabel = markLabel;
  54365. this._domName = domName || '_dom';
  54366. this.nextId = 0;
  54367. }
  54368. Definable.prototype.createElement = createElement;
  54369. /**
  54370. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  54371. *
  54372. * @param {boolean} isForceCreating if need to create when not exists
  54373. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  54374. * exist and isForceCreating is false
  54375. */
  54376. Definable.prototype.getDefs = function (isForceCreating) {
  54377. var svgRoot = this._svgRoot;
  54378. var defs = this._svgRoot.getElementsByTagName('defs');
  54379. if (defs.length === 0) {
  54380. // Not exist
  54381. if (isForceCreating) {
  54382. defs = svgRoot.insertBefore(
  54383. this.createElement('defs'), // Create new tag
  54384. svgRoot.firstChild // Insert in the front of svg
  54385. );
  54386. if (!defs.contains) {
  54387. // IE doesn't support contains method
  54388. defs.contains = function (el) {
  54389. var children = defs.children;
  54390. if (!children) {
  54391. return false;
  54392. }
  54393. for (var i = children.length - 1; i >= 0; --i) {
  54394. if (children[i] === el) {
  54395. return true;
  54396. }
  54397. }
  54398. return false;
  54399. };
  54400. }
  54401. return defs;
  54402. }
  54403. else {
  54404. return null;
  54405. }
  54406. }
  54407. else {
  54408. return defs[0];
  54409. }
  54410. };
  54411. /**
  54412. * Update DOM element if necessary.
  54413. *
  54414. * @param {Object|string} element style element. e.g., for gradient,
  54415. * it may be '#ccc' or {type: 'linear', ...}
  54416. * @param {Function|undefined} onUpdate update callback
  54417. */
  54418. Definable.prototype.update = function (element, onUpdate) {
  54419. if (!element) {
  54420. return;
  54421. }
  54422. var defs = this.getDefs(false);
  54423. if (element[this._domName] && defs.contains(element[this._domName])) {
  54424. // Update DOM
  54425. if (typeof onUpdate === 'function') {
  54426. onUpdate(element);
  54427. }
  54428. }
  54429. else {
  54430. // No previous dom, create new
  54431. var dom = this.add(element);
  54432. if (dom) {
  54433. element[this._domName] = dom;
  54434. }
  54435. }
  54436. };
  54437. /**
  54438. * Add gradient dom to defs
  54439. *
  54440. * @param {SVGElement} dom DOM to be added to <defs>
  54441. */
  54442. Definable.prototype.addDom = function (dom) {
  54443. var defs = this.getDefs(true);
  54444. defs.appendChild(dom);
  54445. };
  54446. /**
  54447. * Remove DOM of a given element.
  54448. *
  54449. * @param {SVGElement} element element to remove dom
  54450. */
  54451. Definable.prototype.removeDom = function (element) {
  54452. var defs = this.getDefs(false);
  54453. if (defs && element[this._domName]) {
  54454. defs.removeChild(element[this._domName]);
  54455. element[this._domName] = null;
  54456. }
  54457. };
  54458. /**
  54459. * Get DOMs of this element.
  54460. *
  54461. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  54462. */
  54463. Definable.prototype.getDoms = function () {
  54464. var defs = this.getDefs(false);
  54465. if (!defs) {
  54466. // No dom when defs is not defined
  54467. return [];
  54468. }
  54469. var doms = [];
  54470. each$1(this._tagNames, function (tagName) {
  54471. var tags = defs.getElementsByTagName(tagName);
  54472. // Note that tags is HTMLCollection, which is array-like
  54473. // rather than real array.
  54474. // So `doms.concat(tags)` add tags as one object.
  54475. doms = doms.concat([].slice.call(tags));
  54476. });
  54477. return doms;
  54478. };
  54479. /**
  54480. * Mark DOMs to be unused before painting, and clear unused ones at the end
  54481. * of the painting.
  54482. */
  54483. Definable.prototype.markAllUnused = function () {
  54484. var doms = this.getDoms();
  54485. var that = this;
  54486. each$1(doms, function (dom) {
  54487. dom[that._markLabel] = MARK_UNUSED;
  54488. });
  54489. };
  54490. /**
  54491. * Mark a single DOM to be used.
  54492. *
  54493. * @param {SVGElement} dom DOM to mark
  54494. */
  54495. Definable.prototype.markUsed = function (dom) {
  54496. if (dom) {
  54497. dom[this._markLabel] = MARK_USED;
  54498. }
  54499. };
  54500. /**
  54501. * Remove unused DOMs defined in <defs>
  54502. */
  54503. Definable.prototype.removeUnused = function () {
  54504. var defs = this.getDefs(false);
  54505. if (!defs) {
  54506. // Nothing to remove
  54507. return;
  54508. }
  54509. var doms = this.getDoms();
  54510. var that = this;
  54511. each$1(doms, function (dom) {
  54512. if (dom[that._markLabel] !== MARK_USED) {
  54513. // Remove gradient
  54514. defs.removeChild(dom);
  54515. }
  54516. });
  54517. };
  54518. /**
  54519. * Get SVG proxy.
  54520. *
  54521. * @param {Displayable} displayable displayable element
  54522. * @return {Path|Image|Text} svg proxy of given element
  54523. */
  54524. Definable.prototype.getSvgProxy = function (displayable) {
  54525. if (displayable instanceof Path) {
  54526. return svgPath;
  54527. }
  54528. else if (displayable instanceof ZImage) {
  54529. return svgImage;
  54530. }
  54531. else if (displayable instanceof Text) {
  54532. return svgText;
  54533. }
  54534. else {
  54535. return svgPath;
  54536. }
  54537. };
  54538. /**
  54539. * Get text SVG element.
  54540. *
  54541. * @param {Displayable} displayable displayable element
  54542. * @return {SVGElement} SVG element of text
  54543. */
  54544. Definable.prototype.getTextSvgElement = function (displayable) {
  54545. return displayable.__textSvgEl;
  54546. };
  54547. /**
  54548. * Get SVG element.
  54549. *
  54550. * @param {Displayable} displayable displayable element
  54551. * @return {SVGElement} SVG element
  54552. */
  54553. Definable.prototype.getSvgElement = function (displayable) {
  54554. return displayable.__svgEl;
  54555. };
  54556. /**
  54557. * @file Manages SVG gradient elements.
  54558. * @author Zhang Wenli
  54559. */
  54560. /**
  54561. * Manages SVG gradient elements.
  54562. *
  54563. * @class
  54564. * @extends Definable
  54565. * @param {number} zrId zrender instance id
  54566. * @param {SVGElement} svgRoot root of SVG document
  54567. */
  54568. function GradientManager(zrId, svgRoot) {
  54569. Definable.call(
  54570. this,
  54571. zrId,
  54572. svgRoot,
  54573. ['linearGradient', 'radialGradient'],
  54574. '__gradient_in_use__'
  54575. );
  54576. }
  54577. inherits(GradientManager, Definable);
  54578. /**
  54579. * Create new gradient DOM for fill or stroke if not exist,
  54580. * but will not update gradient if exists.
  54581. *
  54582. * @param {SvgElement} svgElement SVG element to paint
  54583. * @param {Displayable} displayable zrender displayable element
  54584. */
  54585. GradientManager.prototype.addWithoutUpdate = function (
  54586. svgElement,
  54587. displayable
  54588. ) {
  54589. if (displayable && displayable.style) {
  54590. var that = this;
  54591. each$1(['fill', 'stroke'], function (fillOrStroke) {
  54592. if (displayable.style[fillOrStroke]
  54593. && (displayable.style[fillOrStroke].type === 'linear'
  54594. || displayable.style[fillOrStroke].type === 'radial')
  54595. ) {
  54596. var gradient = displayable.style[fillOrStroke];
  54597. var defs = that.getDefs(true);
  54598. // Create dom in <defs> if not exists
  54599. var dom;
  54600. if (gradient._dom) {
  54601. // Gradient exists
  54602. dom = gradient._dom;
  54603. if (!defs.contains(gradient._dom)) {
  54604. // _dom is no longer in defs, recreate
  54605. that.addDom(dom);
  54606. }
  54607. }
  54608. else {
  54609. // New dom
  54610. dom = that.add(gradient);
  54611. }
  54612. that.markUsed(displayable);
  54613. var id = dom.getAttribute('id');
  54614. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  54615. }
  54616. });
  54617. }
  54618. };
  54619. /**
  54620. * Add a new gradient tag in <defs>
  54621. *
  54622. * @param {Gradient} gradient zr gradient instance
  54623. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  54624. * created DOM
  54625. */
  54626. GradientManager.prototype.add = function (gradient) {
  54627. var dom;
  54628. if (gradient.type === 'linear') {
  54629. dom = this.createElement('linearGradient');
  54630. }
  54631. else if (gradient.type === 'radial') {
  54632. dom = this.createElement('radialGradient');
  54633. }
  54634. else {
  54635. logError$1('Illegal gradient type.');
  54636. return null;
  54637. }
  54638. // Set dom id with gradient id, since each gradient instance
  54639. // will have no more than one dom element.
  54640. // id may exists before for those dirty elements, in which case
  54641. // id should remain the same, and other attributes should be
  54642. // updated.
  54643. gradient.id = gradient.id || this.nextId++;
  54644. dom.setAttribute('id', 'zr' + this._zrId
  54645. + '-gradient-' + gradient.id);
  54646. this.updateDom(gradient, dom);
  54647. this.addDom(dom);
  54648. return dom;
  54649. };
  54650. /**
  54651. * Update gradient.
  54652. *
  54653. * @param {Gradient} gradient zr gradient instance
  54654. */
  54655. GradientManager.prototype.update = function (gradient) {
  54656. var that = this;
  54657. Definable.prototype.update.call(this, gradient, function () {
  54658. var type = gradient.type;
  54659. var tagName = gradient._dom.tagName;
  54660. if (type === 'linear' && tagName === 'linearGradient'
  54661. || type === 'radial' && tagName === 'radialGradient'
  54662. ) {
  54663. // Gradient type is not changed, update gradient
  54664. that.updateDom(gradient, gradient._dom);
  54665. }
  54666. else {
  54667. // Remove and re-create if type is changed
  54668. that.removeDom(gradient);
  54669. that.add(gradient);
  54670. }
  54671. });
  54672. };
  54673. /**
  54674. * Update gradient dom
  54675. *
  54676. * @param {Gradient} gradient zr gradient instance
  54677. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  54678. * DOM to update
  54679. */
  54680. GradientManager.prototype.updateDom = function (gradient, dom) {
  54681. if (gradient.type === 'linear') {
  54682. dom.setAttribute('x1', gradient.x);
  54683. dom.setAttribute('y1', gradient.y);
  54684. dom.setAttribute('x2', gradient.x2);
  54685. dom.setAttribute('y2', gradient.y2);
  54686. }
  54687. else if (gradient.type === 'radial') {
  54688. dom.setAttribute('cx', gradient.x);
  54689. dom.setAttribute('cy', gradient.y);
  54690. dom.setAttribute('r', gradient.r);
  54691. }
  54692. else {
  54693. logError$1('Illegal gradient type.');
  54694. return;
  54695. }
  54696. if (gradient.global) {
  54697. // x1, x2, y1, y2 in range of 0 to canvas width or height
  54698. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  54699. }
  54700. else {
  54701. // x1, x2, y1, y2 in range of 0 to 1
  54702. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  54703. }
  54704. // Remove color stops if exists
  54705. dom.innerHTML = '';
  54706. // Add color stops
  54707. var colors = gradient.colorStops;
  54708. for (var i = 0, len = colors.length; i < len; ++i) {
  54709. var stop = this.createElement('stop');
  54710. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  54711. var color = colors[i].color;
  54712. if (color.indexOf('rgba' > -1)) {
  54713. // Fix Safari bug that stop-color not recognizing alpha #9014
  54714. var opacity = parse(color)[3];
  54715. var hex = toHex(color);
  54716. // stop-color cannot be color, since:
  54717. // The opacity value used for the gradient calculation is the
  54718. // *product* of the value of stop-opacity and the opacity of the
  54719. // value of stop-color.
  54720. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  54721. stop.setAttribute('stop-color', '#' + hex);
  54722. stop.setAttribute('stop-opacity', opacity);
  54723. }
  54724. else {
  54725. stop.setAttribute('stop-color', colors[i].color);
  54726. }
  54727. dom.appendChild(stop);
  54728. }
  54729. // Store dom element in gradient, to avoid creating multiple
  54730. // dom instances for the same gradient element
  54731. gradient._dom = dom;
  54732. };
  54733. /**
  54734. * Mark a single gradient to be used
  54735. *
  54736. * @param {Displayable} displayable displayable element
  54737. */
  54738. GradientManager.prototype.markUsed = function (displayable) {
  54739. if (displayable.style) {
  54740. var gradient = displayable.style.fill;
  54741. if (gradient && gradient._dom) {
  54742. Definable.prototype.markUsed.call(this, gradient._dom);
  54743. }
  54744. gradient = displayable.style.stroke;
  54745. if (gradient && gradient._dom) {
  54746. Definable.prototype.markUsed.call(this, gradient._dom);
  54747. }
  54748. }
  54749. };
  54750. /**
  54751. * @file Manages SVG clipPath elements.
  54752. * @author Zhang Wenli
  54753. */
  54754. /**
  54755. * Manages SVG clipPath elements.
  54756. *
  54757. * @class
  54758. * @extends Definable
  54759. * @param {number} zrId zrender instance id
  54760. * @param {SVGElement} svgRoot root of SVG document
  54761. */
  54762. function ClippathManager(zrId, svgRoot) {
  54763. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  54764. }
  54765. inherits(ClippathManager, Definable);
  54766. /**
  54767. * Update clipPath.
  54768. *
  54769. * @param {Displayable} displayable displayable element
  54770. */
  54771. ClippathManager.prototype.update = function (displayable) {
  54772. var svgEl = this.getSvgElement(displayable);
  54773. if (svgEl) {
  54774. this.updateDom(svgEl, displayable.__clipPaths, false);
  54775. }
  54776. var textEl = this.getTextSvgElement(displayable);
  54777. if (textEl) {
  54778. // Make another clipPath for text, since it's transform
  54779. // matrix is not the same with svgElement
  54780. this.updateDom(textEl, displayable.__clipPaths, true);
  54781. }
  54782. this.markUsed(displayable);
  54783. };
  54784. /**
  54785. * Create an SVGElement of displayable and create a <clipPath> of its
  54786. * clipPath
  54787. *
  54788. * @param {Displayable} parentEl parent element
  54789. * @param {ClipPath[]} clipPaths clipPaths of parent element
  54790. * @param {boolean} isText if parent element is Text
  54791. */
  54792. ClippathManager.prototype.updateDom = function (
  54793. parentEl,
  54794. clipPaths,
  54795. isText
  54796. ) {
  54797. if (clipPaths && clipPaths.length > 0) {
  54798. // Has clipPath, create <clipPath> with the first clipPath
  54799. var defs = this.getDefs(true);
  54800. var clipPath = clipPaths[0];
  54801. var clipPathEl;
  54802. var id;
  54803. var dom = isText ? '_textDom' : '_dom';
  54804. if (clipPath[dom]) {
  54805. // Use a dom that is already in <defs>
  54806. id = clipPath[dom].getAttribute('id');
  54807. clipPathEl = clipPath[dom];
  54808. // Use a dom that is already in <defs>
  54809. if (!defs.contains(clipPathEl)) {
  54810. // This happens when set old clipPath that has
  54811. // been previously removed
  54812. defs.appendChild(clipPathEl);
  54813. }
  54814. }
  54815. else {
  54816. // New <clipPath>
  54817. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  54818. ++this.nextId;
  54819. clipPathEl = this.createElement('clipPath');
  54820. clipPathEl.setAttribute('id', id);
  54821. defs.appendChild(clipPathEl);
  54822. clipPath[dom] = clipPathEl;
  54823. }
  54824. // Build path and add to <clipPath>
  54825. var svgProxy = this.getSvgProxy(clipPath);
  54826. if (clipPath.transform
  54827. && clipPath.parent.invTransform
  54828. && !isText
  54829. ) {
  54830. /**
  54831. * If a clipPath has a parent with transform, the transform
  54832. * of parent should not be considered when setting transform
  54833. * of clipPath. So we need to transform back from parent's
  54834. * transform, which is done by multiplying parent's inverse
  54835. * transform.
  54836. */
  54837. // Store old transform
  54838. var transform = Array.prototype.slice.call(
  54839. clipPath.transform
  54840. );
  54841. // Transform back from parent, and brush path
  54842. mul$1(
  54843. clipPath.transform,
  54844. clipPath.parent.invTransform,
  54845. clipPath.transform
  54846. );
  54847. svgProxy.brush(clipPath);
  54848. // Set back transform of clipPath
  54849. clipPath.transform = transform;
  54850. }
  54851. else {
  54852. svgProxy.brush(clipPath);
  54853. }
  54854. var pathEl = this.getSvgElement(clipPath);
  54855. clipPathEl.innerHTML = '';
  54856. /**
  54857. * Use `cloneNode()` here to appendChild to multiple parents,
  54858. * which may happend when Text and other shapes are using the same
  54859. * clipPath. Since Text will create an extra clipPath DOM due to
  54860. * different transform rules.
  54861. */
  54862. clipPathEl.appendChild(pathEl.cloneNode());
  54863. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  54864. if (clipPaths.length > 1) {
  54865. // Make the other clipPaths recursively
  54866. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  54867. }
  54868. }
  54869. else {
  54870. // No clipPath
  54871. if (parentEl) {
  54872. parentEl.setAttribute('clip-path', 'none');
  54873. }
  54874. }
  54875. };
  54876. /**
  54877. * Mark a single clipPath to be used
  54878. *
  54879. * @param {Displayable} displayable displayable element
  54880. */
  54881. ClippathManager.prototype.markUsed = function (displayable) {
  54882. var that = this;
  54883. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  54884. if (displayable.__clipPaths) {
  54885. each$1(displayable.__clipPaths, function (clipPath) {
  54886. if (clipPath._dom) {
  54887. Definable.prototype.markUsed.call(that, clipPath._dom);
  54888. }
  54889. if (clipPath._textDom) {
  54890. Definable.prototype.markUsed.call(that, clipPath._textDom);
  54891. }
  54892. });
  54893. }
  54894. };
  54895. /**
  54896. * @file Manages SVG shadow elements.
  54897. * @author Zhang Wenli
  54898. */
  54899. /**
  54900. * Manages SVG shadow elements.
  54901. *
  54902. * @class
  54903. * @extends Definable
  54904. * @param {number} zrId zrender instance id
  54905. * @param {SVGElement} svgRoot root of SVG document
  54906. */
  54907. function ShadowManager(zrId, svgRoot) {
  54908. Definable.call(
  54909. this,
  54910. zrId,
  54911. svgRoot,
  54912. ['filter'],
  54913. '__filter_in_use__',
  54914. '_shadowDom'
  54915. );
  54916. }
  54917. inherits(ShadowManager, Definable);
  54918. /**
  54919. * Create new shadow DOM for fill or stroke if not exist,
  54920. * but will not update shadow if exists.
  54921. *
  54922. * @param {SvgElement} svgElement SVG element to paint
  54923. * @param {Displayable} displayable zrender displayable element
  54924. */
  54925. ShadowManager.prototype.addWithoutUpdate = function (
  54926. svgElement,
  54927. displayable
  54928. ) {
  54929. if (displayable && hasShadow(displayable.style)) {
  54930. // Create dom in <defs> if not exists
  54931. var dom;
  54932. if (displayable._shadowDom) {
  54933. // Gradient exists
  54934. dom = displayable._shadowDom;
  54935. var defs = this.getDefs(true);
  54936. if (!defs.contains(displayable._shadowDom)) {
  54937. // _shadowDom is no longer in defs, recreate
  54938. this.addDom(dom);
  54939. }
  54940. }
  54941. else {
  54942. // New dom
  54943. dom = this.add(displayable);
  54944. }
  54945. this.markUsed(displayable);
  54946. var id = dom.getAttribute('id');
  54947. svgElement.style.filter = 'url(#' + id + ')';
  54948. }
  54949. };
  54950. /**
  54951. * Add a new shadow tag in <defs>
  54952. *
  54953. * @param {Displayable} displayable zrender displayable element
  54954. * @return {SVGFilterElement} created DOM
  54955. */
  54956. ShadowManager.prototype.add = function (displayable) {
  54957. var dom = this.createElement('filter');
  54958. // Set dom id with shadow id, since each shadow instance
  54959. // will have no more than one dom element.
  54960. // id may exists before for those dirty elements, in which case
  54961. // id should remain the same, and other attributes should be
  54962. // updated.
  54963. displayable._shadowDomId = displayable._shadowDomId || this.nextId++;
  54964. dom.setAttribute('id', 'zr' + this._zrId
  54965. + '-shadow-' + displayable._shadowDomId);
  54966. this.updateDom(displayable, dom);
  54967. this.addDom(dom);
  54968. return dom;
  54969. };
  54970. /**
  54971. * Update shadow.
  54972. *
  54973. * @param {Displayable} displayable zrender displayable element
  54974. */
  54975. ShadowManager.prototype.update = function (svgElement, displayable) {
  54976. var style = displayable.style;
  54977. if (hasShadow(style)) {
  54978. var that = this;
  54979. Definable.prototype.update.call(this, displayable, function () {
  54980. that.updateDom(displayable, displayable._shadowDom);
  54981. });
  54982. }
  54983. else {
  54984. // Remove shadow
  54985. this.remove(svgElement, displayable);
  54986. }
  54987. };
  54988. /**
  54989. * Remove DOM and clear parent filter
  54990. */
  54991. ShadowManager.prototype.remove = function (svgElement, displayable) {
  54992. if (displayable._shadowDomId != null) {
  54993. this.removeDom(svgElement);
  54994. svgElement.style.filter = '';
  54995. }
  54996. };
  54997. /**
  54998. * Update shadow dom
  54999. *
  55000. * @param {Displayable} displayable zrender displayable element
  55001. * @param {SVGFilterElement} dom DOM to update
  55002. */
  55003. ShadowManager.prototype.updateDom = function (displayable, dom) {
  55004. var domChild = dom.getElementsByTagName('feDropShadow');
  55005. if (domChild.length === 0) {
  55006. domChild = this.createElement('feDropShadow');
  55007. }
  55008. else {
  55009. domChild = domChild[0];
  55010. }
  55011. var style = displayable.style;
  55012. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  55013. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  55014. // TODO: textBoxShadowBlur is not supported yet
  55015. var offsetX;
  55016. var offsetY;
  55017. var blur;
  55018. var color;
  55019. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  55020. offsetX = style.shadowOffsetX || 0;
  55021. offsetY = style.shadowOffsetY || 0;
  55022. blur = style.shadowBlur;
  55023. color = style.shadowColor;
  55024. }
  55025. else if (style.textShadowBlur) {
  55026. offsetX = style.textShadowOffsetX || 0;
  55027. offsetY = style.textShadowOffsetY || 0;
  55028. blur = style.textShadowBlur;
  55029. color = style.textShadowColor;
  55030. }
  55031. else {
  55032. // Remove shadow
  55033. this.removeDom(dom, style);
  55034. return;
  55035. }
  55036. domChild.setAttribute('dx', offsetX / scaleX);
  55037. domChild.setAttribute('dy', offsetY / scaleY);
  55038. domChild.setAttribute('flood-color', color);
  55039. // Divide by two here so that it looks the same as in canvas
  55040. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  55041. var stdDx = blur / 2 / scaleX;
  55042. var stdDy = blur / 2 / scaleY;
  55043. var stdDeviation = stdDx + ' ' + stdDy;
  55044. domChild.setAttribute('stdDeviation', stdDeviation);
  55045. // Fix filter clipping problem
  55046. dom.setAttribute('x', '-100%');
  55047. dom.setAttribute('y', '-100%');
  55048. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  55049. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  55050. dom.appendChild(domChild);
  55051. // Store dom element in shadow, to avoid creating multiple
  55052. // dom instances for the same shadow element
  55053. displayable._shadowDom = dom;
  55054. };
  55055. /**
  55056. * Mark a single shadow to be used
  55057. *
  55058. * @param {Displayable} displayable displayable element
  55059. */
  55060. ShadowManager.prototype.markUsed = function (displayable) {
  55061. if (displayable._shadowDom) {
  55062. Definable.prototype.markUsed.call(this, displayable._shadowDom);
  55063. }
  55064. };
  55065. function hasShadow(style) {
  55066. // TODO: textBoxShadowBlur is not supported yet
  55067. return style
  55068. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  55069. || style.textShadowBlur || style.textShadowOffsetX
  55070. || style.textShadowOffsetY);
  55071. }
  55072. /**
  55073. * SVG Painter
  55074. * @module zrender/svg/Painter
  55075. */
  55076. function parseInt10$2(val) {
  55077. return parseInt(val, 10);
  55078. }
  55079. function getSvgProxy(el) {
  55080. if (el instanceof Path) {
  55081. return svgPath;
  55082. }
  55083. else if (el instanceof ZImage) {
  55084. return svgImage;
  55085. }
  55086. else if (el instanceof Text) {
  55087. return svgText;
  55088. }
  55089. else {
  55090. return svgPath;
  55091. }
  55092. }
  55093. function checkParentAvailable(parent, child) {
  55094. return child && parent && child.parentNode !== parent;
  55095. }
  55096. function insertAfter(parent, child, prevSibling) {
  55097. if (checkParentAvailable(parent, child) && prevSibling) {
  55098. var nextSibling = prevSibling.nextSibling;
  55099. nextSibling ? parent.insertBefore(child, nextSibling)
  55100. : parent.appendChild(child);
  55101. }
  55102. }
  55103. function prepend(parent, child) {
  55104. if (checkParentAvailable(parent, child)) {
  55105. var firstChild = parent.firstChild;
  55106. firstChild ? parent.insertBefore(child, firstChild)
  55107. : parent.appendChild(child);
  55108. }
  55109. }
  55110. // function append(parent, child) {
  55111. // if (checkParentAvailable(parent, child)) {
  55112. // parent.appendChild(child);
  55113. // }
  55114. // }
  55115. function remove$1(parent, child) {
  55116. if (child && parent && child.parentNode === parent) {
  55117. parent.removeChild(child);
  55118. }
  55119. }
  55120. function getTextSvgElement(displayable) {
  55121. return displayable.__textSvgEl;
  55122. }
  55123. function getSvgElement(displayable) {
  55124. return displayable.__svgEl;
  55125. }
  55126. /**
  55127. * @alias module:zrender/svg/Painter
  55128. * @constructor
  55129. * @param {HTMLElement} root 绘图容器
  55130. * @param {module:zrender/Storage} storage
  55131. * @param {Object} opts
  55132. */
  55133. var SVGPainter = function (root, storage, opts, zrId) {
  55134. this.root = root;
  55135. this.storage = storage;
  55136. this._opts = opts = extend({}, opts || {});
  55137. var svgRoot = createElement('svg');
  55138. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  55139. svgRoot.setAttribute('version', '1.1');
  55140. svgRoot.setAttribute('baseProfile', 'full');
  55141. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  55142. this.gradientManager = new GradientManager(zrId, svgRoot);
  55143. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  55144. this.shadowManager = new ShadowManager(zrId, svgRoot);
  55145. var viewport = document.createElement('div');
  55146. viewport.style.cssText = 'overflow:hidden;position:relative';
  55147. this._svgRoot = svgRoot;
  55148. this._viewport = viewport;
  55149. root.appendChild(viewport);
  55150. viewport.appendChild(svgRoot);
  55151. this.resize(opts.width, opts.height);
  55152. this._visibleList = [];
  55153. };
  55154. SVGPainter.prototype = {
  55155. constructor: SVGPainter,
  55156. getType: function () {
  55157. return 'svg';
  55158. },
  55159. getViewportRoot: function () {
  55160. return this._viewport;
  55161. },
  55162. getViewportRootOffset: function () {
  55163. var viewportRoot = this.getViewportRoot();
  55164. if (viewportRoot) {
  55165. return {
  55166. offsetLeft: viewportRoot.offsetLeft || 0,
  55167. offsetTop: viewportRoot.offsetTop || 0
  55168. };
  55169. }
  55170. },
  55171. refresh: function () {
  55172. var list = this.storage.getDisplayList(true);
  55173. this._paintList(list);
  55174. },
  55175. setBackgroundColor: function (backgroundColor) {
  55176. // TODO gradient
  55177. this._viewport.style.background = backgroundColor;
  55178. },
  55179. _paintList: function (list) {
  55180. this.gradientManager.markAllUnused();
  55181. this.clipPathManager.markAllUnused();
  55182. this.shadowManager.markAllUnused();
  55183. var svgRoot = this._svgRoot;
  55184. var visibleList = this._visibleList;
  55185. var listLen = list.length;
  55186. var newVisibleList = [];
  55187. var i;
  55188. for (i = 0; i < listLen; i++) {
  55189. var displayable = list[i];
  55190. var svgProxy = getSvgProxy(displayable);
  55191. var svgElement = getSvgElement(displayable)
  55192. || getTextSvgElement(displayable);
  55193. if (!displayable.invisible) {
  55194. if (displayable.__dirty) {
  55195. svgProxy && svgProxy.brush(displayable);
  55196. // Update clipPath
  55197. this.clipPathManager.update(displayable);
  55198. // Update gradient and shadow
  55199. if (displayable.style) {
  55200. this.gradientManager
  55201. .update(displayable.style.fill);
  55202. this.gradientManager
  55203. .update(displayable.style.stroke);
  55204. this.shadowManager
  55205. .update(svgElement, displayable);
  55206. }
  55207. displayable.__dirty = false;
  55208. }
  55209. newVisibleList.push(displayable);
  55210. }
  55211. }
  55212. var diff = arrayDiff$1(visibleList, newVisibleList);
  55213. var prevSvgElement;
  55214. // First do remove, in case element moved to the head and do remove
  55215. // after add
  55216. for (i = 0; i < diff.length; i++) {
  55217. var item = diff[i];
  55218. if (item.removed) {
  55219. for (var k = 0; k < item.count; k++) {
  55220. var displayable = visibleList[item.indices[k]];
  55221. var svgElement = getSvgElement(displayable);
  55222. var textSvgElement = getTextSvgElement(displayable);
  55223. remove$1(svgRoot, svgElement);
  55224. remove$1(svgRoot, textSvgElement);
  55225. }
  55226. }
  55227. }
  55228. for (i = 0; i < diff.length; i++) {
  55229. var item = diff[i];
  55230. if (item.added) {
  55231. for (var k = 0; k < item.count; k++) {
  55232. var displayable = newVisibleList[item.indices[k]];
  55233. var svgElement = getSvgElement(displayable);
  55234. var textSvgElement = getTextSvgElement(displayable);
  55235. prevSvgElement
  55236. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  55237. : prepend(svgRoot, svgElement);
  55238. if (svgElement) {
  55239. insertAfter(svgRoot, textSvgElement, svgElement);
  55240. }
  55241. else if (prevSvgElement) {
  55242. insertAfter(
  55243. svgRoot, textSvgElement, prevSvgElement
  55244. );
  55245. }
  55246. else {
  55247. prepend(svgRoot, textSvgElement);
  55248. }
  55249. // Insert text
  55250. insertAfter(svgRoot, textSvgElement, svgElement);
  55251. prevSvgElement = textSvgElement || svgElement
  55252. || prevSvgElement;
  55253. // zrender.Text only create textSvgElement.
  55254. this.gradientManager
  55255. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55256. this.shadowManager
  55257. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55258. this.clipPathManager.markUsed(displayable);
  55259. }
  55260. }
  55261. else if (!item.removed) {
  55262. for (var k = 0; k < item.count; k++) {
  55263. var displayable = newVisibleList[item.indices[k]];
  55264. var svgElement = getSvgElement(displayable);
  55265. var textSvgElement = getTextSvgElement(displayable);
  55266. var svgElement = getSvgElement(displayable);
  55267. var textSvgElement = getTextSvgElement(displayable);
  55268. this.gradientManager.markUsed(displayable);
  55269. this.gradientManager
  55270. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55271. this.shadowManager.markUsed(displayable);
  55272. this.shadowManager
  55273. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55274. this.clipPathManager.markUsed(displayable);
  55275. if (textSvgElement) { // Insert text.
  55276. insertAfter(svgRoot, textSvgElement, svgElement);
  55277. }
  55278. prevSvgElement = svgElement
  55279. || textSvgElement || prevSvgElement;
  55280. }
  55281. }
  55282. }
  55283. this.gradientManager.removeUnused();
  55284. this.clipPathManager.removeUnused();
  55285. this.shadowManager.removeUnused();
  55286. this._visibleList = newVisibleList;
  55287. },
  55288. _getDefs: function (isForceCreating) {
  55289. var svgRoot = this._svgRoot;
  55290. var defs = this._svgRoot.getElementsByTagName('defs');
  55291. if (defs.length === 0) {
  55292. // Not exist
  55293. if (isForceCreating) {
  55294. var defs = svgRoot.insertBefore(
  55295. createElement('defs'), // Create new tag
  55296. svgRoot.firstChild // Insert in the front of svg
  55297. );
  55298. if (!defs.contains) {
  55299. // IE doesn't support contains method
  55300. defs.contains = function (el) {
  55301. var children = defs.children;
  55302. if (!children) {
  55303. return false;
  55304. }
  55305. for (var i = children.length - 1; i >= 0; --i) {
  55306. if (children[i] === el) {
  55307. return true;
  55308. }
  55309. }
  55310. return false;
  55311. };
  55312. }
  55313. return defs;
  55314. }
  55315. else {
  55316. return null;
  55317. }
  55318. }
  55319. else {
  55320. return defs[0];
  55321. }
  55322. },
  55323. resize: function (width, height) {
  55324. var viewport = this._viewport;
  55325. // FIXME Why ?
  55326. viewport.style.display = 'none';
  55327. // Save input w/h
  55328. var opts = this._opts;
  55329. width != null && (opts.width = width);
  55330. height != null && (opts.height = height);
  55331. width = this._getSize(0);
  55332. height = this._getSize(1);
  55333. viewport.style.display = '';
  55334. if (this._width !== width || this._height !== height) {
  55335. this._width = width;
  55336. this._height = height;
  55337. var viewportStyle = viewport.style;
  55338. viewportStyle.width = width + 'px';
  55339. viewportStyle.height = height + 'px';
  55340. var svgRoot = this._svgRoot;
  55341. // Set width by 'svgRoot.width = width' is invalid
  55342. svgRoot.setAttribute('width', width);
  55343. svgRoot.setAttribute('height', height);
  55344. }
  55345. },
  55346. /**
  55347. * 获取绘图区域宽度
  55348. */
  55349. getWidth: function () {
  55350. return this._width;
  55351. },
  55352. /**
  55353. * 获取绘图区域高度
  55354. */
  55355. getHeight: function () {
  55356. return this._height;
  55357. },
  55358. _getSize: function (whIdx) {
  55359. var opts = this._opts;
  55360. var wh = ['width', 'height'][whIdx];
  55361. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  55362. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  55363. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  55364. if (opts[wh] != null && opts[wh] !== 'auto') {
  55365. return parseFloat(opts[wh]);
  55366. }
  55367. var root = this.root;
  55368. // IE8 does not support getComputedStyle, but it use VML.
  55369. var stl = document.defaultView.getComputedStyle(root);
  55370. return (
  55371. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  55372. - (parseInt10$2(stl[plt]) || 0)
  55373. - (parseInt10$2(stl[prb]) || 0)
  55374. ) | 0;
  55375. },
  55376. dispose: function () {
  55377. this.root.innerHTML = '';
  55378. this._svgRoot =
  55379. this._viewport =
  55380. this.storage =
  55381. null;
  55382. },
  55383. clear: function () {
  55384. if (this._viewport) {
  55385. this.root.removeChild(this._viewport);
  55386. }
  55387. },
  55388. pathToDataUrl: function () {
  55389. this.refresh();
  55390. var html = this._svgRoot.outerHTML;
  55391. return 'data:image/svg+xml;charset=UTF-8,' + html;
  55392. }
  55393. };
  55394. // Not supported methods
  55395. function createMethodNotSupport$1(method) {
  55396. return function () {
  55397. logError$1('In SVG mode painter not support method "' + method + '"');
  55398. };
  55399. }
  55400. // Unsuppoted methods
  55401. each$1([
  55402. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  55403. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  55404. 'toDataURL', 'pathToImage'
  55405. ], function (name) {
  55406. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  55407. });
  55408. registerPainter('svg', SVGPainter);
  55409. /*
  55410. * Licensed to the Apache Software Foundation (ASF) under one
  55411. * or more contributor license agreements. See the NOTICE file
  55412. * distributed with this work for additional information
  55413. * regarding copyright ownership. The ASF licenses this file
  55414. * to you under the Apache License, Version 2.0 (the
  55415. * "License"); you may not use this file except in compliance
  55416. * with the License. You may obtain a copy of the License at
  55417. *
  55418. * http://www.apache.org/licenses/LICENSE-2.0
  55419. *
  55420. * Unless required by applicable law or agreed to in writing,
  55421. * software distributed under the License is distributed on an
  55422. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55423. * KIND, either express or implied. See the License for the
  55424. * specific language governing permissions and limitations
  55425. * under the License.
  55426. */
  55427. exports.version = version;
  55428. exports.dependencies = dependencies;
  55429. exports.PRIORITY = PRIORITY;
  55430. exports.init = init;
  55431. exports.connect = connect;
  55432. exports.disConnect = disConnect;
  55433. exports.disconnect = disconnect;
  55434. exports.dispose = dispose;
  55435. exports.getInstanceByDom = getInstanceByDom;
  55436. exports.getInstanceById = getInstanceById;
  55437. exports.registerTheme = registerTheme;
  55438. exports.registerPreprocessor = registerPreprocessor;
  55439. exports.registerProcessor = registerProcessor;
  55440. exports.registerPostUpdate = registerPostUpdate;
  55441. exports.registerAction = registerAction;
  55442. exports.registerCoordinateSystem = registerCoordinateSystem;
  55443. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  55444. exports.registerLayout = registerLayout;
  55445. exports.registerVisual = registerVisual;
  55446. exports.registerLoading = registerLoading;
  55447. exports.extendComponentModel = extendComponentModel;
  55448. exports.extendComponentView = extendComponentView;
  55449. exports.extendSeriesModel = extendSeriesModel;
  55450. exports.extendChartView = extendChartView;
  55451. exports.setCanvasCreator = setCanvasCreator;
  55452. exports.registerMap = registerMap;
  55453. exports.getMap = getMap;
  55454. exports.dataTool = dataTool;
  55455. exports.zrender = zrender;
  55456. exports.number = number;
  55457. exports.format = format;
  55458. exports.throttle = throttle;
  55459. exports.helper = helper;
  55460. exports.matrix = matrix;
  55461. exports.vector = vector;
  55462. exports.color = color;
  55463. exports.parseGeoJSON = parseGeoJSON;
  55464. exports.parseGeoJson = parseGeoJson;
  55465. exports.util = ecUtil;
  55466. exports.graphic = graphic$1;
  55467. exports.List = List;
  55468. exports.Model = Model;
  55469. exports.Axis = Axis;
  55470. exports.env = env$1;
  55471. })));